问:
How is the time complexity O(N^2) here?
I already know that the answer to this question is O(N^2) but I am not able to see how. I know the for loop runs N times, but how can it run N^2 times?

```<code>public static String rev(String s) {
    String r = "";
    int N = s.length();
    for (int i = 0; i < N; i++) {
        r = s.charAt(i) + r;
    }
    return r;
}
</code>```

答: In Java, String concatenation r = s.charAt(i) + r in a loop is O(N^2), because Strings are immutable - a new copy of the String is created on each concatenation.

Title: How is the time complexity O(N^2) here?

Body:
I already know that the answer to this question is O(N^2) but I am not able to see how. I know the for loop runs N times, but how can it run N^2 times?

public static String rev(String s) {
    String r = "";
    int N = s.length();
    for (int i = 0; i < N; i++) {
        r = s.charAt(i) + r;
    }
    return r;
}


来源: stackexchange

问:
"ValueError: No gradients provided for any variable" when scale_diag of MultivariateNormalDiag() is a Constant
The following is a code snippet which, given a state, generates an action from a state-dependent distribution (prob_policy). Then the weights of the graph are updated according to a loss which is -1 times the probability of that action being selected. In the following example, both the mean (mu) and the covariance (sigma) of the MultivariateNormal are trainable/learned.

```<code>import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp

# make the graph
state = tf.placeholder(tf.float32, (1, 2), name="state")
mu = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.squeeze(sigma)
mu = tf.squeeze(mu)
prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=sigma)
action = prob_policy.sample()
picked_action_prob = prob_policy.prob(action)
loss = -tf.log(picked_action_prob)
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss)

# run the optimizer
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    state_input = np.expand_dims([0.,0.],0)
    _, action_loss = sess.run([train_op, loss], { state: state_input })
    print(action_loss)
</code>```

However, when I replace this line

```<code>prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=sigma)
</code>```

with the following line (and comment out the lines which generate the sigma layer and squeeze it)

```<code>prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=[1.,1.])
</code>```

I get the following error

```<code>ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables ["<tf.Variable 'fully_connected/weights:0' shape=(2, 2) dtype=float32_ref>", "<tf.Variable 'fully_connected/biases:0' shape=(2,) dtype=float32_ref>"] and loss Tensor("Neg:0", shape=(), dtype=float32).
</code>```

I don't understand why this is happening. Shouldn't it still be able to take the gradient with respect to the weights in the mu layer? Why does making the covariance of the distribution constant suddenly make it non-differentiable?

System Details:

Tensorflow 1.13.1

Tensorflow Probability 0.6.0

Python 3.6.8

MacOS 10.13.6

答:
There is an issue caused by some caching we do inside of MVNDiag (and other subclasses of TransformedDistribution) for invertibility.

If you do a + 0 (as a workaround) after your .sample() the gradient will work.

Also I'd suggest using dist.log_prob(..) instead of tf.log(dist.prob(..)). Better numerics.

import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp

# make the graph
state = tf.placeholder(tf.float32, (1, 2), name="state")
mu = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.squeeze(sigma)
mu = tf.squeeze(mu)
prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=[1.,1.])
action = prob_policy.sample() + 0
loss = -prob_policy.log_prob(action)
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss)

# run the optimizer
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    state_input = np.expand_dims([0.,0.],0)
    _, action_loss = sess.run([train_op, loss], { state: state_input })
    print(action_loss)
```

ContentLicense: CC BY-SA 4.0

Body:
The following is a code snippet which, given a state, generates an action from a state-dependent distribution (prob_policy). Then the weights of the graph are updated according to a loss which is -1 times the probability of that action being selected. In the following example, both the mean (mu) and the covariance (sigma) of the MultivariateNormal are trainable/learned.

import numpy as np
import tensorflow as tf
import tensorflow_probability as tfp

# make the graph
state = tf.placeholder(tf.float32, (1, 2), name="state")
mu = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.contrib.layers.fully_connected(
    inputs=state,
    num_outputs=2,
    biases_initializer=tf.ones_initializer)
sigma = tf.squeeze(sigma)
mu = tf.squeeze(mu)
prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=sigma)
action = prob_policy.sample()
picked_action_prob = prob_policy.prob(action)
loss = -tf.log(picked_action_prob)
optimizer = tf.train.AdamOptimizer(learning_rate=0.01)
train_op = optimizer.minimize(loss)

# run the optimizer
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    state_input = np.expand_dims([0.,0.],0)
    _, action_loss = sess.run([train_op, loss], { state: state_input })
    print(action_loss)

However, when I replace this line

prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=sigma)

with the following line (and comment out the lines which generate the sigma layer and squeeze it)

prob_policy = tfp.distributions.MultivariateNormalDiag(loc=mu, scale_diag=[1.,1.])

I get the following error

ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients, between variables ["<tf.Variable 'fully_connected/weights:0' shape=(2, 2) dtype=float32_ref>", "<tf.Variable 'fully_connected/biases:0' shape=(2,) dtype=float32_ref>"] and loss Tensor("Neg:0", shape=(), dtype=float32).

I don't understand why this is happening. Shouldn't it still be able to take the gradient with respect to the weights in the mu layer? Why does making the covariance of the distribution constant suddenly make it non-differentiable?

System Details:

Tensorflow 1.13.1

Tensorflow Probability 0.6.0

Python 3.6.8

MacOS 10.13.6


问:
Searching a tuple element in a list of lists without changing the data structure
I'd like to search user input in a tuple located in a list of lists.

```<code>data = [[('tick1',12),4],[('tick2', 16),7],...]

if user input: 'tick1'
desired output:[('tick1',12),4]
</code>```

I can do this if I change my list to a dictionary:

```<code>data = [[('tick1',12),4],[('tick2', 16),7]]

data = dict(data)

if not any('tick2' in x for x in data):
    print('not found')
else:
    print('found:', x)

#Output
found: [('tick2', 16), 7]
</code>```

But how can I do this if I want to maintain the list type?

答:
```<code>data = [[('tick1',12),4],[('tick2', 16),7]] # user stored dat
userinput = input() # user giving input

def fun(userinput, data): # a function taking 2 argument, data, userinput
    for i in data: # iterate over each element inside data
        if i[0][0]==userinput: # check if value at position [0][0] is equal to user input
            return i # if equal return that value
    return 'not found' # if no value found equal then return not found

print(fun(userinput, data)) # calling of function and giving input argument , printing the result of return  of the function
</code>```

Body:
I'd like to search user input in a tuple located in a list of lists.

data = [[('tick1',12),4],[('tick2', 16),7],...]

if user input: 'tick1'
desired output:[('tick1',12),4]

I can do this if I change my list to a dictionary:

data = [[('tick1',12),4],[('tick2', 16),7]]

data = dict(data)

if not any('tick2' in x for x in data):
    print('not found')
else:
    print('found:', x)

#Output
found: [('tick2', 16), 7]

But how can I do this if I want to maintain the list type?


问:
Hidden features/tricks of Flash development, Flash language (AS2/3), and Flash IDE
Guys, I am thoroughly surprised that there is no Flash Hidden Features post yet in the Hidden Features series that I've been tracking for a while now.

There is a recent AS3/Flex one but it's not very active and I don't exactly mean just AS3 when I say Flash here.

The Hidden Features series is great for people who are new to a certain language. It shows the ropes and certain valuable tricks, all in one place. I think it's a brilliant idea. Even experts sometimes find tricks they'd never heard about.

When I started with Flash, I was taken aback by the Flash IDE and odd concepts of Flash, compared to other programming languages.

So, here goes: what are some hidden features of Flash as a language (AS2/3) and the Flash IDE?

Let the fun begin.

答:
Here's another gotcha:

By default Flash tools strips any metadata tags that you have.  Many frameworks depends on these metadata tags.  What you need to be careful is that this doesn't only apply to the compiler, but also to the optimizer.  Be sure to run both your compiler and optimizer with -keep-as3-metadata-tag option to keep your metadata tag in there.

ContentLicense: CC BY-SA 2.5

ContentLicense: CC BY-SA 3.0


问:
Printing location in memory when printing in the main method objects java
This is printing me the location in memory, why is this happening and how can i fix it.

This is the question of the homework, or exam:

The method multiply multiplies the numerator of this RationalNumber by the numerator of r, and the denominator of this RationalNumber by the denominator of r. Which of the following can be used to replace /* missing code */ so that the multiply() method will work as intended?

These are the solutions and i need to choose:

```<code>num = num * r.num;
den = den * r.den;

this.num = this.num * r.num;
this.den = this.den * r.den;

