问:
CUDA API error on Python with Numba
I'm kind of new to numba and was trying to speed up my monte carlo method with it. Im currently working on Ubuntu 14.04 with GeForce 950M. The CUDA version is 8.0.61.

When I try to run the following code I get some memory associated error from CUDA API

Code:

```<code>@cuda.jit
def SIR(rng_states, y, particles, weight, beta, omega, gamma,
    greater, equal, phi, phi_sub):
    # thread/block index for accessing data
    tx = cuda.threadIdx.x # Thread id in a 1D block = particle index
    ty = cuda.blockIdx.x # Block id in a 1D grid = event index
    bw = cuda.blockDim.x # Block width, i.e. number of threads per block = particle number
    pos = tx + ty * bw # computed flattened index inside the array

    # get current event y_t
    y_current = y[ ty ]

    # get number of time steps
    tn = y_current.size

    # iterator over timestep
    for i in range(1, tn):
       # draw samples
        sirModule_sample_draw(rng_states, particles[ty][i-1], beta,
                                 omega, particles[ty][i])

        # get weight
        sirModule_weight(particles[ty][i], particles[ty][i-1], weight[ty][i-1],
                            weight[ty][i], y_current[i], beta, omega, gamma)

        # normalize weight
        weight_sum = arr_sum(weight[ty][i])
        arr_div(weight[ty][i], weight_sum)

        # calculate tau
        sirModule_tau(particles[ty][i], beta, omega, phi, phi_sub)

        # update greater and equal
        greater[ty][i] = greater[ty][i-1]*dot(weight[ty][i-1], phi)
        equal[ty][i] = greater[ty][i-1]*dot(weight[ty][i-1], phi_sub)

def main():

    beta = 1
    omega = 1
    gamma = 2

    pn = 100
    event_number = 50
    timestep = 100

    y = np.ones((event_number, timestep), dtype = np.int8)
    particles = cuda.to_device(np.zeros((event_number, timestep, pn), dtype = np.float32))
    weight = cuda.to_device(np.ones((event_number, timestep, pn), dtype = np.float32))
    greater = cuda.to_device(np.ones((event_number, timestep), dtype = np.float32))
    equal = cuda.to_device(np.ones((event_number, timestep), dtype = np.float32))

    phi = cuda.to_device(np.zeros(particles[0][0].size, dtype = np.float32))
    phi_sub = cuda.to_device(np.zeros(particles[0][0].size, dtype = np.float32))

    rng_states = create_xoroshiro128p_states(pn, seed=1)

    start = timer()
    SIR[event_number, pn](rng_states, y, particles, weight, beta,
    omega, gamma, greater, equal, phi, phi_sub)

    vectoradd_time = timer() - start

    print("sirModule1 took %f seconds" % vectoradd_time)

if __name__ == '__main__':
    main()
</code>```

Then I get

numba.cuda.cudadrv.driver.CudaAPIError: [715] Call to cuMemcpyDtoH results in UNKNOWN_CUDA_ERROR

numba.cuda.cudadrv.driver.CudaAPIError: [715] Call to cuMemFree results in UNKNOWN_CUDA_ERROR

errors....

Did anybody face the same problem? I checked online and some suggest that the problem arise from WDDM TDR but I thought thats for only Windows, right?

The following is the missing part of the code.

```<code>import numpy as np
import numba as nb
from timeit import default_timer as timer
from matplotlib import pyplot as pt
import math
from numba import cuda
from numba.cuda.random import create_xoroshiro128p_states, xoroshiro128p_normal_float32

"""
Look up table for factorial
"""
LOOKUP_TABLE = cuda.to_device(np.array([
1, 1, 2, 6, 24, 120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600,
6227020800, 87178291200, 1307674368000,
20922789888000, 355687428096000, 6402373705728000,
121645100408832000, 2432902008176640000], dtype='int64'))

"""
arr_sum - sum element in array
"""
@cuda.jit(device=True)
def arr_sum(arr):
    result = 0
    for i in range(arr.size):
        result = result + arr[i]

    return result

"""
dot - dot product of arr1 and arr2
"""
@cuda.jit(device=True)
def dot(arr1, arr2):
    result = 0
    for i in range(arr1.size):
        result = arr1[i]*arr2[i] + result

    return result

"""
arr_div - divide element in array
"""
@cuda.jit(device=True)
def arr_div(arr, div):
    thread_id = cuda.threadIdx.x

    arr[thread_id] = arr[thread_id]/div

"""
SIR module (sample_draw) - module drawing sample for time t (rampling model)
"""
@cuda.jit(device=True)
def sirModule_sample_draw(rng_states, inp, beta, omega, out):
    """Find a value less than 1 from nomral distribution"""
    thread_id = cuda.threadIdx.x

    # draw candidate sample from normal distribution and store
    # when less than 1
    while True:
        candidate = inp[thread_id] + beta + omega * xoroshiro128p_normal_float32(rng_states, thread_id)

        if candidate < 1:
            out[thread_id] = candidate
            break

"""
SIR module (weight calculation) - weight calculation method
"""
@cuda.jit(device=True)
def sirModule_weight(current, previous, weight, out, y, beta, omega, gamma):
    thread_id = cuda.threadIdx.x
    PI = 3.14159265359

    # calculate the pdf/pmf of given state
    Z = ( current[thread_id] - ( previous[ thread_id ] + beta ) ) / omega
    p1_div_p3 = 1.0 / 2.0 * ( 1.0 + math.erf( Z ) )

    mu = math.log( 1 + math.exp( gamma * current[ thread_id ] ) )
    p2 = math.exp( mu ) * mu**y / LOOKUP_TABLE[ y ]

    out[thread_id] = weight[thread_id]*p2*p1_div_p3

"""
SIR module (phi distribution calculator)
"""
@cuda.jit(device=True)
def sirModule_tau(current, beta, omega, phi, phi_sub):
thread_id = cuda.threadIdx.x

    # calculate phi distribution and subtract from 1
    Z = ( 1 - ( current[ thread_id ] + beta ) ) / omega
    phi[ thread_id ] = 1.0 / 2.0 * ( 1.0 + math.erf( Z ) )
    phi_sub[ thread_id ] = 1 - phi[ thread_id ]
</code>```

But these are the device functions. Should this be a source of problem?

And for the error, I get the following error message where line 207 in my code is where I call SIR module.

```<code>Traceback (most recent call last):
  File "CUDA_MonteCarlo_Testesr.py", line 214, in <module>
    main()
  File "CUDA_MonteCarlo_Testesr.py", line 207, in main
    omega, gamma, greater, equal, phi, phi_sub)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/compiler.py", line 703, in __call__
cfg(*args)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/compiler.py", line 483, in __call__
sharedmem=self.sharedmem)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/compiler.py", line 585, in _kernel_call
wb()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/compiler.py", line 600, in <lambda>
retr.append(lambda: devary.copy_to_host(val, stream=stream))
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/devicearray.py", line 198, in copy_to_host
_driver.device_to_host(hostary, self, self.alloc_size, stream=stream)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 1597, in device_to_host
fn(host_pointer(dst), device_pointer(src), size, *varargs)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 288, in safe_cuda_api_call
self._check_error(fname, retcode)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 323, in _check_error
raise CudaAPIError(retcode, msg)
numba.cuda.cudadrv.driver.CudaAPIError: [715] Call to cuMemcpyDtoH results in UNKNOWN_CUDA_ERROR
Traceback (most recent call last):
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/utils.py", line 647, in _exitfunc
f()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/utils.py", line 571, in __call__
return info.func(*info.args, **(info.kwargs or {}))
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 1099, in deref
mem.free()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 1013, in free
self._finalizer()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/utils.py", line 571, in __call__
return info.func(*info.args, **(info.kwargs or {}))
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 863, in core
deallocations.add_item(dtor, handle, size=bytesize)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 519, in add_item
self.clear()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 530, in clear
dtor(handle)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 288, in safe_cuda_api_call
self._check_error(fname, retcode)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 323, in _check_error
raise CudaAPIError(retcode, msg)
numba.cuda.cudadrv.driver.CudaAPIError: [715] Call to cuMemFree results in UNKNOWN_CUDA_ERROR
</code>```

答:
Solved! I am working on Ubuntu 16.04. When I installed Numba for the first time, numba.cuda functions worked fine. However later I encountered these kind of errors

raise CudaAPIError(retcode, msg)

CudaAPIError: Call to cuMemcpyHtoD results in CUDA_ERROR_LAUNCH_FAILED

These errors are encountered when you put your system on 'suspend'. In order to avoid such errors, restart your system or don't suspend.

Title: CUDA API error on Python with Numba

Body:
I'm kind of new to numba and was trying to speed up my monte carlo method with it. Im currently working on Ubuntu 14.04 with GeForce 950M. The CUDA version is 8.0.61.

When I try to run the following code I get some memory associated error from CUDA API

Code:

@cuda.jit
def SIR(rng_states, y, particles, weight, beta, omega, gamma,
    greater, equal, phi, phi_sub):
    # thread/block index for accessing data
    tx = cuda.threadIdx.x # Thread id in a 1D block = particle index
    ty = cuda.blockIdx.x # Block id in a 1D grid = event index
    bw = cuda.blockDim.x # Block width, i.e. number of threads per block = particle number
    pos = tx + ty * bw # computed flattened index inside the array

    # get current event y_t
    y_current = y[ ty ]

    # get number of time steps
    tn = y_current.size

    # iterator over timestep
    for i in range(1, tn):
       # draw samples
        sirModule_sample_draw(rng_states, particles[ty][i-1], beta,
                                 omega, particles[ty][i])

        # get weight
        sirModule_weight(particles[ty][i], particles[ty][i-1], weight[ty][i-1],
                            weight[ty][i], y_current[i], beta, omega, gamma)

        # normalize weight
        weight_sum = arr_sum(weight[ty][i])
        arr_div(weight[ty][i], weight_sum)

        # calculate tau
        sirModule_tau(particles[ty][i], beta, omega, phi, phi_sub)

        # update greater and equal
        greater[ty][i] = greater[ty][i-1]*dot(weight[ty][i-1], phi)
        equal[ty][i] = greater[ty][i-1]*dot(weight[ty][i-1], phi_sub)

def main():

    beta = 1
    omega = 1
    gamma = 2

    pn = 100
    event_number = 50
    timestep = 100

    y = np.ones((event_number, timestep), dtype = np.int8)
    particles = cuda.to_device(np.zeros((event_number, timestep, pn), dtype = np.float32))
    weight = cuda.to_device(np.ones((event_number, timestep, pn), dtype = np.float32))
    greater = cuda.to_device(np.ones((event_number, timestep), dtype = np.float32))
    equal = cuda.to_device(np.ones((event_number, timestep), dtype = np.float32))

    phi = cuda.to_device(np.zeros(particles[0][0].size, dtype = np.float32))
    phi_sub = cuda.to_device(np.zeros(particles[0][0].size, dtype = np.float32))

    rng_states = create_xoroshiro128p_states(pn, seed=1)

    start = timer()
    SIR[event_number, pn](rng_states, y, particles, weight, beta,
    omega, gamma, greater, equal, phi, phi_sub)

    vectoradd_time = timer() - start

    print("sirModule1 took %f seconds" % vectoradd_time)

if __name__ == '__main__':
    main()

Then I get

numba.cuda.cudadrv.driver.CudaAPIError: [715] Call to cuMemcpyDtoH results in UNKNOWN_CUDA_ERROR

numba.cuda.cudadrv.driver.CudaAPIError: [715] Call to cuMemFree results in UNKNOWN_CUDA_ERROR

errors....

Did anybody face the same problem? I checked online and some suggest that the problem arise from WDDM TDR but I thought thats for only Windows, right?

The following is the missing part of the code.

import numpy as np
import numba as nb
from timeit import default_timer as timer
from matplotlib import pyplot as pt
import math
from numba import cuda
from numba.cuda.random import create_xoroshiro128p_states, xoroshiro128p_normal_float32