num = num * r.getNum();
den = den * r.getDen();
</code>```

I tried everything but nothing works.

Here is my code:

```<code>public class RationalNumber {
    private int num;
    private int den; // den != 0

    /** Constructs a RationalNumber object.
     *  @param n the numerator
     *  @param d the denominator
     *  Precondition: d != 0
     */
    public RationalNumber(int n, int d) {
        num = n;
        den = d;
    }

    /** Multiplies this RationalNumber by r.
     *  @param r a RationalNumber object
     *  Precondition: this.den() != 0
     */
    public void multiply(RationalNumber r) {
        /* missing code */
        num = num * r.num;
        den = den * r.den;

         //this.num = this.num * r.num;
        //this.den = this.den * r.den;

        //num = num * r.getNum();
       //den = den * r.getDen();
    }

    /** @return the numerator
     */
    public int getNum() {
        /* implementation not shown */
        return num;
    }

    /** @return the denominator
     */
    public int getDen() {
        /* implementation not shown */
        return den;
    }
    public static void main(String[] args){
        RationalNumber num = new RationalNumber(10, -1);
        System.out.println(num);

    }

    // Other methods not shown.
}
</code>```

答:
You need to override toString() method of the RationalNumber class.

```<code>System.out.println(num);
</code>```

The code above will print the return value of the toString() method of the provided class if we didn't specify any specific attributes or methods of the class.

Since your RationalNumber class didn't override toString(), it looks for its superclass toString() (The Object class).

You could solve this by adding

```<code>@Override
public String toString(){
    return num + "/" + den;
}
</code>```

After that, you will need to have 2 RationalNumber objects.

For example, in mathematic, 1⁄2 * 1⁄3 = 1⁄6

In your main method will have something like this

```<code>public static void main(String[] args){
    RationalNumber rn1 = RationalNumber(1,2); //This represent 1/2
    RationalNUmber rn2 = RationalNumber(1,3); //This represent 1/3
    rn1.multiply(rn2); //This equals to 1/2 * 1/3, it multiply the num and den variable of rn1 object with rn2
    System.out.println(rn1); //This will invoke the toString() of rn1
}
</code>```

Body:
This is printing me the location in memory, why is this happening and how can i fix it.

This is the question of the homework, or exam:

The method multiply multiplies the numerator of this RationalNumber by the numerator of r, and the denominator of this RationalNumber by the denominator of r. Which of the following can be used to replace /* missing code */ so that the multiply() method will work as intended?

These are the solutions and i need to choose:

num = num * r.num;
den = den * r.den;

this.num = this.num * r.num;
this.den = this.den * r.den;

num = num * r.getNum();
den = den * r.getDen();

I tried everything but nothing works.

Here is my code:

public class RationalNumber {
    private int num;
    private int den; // den != 0

    /** Constructs a RationalNumber object.
     *  @param n the numerator
     *  @param d the denominator
     *  Precondition: d != 0
     */
    public RationalNumber(int n, int d) {
        num = n;
        den = d;
    }

    /** Multiplies this RationalNumber by r.
     *  @param r a RationalNumber object
     *  Precondition: this.den() != 0
     */
    public void multiply(RationalNumber r) {
        /* missing code */
        num = num * r.num;
        den = den * r.den;

         //this.num = this.num * r.num;
        //this.den = this.den * r.den;

        //num = num * r.getNum();
       //den = den * r.getDen();
    }

    /** @return the numerator
     */
    public int getNum() {
        /* implementation not shown */
        return num;
    }

    /** @return the denominator
     */
    public int getDen() {
        /* implementation not shown */
        return den;
    }
    public static void main(String[] args){
        RationalNumber num = new RationalNumber(10, -1);
        System.out.println(num);

    }

    // Other methods not shown.
}

Body:
You need to override toString() method of the RationalNumber class.

System.out.println(num);

The code above will print the return value of the toString() method of the provided class if we didn't specify any specific attributes or methods of the class.

Since your RationalNumber class didn't override toString(), it looks for its superclass toString() (The Object class).

You could solve this by adding

@Override
public String toString(){
    return num + "/" + den;
}

After that, you will need to have 2 RationalNumber objects.

For example, in mathematic, 1⁄2 * 1⁄3 = 1⁄6

In your main method will have something like this

public static void main(String[] args){
    RationalNumber rn1 = RationalNumber(1,2); //This represent 1/2
    RationalNUmber rn2 = RationalNumber(1,3); //This represent 1/3
    rn1.multiply(rn2); //This equals to 1/2 * 1/3, it multiply the num and den variable of rn1 object with rn2
    System.out.println(rn1); //This will invoke the toString() of rn1
}


问:
Asyncio task cancellation
This is a test script I created to better understand task cancellation -

import asyncio
import random
import signal
import traceback

async def shutdown(signame, loop):
    print("Shutting down")
    tasks = [task for task in asyncio.Task.all_tasks()]
    for task in tasks:
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            print("Task cancelled: %s", task)
    loop.stop()

async def another():
    await asyncio.sleep(2)

async def some_other_process():
    await asyncio.sleep(5)
    return "Me"

async def process(job, loop, i):
    print(i)
    task = loop.create_task(some_other_process())
    value = await task

    if i < 1:
        another_task = loop.create_task(another())
        await another_task
    # await some_other_process()

def pull(loop):
    i = 0
    while True:
        job = f"random-integer-{random.randint(0, 100)}"
        try:
            loop.run_until_complete(process(job, loop, i))
            i += 1
        except asyncio.CancelledError as e:
            print("Task cancelled")
            break
        except Exception:
            print(traceback.format_exc())
    # asyncio.get_event_loop().stop()

def main():
    try:
        loop = asyncio.get_event_loop()

        for signame in ['SIGINT']:
            loop.add_signal_handler(
                getattr(signal, signame),
                lambda: asyncio.ensure_future(shutdown(signame, loop))
            )

        try:
            pull(loop)
        except Exception:
            print(traceback.format_exc())
        finally:
            loop.close()
    finally:
        print("Done")

if __name__ == "__main__":
    main()
```

<p>And I can not understand why I see - </p>

<pre class="lang-py prettyprint-override"><code>Task was destroyed but it is pending!
task: <Task cancelling coro=<shutdown() done, defined at test.py:6>>
</code>```

答:
```<code>loop.add_signal_handler(
    getattr(signal, signame),
    lambda: asyncio.ensure_future(shutdown(signame, loop))
)
</code>```

Here using asyncio.ensure_future you create task for shutdown coroutine, but you don't await anywhere for this task to be finished. Later when you close event loop it warns you this task is pending.

Upd:

If you want to do some clenup, the best place for it is right before loop.close() regardless of reason your script ended (signal, exception, etc.)

Try to alter your code this way:

```<code># ...

async def shutdown(loop):  # remove `signal` arg

# ...

def main():
    try:
        loop = asyncio.get_event_loop()
        try:
            pull(loop)
        except Exception:
            print(traceback.format_exc())
        finally:
            loop.run_until_complete(shutdown(loop))  # just run until shutdown is done
            loop.close()
    finally:
        print("Done")

# ...
</code>```

Upd2:

In case you still want signal handler, you probably want to do something like this:

```<code>from functools import partial

loop.add_signal_handler(
    getattr(signal, signame),
    partial(cb, signame, loop)
)

def cb(signame, loop):
    loop.stop()
    loop.run_until_complete(shutdown(signame, loop))
</code>```

Title: Asyncio task cancellation

Body:
This is a test script I created to better understand task cancellation -

import asyncio
import random
import signal
import traceback

async def shutdown(signame, loop):
    print("Shutting down")
    tasks = [task for task in asyncio.Task.all_tasks()]
    for task in tasks:
        task.cancel()
        try:
            await task
        except asyncio.CancelledError:
            print("Task cancelled: %s", task)
    loop.stop()

async def another():
    await asyncio.sleep(2)

async def some_other_process():
    await asyncio.sleep(5)
    return "Me"

async def process(job, loop, i):
    print(i)
    task = loop.create_task(some_other_process())
    value = await task

    if i < 1:
        another_task = loop.create_task(another())
        await another_task
    # await some_other_process()

def pull(loop):
    i = 0
    while True:
        job = f"random-integer-{random.randint(0, 100)}"
        try:
            loop.run_until_complete(process(job, loop, i))
            i += 1
        except asyncio.CancelledError as e:
            print("Task cancelled")
            break
        except Exception:
            print(traceback.format_exc())
    # asyncio.get_event_loop().stop()

def main():
    try:
        loop = asyncio.get_event_loop()

        for signame in ['SIGINT']:
            loop.add_signal_handler(
                getattr(signal, signame),
                lambda: asyncio.ensure_future(shutdown(signame, loop))
            )

        try:
            pull(loop)
        except Exception:
            print(traceback.format_exc())
        finally:
            loop.close()
    finally:
        print("Done")

if __name__ == "__main__":
    main()

And I can not understand why I see -

Task was destroyed but it is pending!
task: <Task cancelling coro=<shutdown() done, defined at test.py:6>>

Body:
loop.add_signal_handler(
    getattr(signal, signame),
    lambda: asyncio.ensure_future(shutdown(signame, loop))
)

Here using asyncio.ensure_future you create task for shutdown coroutine, but you don't await anywhere for this task to be finished. Later when you close event loop it warns you this task is pending.

Upd:

If you want to do some clenup, the best place for it is right before loop.close() regardless of reason your script ended (signal, exception, etc.)

Try to alter your code this way:

# ...

async def shutdown(loop):  # remove `signal` arg

# ...

def main():
    try:
        loop = asyncio.get_event_loop()
        try:
            pull(loop)
        except Exception:
            print(traceback.format_exc())
        finally:
            loop.run_until_complete(shutdown(loop))  # just run until shutdown is done
            loop.close()
    finally:
        print("Done")

# ...

Upd2:

In case you still want signal handler, you probably want to do something like this:

from functools import partial

loop.add_signal_handler(
    getattr(signal, signame),
    partial(cb, signame, loop)
)

def cb(signame, loop):
    loop.stop()
    loop.run_until_complete(shutdown(signame, loop))


问:
How to open an application from a Flutter app?
I am developing a Flutter app, in which I need to show navigation to the user for a place. So, how can I open a map application from my Flutter app like we do using external intent in Android?

Or their is any flutter-plugin for it?

答:
For iOS use, no browser involved, directly to apps:

```<code>//waze
canLaunch("waze://")
launch("waze://?ll=${latitude},${longitude}&navigate=yes");
//gmaps
canLaunch("comgooglemaps://")
launch("comgooglemaps://?saddr=${latitude},${longitude}&directionsmode=driving")
</code>```

What you need to do is to add to Info.plist:

```<code><key>LSApplicationQueriesSchemes</key>
<array>
  <string>comgooglemaps</string>
  <string>waze</string>
</array>
</code>```

Body:
For iOS use, no browser involved, directly to apps:

//waze
canLaunch("waze://")
launch("waze://?ll=${latitude},${longitude}&navigate=yes");
//gmaps
canLaunch("comgooglemaps://")
launch("comgooglemaps://?saddr=${latitude},${longitude}&directionsmode=driving")

What you need to do is to add to Info.plist:

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>comgooglemaps</string>
  <string>waze</string>
</array>


问:
Access to heroku apps lost
I've lost access to Heroku apps that I created and are currently live

when I run 'heroku git:remote -a myappname' the response is

Error: You do not have access to the app myappname

```<code>    'heroku git:remote -a myappname'
</code>```

Error: You do not have access to the app myappname

How can I restore access to my apps ?

答: Might have to re-enter your Heroku login credentials.</p>

Title: Access to heroku apps lost

Body:
I've lost access to Heroku apps that I created and are currently live

when I run 'heroku git:remote -a myappname' the response is

Error: You do not have access to the app myappname

    'heroku git:remote -a myappname'

Error: You do not have access to the app myappname

How can I restore access to my apps ?


问:
Using launch4j to build executable with encoding option
I'm trying to write korean to a txt file. I've done the coding part and exported project to runnable jar.
When I run jar file using terminal as  Java -Dfile.encoding="UTF-8" -jar Utul.jar  it works perfectly fine.
Now I'm trying to make .exe using launch4j can anyone help me set this option? In output file I'm getting gibberish instead of Korean characters.</p>

答: I've got the answer now. I wasn't aware of the JVM options field under JRE tab. I included this option there and result was satisfactory.</p>


问:
Create react app typescript does not load d.ts file
I have created a project using create react app typescript. I have a few d.ts files where I have defined interfaces types and enums. When I run start script. It is not able to load the d.ts files.

following is my tsconfig file.

```<code>{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "es2017"
    ],
    "allowJs": true,
    "skipLibCheck": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "pretty": true,
    "preserveConstEnums": true,
    "typeRoots": [
      "./node_modules/@types",
      "src/*"
    ]
  },
  "include": [
    "src/*"
  ]
}
</code>```

typeRoot points to src/* , where i have my d.ts files  but none of the d.ts is loaded. and I get following error:

Type error: Cannot find name 'IAlarmsDetails'.  TS2304

```<code>interface IAlarmProps {
        alarm: IAlarmsDetails;
}
</code>```

This is the declaration for IAlarmsDetails in one of Alarm.d.ts

```<code>declare type IAlarmsList = IAlarmsDetails[];
</code>```

Please let me know what I'm missing here.
I do not want to use eject option and write my own build config.

答:
It seems that the only way to use a .d.ts file out of the box with create-react-app (version 3.0.1) is to name it global.d.ts and put it in the src directory:

src/global.d.ts

I'm not sure why this rule isn't documented anywhere but that was the only way I was able to get it to work.

Body:
I have created a project using create react app typescript. I have a few d.ts files where I have defined interfaces types and enums. When I run start script. It is not able to load the d.ts files.

following is my tsconfig file.

{
  "compilerOptions": {
    "target": "es6",
    "lib": [
      "dom",
      "dom.iterable",
      "es2017"
    ],
    "allowJs": true,
    "skipLibCheck": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": false,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve",
    "pretty": true,
    "preserveConstEnums": true,
    "typeRoots": [
      "./node_modules/@types",
      "src/*"
    ]
  },
  "include": [
    "src/*"
  ]
}

typeRoot points to src/* , where i have my d.ts files  but none of the d.ts is loaded. and I get following error:

Type error: Cannot find name 'IAlarmsDetails'.  TS2304

interface IAlarmProps {
        alarm: IAlarmsDetails;
}

This is the declaration for IAlarmsDetails in one of Alarm.d.ts

declare type IAlarmsList = IAlarmsDetails[];

Please let me know what I'm missing here.
I do not want to use eject option and write my own build config.


问:
React: issue with the search and filter function
I'm working on a component that should be able to:

Search by input - Using the input field a function will be called after the onBlur event got triggered. After the onBlur event the startSearch() method will run.

Filter by a selected genre - From an other component the user can select a genre from a list  with genres. After the onClick event the startFilter() method will run.

GOOD NEWS:
I got the 2 functions above working.

BAD NEWS:
The above 2 functions don't work correct. Please see the code underneath. The 2 calls underneath work, but only if I comment one of the 2 out.  I tried to tweak the startSearch() method in various ways, but I just keep walking to a big fat wall.

```<code>//////Searching works
//////this.filter(this.state.searchInput);

//Filtering works
this.startFilter(this.state.searchInput);
</code>```

QUESTION
How can I get the filter/search method working?. Unfortunately simply putting them in an if/else is not the solution (see comments in the code).

import { Component } from 'preact';
import listData from '../../assets/data.json';
import { Link } from 'preact-router/match';
import style from './style';

export default class List extends Component {
  state = {
    selectedStreamUrl: '',
    searchInput: '',
    showDeleteButton: false,
    searchByGenre: false,
    list: []
  };

  startFilter(input, filterByGenre) {
    this.setState({
      searchByGenre: true,
      searchInput: input,
      showDeleteButton: true
    });
    alert('startFilter  ');
    console.log(this.state.searchByGenre);
    /////////---------------------------------
    document.getElementById('searchField').disabled = false;
    document.getElementById('searchField').value = input;
    document.getElementById('searchField').focus();
    // document.getElementById('searchField').blur()
    document.getElementById('searchField').disabled = true;

    console.log(input);
    this.filter(input);
  }

  //search
  startSearch(input) {
    alert('startSearch  ');
    console.log(this.state.searchByGenre);

    //komt uit render()
    if (!this.state.searchByGenre) {
      //check for input

      this.setState({
        searchInput: input.target.value,
        showDeleteButton: true
      });

      //Searching works
      //this.filter(this.state.searchInput);

      //Filtering works
      this.startFilter(this.state.searchInput);

      // DOESNT WORK:
      // if (this.state.searchInput != "") {
      //  this.filter(this.state.searchInput);
      // } else {
      //  this.startFilter(this.state.searchInput);
      // }
    }
  }

  setAllLists(allLists) {
    console.log('setAllLists');
    console.log(this.state.searchByGenre);
    this.setState({ list: allLists });
    //document.body.style.backgroundColor = "red";
  }

  filter(input) {
    let corresondingGenre = [];
    let filteredLists = listData.filter(item1 => {
      var test;
      if (this.state.searchByGenre) {
        alert('--this.state.searchByGenre');
        //filterByGenre
        //& item1.properties.genre == input

        for (var i = 0; i < item1.properties.genre.length; i++) {
          if (item1.properties.genre[i].includes(input)) {
            corresondingGenre.push(item1);
            test = item1.properties.genre[i].indexOf(input) !== -1;

            return test;
          }
          this.setState({ list: corresondingGenre });
        }
      } else {
        //searchByTitle
        alert('--default');
        test = item1.title.indexOf(input.charAt(0).toUpperCase()) !== -1;
      }
      return test;
    });
    console.log('filterdLists:');
    console.log(filteredLists);
    console.log('corresondingGenre:');
    console.log(corresondingGenre);
    //alert(JSON.stringify(filteredLists))
    this.setState({ list: filteredLists });
  }

  removeInput() {
    console.log('removeInput    ');
    console.log(this.state.searchByGenre);
    this.setState({
      searchInput: '',
      showDeleteButton: false,
      searchByGenre: false
    });
    document.getElementById('searchField').disabled = false;
    this.filter(this.state.searchInput);
  }

  render() {
    //alle 's komen in deze array, zodat ze gefilterd kunnen worden OBV title.
    if (
      this.state.list === undefined ||
      (this.state.list.length == 0 && this.state.searchInput == '')
    ) {
      //init list
      console.log('render ');
      console.log(this.state.searchByGenre);
      this.filter(this.state.searchInput);
    }

    return (

        <input
          class={style.searchBar}
          type="text"
          id="searchField"
          placeholder={this.state.searchInput}
          onBlur={this.startSearch.bind(this)}
        />

        {this.state.searchByGenre ?
ja
 :
nee
}
        {this.state.showDeleteButton ? (
          <button class={style.deleteButton} onClick={() => this.removeInput()}>
            Remove
          </button>
        ) : null}
        {this.state.list.map((item, index) => {
          return (

{item.title}

          );
        })}

    );
  }
}```

答:
To make your search and filter work properly you need two arrays.

```<code>state = {
  selectedStreamUrl: "",
  searchInput: "",
  showDeleteButton: false,
  // searchByGenre: false, // removed, will use filter by from a list
  // by default both arrays have the same value
  list: listData, // holds the original data, doesn't change
  filteredList: listData, // holds filterd list, filtered when the user types in input
  // by default filter by title, will change when user, use a value from a list
  filterBy: 'title',
}
</code>```

Your search function will use this.state.filterBy value, to filter the array. No need to create multiple functions. This gives you flexibility as you can filter using multiple values from a dropdown and you don't have to change the code.

```<code>startSearch = (value) => {

  const search = value.toLowerCase();
  // get filter value title, genre, etc
  const searchKey = this.state.filterBy;

  this.setState({
    searchInput: value,
    filteredList: this.state.list.filter(item => {
      // filter base on key item['title'] or item['genre'] etc
      return item && item[searchKey].toLowerCase().includes(search)
    }),
    showDeleteButton: !!value,
  })

}
</code>```

Remove input function

```<code>removeInput = () => {
  this.setState({
    filterBy: 'title',
    showDeleteButton: false,
    searchInput: '',
  }, () => this.startSearch(this.state.searchInput));
}
</code>```

I see you are doing a lot of document.getElementById("searchField").disabled = false;. Don't manipulate the dom directly, let react manages this for you.

SEE DEMO BELOW

h1, p {
  font-family: Lato;
}

.container {
  display: flex;
  flex-direction: row;
  border-bottom-style: solid;
  margin-bottom: 5px;
}

.image-container {
  flex-grow: 0;
}

.info-container {
  flex-grow: 1;
  margin-left: 10px
}

.title {
  margin-top: 0;
}