"""
Look up table for factorial
"""
LOOKUP_TABLE = cuda.to_device(np.array([
1, 1, 2, 6, 24, 120, 720, 5040, 40320,
362880, 3628800, 39916800, 479001600,
6227020800, 87178291200, 1307674368000,
20922789888000, 355687428096000, 6402373705728000,
121645100408832000, 2432902008176640000], dtype='int64'))

"""
arr_sum - sum element in array
"""
@cuda.jit(device=True)
def arr_sum(arr):
    result = 0
    for i in range(arr.size):
        result = result + arr[i]

    return result

"""
dot - dot product of arr1 and arr2
"""
@cuda.jit(device=True)
def dot(arr1, arr2):
    result = 0
    for i in range(arr1.size):
        result = arr1[i]*arr2[i] + result

    return result

"""
arr_div - divide element in array
"""
@cuda.jit(device=True)
def arr_div(arr, div):
    thread_id = cuda.threadIdx.x

    arr[thread_id] = arr[thread_id]/div

"""
SIR module (sample_draw) - module drawing sample for time t (rampling model)
"""
@cuda.jit(device=True)
def sirModule_sample_draw(rng_states, inp, beta, omega, out):
    """Find a value less than 1 from nomral distribution"""
    thread_id = cuda.threadIdx.x

    # draw candidate sample from normal distribution and store
    # when less than 1
    while True:
        candidate = inp[thread_id] + beta + omega * xoroshiro128p_normal_float32(rng_states, thread_id)

        if candidate < 1:
            out[thread_id] = candidate
            break

"""
SIR module (weight calculation) - weight calculation method
"""
@cuda.jit(device=True)
def sirModule_weight(current, previous, weight, out, y, beta, omega, gamma):
    thread_id = cuda.threadIdx.x
    PI = 3.14159265359

    # calculate the pdf/pmf of given state
    Z = ( current[thread_id] - ( previous[ thread_id ] + beta ) ) / omega
    p1_div_p3 = 1.0 / 2.0 * ( 1.0 + math.erf( Z ) )

    mu = math.log( 1 + math.exp( gamma * current[ thread_id ] ) )
    p2 = math.exp( mu ) * mu**y / LOOKUP_TABLE[ y ]

    out[thread_id] = weight[thread_id]*p2*p1_div_p3

"""
SIR module (phi distribution calculator)
"""
@cuda.jit(device=True)
def sirModule_tau(current, beta, omega, phi, phi_sub):
thread_id = cuda.threadIdx.x

    # calculate phi distribution and subtract from 1
    Z = ( 1 - ( current[ thread_id ] + beta ) ) / omega
    phi[ thread_id ] = 1.0 / 2.0 * ( 1.0 + math.erf( Z ) )
    phi_sub[ thread_id ] = 1 - phi[ thread_id ]

But these are the device functions. Should this be a source of problem?

And for the error, I get the following error message where line 207 in my code is where I call SIR module.

Traceback (most recent call last):
  File "CUDA_MonteCarlo_Testesr.py", line 214, in <module>
    main()
  File "CUDA_MonteCarlo_Testesr.py", line 207, in main
    omega, gamma, greater, equal, phi, phi_sub)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/compiler.py", line 703, in __call__
cfg(*args)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/compiler.py", line 483, in __call__
sharedmem=self.sharedmem)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/compiler.py", line 585, in _kernel_call
wb()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/compiler.py", line 600, in <lambda>
retr.append(lambda: devary.copy_to_host(val, stream=stream))
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/devicearray.py", line 198, in copy_to_host
_driver.device_to_host(hostary, self, self.alloc_size, stream=stream)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 1597, in device_to_host
fn(host_pointer(dst), device_pointer(src), size, *varargs)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 288, in safe_cuda_api_call
self._check_error(fname, retcode)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 323, in _check_error
raise CudaAPIError(retcode, msg)
numba.cuda.cudadrv.driver.CudaAPIError: [715] Call to cuMemcpyDtoH results in UNKNOWN_CUDA_ERROR
Traceback (most recent call last):
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/utils.py", line 647, in _exitfunc
f()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/utils.py", line 571, in __call__
return info.func(*info.args, **(info.kwargs or {}))
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 1099, in deref
mem.free()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 1013, in free
self._finalizer()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/utils.py", line 571, in __call__
return info.func(*info.args, **(info.kwargs or {}))
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 863, in core
deallocations.add_item(dtor, handle, size=bytesize)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 519, in add_item
self.clear()
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 530, in clear
dtor(handle)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 288, in safe_cuda_api_call
self._check_error(fname, retcode)
  File "/home/ryan/anaconda3/envs/py53/lib/python3.5/site-packages/numba/cuda/cudadrv/driver.py", line 323, in _check_error
raise CudaAPIError(retcode, msg)
numba.cuda.cudadrv.driver.CudaAPIError: [715] Call to cuMemFree results in UNKNOWN_CUDA_ERROR


来源: stackexchange

问:
MonoTouch random Background color
I'm a MonoTouch 4 newbie and just experimenting with random colors on the window and to my surprise the code shown below is not working:

// The name AppDelegate is referenced in the MainWindow.xib file.
    public partial class AppDelegate : UIApplicationDelegate
    {
        Random rand = new Random();

```<code>    // This method is invoked when the application has loaded its UI and its ready to run
    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
    {
        // If you have defined a view, add it here:
        // window.AddSubview (navigationController.View);

        objButton.TouchDown += HandleObjButtonTouchDown;
        window.MakeKeyAndVisible ();

        return true;
    }

    void HandleObjButtonTouchDown (object sender, EventArgs e)
    {

        float red, green, blue;
        red = (float) rand.Next(100, 150);
        green = (float) rand.Next(151, 200);
        blue = (float) rand.Next(201, 255);

        window.BackgroundColor = UIColor.Clear;
        window.BackgroundColor = UIColor.FromRGB(red, green, blue);
        objLabel.Text = red.ToString() + "," + blue.ToString() + "," + green.ToString();
    }
</code>```

Each time I click on the button, the TouchDown event is firing properly and also the label is set with random red, green and blue color values but not seeing any effect on the window color.

Please help.

答:
You do not see any effect because the range of RGB values for the UIColor class must be from 0.0 to 1.0. Anything smaller than 0.0 is considered as 0.0 and anything larger than 1.0 is considered as 1.0. So your code will basically always create white color.

To create a color with RGB values of R:100, G:150 and B: 200, do it like this:

```<code>UIColor color = UIColor.FromRGB(100 / 255, 150 / 255, 200 / 255);
</code>```

ContentLicense: CC BY-SA 3.0

Title: MonoTouch random Background color

Body:
I'm a MonoTouch 4 newbie and just experimenting with random colors on the window and to my surprise the code shown below is not working:

// The name AppDelegate is referenced in the MainWindow.xib file.
    public partial class AppDelegate : UIApplicationDelegate
    {
        Random rand = new Random();

    // This method is invoked when the application has loaded its UI and its ready to run
    public override bool FinishedLaunching (UIApplication app, NSDictionary options)
    {
        // If you have defined a view, add it here:
        // window.AddSubview (navigationController.View);

        objButton.TouchDown += HandleObjButtonTouchDown;
        window.MakeKeyAndVisible ();

        return true;
    }

    void HandleObjButtonTouchDown (object sender, EventArgs e)
    {

        float red, green, blue;
        red = (float) rand.Next(100, 150);
        green = (float) rand.Next(151, 200);
        blue = (float) rand.Next(201, 255);

        window.BackgroundColor = UIColor.Clear;
        window.BackgroundColor = UIColor.FromRGB(red, green, blue);
        objLabel.Text = red.ToString() + "," + blue.ToString() + "," + green.ToString();
    }

Each time I click on the button, the TouchDown event is firing properly and also the label is set with random red, green and blue color values but not seeing any effect on the window color.

Please help.

Body:
You do not see any effect because the range of RGB values for the UIColor class must be from 0.0 to 1.0. Anything smaller than 0.0 is considered as 0.0 and anything larger than 1.0 is considered as 1.0. So your code will basically always create white color.

To create a color with RGB values of R:100, G:150 and B: 200, do it like this:

UIColor color = UIColor.FromRGB(100 / 255, 150 / 255, 200 / 255);


问:
Deleting sub-element from JSON file
I thought it was simple to delete a key from JSON nested dict, but I end up with errors .
I have JSON file as shown below, and want to delete a key "8888" from its element "Codes".

dummy.json:

```<code>{
    "Codes": {
        "8888": "code1|18888",
        "9999": "code2|19999",
        "7777": "code3|17777"
    },
    "Names": {
        "Site1": "Site1|18888",
        "Site2": "Site2|19999",
        "Site3": "Site3|17777"
    }
}
</code>```

Python code:

```<code>import json

with open('dummy.json') as json_data:
    data = json.load(json_data)
    for element in data["Codes"]:
        #del element['8888']
        element.pop('8888', None)

with open('dummy.json'), 'w') as outfile:
    json.dump(data, outfile)
</code>```

Result:

For the first attempt, I tried del element['8888'] and it throws TypeError: 'str' object does not support item deletion

As per example found here I have tried with element.pop('8888', None) and it throws AttributeError: 'str' object has no attribute 'pop' error.

I am not sure what mistake I did, please help.

答:
While iterating over data["Codes"], element will be a key of the data["Codes"] dictionary and it's a string, which doesn't have a pop function (can be applied on dicts only).

Try instead:

```<code>import json
with open('dummy.json') as json_data:
    data = json.load(json_data)
    data["Codes"].pop("8888")

with open('dummy.json', 'w') as outfile:
    json.dump(data, outfile)

</code>```

ContentLicense: CC BY-SA 4.0

Title: Deleting sub-element from JSON file

Body:
I thought it was simple to delete a key from JSON nested dict, but I end up with errors .
I have JSON file as shown below, and want to delete a key "8888" from its element "Codes".

dummy.json:

{
    "Codes": {
        "8888": "code1|18888",
        "9999": "code2|19999",
        "7777": "code3|17777"
    },
    "Names": {
        "Site1": "Site1|18888",
        "Site2": "Site2|19999",
        "Site3": "Site3|17777"
    }
}

Python code:

import json

with open('dummy.json') as json_data:
    data = json.load(json_data)
    for element in data["Codes"]:
        #del element['8888']
        element.pop('8888', None)

with open('dummy.json'), 'w') as outfile:
    json.dump(data, outfile)

Result:

For the first attempt, I tried del element['8888'] and it throws TypeError: 'str' object does not support item deletion

As per example found here I have tried with element.pop('8888', None) and it throws AttributeError: 'str' object has no attribute 'pop' error.

I am not sure what mistake I did, please help.

Body:
While iterating over data["Codes"], element will be a key of the data["Codes"] dictionary and it's a string, which doesn't have a pop function (can be applied on dicts only).

Try instead:

import json
with open('dummy.json') as json_data:
    data = json.load(json_data)
    data["Codes"].pop("8888")

with open('dummy.json', 'w') as outfile:
    json.dump(data, outfile)


问:
Can't import torch in jupyter notebook
System: macOS 10.13.6
Python: 3.7
Anaconda3

I have trouble when import torch in jupyter notebook.

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

Here is how I install pytorch:

```<code>conda install pytorch torchvision -c pytorch
</code>```

I've checked PyTorch is installed in my anaconda environment:

When I command python3 in my terminal and import torch, it works. But not work in jupyter notebook

I've tried:

```<code>conda update conda
conda install mkl=2018
</code>```

But still the same error.

答:
I experienced the same bug. I tried the following line on anaconda command prompt.

(pytorch)C:\Users\user> conda install jupyter

Then, I used the command C:\Users\user> jupyter notebook which launched the Jupyter notebook, and the import torch keyword started to work.

Title: Can't import torch in jupyter notebook

Body:
System: macOS 10.13.6
Python: 3.7
Anaconda3

I have trouble when import torch in jupyter notebook.

ModuleNotFoundError: No module named 'torch'

Here is how I install pytorch:

conda install pytorch torchvision -c pytorch

I've checked PyTorch is installed in my anaconda environment:

When I command python3 in my terminal and import torch, it works. But not work in jupyter notebook

I've tried:

conda update conda
conda install mkl=2018

But still the same error.


问:
Failed to instantiate module myApp due to: Error: [$injector:nomod]
I am having an error on this code. I don't know why I am using angularjs 1.7.x version </p>

```<code>$(document).ready(function () {
    $('#signupBtn-spinner').hide();

    var app = angular.module('myApp', []);
    $('#signupBtn').click(signup);
    function signup() {
        app.controller('signupController', ['$scope', '$http', function ($scope, $http) {
            alert('hello')
        }]);
    }
})
</code>```

答:
I strongly recommend you to avoid to use jquery with Angular/js

If you want to implement signup/login logic, suggest you to use ui-router. Some example.

Also please read this great Josh David Miller's answer “Thinking in AngularJS” if I have a jQuery background

About your problem:

You get this error from ng-app.

Put var app = angular.module('myApp', []); out of $(document).ready

Angularjs is loaded and it does not see any module because it is still not ready.

```<code>var app = angular.module('myApp', []);

$(document).ready(function () {
    $('#signupBtn-spinner').hide();

    $('#signupBtn').click(signup);
    function signup() {
        app.controller('signupController', ['$scope', '$http', function ($scope, $http) {
            alert('hello')
        }]);
    }
})
</code>```

Body:
I am having an error on this code. I don't know why I am using angularjs 1.7.x version

$(document).ready(function () {
    $('#signupBtn-spinner').hide();

    var app = angular.module('myApp', []);
    $('#signupBtn').click(signup);
    function signup() {
        app.controller('signupController', ['$scope', '$http', function ($scope, $http) {
            alert('hello')
        }]);
    }
})

Body:
I strongly recommend you to avoid to use jquery with Angular/js

If you want to implement signup/login logic, suggest you to use ui-router. Some example.

Also please read this great Josh David Miller's answer “Thinking in AngularJS” if I have a jQuery background

About your problem:

You get this error from ng-app.

Put var app = angular.module('myApp', []); out of $(document).ready

Angularjs is loaded and it does not see any module because it is still not ready.

var app = angular.module('myApp', []);

$(document).ready(function () {
    $('#signupBtn-spinner').hide();

    $('#signupBtn').click(signup);
    function signup() {
        app.controller('signupController', ['$scope', '$http', function ($scope, $http) {
            alert('hello')
        }]);
    }
})


问:
Write a code that Calculates the average number of non-zero ratings per individual in our data set
So I've written my code below but I am having a hard time getting the code to not include the number of zeros. It runs but unfortunately not the way I want it to. Can anyone shed some light?

the variable movies is basically a list of movies we were given  The code will be right if an average of 21.4 is the output.

```<code>all_ratings =[
[5,5,4,4,3,1,2,3,4,4,4,3,4,0,0,0,1,2,3,4,4,4,1,4,0,0,0,1,2,5],
[5,0,1,2,3,1,2,3,4,4,4,5,4,2,1,0,1,2,0,5,0,4,1,4,2,0,0,1,0,5],
[5,2,3,4,4,0,0,0,4,5,0,3,0,0,0,3,4,0,1,4,4,4,0,4,0,3,0,1,2,5],
[5,0,4,0,0,4,2,3,0,0,4,0,3,0,1,0,1,2,3,0,2,0,1,0,0,0,4,0,1,5],
[5,4,3,2,1,1,2,3,4,3,4,3,4,0,3,0,1,2,4,4,4,4,1,4,0,0,0,1,2,5],
]

total=[]
average=[]

for index in range (len(all_ratings)):
    total+=[sum(all_ratings[index])]

for index in range(len(all_ratings)):
    average = average + [total[index]/30]

for index in range(len(movies)):
    print(average)
</code>```

答:
You can use numpy array to select nonzero elements and numpy mean to get the average

```<code>from numpy import array, mean

answ = [mean(array(el)[array(el)!=0]) for el in
all_ratings]

print (answ)
</code>```

Output:

```<code>[3.2083333333333335, 2.869565217391304, 3.4210526315789473, 2.8125, 2.96]
</code>```

Body:
So I've written my code below but I am having a hard time getting the code to not include the number of zeros. It runs but unfortunately not the way I want it to. Can anyone shed some light?

the variable movies is basically a list of movies we were given  The code will be right if an average of 21.4 is the output.

all_ratings =[
[5,5,4,4,3,1,2,3,4,4,4,3,4,0,0,0,1,2,3,4,4,4,1,4,0,0,0,1,2,5],
[5,0,1,2,3,1,2,3,4,4,4,5,4,2,1,0,1,2,0,5,0,4,1,4,2,0,0,1,0,5],
[5,2,3,4,4,0,0,0,4,5,0,3,0,0,0,3,4,0,1,4,4,4,0,4,0,3,0,1,2,5],
[5,0,4,0,0,4,2,3,0,0,4,0,3,0,1,0,1,2,3,0,2,0,1,0,0,0,4,0,1,5],
[5,4,3,2,1,1,2,3,4,3,4,3,4,0,3,0,1,2,4,4,4,4,1,4,0,0,0,1,2,5],
]

total=[]
average=[]

for index in range (len(all_ratings)):
    total+=[sum(all_ratings[index])]

for index in range(len(all_ratings)):
    average = average + [total[index]/30]

for index in range(len(movies)):
    print(average)

Body:
You can use numpy array to select nonzero elements and numpy mean to get the average

from numpy import array, mean

answ = [mean(array(el)[array(el)!=0]) for el in
all_ratings]

print (answ)

Output:

[3.2083333333333335, 2.869565217391304, 3.4210526315789473, 2.8125, 2.96]


问:
ASM 8086 division without div
I need to write in asm 8086 a program like b=a/6 but without the DIV instruction. I know how to do it with SAR but only 2,4,8,16...

```<code>mov ax,a
sar ax,1 ;//div a by 2
mov b,ax
</code>```

my question is how can I do it to div by 6?

答:
From grade school

x/6 = x * 1/6;

Look at what happens when you let the C compiler do it

```<code>unsigned short fun ( unsigned short x )
{
    return(x/6);
}
</code>```

32 bit x86

```<code>0000000000000000 <fun>:
   0:   0f b7 c7                movzwl %di,%eax
   3:   69 c0 ab aa 00 00       imul   $0xaaab,%eax,%eax
   9:   c1 e8 12                shr    $0x12,%eax
   c:   c3                      retq
</code>```

32 bit arm

```<code>00000000 <fun>:
   0:   e59f3008    ldr r3, [pc, #8]    ; 10 <fun+0x10>
   4:   e0802093    umull   r2, r0, r3, r0
   8:   e1a00120    lsr r0, r0, #2
   c:   e12fff1e    bx  lr
  10:   aaaaaaab
</code>```

same story.  Translate that to 8086.

so 6 = 3 * 2, so we really need to divide by 3. then adjust

```<code>unsigned short fun ( unsigned short x )
{
    return(x/3);
}

00000000 <fun>:
   0:   e59f3008    ldr r3, [pc, #8]    ; 10 <fun+0x10>
   4:   e0802093    umull   r2, r0, r3, r0
   8:   e1a000a0    lsr r0, r0, #1
   c:   e12fff1e    bx  lr
  10:   aaaaaaab
</code>```

one less bit of shift.  One of the shifts is to increase precision the other is because there is a divide by 2 in there.

You can do the subtraction loop of course.  Otherwise it is long division which is actually pretty easy to code.

Title: ASM 8086 division without div

Body:
I need to write in asm 8086 a program like b=a/6 but without the DIV instruction. I know how to do it with SAR but only 2,4,8,16...

mov ax,a
sar ax,1 ;//div a by 2
mov b,ax

my question is how can I do it to div by 6?

Body:
From grade school

x/6 = x * 1/6;

Look at what happens when you let the C compiler do it

unsigned short fun ( unsigned short x )
{
    return(x/6);
}

32 bit x86

0000000000000000 <fun>:
   0:   0f b7 c7                movzwl %di,%eax
   3:   69 c0 ab aa 00 00       imul   $0xaaab,%eax,%eax
   9:   c1 e8 12                shr    $0x12,%eax
   c:   c3                      retq

32 bit arm

00000000 <fun>:
   0:   e59f3008    ldr r3, [pc, #8]    ; 10 <fun+0x10>
   4:   e0802093    umull   r2, r0, r3, r0
   8:   e1a00120    lsr r0, r0, #2
   c:   e12fff1e    bx  lr
  10:   aaaaaaab

same story.  Translate that to 8086.

so 6 = 3 * 2, so we really need to divide by 3. then adjust

unsigned short fun ( unsigned short x )
{
    return(x/3);
}

00000000 <fun>:
   0:   e59f3008    ldr r3, [pc, #8]    ; 10 <fun+0x10>
   4:   e0802093    umull   r2, r0, r3, r0
   8:   e1a000a0    lsr r0, r0, #1
   c:   e12fff1e    bx  lr
  10:   aaaaaaab

one less bit of shift.  One of the shifts is to increase precision the other is because there is a divide by 2 in there.

You can do the subtraction loop of course.  Otherwise it is long division which is actually pretty easy to code.


问:
Does Tkinter have a refresh method?
I am using Tkinter.

```<code>import Tkinter as tk

class App(tk.Frame):
  def __init__(self, *args, **kwargs):
    tk.Frame.__init__(self, *args, **kwargs)
     ....
root = tk.Tk()
root.title("title")

app = App(root)
root.mainloop()
</code>```

Does it has a refresh? Because I want to refresh my frame.
Is root.refresh() is possible?

答:
It's very simple :) Create a function to refresh as given below and call it using a widget.

```<code>def refresh(self):
    self.destroy()
    self.__init__()
</code>```

It worked for me. All you have to do is destroy your main frame tk.Frameand call the constructor again self.__init__().

Title: Does Tkinter have a refresh method?

Body:
I am using Tkinter.

import Tkinter as tk

class App(tk.Frame):
  def __init__(self, *args, **kwargs):
    tk.Frame.__init__(self, *args, **kwargs)
     ....
root = tk.Tk()
root.title("title")

app = App(root)
root.mainloop()

Does it has a refresh? Because I want to refresh my frame.
Is root.refresh() is possible?

Body:
It's very simple :) Create a function to refresh as given below and call it using a widget.

def refresh(self):
    self.destroy()
    self.__init__()

It worked for me. All you have to do is destroy your main frame tk.Frameand call the constructor again self.__init__().


问:
AWS EC2 ssh connection closes after 10 seconds
I was able to properly access my EC2 instance till yesterday. I don't know what happened but suddenly today I am able to login to the instance but the server closes the connection after 10 seconds of login. What could be the reason?

The message I am getting

```<code>[ec2-user@ip-172-31-32-248 ~]$ Connection to ec2-18-221-152-137.us-east-2.compute.amazonaws.com closed by remote host.
Connection to ec2-18-221-152-137.us-east-2.compute.amazonaws.com closed.```
```

答: The problem is simple, a stable internet connection is required to maintain the ssh connection as suggested by @John Rotenstien.</p>

Body:
I was able to properly access my EC2 instance till yesterday. I don't know what happened but suddenly today I am able to login to the instance but the server closes the connection after 10 seconds of login. What could be the reason?

The message I am getting

[ec2-user@ip-172-31-32-248 ~]$ Connection to ec2-18-221-152-137.us-east-2.compute.amazonaws.com closed by remote host.
Connection to ec2-18-221-152-137.us-east-2.compute.amazonaws.com closed.```


问:
2-D array changes value with var AND let
My code currently has a bug where my 2-d array with the bool value false suddenly contains true values before it is assigned any. My current guesses is either console.log somehow is delayed and picks up the values after it is called, with the updated values or that there is some issue that I don't understand about how scope works in javascript.

As seen below console.log(visited[i][j]) results in false for all values but the
new visited line contains true values even before the following is called.

const field_size = 800;
const cells_in_row = 5;
const frames_per_second = 1;
const cell_size = field_size / cells_in_row;

class Cell {
    constructor(x,y) {
        this.value = 0;
        this.x = x;
        this.y = y;
        this.coordinates = [x*cell_size,y*cell_size];
    }

    fill() {
        this.value = 1;
    }
    clear() {
        this.value = 0;
    }

}

const get_new_grid = (random = 0) => {
    const grid = new Array(cells_in_row);
    for (let i = 0; i < grid.length; i++) {
        grid[i] = new Array(cells_in_row);
        for (let j = 0; j < grid.length; j++) {
            grid[i][j] = new Cell(i,j);
            v = 0;
            if (random) {
                v = Math.floor(Math.random() * 2);
            }
            grid[i][j].value = v;
        }
    }
    return grid;
}

const get_islands = (grid) => {
  // bool array to mark visited cells
  let visited = new Array(cells_in_row);
  for (let i = 0; i < grid.length; i++) {
    visited[i] = new Array(cells_in_row);
    for (let j = 0; j < grid[0].length; j++) {

      visited[i][j] = false;
    }
  }

  console.log("New Visited", visited);
  let count = 0;
  let islands = [];
  let island_coords = [];
  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid.length; j++) {
      if (visited[i][j] == false && grid[i][j].value == 1) {
        // visit all cells in this island and increment island count
        // dfs will return array of coordinates of island
        [visited, island_coords] = dfs(i, j, grid, visited, island_coords);
        console.log(visited);
        islands.push(island_coords);
        count += 1;
      }
    }
  }

  return [count, islands];
}

const dfs = (i, j, grid, visited, island_coords) => {
  let row_nbr = [-1, -1, -1, 0, 0, 1, 1, 1];
  let col_nbr = [-1, 0, 1, -1, 1, -1, 0, 1];

  visited[i][j] = true;
  island_coords.push([i,j]);

  for (let k = 0; k < 8; k++) {
      if (is_safe(i + row_nbr[k], j + col_nbr[k], grid, visited)) {
          console.log("DFSing " + i + "," + j);
          [visited, island_coords] = dfs(i + row_nbr[k], j + col_nbr[k],
                                         grid, visited, island_coords);
      }
  }

  return [visited, island_coords];
}

const is_safe = (i, j, grid, visited) => {
    return (i >= 0 && i < grid.length &&
            j >= 0 && j < grid.length &&
            !(visited[i][j]) && grid[i][j].value === 1);
}

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function () {
      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '
';
        } else {
            logger.innerHTML += arguments[i] + '
';
        }
      }
    }
})();