.cover {
  width: 60px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">

const style = {};
const listData = [
    {
      "vote_count": 806,
      "id": 420817,
      "video": false,
      "vote_average": 7.2,
      "title": "Aladdin",
      "popularity": 476.676,
      "poster_path": "/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
      "original_language": "en",
      "original_title": "Aladdin",
      "genre": "Adventure",
      "backdrop_path": "/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
      "adult": false,
      "overview": "A kindhearted street urchin named Aladdin embarks on a magical adventure after finding a lamp that releases a wisecracking genie while a power-hungry Grand Vizier vies for the same lamp that has the power to make their deepest wishes come true.",
      "release_date": "2019-05-22"
    },
    {
      "vote_count": 70,
      "id": 373571,
      "video": false,
      "vote_average": 6.4,
      "title": "Godzilla: King of the Monsters",
      "popularity": 143.161,
      "poster_path": "/pU3bnutJU91u3b4IeRPQTOP8jhV.jpg",
      "original_language": "en",
      "original_title": "Godzilla: King of the Monsters",
      "genre": "Action",
      "backdrop_path": "/mzRJpkWPjXdXak0WCc8ZxVH4hug.jpg",
      "adult": false,
      "overview": "The new story follows the heroic efforts of the crypto-zoological agency Monarch as its members face off against a battery of god-sized monsters, including the mighty Godzilla, who collides with Mothra, Rodan, and his ultimate nemesis, the three-headed King Ghidorah. When these ancient super-species—thought to be mere myths—rise again, they all vie for supremacy, leaving humanity’s very existence hanging in the balance.",
      "release_date": "2019-05-29"
    },
    {
      "vote_count": 984,
      "id": 447404,
      "video": false,
      "vote_average": 7,
      "title": "Pokémon Detective Pikachu",
      "popularity": 109.979,
      "poster_path": "/wgQ7APnFpf1TuviKHXeEe3KnsTV.jpg",
      "original_language": "en",
      "original_title": "Pokémon Detective Pikachu",
      "genre": "Mystery",
      "backdrop_path": "/nDP33LmQwNsnPv29GQazz59HjJI.jpg",
      "adult": false,
      "overview": "In a world where people collect pocket-size monsters (Pokémon) to do battle, a boy comes across an intelligent monster who seeks to be a detective.",
      "release_date": "2019-05-03"
    },
    {
      "vote_count": 136,
      "id": 531309,
      "video": false,
      "vote_average": 5.6,
      "title": "Brightburn",
      "popularity": 108.875,
      "poster_path": "/sJWwkYc9ajwnPRSkqj8Aue5JbKz.jpg",
      "original_language": "en",
      "original_title": "Brightburn",
      "genre": "Horror",
      "backdrop_path": "/uHEI6v8ApQusjbaRZ8o7WcLYeWb.jpg",
      "adult": false,
      "overview": "What if a child from another world crash-landed on Earth, but instead of becoming a hero to mankind, he proved to be something far more sinister?",
      "release_date": "2019-05-09"
    },
    {
      "vote_count": 570,
      "id": 527641,
      "video": false,
      "vote_average": 8.1,
      "title": "Five Feet Apart",
      "popularity": 72.32,
      "poster_path": "/kreTuJBkUjVWePRfhHZuYfhNE1T.jpg",
      "original_language": "en",
      "original_title": "Five Feet Apart",
      "genre": "Romance",
      "backdrop_path": "/27ZkYMWynuK2qiDP6awc3MsCaOs.jpg",
      "adult": false,
      "overview": "Seventeen-year-old Stella spends most of her time in the hospital as a cystic fibrosis patient. Her life is full of routines, boundaries and self-control -- all of which get put to the test when she meets Will, an impossibly charming teen who has the same illness. There's an instant flirtation, though restrictions dictate that they must maintain a safe distance between them. As their connection intensifies, so does the temptation to throw the rules out the window and embrace that attraction.",
      "release_date": "2019-03-15"
    },
    {
      "vote_count": 162,
      "id": 449562,
      "video": false,
      "vote_average": 6.1,
      "title": "The Hustle",
      "popularity": 71.346,
      "poster_path": "/qibqW5Dnvqp4hcEnoTARbQgxwJy.jpg",
      "original_language": "en",
      "original_title": "The Hustle",
      "genre": "Comedy",
      "backdrop_path": "/s6awXOxTKYQLSktiIJfI3969dZH.jpg",
      "adult": false,
      "overview": "Two female scam artists, one low rent and the other high class, compete to swindle a naïve tech prodigy out of his fortune. A remake of the 1988 comedy \"Dirty Rotten Scoundrels.\"",
      "release_date": "2019-05-09"
    },
    {
      "vote_count": 88,
      "id": 504608,
      "video": false,
      "vote_average": 7.7,
      "title": "Rocketman",
      "popularity": 66.812,
      "poster_path": "/f4FF18ia7yTvHf2izNrHqBmgH8U.jpg",
      "original_language": "en",
      "original_title": "Rocketman",
      "genre": "Drama",
      "backdrop_path": "/oAr5bgf49vxga9etWoQpAeRMvhp.jpg",
      "adult": false,
      "overview": "The story of Elton John's life, from his years as a prodigy at the Royal Academy of Music through his influential and enduring musical partnership with Bernie Taupin.",
      "release_date": "2019-05-22"
    },
    {
      "vote_count": 124,
      "id": 505600,
      "video": false,
      "vote_average": 7,
      "title": "Booksmart",
      "popularity": 57.801,
      "poster_path": "/Awyg5IdELQV3sBoErhJ9QVcX8TA.jpg",
      "original_language": "en",
      "original_title": "Booksmart",
      "genre": "Drama, Comedy",
      "backdrop_path": "/wcAqndL2MkIjPrCrYeuE794weNE.jpg",
      "adult": false,
      "overview": "Two academic teenage superstars realize, on the eve of their high school graduation, that they should have worked less and played more. Determined to never fall short of their peers, the girls set out on a mission to cram four years of fun into one night.",
      "release_date": "2019-05-24"
    },
    {
      "vote_count": 10,
      "id": 502416,
      "video": false,
      "vote_average": 4.8,
      "title": "Ma",
      "popularity": 55.328,
      "poster_path": "/6n7ASmQ1wY2cxTubFFGlcvPpyk7.jpg",
      "original_language": "en",
      "original_title": "Ma",
      "genre": "Comedy, Horror",
      "backdrop_path": "/mBOv5YrX5QGr5CusK0PKSHuxOt9.jpg",
      "adult": false,
      "overview": "Sue Ann is a loner who keeps to herself in her quiet Ohio town. One day, she is asked by Maggie, a new teenager in town, to buy some booze for her and her friends, and Sue Ann sees the chance to make some unsuspecting, if younger, friends of her own.  She offers the kids the chance to avoid drinking and driving by hanging out in the basement of her home. But there are some house rules: One of the kids has to stay sober. Don’t curse. Never go upstairs. And call her “Ma.”  But as Ma’s hospitality starts to curdle into obsession, what began as a teenage dream turns into a terrorizing nightmare, and Ma’s place goes from the best place in town to the worst place on earth.",
      "release_date": "2019-05-29"
    },
    {
      "vote_count": 88,
      "id": 535581,
      "video": false,
      "vote_average": 5.9,
      "title": "The Dead Don't Die",
      "popularity": 52.857,
      "poster_path": "/ycMSfP8KRFsVUWfbSxSFpD97QfD.jpg",
      "original_language": "en",
      "original_title": "The Dead Don't Die",
      "genre": "Comedy, Horror",
      "backdrop_path": "/cXyfAViYly0Lk2CVpEKgYbt9wKQ.jpg",
      "adult": false,
      "overview": "In a small peaceful town, zombies suddenly rise to terrorize the town. Now three bespectacled police officers and a strange Scottish morgue expert must band together to defeat the undead.",
      "release_date": "2019-05-15"
    },
    {
      "vote_count": 0,
      "id": 320288,
      "video": false,
      "vote_average": 0,
      "title": "Dark Phoenix",
      "popularity": 52.433,
      "poster_path": "/kZv92eTc0Gg3mKxqjjDAM73z9cy.jpg",
      "original_language": "en",
      "original_title": "Dark Phoenix",
      "genre": "Action, Science Fiction",
      "backdrop_path": "/A2oPzeKjSpCovYLqoDDXFbrJgyS.jpg",
      "adult": false,
      "overview": "The X-Men face their most formidable and powerful foe when one of their own, Jean Grey, starts to spiral out of control. During a rescue mission in outer space, Jean is nearly killed when she's hit by a mysterious cosmic force. Once she returns home, this force not only makes her infinitely more powerful, but far more unstable. The X-Men must now band together to save her soul and battle aliens that want to use Grey's new abilities to rule the galaxy.",
      "release_date": "2019-06-05"
    },
    {
      "vote_count": 10,
      "id": 496243,
      "video": false,
      "vote_average": 9.4,
      "title": "Parasite",
      "popularity": 46.835,
      "poster_path": "/7IiTTgloJzvGI1TAYymCfbfl3vT.jpg",
      "original_language": "ko",
      "original_title": "기생충",
      "genre": "Drama, Comedy",
      "backdrop_path": "/ny5aCtglk2kceGAuAdiyqbhBBAf.jpg",
      "adult": false,
      "overview": "All unemployed, Ki-taek's family takes peculiar interest in the wealthy and glamorous Parks for their livelihood until they get entangled in an unexpected incident.",
      "release_date": "2019-05-30"
    },
    {
      "vote_count": 71,
      "id": 526050,
      "video": false,
      "vote_average": 6.2,
      "title": "Little",
      "popularity": 43.334,
      "poster_path": "/4MDB6jJl3U7xK1Gw64zIqt9pQA4.jpg",
      "original_language": "en",
      "original_title": "Little",
      "genre": "Comedy, Fantasy",
      "backdrop_path": "/tmM78qRhpg0i2Cky8Q8hXKASOXY.jpg",
      "adult": false,
      "overview": "A woman receives the chance to relive the life of her younger self, at a point in her life when the pressures of adulthood become too much for her to bear.",
      "release_date": "2019-04-04"
    },
    {
      "vote_count": 1181,
      "id": 329996,
      "video": false,
      "vote_average": 6.6,
      "title": "Dumbo",
      "popularity": 39.349,
      "poster_path": "/279PwJAcelI4VuBtdzrZASqDPQr.jpg",
      "original_language": "en",
      "original_title": "Dumbo",
      "genre": "Adventure, Animation, Fantasy",
      "backdrop_path": "/5tFt6iuGnKapHl5tw0X0cKcnuVo.jpg",
      "adult": false,
      "overview": "A young elephant, whose oversized ears enable him to fly, helps save a struggling circus, but when the circus plans a new venture, Dumbo and his friends discover dark secrets beneath its shiny veneer.",
      "release_date": "2019-03-27"
    },
    {
      "vote_count": 19,
      "id": 412117,
      "video": false,
      "vote_average": 6.5,
      "title": "The Secret Life of Pets 2",
      "popularity": 38.485,
      "poster_path": "/q3mKnSkzp1doIsCye6ap4KIUAbu.jpg",
      "original_language": "en",
      "original_title": "The Secret Life of Pets 2",
      "genre": "Comedy, Animation, Adventure",
      "backdrop_path": "/5mFcjZ58f9Pqg5RNv493XlfgzIX.jpg",
      "adult": false,
      "overview": "The further adventures of Max the dog and his furry animal friends.",
      "release_date": "2019-05-24"
    },
    {
      "vote_count": 104,
      "id": 471506,
      "video": false,
      "vote_average": 6.1,
      "title": "Greta",
      "popularity": 34.139,
      "poster_path": "/9hBpFyJ3pGdupXbaC2L7nGvLMBn.jpg",
      "original_language": "en",
      "original_title": "Greta",
      "genre": "Thriller, Drama, Mystery",
      "backdrop_path": "/n67gpLtNFXqpGkM2ZdQoPLjTnI.jpg",
      "adult": false,
      "overview": "A young woman returns an elderly widow’s lost purse, leading to an unlikely relationship between the two — until the young woman discovers her elder might not be all that she seems.",
      "release_date": "2019-02-28"
    },
    {
      "vote_count": 0,
      "id": 455957,
      "video": false,
      "vote_average": 0,
      "title": "Domino",
      "popularity": 31.812,
      "poster_path": "/rrX1ojdd068aHlrGq5Khd92a3ba.jpg",
      "original_language": "en",
      "original_title": "Domino",
      "genre": "Crime, Thriller",
      "backdrop_path": "/1NGFwLyUo6YYLYD6jUaiWXgxh6n.jpg",
      "adult": false,
      "overview": "Seeking justice for his partner’s murder by an ISIS member, a Copenhagen police officer finds himself caught in a cat and mouse game with a duplicitous CIA agent who is using the killer as a pawn to trap other ISIS members.",
      "release_date": "2019-05-31"
    },
    {
      "vote_count": 45,
      "id": 514439,
      "video": false,
      "vote_average": 6.5,
      "title": "Breakthrough",
      "popularity": 29.475,
      "poster_path": "/t58dx7JIgchr9If5uxn3NmHaHoS.jpg",
      "original_language": "en",
      "original_title": "Breakthrough",
      "genre": "Drama",
      "backdrop_path": "/6jaNHf9ja84YG3KWMDK1nOnvGDg.jpg",
      "adult": false,
      "overview": "When he was 14, Smith drowned in Lake St. Louis and was dead for nearly an hour. According to reports at the time, CPR was performed 27 minutes to no avail. Then the youth's mother, Joyce Smith, entered the room, praying loudly. Suddenly, there was a pulse, and Smith came around.",
      "release_date": "2019-04-11"
    },
    {
      "vote_count": 98,
      "id": 459992,
      "video": false,
      "vote_average": 6.8,
      "title": "Long Shot",
      "popularity": 28.19,
      "poster_path": "/m2ttWZ8rMRwIMT7zA48Jo6mTkDS.jpg",
      "original_language": "en",
      "original_title": "Long Shot",
      "genre": "Comedy, Romance",
      "backdrop_path": "/88r25ghJzVYKq0vaOApqEOZsQlD.jpg",
      "adult": false,
      "overview": "When Fred Flarsky reunites with his first crush, one of the most influential women in the world, Charlotte Field, he charms her. As she prepares to make a run for the Presidency, Charlotte hires Fred as her speechwriter and sparks fly.",
      "release_date": "2019-05-02"
    },
    {
      "vote_count": 145,
      "id": 376865,
      "video": false,
      "vote_average": 5.8,
      "title": "High Life",
      "popularity": 27.909,
      "poster_path": "/wElOvH7H6sLElsTOLu1MY6oWRUx.jpg",
      "original_language": "en",
      "original_title": "High Life",
      "genre": "Science Fiction, Drama, Mystery, Thriller",
      "backdrop_path": "/6gHdAO1Lvk9bjzhY4hX3wVRkAhF.jpg",
      "adult": false,
      "overview": "Monte and his baby daughter are the last survivors of a damned and dangerous mission to the outer reaches of the solar system. They must now rely on each other to survive as they hurtle toward the oblivion of a black hole.",
      "release_date": "2018-11-07"
    }
  ]

class SearchItem extends React.Component {
  render() {
    return (
      <div className="container">
        <div className="image-container">
          <img className="cover" src={`https://image.tmdb.org/t/p/w500/${this.props.image}`} />
        </div>
        <div className="info-container">
          <p className="title">{this.props.title}</p>
          <p>Genre: {this.props.genre}</p>
        </div>
      </div>
    )
  }
}

class List extends React.Component {
  state = {
    selectedStreamUrl: "",
    searchInput: "",
    showDeleteButton: false,
    searchByGenre: false,
    list: listData,
    filteredList: listData,
    filterBy: 'title',
  }

  //search
  startSearch = (value) => {

    const search = value.toLowerCase();
    const searchKey = this.state.filterBy;

    this.setState({
      searchInput: value,
      filteredList: this.state.list.filter(item => {
        return item && item[searchKey].toLowerCase().includes(search)
      }),
      showDeleteButton: value ? true : false,
    })

  }

  setAllLists = (allLists) => {
    console.log("setAllLists")
    console.log(this.state.searchByGenre)
    this.setState({ filteredList: allLists })
    //document.body.style.backgroundColor = "red";
  }

  removeInput = () => {
    this.setState({
      filterBy: 'title',
      showDeleteButton: false,
      searchInput: '',
    }, () => this.startSearch(this.state.searchInput));
  }

  filterBy = (event) => {
    const filter =  event.target.value;

    this.setState({
      filterBy: filter
    });

  }

  render() {

    return (
      <div class={style.list_container}>
        <div>
          <input value={this.state.searchInput} class={style.searchBar} type="text" id="searchField" placeholder={this.state.searchInput} onChange={(e) => this.startSearch(e.target.value)} ></input>
          <select onChange={this.filterBy}>
            <option selected={this.state.filterBy === 'title'} value="title">Title</option>
            <option selected={this.state.filterBy === 'genre'} value="genre">Genre</option>
          </select>
        </div>
        {
          this.state.filterBy === 'genre' ?
            <h1>ja</h1>
            :
            <h1>nee</h1>
        }
        {
          this.state.showDeleteButton ?
            <button class={style.deleteButton} onClick={() => this.removeInput()}>Remove</button>
            : null
        }
        {
          this.state.filteredList.map((item, index) => {
            return <SearchItem image={item.poster_path} title={item.title} genre={item.genre} />
          })
        }
      </div>
    );
  }
}

ReactDOM.render(<List />, document.getElementById('root'));
</script></code>```

Body:
I'm working on a component that should be able to:

Search by input - Using the input field a function will be called after the onBlur event got triggered. After the onBlur event the startSearch() method will run.

Filter by a selected genre - From an other component the user can select a genre from a list  with genres. After the onClick event the startFilter() method will run.

GOOD NEWS:
I got the 2 functions above working.

BAD NEWS:
The above 2 functions don't work correct. Please see the code underneath. The 2 calls underneath work, but only if I comment one of the 2 out.  I tried to tweak the startSearch() method in various ways, but I just keep walking to a big fat wall.

//////Searching works
//////this.filter(this.state.searchInput);

//Filtering works
this.startFilter(this.state.searchInput);

QUESTION
How can I get the filter/search method working?. Unfortunately simply putting them in an if/else is not the solution (see comments in the code).

import { Component } from 'preact';
import listData from '../../assets/data.json';
import { Link } from 'preact-router/match';
import style from './style';

export default class List extends Component {
  state = {
    selectedStreamUrl: '',
    searchInput: '',
    showDeleteButton: false,
    searchByGenre: false,
    list: []
  };

  startFilter(input, filterByGenre) {
    this.setState({
      searchByGenre: true,
      searchInput: input,
      showDeleteButton: true
    });
    alert('startFilter  ');
    console.log(this.state.searchByGenre);
    /////////---------------------------------
    document.getElementById('searchField').disabled = false;
    document.getElementById('searchField').value = input;
    document.getElementById('searchField').focus();
    // document.getElementById('searchField').blur()
    document.getElementById('searchField').disabled = true;

    console.log(input);
    this.filter(input);
  }

  //search
  startSearch(input) {
    alert('startSearch  ');
    console.log(this.state.searchByGenre);

    //komt uit render()
    if (!this.state.searchByGenre) {
      //check for input

      this.setState({
        searchInput: input.target.value,
        showDeleteButton: true
      });

      //Searching works
      //this.filter(this.state.searchInput);

      //Filtering works
      this.startFilter(this.state.searchInput);

      // DOESNT WORK:
      // if (this.state.searchInput != "") {
      //  this.filter(this.state.searchInput);
      // } else {
      //  this.startFilter(this.state.searchInput);
      // }
    }
  }

  setAllLists(allLists) {
    console.log('setAllLists');
    console.log(this.state.searchByGenre);
    this.setState({ list: allLists });
    //document.body.style.backgroundColor = "red";
  }

  filter(input) {
    let corresondingGenre = [];
    let filteredLists = listData.filter(item1 => {
      var test;
      if (this.state.searchByGenre) {
        alert('--this.state.searchByGenre');
        //filterByGenre
        //& item1.properties.genre == input

        for (var i = 0; i < item1.properties.genre.length; i++) {
          if (item1.properties.genre[i].includes(input)) {
            corresondingGenre.push(item1);
            test = item1.properties.genre[i].indexOf(input) !== -1;

            return test;
          }
          this.setState({ list: corresondingGenre });
        }
      } else {
        //searchByTitle
        alert('--default');
        test = item1.title.indexOf(input.charAt(0).toUpperCase()) !== -1;
      }
      return test;
    });
    console.log('filterdLists:');
    console.log(filteredLists);
    console.log('corresondingGenre:');
    console.log(corresondingGenre);
    //alert(JSON.stringify(filteredLists))
    this.setState({ list: filteredLists });
  }

  removeInput() {
    console.log('removeInput    ');
    console.log(this.state.searchByGenre);
    this.setState({
      searchInput: '',
      showDeleteButton: false,
      searchByGenre: false
    });
    document.getElementById('searchField').disabled = false;
    this.filter(this.state.searchInput);
  }

  render() {
    //alle 's komen in deze array, zodat ze gefilterd kunnen worden OBV title.
    if (
      this.state.list === undefined ||
      (this.state.list.length == 0 && this.state.searchInput == '')
    ) {
      //init list
      console.log('render ');
      console.log(this.state.searchByGenre);
      this.filter(this.state.searchInput);
    }

    return (

        <input
          class={style.searchBar}
          type="text"
          id="searchField"
          placeholder={this.state.searchInput}
          onBlur={this.startSearch.bind(this)}
        />

        {this.state.searchByGenre ?
ja
 :
nee
}
        {this.state.showDeleteButton ? (
          <button class={style.deleteButton} onClick={() => this.removeInput()}>
            Remove
          </button>
        ) : null}
        {this.state.list.map((item, index) => {
          return (

{item.title}

          );
        })}

    );
  }
}

Body:
To make your search and filter work properly you need two arrays.

state = {
  selectedStreamUrl: "",
  searchInput: "",
  showDeleteButton: false,
  // searchByGenre: false, // removed, will use filter by from a list
  // by default both arrays have the same value
  list: listData, // holds the original data, doesn't change
  filteredList: listData, // holds filterd list, filtered when the user types in input
  // by default filter by title, will change when user, use a value from a list
  filterBy: 'title',
}

Your search function will use this.state.filterBy value, to filter the array. No need to create multiple functions. This gives you flexibility as you can filter using multiple values from a dropdown and you don't have to change the code.

startSearch = (value) => {

  const search = value.toLowerCase();
  // get filter value title, genre, etc
  const searchKey = this.state.filterBy;

  this.setState({
    searchInput: value,
    filteredList: this.state.list.filter(item => {
      // filter base on key item['title'] or item['genre'] etc
      return item && item[searchKey].toLowerCase().includes(search)
    }),
    showDeleteButton: !!value,
  })

}

Remove input function

removeInput = () => {
  this.setState({
    filterBy: 'title',
    showDeleteButton: false,
    searchInput: '',
  }, () => this.startSearch(this.state.searchInput));
}

I see you are doing a lot of document.getElementById("searchField").disabled = false;. Don't manipulate the dom directly, let react manages this for you.

SEE DEMO BELOW

h1, p {
  font-family: Lato;
}

.container {
  display: flex;
  flex-direction: row;
  border-bottom-style: solid;
  margin-bottom: 5px;
}

.image-container {
  flex-grow: 0;
}

.info-container {
  flex-grow: 1;
  margin-left: 10px
}

.title {
  margin-top: 0;
}

.cover {
  width: 60px;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.0/umd/react-dom.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-standalone/6.21.1/babel.min.js"></script>
<div id="root"></div>

<script type="text/babel">

const style = {};
const listData = [
    {
      "vote_count": 806,
      "id": 420817,
      "video": false,
      "vote_average": 7.2,
      "title": "Aladdin",
      "popularity": 476.676,
      "poster_path": "/3iYQTLGoy7QnjcUYRJy4YrAgGvp.jpg",
      "original_language": "en",
      "original_title": "Aladdin",
      "genre": "Adventure",
      "backdrop_path": "/v4yVTbbl8dE1UP2dWu5CLyaXOku.jpg",
      "adult": false,
      "overview": "A kindhearted street urchin named Aladdin embarks on a magical adventure after finding a lamp that releases a wisecracking genie while a power-hungry Grand Vizier vies for the same lamp that has the power to make their deepest wishes come true.",
      "release_date": "2019-05-22"
    },
    {
      "vote_count": 70,
      "id": 373571,
      "video": false,
      "vote_average": 6.4,
      "title": "Godzilla: King of the Monsters",
      "popularity": 143.161,
      "poster_path": "/pU3bnutJU91u3b4IeRPQTOP8jhV.jpg",
      "original_language": "en",
      "original_title": "Godzilla: King of the Monsters",
      "genre": "Action",
      "backdrop_path": "/mzRJpkWPjXdXak0WCc8ZxVH4hug.jpg",
      "adult": false,
      "overview": "The new story follows the heroic efforts of the crypto-zoological agency Monarch as its members face off against a battery of god-sized monsters, including the mighty Godzilla, who collides with Mothra, Rodan, and his ultimate nemesis, the three-headed King Ghidorah. When these ancient super-species—thought to be mere myths—rise again, they all vie for supremacy, leaving humanity’s very existence hanging in the balance.",
      "release_date": "2019-05-29"
    },
    {
      "vote_count": 984,
      "id": 447404,
      "video": false,
      "vote_average": 7,
      "title": "Pokémon Detective Pikachu",
      "popularity": 109.979,
      "poster_path": "/wgQ7APnFpf1TuviKHXeEe3KnsTV.jpg",
      "original_language": "en",
      "original_title": "Pokémon Detective Pikachu",
      "genre": "Mystery",
      "backdrop_path": "/nDP33LmQwNsnPv29GQazz59HjJI.jpg",
      "adult": false,
      "overview": "In a world where people collect pocket-size monsters (Pokémon) to do battle, a boy comes across an intelligent monster who seeks to be a detective.",
      "release_date": "2019-05-03"
    },
    {
      "vote_count": 136,
      "id": 531309,
      "video": false,
      "vote_average": 5.6,
      "title": "Brightburn",
      "popularity": 108.875,
      "poster_path": "/sJWwkYc9ajwnPRSkqj8Aue5JbKz.jpg",
      "original_language": "en",
      "original_title": "Brightburn",
      "genre": "Horror",
      "backdrop_path": "/uHEI6v8ApQusjbaRZ8o7WcLYeWb.jpg",
      "adult": false,
      "overview": "What if a child from another world crash-landed on Earth, but instead of becoming a hero to mankind, he proved to be something far more sinister?",
      "release_date": "2019-05-09"
    },
    {
      "vote_count": 570,
      "id": 527641,
      "video": false,
      "vote_average": 8.1,
      "title": "Five Feet Apart",
      "popularity": 72.32,
      "poster_path": "/kreTuJBkUjVWePRfhHZuYfhNE1T.jpg",
      "original_language": "en",
      "original_title": "Five Feet Apart",
      "genre": "Romance",
      "backdrop_path": "/27ZkYMWynuK2qiDP6awc3MsCaOs.jpg",
      "adult": false,
      "overview": "Seventeen-year-old Stella spends most of her time in the hospital as a cystic fibrosis patient. Her life is full of routines, boundaries and self-control -- all of which get put to the test when she meets Will, an impossibly charming teen who has the same illness. There's an instant flirtation, though restrictions dictate that they must maintain a safe distance between them. As their connection intensifies, so does the temptation to throw the rules out the window and embrace that attraction.",
      "release_date": "2019-03-15"
    },
    {
      "vote_count": 162,
      "id": 449562,
      "video": false,
      "vote_average": 6.1,
      "title": "The Hustle",
      "popularity": 71.346,
      "poster_path": "/qibqW5Dnvqp4hcEnoTARbQgxwJy.jpg",
      "original_language": "en",
      "original_title": "The Hustle",
      "genre": "Comedy",
      "backdrop_path": "/s6awXOxTKYQLSktiIJfI3969dZH.jpg",
      "adult": false,
      "overview": "Two female scam artists, one low rent and the other high class, compete to swindle a naïve tech prodigy out of his fortune. A remake of the 1988 comedy \"Dirty Rotten Scoundrels.\"",
      "release_date": "2019-05-09"
    },
    {
      "vote_count": 88,
      "id": 504608,
      "video": false,
      "vote_average": 7.7,
      "title": "Rocketman",
      "popularity": 66.812,
      "poster_path": "/f4FF18ia7yTvHf2izNrHqBmgH8U.jpg",
      "original_language": "en",
      "original_title": "Rocketman",
      "genre": "Drama",
      "backdrop_path": "/oAr5bgf49vxga9etWoQpAeRMvhp.jpg",
      "adult": false,
      "overview": "The story of Elton John's life, from his years as a prodigy at the Royal Academy of Music through his influential and enduring musical partnership with Bernie Taupin.",
      "release_date": "2019-05-22"
    },
    {
      "vote_count": 124,
      "id": 505600,
      "video": false,
      "vote_average": 7,
      "title": "Booksmart",
      "popularity": 57.801,
      "poster_path": "/Awyg5IdELQV3sBoErhJ9QVcX8TA.jpg",
      "original_language": "en",
      "original_title": "Booksmart",
      "genre": "Drama, Comedy",
      "backdrop_path": "/wcAqndL2MkIjPrCrYeuE794weNE.jpg",
      "adult": false,
      "overview": "Two academic teenage superstars realize, on the eve of their high school graduation, that they should have worked less and played more. Determined to never fall short of their peers, the girls set out on a mission to cram four years of fun into one night.",
      "release_date": "2019-05-24"
    },
    {
      "vote_count": 10,
      "id": 502416,
      "video": false,
      "vote_average": 4.8,
      "title": "Ma",
      "popularity": 55.328,
      "poster_path": "/6n7ASmQ1wY2cxTubFFGlcvPpyk7.jpg",
      "original_language": "en",
      "original_title": "Ma",
      "genre": "Comedy, Horror",
      "backdrop_path": "/mBOv5YrX5QGr5CusK0PKSHuxOt9.jpg",
      "adult": false,
      "overview": "Sue Ann is a loner who keeps to herself in her quiet Ohio town. One day, she is asked by Maggie, a new teenager in town, to buy some booze for her and her friends, and Sue Ann sees the chance to make some unsuspecting, if younger, friends of her own.  She offers the kids the chance to avoid drinking and driving by hanging out in the basement of her home. But there are some house rules: One of the kids has to stay sober. Don’t curse. Never go upstairs. And call her “Ma.”  But as Ma’s hospitality starts to curdle into obsession, what began as a teenage dream turns into a terrorizing nightmare, and Ma’s place goes from the best place in town to the worst place on earth.",
      "release_date": "2019-05-29"
    },
    {
      "vote_count": 88,
      "id": 535581,
      "video": false,
      "vote_average": 5.9,
      "title": "The Dead Don't Die",
      "popularity": 52.857,
      "poster_path": "/ycMSfP8KRFsVUWfbSxSFpD97QfD.jpg",
      "original_language": "en",
      "original_title": "The Dead Don't Die",
      "genre": "Comedy, Horror",
      "backdrop_path": "/cXyfAViYly0Lk2CVpEKgYbt9wKQ.jpg",
      "adult": false,
      "overview": "In a small peaceful town, zombies suddenly rise to terrorize the town. Now three bespectacled police officers and a strange Scottish morgue expert must band together to defeat the undead.",
      "release_date": "2019-05-15"
    },
    {
      "vote_count": 0,
      "id": 320288,
      "video": false,
      "vote_average": 0,
      "title": "Dark Phoenix",
      "popularity": 52.433,
      "poster_path": "/kZv92eTc0Gg3mKxqjjDAM73z9cy.jpg",
      "original_language": "en",
      "original_title": "Dark Phoenix",
      "genre": "Action, Science Fiction",
      "backdrop_path": "/A2oPzeKjSpCovYLqoDDXFbrJgyS.jpg",
      "adult": false,
      "overview": "The X-Men face their most formidable and powerful foe when one of their own, Jean Grey, starts to spiral out of control. During a rescue mission in outer space, Jean is nearly killed when she's hit by a mysterious cosmic force. Once she returns home, this force not only makes her infinitely more powerful, but far more unstable. The X-Men must now band together to save her soul and battle aliens that want to use Grey's new abilities to rule the galaxy.",
      "release_date": "2019-06-05"
    },
    {
      "vote_count": 10,
      "id": 496243,
      "video": false,
      "vote_average": 9.4,
      "title": "Parasite",
      "popularity": 46.835,
      "poster_path": "/7IiTTgloJzvGI1TAYymCfbfl3vT.jpg",
      "original_language": "ko",
      "original_title": "기생충",
      "genre": "Drama, Comedy",
      "backdrop_path": "/ny5aCtglk2kceGAuAdiyqbhBBAf.jpg",
      "adult": false,
      "overview": "All unemployed, Ki-taek's family takes peculiar interest in the wealthy and glamorous Parks for their livelihood until they get entangled in an unexpected incident.",
      "release_date": "2019-05-30"
    },
    {
      "vote_count": 71,
      "id": 526050,
      "video": false,
      "vote_average": 6.2,
      "title": "Little",
      "popularity": 43.334,
      "poster_path": "/4MDB6jJl3U7xK1Gw64zIqt9pQA4.jpg",
      "original_language": "en",
      "original_title": "Little",
      "genre": "Comedy, Fantasy",
      "backdrop_path": "/tmM78qRhpg0i2Cky8Q8hXKASOXY.jpg",
      "adult": false,
      "overview": "A woman receives the chance to relive the life of her younger self, at a point in her life when the pressures of adulthood become too much for her to bear.",
      "release_date": "2019-04-04"
    },
    {
      "vote_count": 1181,
      "id": 329996,
      "video": false,
      "vote_average": 6.6,
      "title": "Dumbo",
      "popularity": 39.349,
      "poster_path": "/279PwJAcelI4VuBtdzrZASqDPQr.jpg",
      "original_language": "en",
      "original_title": "Dumbo",
      "genre": "Adventure, Animation, Fantasy",
      "backdrop_path": "/5tFt6iuGnKapHl5tw0X0cKcnuVo.jpg",
      "adult": false,
      "overview": "A young elephant, whose oversized ears enable him to fly, helps save a struggling circus, but when the circus plans a new venture, Dumbo and his friends discover dark secrets beneath its shiny veneer.",
      "release_date": "2019-03-27"
    },
    {
      "vote_count": 19,
      "id": 412117,
      "video": false,
      "vote_average": 6.5,
      "title": "The Secret Life of Pets 2",
      "popularity": 38.485,
      "poster_path": "/q3mKnSkzp1doIsCye6ap4KIUAbu.jpg",
      "original_language": "en",
      "original_title": "The Secret Life of Pets 2",
      "genre": "Comedy, Animation, Adventure",
      "backdrop_path": "/5mFcjZ58f9Pqg5RNv493XlfgzIX.jpg",
      "adult": false,
      "overview": "The further adventures of Max the dog and his furry animal friends.",
      "release_date": "2019-05-24"
    },
    {
      "vote_count": 104,
      "id": 471506,
      "video": false,
      "vote_average": 6.1,
      "title": "Greta",
      "popularity": 34.139,
      "poster_path": "/9hBpFyJ3pGdupXbaC2L7nGvLMBn.jpg",
      "original_language": "en",
      "original_title": "Greta",
      "genre": "Thriller, Drama, Mystery",
      "backdrop_path": "/n67gpLtNFXqpGkM2ZdQoPLjTnI.jpg",
      "adult": false,
      "overview": "A young woman returns an elderly widow’s lost purse, leading to an unlikely relationship between the two — until the young woman discovers her elder might not be all that she seems.",
      "release_date": "2019-02-28"
    },
    {
      "vote_count": 0,
      "id": 455957,
      "video": false,
      "vote_average": 0,
      "title": "Domino",
      "popularity": 31.812,
      "poster_path": "/rrX1ojdd068aHlrGq5Khd92a3ba.jpg",
      "original_language": "en",
      "original_title": "Domino",
      "genre": "Crime, Thriller",
      "backdrop_path": "/1NGFwLyUo6YYLYD6jUaiWXgxh6n.jpg",
      "adult": false,
      "overview": "Seeking justice for his partner’s murder by an ISIS member, a Copenhagen police officer finds himself caught in a cat and mouse game with a duplicitous CIA agent who is using the killer as a pawn to trap other ISIS members.",
      "release_date": "2019-05-31"
    },
    {
      "vote_count": 45,
      "id": 514439,
      "video": false,
      "vote_average": 6.5,
      "title": "Breakthrough",
      "popularity": 29.475,
      "poster_path": "/t58dx7JIgchr9If5uxn3NmHaHoS.jpg",
      "original_language": "en",
      "original_title": "Breakthrough",
      "genre": "Drama",
      "backdrop_path": "/6jaNHf9ja84YG3KWMDK1nOnvGDg.jpg",
      "adult": false,
      "overview": "When he was 14, Smith drowned in Lake St. Louis and was dead for nearly an hour. According to reports at the time, CPR was performed 27 minutes to no avail. Then the youth's mother, Joyce Smith, entered the room, praying loudly. Suddenly, there was a pulse, and Smith came around.",
      "release_date": "2019-04-11"
    },
    {
      "vote_count": 98,
      "id": 459992,
      "video": false,
      "vote_average": 6.8,
      "title": "Long Shot",
      "popularity": 28.19,
      "poster_path": "/m2ttWZ8rMRwIMT7zA48Jo6mTkDS.jpg",
      "original_language": "en",
      "original_title": "Long Shot",
      "genre": "Comedy, Romance",
      "backdrop_path": "/88r25ghJzVYKq0vaOApqEOZsQlD.jpg",
      "adult": false,
      "overview": "When Fred Flarsky reunites with his first crush, one of the most influential women in the world, Charlotte Field, he charms her. As she prepares to make a run for the Presidency, Charlotte hires Fred as her speechwriter and sparks fly.",
      "release_date": "2019-05-02"
    },
    {
      "vote_count": 145,
      "id": 376865,
      "video": false,
      "vote_average": 5.8,
      "title": "High Life",
      "popularity": 27.909,
      "poster_path": "/wElOvH7H6sLElsTOLu1MY6oWRUx.jpg",
      "original_language": "en",
      "original_title": "High Life",
      "genre": "Science Fiction, Drama, Mystery, Thriller",
      "backdrop_path": "/6gHdAO1Lvk9bjzhY4hX3wVRkAhF.jpg",
      "adult": false,
      "overview": "Monte and his baby daughter are the last survivors of a damned and dangerous mission to the outer reaches of the solar system. They must now rely on each other to survive as they hurtle toward the oblivion of a black hole.",
      "release_date": "2018-11-07"
    }
  ]

class SearchItem extends React.Component {
  render() {
    return (
      <div className="container">
        <div className="image-container">
          <img className="cover" src={`https://image.tmdb.org/t/p/w500/${this.props.image}`} />
        </div>
        <div className="info-container">
          <p className="title">{this.props.title}</p>
          <p>Genre: {this.props.genre}</p>
        </div>
      </div>
    )
  }
}

class List extends React.Component {
  state = {
    selectedStreamUrl: "",
    searchInput: "",
    showDeleteButton: false,
    searchByGenre: false,
    list: listData,
    filteredList: listData,
    filterBy: 'title',
  }

  //search
  startSearch = (value) => {

    const search = value.toLowerCase();
    const searchKey = this.state.filterBy;

    this.setState({
      searchInput: value,
      filteredList: this.state.list.filter(item => {
        return item && item[searchKey].toLowerCase().includes(search)
      }),
      showDeleteButton: value ? true : false,
    })

  }

  setAllLists = (allLists) => {
    console.log("setAllLists")
    console.log(this.state.searchByGenre)
    this.setState({ filteredList: allLists })
    //document.body.style.backgroundColor = "red";
  }

  removeInput = () => {
    this.setState({
      filterBy: 'title',
      showDeleteButton: false,
      searchInput: '',
    }, () => this.startSearch(this.state.searchInput));
  }

  filterBy = (event) => {
    const filter =  event.target.value;

    this.setState({
      filterBy: filter
    });

  }

  render() {

    return (
      <div class={style.list_container}>
        <div>
          <input value={this.state.searchInput} class={style.searchBar} type="text" id="searchField" placeholder={this.state.searchInput} onChange={(e) => this.startSearch(e.target.value)} ></input>
          <select onChange={this.filterBy}>
            <option selected={this.state.filterBy === 'title'} value="title">Title</option>
            <option selected={this.state.filterBy === 'genre'} value="genre">Genre</option>
          </select>
        </div>
        {
          this.state.filterBy === 'genre' ?
            <h1>ja</h1>
            :
            <h1>nee</h1>
        }
        {
          this.state.showDeleteButton ?
            <button class={style.deleteButton} onClick={() => this.removeInput()}>Remove</button>
            : null
        }
        {
          this.state.filteredList.map((item, index) => {
            return <SearchItem image={item.poster_path} title={item.title} genre={item.genre} />
          })
        }
      </div>
    );
  }
}