window.onload = () => {
    const canvas = document.getElementById('canvas');
    const grid = get_new_grid(random = 0);
    grid[0][0].value = true;
    grid[0][1].value = true;
    grid[1][0].value = true;
    grid[1][1].value = true;
    const islands = get_islands(grid);
    console.log(grid);
    console.log(islands);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<body>

  <script src="gameoflife.js"></script>
  <pre id="log">```

```

EDIT:
So I updated the snippet but it looks like it works on this end, however it shows the behavior I mentioned before on my own browser even with the exact same javascript code and html in the snippet.

答: Mentioned in the comments by Niet, objects logged to the console are live.</p>

Body:
My code currently has a bug where my 2-d array with the bool value false suddenly contains true values before it is assigned any. My current guesses is either console.log somehow is delayed and picks up the values after it is called, with the updated values or that there is some issue that I don't understand about how scope works in javascript.

As seen below console.log(visited[i][j]) results in false for all values but the
new visited line contains true values even before the following is called.

const field_size = 800;
const cells_in_row = 5;
const frames_per_second = 1;
const cell_size = field_size / cells_in_row;

class Cell {
    constructor(x,y) {
        this.value = 0;
        this.x = x;
        this.y = y;
        this.coordinates = [x*cell_size,y*cell_size];
    }

    fill() {
        this.value = 1;
    }
    clear() {
        this.value = 0;
    }

}

const get_new_grid = (random = 0) => {
    const grid = new Array(cells_in_row);
    for (let i = 0; i < grid.length; i++) {
        grid[i] = new Array(cells_in_row);
        for (let j = 0; j < grid.length; j++) {
            grid[i][j] = new Cell(i,j);
            v = 0;
            if (random) {
                v = Math.floor(Math.random() * 2);
            }
            grid[i][j].value = v;
        }
    }
    return grid;
}

const get_islands = (grid) => {
  // bool array to mark visited cells
  let visited = new Array(cells_in_row);
  for (let i = 0; i < grid.length; i++) {
    visited[i] = new Array(cells_in_row);
    for (let j = 0; j < grid[0].length; j++) {

      visited[i][j] = false;
    }
  }

  console.log("New Visited", visited);
  let count = 0;
  let islands = [];
  let island_coords = [];
  for (let i = 0; i < grid.length; i++) {
    for (let j = 0; j < grid.length; j++) {
      if (visited[i][j] == false && grid[i][j].value == 1) {
        // visit all cells in this island and increment island count
        // dfs will return array of coordinates of island
        [visited, island_coords] = dfs(i, j, grid, visited, island_coords);
        console.log(visited);
        islands.push(island_coords);
        count += 1;
      }
    }
  }

  return [count, islands];
}

const dfs = (i, j, grid, visited, island_coords) => {
  let row_nbr = [-1, -1, -1, 0, 0, 1, 1, 1];
  let col_nbr = [-1, 0, 1, -1, 1, -1, 0, 1];

  visited[i][j] = true;
  island_coords.push([i,j]);

  for (let k = 0; k < 8; k++) {
      if (is_safe(i + row_nbr[k], j + col_nbr[k], grid, visited)) {
          console.log("DFSing " + i + "," + j);
          [visited, island_coords] = dfs(i + row_nbr[k], j + col_nbr[k],
                                         grid, visited, island_coords);
      }
  }

  return [visited, island_coords];
}

const is_safe = (i, j, grid, visited) => {
    return (i >= 0 && i < grid.length &&
            j >= 0 && j < grid.length &&
            !(visited[i][j]) && grid[i][j].value === 1);
}

(function () {
    var old = console.log;
    var logger = document.getElementById('log');
    console.log = function () {
      for (var i = 0; i < arguments.length; i++) {
        if (typeof arguments[i] == 'object') {
            logger.innerHTML += (JSON && JSON.stringify ? JSON.stringify(arguments[i], undefined, 2) : arguments[i]) + '
';
        } else {
            logger.innerHTML += arguments[i] + '
';
        }
      }
    }
})();

window.onload = () => {
    const canvas = document.getElementById('canvas');
    const grid = get_new_grid(random = 0);
    grid[0][0].value = true;
    grid[0][1].value = true;
    grid[1][0].value = true;
    grid[1][1].value = true;
    const islands = get_islands(grid);
    console.log(grid);
    console.log(islands);
}

<!DOCTYPE html>

EDIT:
So I updated the snippet but it looks like it works on this end, however it shows the behavior I mentioned before on my own browser even with the exact same javascript code and html in the snippet.


问:
Create a New Column by evaluating multiple columns
I have a data.frame dt_info that looks like the following:

```<code>date       col_1     col_2    col_3  ... col_100
d/m/y       info1     n/a      n/a   ...  n/a
d/m/y       n/a       n/a     info2  ...  n/a
d/m/y       n/a       n/a       n/a  ...  infon
</code>```

The output I'm looking for should be like this:

```<code>date       col_1     col_2    col_3  ... col_100    new_col
d/m/y       info1     n/a      n/a   ...  n/a         info1
d/m/y       n/a       n/a     info2  ...  n/a         info2
d/m/y       n/a       n/a       n/a  ...  infon       infon
</code>```

I'm using this code line

```<code>dt_info$new_col <- apply(dt_info[2],1, function(x){
ifelse(x != "n/a", x, "")})
</code>```

That kinda do what I want but I have two issues
I'm not able to go do it for each column using [1:n]
If I change Manually the [] index and run the code, the whole column got replaced.

What am I lacking in my script?
Is there another way to achieve what I'm trying to do?

答:
Here is solution uisng tidyverse and gsub

```<code>library(dplyr)
library(tidyr)
df1<- df %>%
  dplyr::select(-date) %>%
  tidyr::unite(newCol,everything(),remove = FALSE) %>%  # concat all columsn except date
  dplyr::mutate(newCol=gsub("n/a","",newCol), # removing n/a as text
                newCol=gsub("\\_","\\1",newCol)) %>% # removing all '_' cretaed during concat
  dplyr::bind_cols(date=df$date) # merging date column back

df1

   newCol col_1 col_2 col_3 col_100  date
1:  info1 info1   n/a   n/a     n/a d/m/y
2:  info2   n/a   n/a info2     n/a d/m/y
3:  infon   n/a   n/a   n/a   infon d/m/y
</code>```

Body:
I have a data.frame dt_info that looks like the following:

date       col_1     col_2    col_3  ... col_100
d/m/y       info1     n/a      n/a   ...  n/a
d/m/y       n/a       n/a     info2  ...  n/a
d/m/y       n/a       n/a       n/a  ...  infon

The output I'm looking for should be like this:

date       col_1     col_2    col_3  ... col_100    new_col
d/m/y       info1     n/a      n/a   ...  n/a         info1
d/m/y       n/a       n/a     info2  ...  n/a         info2
d/m/y       n/a       n/a       n/a  ...  infon       infon

I'm using this code line

dt_info$new_col <- apply(dt_info[2],1, function(x){
ifelse(x != "n/a", x, "")})

That kinda do what I want but I have two issues
I'm not able to go do it for each column using [1:n]
If I change Manually the [] index and run the code, the whole column got replaced.

What am I lacking in my script?
Is there another way to achieve what I'm trying to do?

Body:
Here is solution uisng tidyverse and gsub

library(dplyr)
library(tidyr)
df1<- df %>%
  dplyr::select(-date) %>%
  tidyr::unite(newCol,everything(),remove = FALSE) %>%  # concat all columsn except date
  dplyr::mutate(newCol=gsub("n/a","",newCol), # removing n/a as text
                newCol=gsub("\\_","\\1",newCol)) %>% # removing all '_' cretaed during concat
  dplyr::bind_cols(date=df$date) # merging date column back

df1

   newCol col_1 col_2 col_3 col_100  date
1:  info1 info1   n/a   n/a     n/a d/m/y
2:  info2   n/a   n/a info2     n/a d/m/y
3:  infon   n/a   n/a   n/a   infon d/m/y


问:
PHP reduced value from another input value
I want make value of input from another input value,
 so if i add number in first input,
 second input is reduced from first input,
 can someone help me...

```<code>$value1 = 10;
echo "<input type='text' value='$value2'></input>";
$value3 = $value1 - $value2;
echo "<input type='text' value='$value3'></input>";
</code>```

答:
```<code>// i use the REQUEST  HTTP Request variables (is can changed by GET Or Post request
$secoundVarible = $_REQUEST['value'];

$staticValue = 10;
function reduceValue($num1,$num2){
  return $result = $num1 - $num2;

 }

 $reducedValue = reduceValue($staticValue, $secoundVarible);
echo "<input type='text' value='$reducedValue'></input>";
</code>```

Body:
I want make value of input from another input value,
 so if i add number in first input,
 second input is reduced from first input,
 can someone help me...

$value1 = 10;
echo "<input type='text' value='$value2'></input>";
$value3 = $value1 - $value2;
echo "<input type='text' value='$value3'></input>";


问:
page not found 404 django

Page not found (404) Request Method:    GET Request URL:    http://127.0.0.1:8000/about/ Using the URLconf defined in
    Hello.urls, Django tried these URL patterns, in this order:

admin/ admin/ [name='home'] service [name='service'] contact
  [name='contact'] about [name='about'] The current path, about/, didn't
  match any of these.[![enter image description here][1]][1]

[1]: https://i.stack.imgur.com/jZMW9.png

答: You are getting this warning because you haven't defined a pattern that will direct the user to that page. So if you are doing this in a new application or the root part? Inform us about that. Either way you should go to "urls" and add the path to that folder. You can use the default "admin/" to teach you. For examle delete admin and write "abc/" and when you write"/abc" to your browser it'll show up.</p>

Title: page not found 404 django


问:
ReferenceError: member is not defined
I've Been Searching For A Solutions For This Error But Until Now I Didn't Found Any Solutions And Now I've Give Up Because I Took More Than 1 Days To Find A Solution And Now I Published My Problem Here So Anybody Can See It And Comment Why The Error Shows ?

The Problem : ReferenceError: member is not defined(8:16)

My Code :

```<code>1: const discord = require("discord.js");
2: const config = require('../config.json');
3:
4: module.exports.run = async (bot, message, args) => {
5:
6:     let target = message.guild.member(message.mentions.users.first());
7:     let reason = args.slice(1).join(' ');
8:     let logs = member.guild.channels.find(channel => channel.name === "⚠server_logs");
9:
10:    // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
11:
12:    if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
13:
14:    if (!target) return message.reply('please specify a member to ban!');
15:    if (!reason) return message.reply('please specify a reason for this ban!');
16:    if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
17:
18:    let embed = new discord.RichEmbed()
19:         .setColor('RANDOM')
20:         .setThumbnail(target.user.avatarURL)
21:         .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
22:         .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
23:         .addField('Banned Time', message.createdAt)
24:         .addField('Banned At', message.channel)
25:         .addField('Banned Reason', reason)
26:         .addFooter('Banned user information', target.user.displayAvatarURL);
27:
28:    message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
29:    target.ban(reason);
30:    logs.send(embed);
31: };
32:
33: module.exports.help = {
34:     name: 'ban'
35: };
</code>```

答:
In the code, line no. 8

```<code>6:     let target = message.guild.member(message.mentions.users.first());
7:     let reason = args.slice(1).join(' ');
8:     let logs = member.guild.channels.find(channel => channel.name === "⚠server_logs");
</code>```

You are using member.guild.channels without defining member nad hence the reference error. I believe it should be message.guild.member.

Here is a blogpost explaining reference errors:

https://airbrake.io/blog/nodejs-error-handling/referenceerror

Title: ReferenceError: member is not defined

Body:
I've Been Searching For A Solutions For This Error But Until Now I Didn't Found Any Solutions And Now I've Give Up Because I Took More Than 1 Days To Find A Solution And Now I Published My Problem Here So Anybody Can See It And Comment Why The Error Shows ?

The Problem : ReferenceError: member is not defined(8:16)

My Code :

1: const discord = require("discord.js");
2: const config = require('../config.json');
3:
4: module.exports.run = async (bot, message, args) => {
5:
6:     let target = message.guild.member(message.mentions.users.first());
7:     let reason = args.slice(1).join(' ');
8:     let logs = member.guild.channels.find(channel => channel.name === "⚠server_logs");
9:
10:    // member.guild.channels.cache.find('⚠server_logs', config.logsChannel);
11:
12:    if (!message.member.hasPermission('BAN_MEMBERS')) return message.reply('you don\'t have permissions to use this command!s');
13:
14:    if (!target) return message.reply('please specify a member to ban!');
15:    if (!reason) return message.reply('please specify a reason for this ban!');
16:    if (!logs) return message.reply(`please create a channel called ${config.logsChannel} to log the bans!`);
17:
18:    let embed = new discord.RichEmbed()
19:         .setColor('RANDOM')
20:         .setThumbnail(target.user.avatarURL)
21:         .addField('Banned Member', `${target.user.username} with an ID: ${target.user,id}`)
22:         .addField('Banned By', `${message.author.username} with an ID: ${message.author.id}`)
23:         .addField('Banned Time', message.createdAt)
24:         .addField('Banned At', message.channel)
25:         .addField('Banned Reason', reason)
26:         .addFooter('Banned user information', target.user.displayAvatarURL);
27:
28:    message.channel.send(`${target.user.username} was banned by ${message.author} for ${reason}`);
29:    target.ban(reason);
30:    logs.send(embed);
31: };
32:
33: module.exports.help = {
34:     name: 'ban'
35: };

Body:
In the code, line no. 8

6:     let target = message.guild.member(message.mentions.users.first());
7:     let reason = args.slice(1).join(' ');
8:     let logs = member.guild.channels.find(channel => channel.name === "⚠server_logs");

You are using member.guild.channels without defining member nad hence the reference error. I believe it should be message.guild.member.

Here is a blogpost explaining reference errors:

https://airbrake.io/blog/nodejs-error-handling/referenceerror


问:
Getting Exception thrown for glViewport(0, 0, framebufferWidth, framebufferHight);

#include "list.h"

int main()
{
    //INIT GLFW
    glfwInit();

    //CREATE WINDOW

    const int WINDOW_WIDTH = 640;
    const int WINDOW_HEIGHT = 480;
    int framebufferWidth = 0;
    int framebufferHight = 0;

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH,WINDOW_HEIGHT,"Title", NULL, NULL);

    glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHight);

    glViewport(0, 0, framebufferWidth, framebufferHight);

    glfwMakeContextCurrent(window);//IMPORTIANT!!

    //INIT GLEW (NEEDS WINDOW AND OPENGL CONTEXT)
    glewExperimental = GL_TRUE;

    >//Error

    if (glewInit() != GLEW_OK)
    {
        std::cout << "ERROR::MAIN.CPP::GLEW_INIT_FAILED" << "\n";
        glfwTerminate();
    }

    //MAIN LOOP
    while (glfwWindowShouldClose(window))
    {
        //UPDATE INPUT ---

        //UPDATE ---

        //DRAW ---
        //Clear

        //Draw

        //End Draw
    }

    //END OF PROGAM
    glfwTerminate();

    return 0;
}
```

glViewport(0, 0, framebufferWidth, framebufferHight); is giving me

Unhandled exception at >0x00007FF704D6E7D9 in OpenzGL4.exe: 0xC0000005: Access violation reading >location >0x0000000000000348.

when I run it.

答:
For any OpenGL instruction is required a valid and current OpenGL Context. Hence glfwMakeContextCurrent hast to be invoked before any OpneGL instruction:

GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH,WINDOW_HEIGHT,"Title", NULL, NULL);

glfwMakeContextCurrent(window); // <----- ADD

glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHight);

glViewport(0, 0, framebufferWidth, framebufferHight);

glfwMakeContextCurrent(window); // <----- DELETE
```