ReactDOM.render(<List />, document.getElementById('root'));
</script>


问:
SQL IN function and select not match criteria
Using a SQL IN clause to get student scores for a given grade e.g. 1,2,3,4 in Reading. A student may not receive any scores that have 4. Is there a way to select a not matched condition IN SQL clause

Here is the query

```<code>select
score,
count(*) as [countTimes]
from ScoresTable
where  score IN (1,2,3,4)
</code>```

Score

If a student has never received a 4, I need to create a row like 4,0
example resultset

```<code>Score Count
1       2
2       3
3       1
4       0
</code>```

the current query is using an IN clause. If there are no records that match IN clause, the row is not diislayed

```<code>Score Count
1       2
2       3
3       1
4       0
</code>```

答:
You are looking for a left join:

```<code>select v.score, count(s.score) as [countTimes]
from (values (1), (2), (3), (4)
     ) v(score) left join
     ScoresTable s
     on s.score = v.score
group by v.score;
</code>```

Body:
Using a SQL IN clause to get student scores for a given grade e.g. 1,2,3,4 in Reading. A student may not receive any scores that have 4. Is there a way to select a not matched condition IN SQL clause

Here is the query

select
score,
count(*) as [countTimes]
from ScoresTable
where  score IN (1,2,3,4)

Score

If a student has never received a 4, I need to create a row like 4,0
example resultset

Score Count
1       2
2       3
3       1
4       0

the current query is using an IN clause. If there are no records that match IN clause, the row is not diislayed

Score Count
1       2
2       3
3       1
4       0

Body:
You are looking for a left join:

select v.score, count(s.score) as [countTimes]
from (values (1), (2), (3), (4)
     ) v(score) left join
     ScoresTable s
     on s.score = v.score
group by v.score;


问:
simple python for loop doesn't update the element
My first time trying anything in python and I can't even get the for loop to update the element. Please, what am I not seeing?

I have this data in a text file

Y|Contents/MacOS/Safari|1500

   N|Contents/MacOS/firefox|1200

  Y|Contents/MacOS/Evernote|1100

And I want to change N in the second line to Y. It prints out the form I want inside the loop but not outside? What is this?

```<code>def setTrackable(self,appName):
        lookfor = 'Contents/MacOS/'+appName
        with open (self.__dataFile,"r") as myfile:
            data = myfile.readlines()

        for line in data:
            temp = line.split("|")
            if (temp[1] == lookfor):
                line = 'Y|'+lookfor+"|"+temp[2]
                print("line: "+line)

        print (data[1])
        with open (self.__dataFile, "w") as myfile:
            myfile.writelines(data)
</code>```