Body:
#include "list.h"

int main()
{
    //INIT GLFW
    glfwInit();

    //CREATE WINDOW

    const int WINDOW_WIDTH = 640;
    const int WINDOW_HEIGHT = 480;
    int framebufferWidth = 0;
    int framebufferHight = 0;

    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 4);
    glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);

    GLFWwindow* window = glfwCreateWindow(WINDOW_WIDTH,WINDOW_HEIGHT,"Title", NULL, NULL);

    glfwGetFramebufferSize(window, &framebufferWidth, &framebufferHight);

    glViewport(0, 0, framebufferWidth, framebufferHight);

    glfwMakeContextCurrent(window);//IMPORTIANT!!

    //INIT GLEW (NEEDS WINDOW AND OPENGL CONTEXT)
    glewExperimental = GL_TRUE;

    >//Error

    if (glewInit() != GLEW_OK)
    {
        std::cout << "ERROR::MAIN.CPP::GLEW_INIT_FAILED" << "\n";
        glfwTerminate();
    }

    //MAIN LOOP
    while (glfwWindowShouldClose(window))
    {
        //UPDATE INPUT ---

        //UPDATE ---

        //DRAW ---
        //Clear

        //Draw

        //End Draw
    }

    //END OF PROGAM
    glfwTerminate();

    return 0;
}

glViewport(0, 0, framebufferWidth, framebufferHight); is giving me

Unhandled exception at >0x00007FF704D6E7D9 in OpenzGL4.exe: 0xC0000005: Access violation reading >location >0x0000000000000348.

when I run it.


问:
Replacing '?' with nothing
I have "?35249509094742" in a column and I want to remove '?' from it so as to have a number "35249509094742". Why I cannot remove the '?' with

```<code>df8.replace({ "IMEI1": "?" }, 0)
</code>```

I have also tried

```<code>df8.replace({ "IMEI1": "?35249509094742" }, 35249509094742)
</code>```

After using I am using code

```<code>df8["IMEI1"] = df8["IMEI1"].astype("int64")
</code>```

to convert the column to float from object.
I am getting error

```<code>invalid literal for int() with base 10: '?35249509094742
</code>```

答:
The syntax of replace is not correct. You can find the documentation here

Below is a working example:

```<code>import pandas as pd
df = pd.DataFrame({'A': [0, '?', 2, '?', 4],
                   'B': [5, 6, 7, 8, 9]})
df.replace({'A': '?'}, value='123', inplace=True)
print(df)
</code>```

In this example, 'A' is the column name where we have a '?' as the value and we are replacing it to '123'.

This is because, the syntax of replace treats the dict to identify the column and the value to find. The value to replace needs to be provided as value=. The inplace argument make the changes to your original dataframe.

Hope this helps!

btw, as @Tomalak pointed out in the comments, please use code blocks to format your code in the question. Also, try to provide as much information as possible to get accurate answers.

Title: Replacing '?' with nothing

Body:
I have "?35249509094742" in a column and I want to remove '?' from it so as to have a number "35249509094742". Why I cannot remove the '?' with

df8.replace({ "IMEI1": "?" }, 0)

I have also tried

df8.replace({ "IMEI1": "?35249509094742" }, 35249509094742)

After using I am using code

df8["IMEI1"] = df8["IMEI1"].astype("int64")

to convert the column to float from object.
I am getting error

invalid literal for int() with base 10: '?35249509094742

Body:
The syntax of replace is not correct. You can find the documentation here

Below is a working example:

import pandas as pd
df = pd.DataFrame({'A': [0, '?', 2, '?', 4],
                   'B': [5, 6, 7, 8, 9]})
df.replace({'A': '?'}, value='123', inplace=True)
print(df)

In this example, 'A' is the column name where we have a '?' as the value and we are replacing it to '123'.

This is because, the syntax of replace treats the dict to identify the column and the value to find. The value to replace needs to be provided as value=. The inplace argument make the changes to your original dataframe.

Hope this helps!

btw, as @Tomalak pointed out in the comments, please use code blocks to format your code in the question. Also, try to provide as much information as possible to get accurate answers.


问:
Not Getting the Laravel Relantionship
Student Info Table:

id | school_info_id | roll_no | classes_id | religion | caste | parent_id | student_name

Classes Table

id | school_info_id | class_title | section | created_at | updated_at

I wanted StudentInfo->with('classes')->get()
But not getting any.

```<code>class StudentInfo extends Model{
  public function classes(){
        return $this->belongsTo(Classes::class);
  }
}

</code>```

答: Can you try $this->belongsTo(Classes::class,'classes_id','id'); and see if that works?

Title: Not Getting the Laravel Relantionship

Body:
Student Info Table:

id | school_info_id | roll_no | classes_id | religion | caste | parent_id | student_name

Classes Table

id | school_info_id | class_title | section | created_at | updated_at

I wanted StudentInfo->with('classes')->get()
But not getting any.

class StudentInfo extends Model{
  public function classes(){
        return $this->belongsTo(Classes::class);
  }
}


问:
Traversing a vector vs array which one is faster?
While traversing a vector and a array which one is faster and helpful in compititive programming? </p>

答: It doesn't matter. But an array is faster to create because it has a fixed size</p>


问:
Is there way to programmatically enable GPS on Android 2.1 & above?
I have been seeing different posts that GPS cannot be enabled programmatically How do I find out if the GPS of an Android device is enabled

But this app enables the GPS when it is disabled. Can anyone please help me out.

Thanks,
Prateek

答:
No you can't. But you can prompt the user to enable it. Here's the code.</p>

```<code>private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(
            "Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false).setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(
                                @SuppressWarnings("unused") final DialogInterface dialog,
                                @SuppressWarnings("unused") final int id) {
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    }).setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog,
                                @SuppressWarnings("unused") final int id) {
                            dialog.cancel();
                        }
                    });
    final AlertDialog alert = builder.create();
    alert.show();
}
</code>```