答:
A shorter more pythonic way using regex:

```<code>with open(self.__dataFile,"r") as myfile1, open(self.__dataFile, "w") as myfile2:
    for line in myfile1:
        myfile2.write(re.sub(f'^N(|{lookfor}|\d+)', 'Y\\1', line))
</code>```

As discussed in comments and in other answers, line is just a local variable whose scope is local and does not change the original data.

Note please don't forget to import re.

Body:
My first time trying anything in python and I can't even get the for loop to update the element. Please, what am I not seeing?

I have this data in a text file

Y|Contents/MacOS/Safari|1500

   N|Contents/MacOS/firefox|1200

  Y|Contents/MacOS/Evernote|1100

And I want to change N in the second line to Y. It prints out the form I want inside the loop but not outside? What is this?

def setTrackable(self,appName):
        lookfor = 'Contents/MacOS/'+appName
        with open (self.__dataFile,"r") as myfile:
            data = myfile.readlines()

        for line in data:
            temp = line.split("|")
            if (temp[1] == lookfor):
                line = 'Y|'+lookfor+"|"+temp[2]
                print("line: "+line)

        print (data[1])
        with open (self.__dataFile, "w") as myfile:
            myfile.writelines(data)

Body:
A shorter more pythonic way using regex:

with open(self.__dataFile,"r") as myfile1, open(self.__dataFile, "w") as myfile2:
    for line in myfile1:
        myfile2.write(re.sub(f'^N(|{lookfor}|\d+)', 'Y\\1', line))

As discussed in comments and in other answers, line is just a local variable whose scope is local and does not change the original data.

Note please don't forget to import re.


问:
DAO.TableDef not defined in excel
I am trying to convert to  to five formats but when i execute the code on line 2
it  says DAO.TableDef is not defined.
If the code would run succesfully it would create five formats: csv,xml.laccdb, acccdb, xls.
The following programs is going to be created as new files in excel vba.</p>

```<code>Sub exportTables2XLS()
Dim td As DAO.TableDef, db As DAO.Database
Dim out_file As String
out_file = CurrentProject.Path & "\test.xls"
Set db = CurrentDb()
For Each td In db.TableDefs
If Left(td.Name, 4) = "MSys" Then
'//do nothing -- skip
Else
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
td.Name, out_file, True, Replace(td.Name, "dbo_", "")
End If
Next
End Sub
'expeced ouput :test.xls, test.xml, test.csv, test.accdb,test.laccdb,
</code>```

答:
If its failing on your definition of the DAO.TableDef, then its probably your References

Alt + F11 > Tools > References

Make sure this is checked, where x is your specific version number: Microsoft DAO x.x Object Library

https://stackoverflow.com/a/13919392/4731063

Title: DAO.TableDef not defined in excel

Body:
I am trying to convert to  to five formats but when i execute the code on line 2
it  says DAO.TableDef is not defined.
If the code would run succesfully it would create five formats: csv,xml.laccdb, acccdb, xls.
The following programs is going to be created as new files in excel vba.

Sub exportTables2XLS()
Dim td As DAO.TableDef, db As DAO.Database
Dim out_file As String
out_file = CurrentProject.Path & "\test.xls"
Set db = CurrentDb()
For Each td In db.TableDefs
If Left(td.Name, 4) = "MSys" Then
'//do nothing -- skip
Else
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, _
td.Name, out_file, True, Replace(td.Name, "dbo_", "")
End If
Next
End Sub
'expeced ouput :test.xls, test.xml, test.csv, test.accdb,test.laccdb,


问:
Moving left brace in C code to the next line?
I have several C source files that need to have one particular formatting feature changed.  In some parts of the file,

```<code>if (x == NULL) {
    ...
}
</code>```

needs to be changed to

```<code>if (x == NULL)
{
    ...
}
</code>```

I was hoping to use the "indent" command, but it's far too aggressive.  It wants to change the entire file with all options.

I suppose I can do this in Perl or maybe even Sed, but I don't know either well enough to figure that out.

答:
What's wrong with this?

```<code>$ cat tst.c
#include "stdio.h"

int
main ()
{
    void *x;

    if (x == NULL) {
        printf("darn\n");
    }

    return 0;
}
</code>```

.

```<code>$ indent -i 4 -bli 0 -npcs -st tst.c
#include "stdio.h"

int
main()
{
    void *x;

    if (x == NULL)
    {
        printf("darn\n");
    }

    return 0;
}
</code>```

If you have other examples of code segments that shouldn't be changed then create a sample program that includes those and tweak the indent options until you're happy that the style of code it's outputting is the style you want.

In a comment @melpomene had mentioned that indent doesn't always handle obfuscated code properly and gave the example of prin\<newline>tf("..."). idk about other cases but you can handle that one by pre-processing with the help of sed and gcc:

```<code>$ cat tst.c
#include "stdio.h"

int
main ()
{
    void *x;

    // here is a comment
    if (x == NULL) {
        prin\
tf("darn\n");
    }

    return 0;
}
</code>```

.

```<code>$ indent -i 4 -bli 0 -npcs -st tst.c
#include "stdio.h"

int
main()
{
    void *x;

    // here is a comment
    if (x == NULL)
    {
        prin tf("darn\n");
    }

    return 0;
}
</code>```

.

```<code>$ sed 's/a/aA/g;s/__/aB/g;s/#/aC/g' tst.c |
    gcc -CC -P -traditional-cpp -E - |
    sed 's/aC/#/g;s/aB/__/g;s/aA/a/g'
#include "stdio.h"

int
main ()
{
    void *x;

    // here is a comment
    if (x == NULL) {
        printf("darn\n");
    }

    return 0;
}
</code>```

.

```<code>$ sed 's/a/aA/g;s/__/aB/g;s/#/aC/g' tst.c |
    gcc -CC -P -traditional-cpp -E - |
    sed 's/aC/#/g;s/aB/__/g;s/aA/a/g' |
    indent -i 4 -bli 0 -npcs -st
#include "stdio.h"

int
main()
{
    void *x;

    // here is a comment
    if (x == NULL)
    {
        printf("darn\n");
    }

    return 0;
}
</code>```

Body:
I have several C source files that need to have one particular formatting feature changed.  In some parts of the file,

if (x == NULL) {
    ...
}

needs to be changed to

if (x == NULL)
{
    ...
}

I was hoping to use the "indent" command, but it's far too aggressive.  It wants to change the entire file with all options.

I suppose I can do this in Perl or maybe even Sed, but I don't know either well enough to figure that out.

Body:
What's wrong with this?

$ cat tst.c
#include "stdio.h"

int
main ()
{
    void *x;

    if (x == NULL) {
        printf("darn\n");
    }

    return 0;
}

.

$ indent -i 4 -bli 0 -npcs -st tst.c
#include "stdio.h"

int
main()
{
    void *x;

    if (x == NULL)
    {
        printf("darn\n");
    }

    return 0;
}

If you have other examples of code segments that shouldn't be changed then create a sample program that includes those and tweak the indent options until you're happy that the style of code it's outputting is the style you want.

In a comment @melpomene had mentioned that indent doesn't always handle obfuscated code properly and gave the example of prin\<newline>tf("..."). idk about other cases but you can handle that one by pre-processing with the help of sed and gcc:

$ cat tst.c
#include "stdio.h"

int
main ()
{
    void *x;

    // here is a comment
    if (x == NULL) {
        prin\
tf("darn\n");
    }

    return 0;
}

.

$ indent -i 4 -bli 0 -npcs -st tst.c
#include "stdio.h"

int
main()
{
    void *x;

    // here is a comment
    if (x == NULL)
    {
        prin tf("darn\n");
    }

    return 0;
}

.

$ sed 's/a/aA/g;s/__/aB/g;s/#/aC/g' tst.c |
    gcc -CC -P -traditional-cpp -E - |
    sed 's/aC/#/g;s/aB/__/g;s/aA/a/g'
#include "stdio.h"

int
main ()
{
    void *x;

    // here is a comment
    if (x == NULL) {
        printf("darn\n");
    }

    return 0;
}

.

$ sed 's/a/aA/g;s/__/aB/g;s/#/aC/g' tst.c |
    gcc -CC -P -traditional-cpp -E - |
    sed 's/aC/#/g;s/aB/__/g;s/aA/a/g' |
    indent -i 4 -bli 0 -npcs -st
#include "stdio.h"

int
main()
{
    void *x;

    // here is a comment
    if (x == NULL)
    {
        printf("darn\n");
    }

    return 0;
}