Body:
No you can't. But you can prompt the user to enable it. Here's the code.

private void buildAlertMessageNoGps() {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setMessage(
            "Your GPS seems to be disabled, do you want to enable it?")
            .setCancelable(false).setPositiveButton("Yes",
                    new DialogInterface.OnClickListener() {
                        public void onClick(
                                @SuppressWarnings("unused") final DialogInterface dialog,
                                @SuppressWarnings("unused") final int id) {
                            Intent intent = new Intent(
                                    Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(intent);
                        }
                    }).setNegativeButton("No",
                    new DialogInterface.OnClickListener() {
                        public void onClick(final DialogInterface dialog,
                                @SuppressWarnings("unused") final int id) {
                            dialog.cancel();
                        }
                    });
    final AlertDialog alert = builder.create();
    alert.show();
}


问:
MongoExpress shows "Cannot read property 'listDatabases' of undefined" error
I tried to create Mongo and Mongo-Express server using docker-compose.yml. Here's my setting

```<code>version: "3"
services:
  mongo:
    image: "mongo:3-stretch"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=devroot
      - MONGO_INITDB_ROOT_PASSWORD=devroot
      - MONGO_INITDB_DATABASE=DataBank
    ports:
       - "27017:27017"
  mongo-express:
    image: "mongo-express:latest"
    environment:
      - ME_CONFIG_MONGODB_SERVER=mongo
      - ME_CONFIG_MONGODB_PORT=27017
      - ME_CONFIG_MONGODB_ENABLE_ADMIN=false
      - ME_CONFIG_MONGODB_AUTH_DATABASE=admin
      - ME_CONFIG_MONGODB_AUTH_USERNAME=devroot
      - ME_CONFIG_MONGODB_AUTH_PASSWORD=devroot
      - ME_CONFIG_OPTIONS_EDITORTHEME=ambiance
      - ME_CONFIG_BASICAUTH_USERNAME=dev
      - ME_CONFIG_BASICAUTH_PASSWORD=dev
    depends_on:
      - mongo
    ports:
      - "8081:8081"
</code>```

Results (There's an error here):

```<code>mongo-express_1  | Thu Feb  6 03:11:36 UTC 2020 retrying to connect to mongo:27017 (3/5)
mongo-express_1  | /docker-entrypoint.sh: connect: Connection refused
mongo-express_1  | /docker-entrypoint.sh: line 14: /dev/tcp/mongo/27017: Connection refused
</code>```

Despite the first error, I still was able to access http://localhost:8081/ But when logged-in successfully, it shows (another error):

```<code>mongo-express_1  | Database connected
mongo-express_1  | Connecting to admin...
mongo_1          | 2020-02-06T03:11:39.826+0000 I ACCESS   [conn2] Successfully authenticated as principal devroot on admin
mongo-express_1  | Database admin connected
mongo-express_1  | Admin database is not accessible
mongo-express_1  | TypeError: Cannot read property 'listDatabases' of undefined
mongo-express_1  |     at Object.connectionData.updateDatabases (/node_modules/mongo-express/lib/db.js:41:11)
mongo-express_1  |     at /node_modules/mongo-express/lib/router.js:94:11
mongo-express_1  |     at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:95:5)
mongo-express_1  |     at next (/node_modules/express/lib/router/route.js:137:13)
mongo-express_1  |     at Route.dispatch (/node_modules/express/lib/router/route.js:112:3)
mongo-express_1  |     at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:95:5)
mongo-express_1  |     at /node_modules/express/lib/router/index.js:281:22
mongo-express_1  |     at param (/node_modules/express/lib/router/index.js:354:14)
mongo-express_1  |     at param (/node_modules/express/lib/router/index.js:365:14)
mongo-express_1  |     at Function.process_params (/node_modules/express/lib/router/index.js:410:3)
mongo-express_1  | GET / 500 12.737 ms - 1049
</code>```

What should I look in to?

答:
Problem here is that mongo-express is not able to access the admin database. Adding these environment variables to mongo express should fix your problem

```<code>- ME_CONFIG_MONGODB_ENABLE_ADMIN=true
- ME_CONFIG_MONGODB_ADMINUSERNAME=${MONGO_ROOT_USER}
- ME_CONFIG_MONGODB_ADMINPASSWORD=${MONGO_ROOT_PASSWORD}
</code>```

My final docker-compose file looks like this and it works for me

```<code>version: '3.3' # specify docker-compose version

services:
  mongo:
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=${MONGO_ROOT_USER}
      - MONGO_INITDB_ROOT_PASSWORD=${MONGO_ROOT_PASSWORD}
      - MONGO_INITDB_DATABASE=project

  mongo-express:
    image: mongo-express
    environment:
      - ME_CONFIG_MONGODB_SERVER=mongo
      - ME_CONFIG_MONGODB_PORT=27017
      - ME_CONFIG_MONGODB_ENABLE_ADMIN=true
      - ME_CONFIG_MONGODB_ADMINUSERNAME=${MONGO_ROOT_USER}
      - ME_CONFIG_MONGODB_ADMINPASSWORD=${MONGO_ROOT_PASSWORD}
      - ME_CONFIG_MONGODB_AUTH_DATABASE=admin
      - ME_CONFIG_MONGODB_AUTH_USERNAME=${MONGO_ROOT_USER}
      - ME_CONFIG_MONGODB_AUTH_PASSWORD=${MONGO_ROOT_PASSWORD}
      - ME_CONFIG_BASICAUTH_USERNAME=${MONGOEXPRESS_LOGIN}
      - ME_CONFIG_BASICAUTH_PASSWORD=${MONGOEXPRESS_PASSWORD}
    depends_on:
      - mongo

</code>```

NOTE: Please don't use this in production.

Reference:
https://hub.docker.com/_/mongo-express

Body:
I tried to create Mongo and Mongo-Express server using docker-compose.yml. Here's my setting

version: "3"
services:
  mongo:
    image: "mongo:3-stretch"
    environment:
      - MONGO_INITDB_ROOT_USERNAME=devroot
      - MONGO_INITDB_ROOT_PASSWORD=devroot
      - MONGO_INITDB_DATABASE=DataBank
    ports:
       - "27017:27017"
  mongo-express:
    image: "mongo-express:latest"
    environment:
      - ME_CONFIG_MONGODB_SERVER=mongo
      - ME_CONFIG_MONGODB_PORT=27017
      - ME_CONFIG_MONGODB_ENABLE_ADMIN=false
      - ME_CONFIG_MONGODB_AUTH_DATABASE=admin
      - ME_CONFIG_MONGODB_AUTH_USERNAME=devroot
      - ME_CONFIG_MONGODB_AUTH_PASSWORD=devroot
      - ME_CONFIG_OPTIONS_EDITORTHEME=ambiance
      - ME_CONFIG_BASICAUTH_USERNAME=dev
      - ME_CONFIG_BASICAUTH_PASSWORD=dev
    depends_on:
      - mongo
    ports:
      - "8081:8081"

Results (There's an error here):

mongo-express_1  | Thu Feb  6 03:11:36 UTC 2020 retrying to connect to mongo:27017 (3/5)
mongo-express_1  | /docker-entrypoint.sh: connect: Connection refused
mongo-express_1  | /docker-entrypoint.sh: line 14: /dev/tcp/mongo/27017: Connection refused

Despite the first error, I still was able to access http://localhost:8081/ But when logged-in successfully, it shows (another error):

mongo-express_1  | Database connected
mongo-express_1  | Connecting to admin...
mongo_1          | 2020-02-06T03:11:39.826+0000 I ACCESS   [conn2] Successfully authenticated as principal devroot on admin
mongo-express_1  | Database admin connected
mongo-express_1  | Admin database is not accessible
mongo-express_1  | TypeError: Cannot read property 'listDatabases' of undefined
mongo-express_1  |     at Object.connectionData.updateDatabases (/node_modules/mongo-express/lib/db.js:41:11)
mongo-express_1  |     at /node_modules/mongo-express/lib/router.js:94:11
mongo-express_1  |     at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:95:5)
mongo-express_1  |     at next (/node_modules/express/lib/router/route.js:137:13)
mongo-express_1  |     at Route.dispatch (/node_modules/express/lib/router/route.js:112:3)
mongo-express_1  |     at Layer.handle [as handle_request] (/node_modules/express/lib/router/layer.js:95:5)
mongo-express_1  |     at /node_modules/express/lib/router/index.js:281:22
mongo-express_1  |     at param (/node_modules/express/lib/router/index.js:354:14)
mongo-express_1  |     at param (/node_modules/express/lib/router/index.js:365:14)
mongo-express_1  |     at Function.process_params (/node_modules/express/lib/router/index.js:410:3)
mongo-express_1  | GET / 500 12.737 ms - 1049

What should I look in to?

Body:
Problem here is that mongo-express is not able to access the admin database. Adding these environment variables to mongo express should fix your problem

- ME_CONFIG_MONGODB_ENABLE_ADMIN=true
- ME_CONFIG_MONGODB_ADMINUSERNAME=${MONGO_ROOT_USER}
- ME_CONFIG_MONGODB_ADMINPASSWORD=${MONGO_ROOT_PASSWORD}

My final docker-compose file looks like this and it works for me

version: '3.3' # specify docker-compose version

services:
  mongo:
    image: mongo
    environment:
      - MONGO_INITDB_ROOT_USERNAME=${MONGO_ROOT_USER}
      - MONGO_INITDB_ROOT_PASSWORD=${MONGO_ROOT_PASSWORD}
      - MONGO_INITDB_DATABASE=project

  mongo-express:
    image: mongo-express
    environment:
      - ME_CONFIG_MONGODB_SERVER=mongo
      - ME_CONFIG_MONGODB_PORT=27017
      - ME_CONFIG_MONGODB_ENABLE_ADMIN=true
      - ME_CONFIG_MONGODB_ADMINUSERNAME=${MONGO_ROOT_USER}
      - ME_CONFIG_MONGODB_ADMINPASSWORD=${MONGO_ROOT_PASSWORD}
      - ME_CONFIG_MONGODB_AUTH_DATABASE=admin
      - ME_CONFIG_MONGODB_AUTH_USERNAME=${MONGO_ROOT_USER}
      - ME_CONFIG_MONGODB_AUTH_PASSWORD=${MONGO_ROOT_PASSWORD}
      - ME_CONFIG_BASICAUTH_USERNAME=${MONGOEXPRESS_LOGIN}
      - ME_CONFIG_BASICAUTH_PASSWORD=${MONGOEXPRESS_PASSWORD}
    depends_on:
      - mongo

NOTE: Please don't use this in production.

Reference:
https://hub.docker.com/_/mongo-express


问:
How do I install packages in PyCharm for all projects?
I use PyCharm and all the initial settings are okay.Simple package installation is working. Then why do I need to reinstall a package for each project? Is there any way to install the packages for all projects from now on?</p>

答:
You can download Package from the Pycharm IDE

```<code>1. Open Pycharm and Go to File
2. Click on Settings
3. On left Side, You will find Projects Option. Click & Expend it
4. Click on Interpreter
5. A list of installed package will be shown
6. On Right Side, You will see a + button. Click This to install new package
7. A window will appear with Search bar, then search your package name and hit install button.
</code>```

All steps are taken from this One minute Video.

Body:
You can download Package from the Pycharm IDE

1. Open Pycharm and Go to File
2. Click on Settings
3. On left Side, You will find Projects Option. Click & Expend it
4. Click on Interpreter
5. A list of installed package will be shown
6. On Right Side, You will see a + button. Click This to install new package
7. A window will appear with Search bar, then search your package name and hit install button.

All steps are taken from this One minute Video.


问:
Find sets that contain at least one element from other sets
Suppose we are given n sets and want to construct all minimal sets that have at least one element in common with each of the input sets. A set S is called minimal, if there is no admissible set S' that is a subset of S.

An example:

```<code>In: s1 = {1, 2, 3}; s2 = {3, 4, 5}; s3 = {5, 6}

Out: [{1, 4, 6}, {1, 5}, {2, 4, 6}, {2, 5}, {3, 5}, {3, 6}]
</code>```

My idea was to iteratively add one set after the other to the solution:

```<code>result = f(s1, f(s2, f(s3, ...)))
</code>```

whereby f is a merge function that could look as follows:

```<code>function f(newSet, setOfSets):
   Step 1:
      return all elements of setOfSets that share an element with newSet

   Step 2:
      for each remaining element setE of setOfSets:
         for each element e of newSet:
            return union(setE, {e})
</code>```

The issue with the above appraoch is that the cartesian product computed in step 2 may contain supersets of sets returned in step 1. I was thinking of going through all already returned sets (see Find minimal set of subsets that covers a given set), but this seems to be too complicated and inefficient, and I hope that there is a better solution in my special case.

How could I achieve the goal without determining the full cartesian product in step 2?

Note that this question is related to the question of finding the smallest set only, but I need to find all sets that are minimal in the way specified above. I am aware that the number of solutions will not be polynomial.

The number n of input sets will be several hundret, but the sets contain only elements from a limited range (e.g. about 20 different values), which also limits the sets' sizes. It would be acceptible if the algorithm runs in O(n^2), but it should be basically linear (maybe with a log multiplier) of the output sets.

答:
Since your space is so constrained -- only 20 values from which to choose -- beat this thing to death with a blunt instrument:

Convert each of your target sets (the ones to be covered) to a bit-map.  In your given case, this will correspond to an integer of 20 bits, one bit position for each of the 20 values.

Create a list of candidate covering bitmaps, the integers 0 through (2^20-1)

Take the integers in order.  Use bit operations to determine whether each target set has a 1 bit in common with the candidate.  If all satisfy the basic condition, the candidate is validated.

When you validate a candidate, remove all super-set integers from the list of candidates.

When you run out of candidates, your validates candidates are the desired collection.  In the code below, I simply print each as it is identified.

Code:

```<code>from time import time
start = time()

s1 = {1, 2, 3}
s2 = {3, 4, 5}
s3 = {5, 6}

# Convert each set to its bit-map
point_set = [7, 28, 48]

# make list of all possible covering bitmaps
cover = list(range(2**20))

while cover:
    # Pop any item from remaining covering sets
    candidate = cover.pop(0)
    # Does this bitmap have a bit in common with each target set?
    if all((candidate & point) for point in point_set):
        print(candidate)

        # Remove all candidates that are supersets of the successful covering one.
        superset = set([other for other in cover if (candidate & ~other) == 0])
        cover = [item for item in cover if item not in superset]
        print(time() - start, "lag time")

print(time() - start, "seconds")
</code>```

Output -- I have not converted the candidate integers back to their constituent elements.  This is a straightforward task.

Note that most of the time in this example is spent in exhausting the list of integers that were not supersets of a validated cover set, such as all multiples of 32 (the lower 6 bits are all zero, and thus are disjoint from any cover set).

This 33 seconds is on my aging desktop computer; your laptop or other platform is almost certainly faster.  I trust that any improvement from a more efficient algorithm is easily offset in that this algorithm is quick to implement and easier to understand.

```<code>17
0.4029195308685303 lag time
18
0.6517734527587891 lag time
20
0.8456630706787109 lag time
36
1.0555419921875 lag time
41
1.2604553699493408 lag time
42
1.381387710571289 lag time
33.005757570266724 seconds
</code>```

Body:
Suppose we are given n sets and want to construct all minimal sets that have at least one element in common with each of the input sets. A set S is called minimal, if there is no admissible set S' that is a subset of S.

An example:

In: s1 = {1, 2, 3}; s2 = {3, 4, 5}; s3 = {5, 6}

Out: [{1, 4, 6}, {1, 5}, {2, 4, 6}, {2, 5}, {3, 5}, {3, 6}]

My idea was to iteratively add one set after the other to the solution:

result = f(s1, f(s2, f(s3, ...)))

whereby f is a merge function that could look as follows:

function f(newSet, setOfSets):
   Step 1:
      return all elements of setOfSets that share an element with newSet

   Step 2:
      for each remaining element setE of setOfSets:
         for each element e of newSet:
            return union(setE, {e})

The issue with the above appraoch is that the cartesian product computed in step 2 may contain supersets of sets returned in step 1. I was thinking of going through all already returned sets (see Find minimal set of subsets that covers a given set), but this seems to be too complicated and inefficient, and I hope that there is a better solution in my special case.

How could I achieve the goal without determining the full cartesian product in step 2?

Note that this question is related to the question of finding the smallest set only, but I need to find all sets that are minimal in the way specified above. I am aware that the number of solutions will not be polynomial.

The number n of input sets will be several hundret, but the sets contain only elements from a limited range (e.g. about 20 different values), which also limits the sets' sizes. It would be acceptible if the algorithm runs in O(n^2), but it should be basically linear (maybe with a log multiplier) of the output sets.

Body:
Since your space is so constrained -- only 20 values from which to choose -- beat this thing to death with a blunt instrument:

Convert each of your target sets (the ones to be covered) to a bit-map.  In your given case, this will correspond to an integer of 20 bits, one bit position for each of the 20 values.

Create a list of candidate covering bitmaps, the integers 0 through (2^20-1)

Take the integers in order.  Use bit operations to determine whether each target set has a 1 bit in common with the candidate.  If all satisfy the basic condition, the candidate is validated.

When you validate a candidate, remove all super-set integers from the list of candidates.

When you run out of candidates, your validates candidates are the desired collection.  In the code below, I simply print each as it is identified.

Code:

from time import time
start = time()

s1 = {1, 2, 3}
s2 = {3, 4, 5}
s3 = {5, 6}

# Convert each set to its bit-map
point_set = [7, 28, 48]

# make list of all possible covering bitmaps
cover = list(range(2**20))

while cover:
    # Pop any item from remaining covering sets
    candidate = cover.pop(0)
    # Does this bitmap have a bit in common with each target set?
    if all((candidate & point) for point in point_set):
        print(candidate)

        # Remove all candidates that are supersets of the successful covering one.
        superset = set([other for other in cover if (candidate & ~other) == 0])
        cover = [item for item in cover if item not in superset]
        print(time() - start, "lag time")

print(time() - start, "seconds")

Output -- I have not converted the candidate integers back to their constituent elements.  This is a straightforward task.

Note that most of the time in this example is spent in exhausting the list of integers that were not supersets of a validated cover set, such as all multiples of 32 (the lower 6 bits are all zero, and thus are disjoint from any cover set).

This 33 seconds is on my aging desktop computer; your laptop or other platform is almost certainly faster.  I trust that any improvement from a more efficient algorithm is easily offset in that this algorithm is quick to implement and easier to understand.

17
0.4029195308685303 lag time
18
0.6517734527587891 lag time
20
0.8456630706787109 lag time
36
1.0555419921875 lag time
41
1.2604553699493408 lag time
42
1.381387710571289 lag time
33.005757570266724 seconds


问:
Is there a better way to check if a number is range of two numbers
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

```<code>def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000
</code>```

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

答:
First of all, let me clear the range function. It works excluding the ending limit.
So the if condition you are using with range(0,5499) will check for the number in this list [0, 1, ..... , 5477, 5488] not this list [0, 1, ..... , 5477, 5488, 5499].

Now to answer your question, there can be multiple efficient ways to do the job(depending upon the end result) so, the bisect package mentioned as the accepted answer does the job pretty well.
In case you want to do it in an efficient way without any library, below code should help:

```<code>rangeList =  [5499, 9499, 14499, 19499, 24499, 29499, 34499, 39499, 44499]
returnList = [5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000]

def checkRange(number):
    for i in range(len(rangeList)):
        if number<=rangeList[i]:
            return returnList[i]
    return -1

inp: checkRange(5499)
op: 5000
</code>```

This code works efficiently using basic principles of if condition and considering that your ranges are in ascending order.

Body:
I am trying to check if a number is in range of integers and returns a number based on which range it lies. I was wondering if is there a better and more efficient way of doing this:

def checkRange(number):
    if number in range(0, 5499):
        return 5000
    elif number in range(5500, 9499):
        return 10000
    elif number in range(9500, 14499):
        return 15000
    elif number in range(14500, 19499):
        return 20000
    elif number in range(19500, 24499):
        return 25000
    elif number in range(24500, 29499):
        return 30000
    elif number in range(29500, 34499):
        return 35000
    elif number in range(34500, 39499):
        return 40000
    elif number in range(39500, 44499):
        return 45000

This felt like a waste of resources and would greatly appreciate if there is a better way to do this.

Body:
First of all, let me clear the range function. It works excluding the ending limit.
So the if condition you are using with range(0,5499) will check for the number in this list [0, 1, ..... , 5477, 5488] not this list [0, 1, ..... , 5477, 5488, 5499].

Now to answer your question, there can be multiple efficient ways to do the job(depending upon the end result) so, the bisect package mentioned as the accepted answer does the job pretty well.
In case you want to do it in an efficient way without any library, below code should help:

rangeList =  [5499, 9499, 14499, 19499, 24499, 29499, 34499, 39499, 44499]
returnList = [5000, 10000, 15000, 20000, 25000, 30000, 35000, 40000, 45000]

def checkRange(number):
    for i in range(len(rangeList)):
        if number<=rangeList[i]:
            return returnList[i]
    return -1

inp: checkRange(5499)
op: 5000

This code works efficiently using basic principles of if condition and considering that your ranges are in ascending order.


问:
XC1020: Build error occurred in the XAML MSBuild task in WWF4.0 console application
I have started with doing a sample in Widows Workflow Foundation 4.0, i have created a console application with a sequential workflow and tried to execute it, but then I am getting the error as "could not load file or assembly, microsoftcsharp.dll or some other dependencies are missing".

I have checked out the references and i could see that this dll is added, unable to get the root cause of the error.

would be helpful if i would get any help.

答: Use the Fusion Log Viewer. That will show you any assembly bind failures.</p>


问:
FireBase Firestore retrieve multiple documents by list of ID's
I've got two collections for example Cities and Houses. Houses are not a nested collection of Cities, but a house contains a reference to a City.

Wat is the most efficient way to get city information for each house in a list?

For Example

```<code>class City {
  var name: String = ""
  var property1: String = ""
  var property2: String = ""
}

class House {
  var cityId: String = ""
  var propertyA: String = ""
  var propertyB: String = ""
}
</code>```

I've got a list of houses, how do I get for each house in this list the name of the city? Is this possible by query, or should I just get all the cities (or each one seperate) and map them in code.

The cities and houses are just an example, but simular to my real situation.

答:
You can use com.google.firebase.firestore.FieldPath. This is working for me in kotlin:</p>

```<code>//friendsIDs is ArrayList<String>
    firestore!!.collection("users").whereIn(FieldPath.documentId(), friendsIDs).get().addOnCompleteListener {usersDocs ->
        if (usersDocs.isSuccessful) {
            val result = usersDocs.result!!
            val docs = result.documents
            for (userDoc in docs) {
                val friendData = userDoc.data!!
                //...
            }
        } else {
            Log.e("FirestoreRequest", "Error getting documents.", usersDocs.exception)
        }
    }
</code>```

Body:
I've got two collections for example Cities and Houses. Houses are not a nested collection of Cities, but a house contains a reference to a City.

Wat is the most efficient way to get city information for each house in a list?

For Example

class City {
  var name: String = ""
  var property1: String = ""
  var property2: String = ""
}

class House {
  var cityId: String = ""
  var propertyA: String = ""
  var propertyB: String = ""
}

I've got a list of houses, how do I get for each house in this list the name of the city? Is this possible by query, or should I just get all the cities (or each one seperate) and map them in code.

The cities and houses are just an example, but simular to my real situation.

Body:
You can use com.google.firebase.firestore.FieldPath. This is working for me in kotlin:

//friendsIDs is ArrayList<String>
    firestore!!.collection("users").whereIn(FieldPath.documentId(), friendsIDs).get().addOnCompleteListener {usersDocs ->
        if (usersDocs.isSuccessful) {
            val result = usersDocs.result!!
            val docs = result.documents
            for (userDoc in docs) {
                val friendData = userDoc.data!!
                //...
            }
        } else {
            Log.e("FirestoreRequest", "Error getting documents.", usersDocs.exception)
        }
    }


问:
How to call function from other script in arduino
Hi i have my script which is running completely fine .But it is too long because of its menu part. i need to write the menu to separate script and call that separate script in to my main script so that my code looks good how i can do this . This is my main script menu part that i need to write it separate script and call it from main script how to include it and how to call this function.</p>

```<code>  // ========================================== Start of MENU:
        if (menu1==1){
  if (myEnc.getCount()>oldenc+8){MODE=MODE+1; oldenc=myEnc.getCount();}
  if (myEnc.getCount()<oldenc-8){MODE=MODE-1; oldenc=myEnc.getCount();}
  if (MODE<1){MODE=4;}
  if (MODE>4){MODE=1;}
  lcd.setCursor(0,0); lcd.print(">");
 // Serial.print("MODE :"), Serial.println(MODE);
  lcd.setCursor(1,0);
  if (MODE==1){lcd.print(String("CMV-P "));}
  if (MODE==2){lcd.print(String("CMV-V "));}
  if (MODE==3){lcd.print(String("SIMVP"));}
  if (MODE==4){lcd.print(String("SIMVV"));}
  if (MODE==5){lcd.print(String("PS-CP "));}
 // Serial.print(" F:"), Serial.println(MODE);
  }
  if (menu1!=1 ){lcd.setCursor(0,0);lcd.print(" ");}
  if (menu1==2){
    if (myEnc.getCount()>oldenc+8){BPM=BPM+1; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){BPM=BPM-1; oldenc=myEnc.getCount();}
    if (BPM<12){BPM=12;}
    if (BPM>30){BPM=30;}
    lcd.setCursor(6,0);lcd.print(">");
    lcd.setCursor(7,0);lcd.print(String("BPM:")+String(BPM));
    Serial.print(" G:"), Serial.println(BPM);
  }
 if (menu1!=2){lcd.setCursor(6,0);lcd.print(" ");}
 if (menu1==3){
    if (myEnc.getCount()>oldenc+8){IE=IE+0.1; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){IE=IE-0.1; oldenc=myEnc.getCount();}
    if (IE>4){IE=4;}
    if (IE<1){IE=1;}

    sprintf(buff, "%3.1f", IE);
    lcd.setCursor(13,0); lcd.print(">");
    lcd.setCursor(14,0);lcd.print(String("IE:")+buff);
    Serial.print(" H:"), Serial.println(IE);
  }
  if (menu1!=3 && menu1!=9){lcd.setCursor(13,0);lcd.print(" ");}
  if (menu1==4){
    if (myEnc.getCount()>oldenc+8){PRES=PRES+1; PSync=0; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){PRES=PRES-1; PSync=0; oldenc=myEnc.getCount();}
    if (PRES>50){PRES=50;}
    if (PRES<10){PRES=10;}
    lcd.setCursor(0,1);lcd.print(">");
    lcd.setCursor(1,1);lcd.print(String("Pr:")+String(PRES));
    Serial.print(" I:"), Serial.println(PRES);
    }
    if (menu1!=4 && menu1!=9){lcd.setCursor(0,1);lcd.print(" ");}
    if (menu1==5){
    if (myEnc.getCount()>oldenc+8){TV=TV+10; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){TV=TV-10; oldenc=myEnc.getCount();}
    if (TV<250){TV=250;}
    if (TV>700){TV=700;}
    lcd.setCursor(6,1); lcd.print(">");
    lcd.setCursor(7,1);lcd.print(String("TV:")+String(TV));
    Serial.print(" J:"), Serial.println(TV);
  }
  if (menu1!=5 && menu1!=9){lcd.setCursor(6,1);lcd.print(" ");}
  if (menu1==6){
    if (myEnc.getCount()>oldenc+8){FIOD=FIOD+5; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){FIOD=FIOD-5; oldenc=myEnc.getCount();}
    FIO=FIOD;
    if(FIOD<=20){FIOD=20; FIO=21;}
    if(FIOD>99){FIOD=99; FIO=99;}
    lcd.setCursor(13,1);lcd.print(">");
    lcd.setCursor(14,1);lcd.print(String("FIO:")+String(FIO));
    Serial.print(" K:"), Serial.println(FIO);
  }
  if (menu1!=6 && menu1!=9){lcd.setCursor(13,1); lcd.print(" "); }
     if (menu1==7){
      if (myEnc.getCount()>oldenc+8){PEEP=PEEP+1; oldenc=myEnc.getCount();}
      if (myEnc.getCount()<oldenc-8){PEEP=PEEP-1; oldenc=myEnc.getCount();}
      if(PEEP<2){PEEP=2;}
      if(PEEP>25){PEEP=25;}
      lcd.setCursor(0,2);lcd.print(">");
      sprintf(buff, "%02d", PEEP);
      lcd.setCursor(1,2);lcd.print(String("PEEP:")+buff);
      Serial.print(" L:"), Serial.println(PEEP);
  }
  if (menu1!=7 && menu1!=9){lcd.setCursor(0,2);lcd.print(" ");}

  if (menu1==8){
    if (myEnc.getCount()>oldenc+8){TRIGSEN=TRIGSEN+1; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){TRIGSEN=TRIGSEN-1; oldenc=myEnc.getCount();}
    if(TRIGSEN<2){TRIGSEN=2;}
    if(TRIGSEN>20){TRIGSEN=20;}
    lcd.setCursor(8,2); lcd.print(">");
    lcd.setCursor(9,2);lcd.print(String("TRG:")+String(TRIGSEN));
    Serial.print(" M:"), Serial.println(TRIGSEN);
    }
  if (menu1!=8 && menu1!=9){lcd.setCursor(8,2);lcd.print(" ");}
  //================ END OF MENU

      delay(10);
  //    Serial.print(" PRS:"), Serial.print(PrsMed.getMedian());
    } // End of main loop
</code>```

答: Write script in separate file with .ino extension and add that file in same arduino project directory.</p>

Body:
Hi i have my script which is running completely fine .But it is too long because of its menu part. i need to write the menu to separate script and call that separate script in to my main script so that my code looks good how i can do this . This is my main script menu part that i need to write it separate script and call it from main script how to include it and how to call this function.

  // ========================================== Start of MENU:
        if (menu1==1){
  if (myEnc.getCount()>oldenc+8){MODE=MODE+1; oldenc=myEnc.getCount();}
  if (myEnc.getCount()<oldenc-8){MODE=MODE-1; oldenc=myEnc.getCount();}
  if (MODE<1){MODE=4;}
  if (MODE>4){MODE=1;}
  lcd.setCursor(0,0); lcd.print(">");
 // Serial.print("MODE :"), Serial.println(MODE);
  lcd.setCursor(1,0);
  if (MODE==1){lcd.print(String("CMV-P "));}
  if (MODE==2){lcd.print(String("CMV-V "));}
  if (MODE==3){lcd.print(String("SIMVP"));}
  if (MODE==4){lcd.print(String("SIMVV"));}
  if (MODE==5){lcd.print(String("PS-CP "));}
 // Serial.print(" F:"), Serial.println(MODE);
  }
  if (menu1!=1 ){lcd.setCursor(0,0);lcd.print(" ");}
  if (menu1==2){
    if (myEnc.getCount()>oldenc+8){BPM=BPM+1; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){BPM=BPM-1; oldenc=myEnc.getCount();}
    if (BPM<12){BPM=12;}
    if (BPM>30){BPM=30;}
    lcd.setCursor(6,0);lcd.print(">");
    lcd.setCursor(7,0);lcd.print(String("BPM:")+String(BPM));
    Serial.print(" G:"), Serial.println(BPM);
  }
 if (menu1!=2){lcd.setCursor(6,0);lcd.print(" ");}
 if (menu1==3){
    if (myEnc.getCount()>oldenc+8){IE=IE+0.1; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){IE=IE-0.1; oldenc=myEnc.getCount();}
    if (IE>4){IE=4;}
    if (IE<1){IE=1;}

    sprintf(buff, "%3.1f", IE);
    lcd.setCursor(13,0); lcd.print(">");
    lcd.setCursor(14,0);lcd.print(String("IE:")+buff);
    Serial.print(" H:"), Serial.println(IE);
  }
  if (menu1!=3 && menu1!=9){lcd.setCursor(13,0);lcd.print(" ");}
  if (menu1==4){
    if (myEnc.getCount()>oldenc+8){PRES=PRES+1; PSync=0; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){PRES=PRES-1; PSync=0; oldenc=myEnc.getCount();}
    if (PRES>50){PRES=50;}
    if (PRES<10){PRES=10;}
    lcd.setCursor(0,1);lcd.print(">");
    lcd.setCursor(1,1);lcd.print(String("Pr:")+String(PRES));
    Serial.print(" I:"), Serial.println(PRES);
    }
    if (menu1!=4 && menu1!=9){lcd.setCursor(0,1);lcd.print(" ");}
    if (menu1==5){
    if (myEnc.getCount()>oldenc+8){TV=TV+10; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){TV=TV-10; oldenc=myEnc.getCount();}
    if (TV<250){TV=250;}
    if (TV>700){TV=700;}
    lcd.setCursor(6,1); lcd.print(">");
    lcd.setCursor(7,1);lcd.print(String("TV:")+String(TV));
    Serial.print(" J:"), Serial.println(TV);
  }
  if (menu1!=5 && menu1!=9){lcd.setCursor(6,1);lcd.print(" ");}
  if (menu1==6){
    if (myEnc.getCount()>oldenc+8){FIOD=FIOD+5; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){FIOD=FIOD-5; oldenc=myEnc.getCount();}
    FIO=FIOD;
    if(FIOD<=20){FIOD=20; FIO=21;}
    if(FIOD>99){FIOD=99; FIO=99;}
    lcd.setCursor(13,1);lcd.print(">");
    lcd.setCursor(14,1);lcd.print(String("FIO:")+String(FIO));
    Serial.print(" K:"), Serial.println(FIO);
  }
  if (menu1!=6 && menu1!=9){lcd.setCursor(13,1); lcd.print(" "); }
     if (menu1==7){
      if (myEnc.getCount()>oldenc+8){PEEP=PEEP+1; oldenc=myEnc.getCount();}
      if (myEnc.getCount()<oldenc-8){PEEP=PEEP-1; oldenc=myEnc.getCount();}
      if(PEEP<2){PEEP=2;}
      if(PEEP>25){PEEP=25;}
      lcd.setCursor(0,2);lcd.print(">");
      sprintf(buff, "%02d", PEEP);
      lcd.setCursor(1,2);lcd.print(String("PEEP:")+buff);
      Serial.print(" L:"), Serial.println(PEEP);
  }
  if (menu1!=7 && menu1!=9){lcd.setCursor(0,2);lcd.print(" ");}

  if (menu1==8){
    if (myEnc.getCount()>oldenc+8){TRIGSEN=TRIGSEN+1; oldenc=myEnc.getCount();}
    if (myEnc.getCount()<oldenc-8){TRIGSEN=TRIGSEN-1; oldenc=myEnc.getCount();}
    if(TRIGSEN<2){TRIGSEN=2;}
    if(TRIGSEN>20){TRIGSEN=20;}
    lcd.setCursor(8,2); lcd.print(">");
    lcd.setCursor(9,2);lcd.print(String("TRG:")+String(TRIGSEN));
    Serial.print(" M:"), Serial.println(TRIGSEN);
    }
  if (menu1!=8 && menu1!=9){lcd.setCursor(8,2);lcd.print(" ");}
  //================ END OF MENU

      delay(10);
  //    Serial.print(" PRS:"), Serial.print(PrsMed.getMedian());
    } // End of main loop