问:
TypeError: onSelect() is not a function in ReactJS, using functional component
I have following code.

I'm trying to store a value in my state and every time the user goes to the previous step he can see what he has selected and after that he can change and move on to the next step.

At the first step, everything works good. For example, the user selects the second text and proceeds to the next step, and when he returns to this step, he sees that the second text has already been selected...

The problem is with the second step, I write all the same, but it doesn't work for the second step.

The error says onSelect is not a function in src/component/SelectCard.js. Please help me solve this problem.

Here is my code.

App file

```<code> export default function App() {
     const [selected, setSelected] = useState(1);
     const [term, setTerm] = useState(1);

     const [current, setCurrent] = useState(0);

     const [data, setData] = useState({
       firstName: "bob",
       lastName: "Forest",
       age: 47
     });
      const steps = [
        {
          title: "Package Choose",
          content: (
            <PackageChoose
              setCurrent={setCurrent}
              data={data}
              setData={setData}
              selected={selected}
              setSelected={setSelected}
            />
         ),
          id: 0
        },
        {
          title: "Term",
          content: (
            <Term
              setCurrent={setCurrent}
              data={data}
              selected={term}
              setSelected={setTerm}
            />
          ),
          id: 1
        },
        {
          title: "Last step",
          content: <LastStep setCurrent={setCurrent} data={data} />,
          id: 2
        }
      ];
      return (
        <div className="App">
          <div>{steps[current].content}</div>
        </div>
      );
    }
</code>```

first step package choose file

```<code>    const PackageChoose = ({
      setCurrent,
      data,
      setData,
      setSelected,
      selected
    }) => {
      return (
        <div>
          <div
            onClick={() => {
              setData({ ...data, packageType: "choice" });
            }}
          >
            <SelectCard
              id={1}
              selected={selected}
              onSelect={setSelected}
              text="text 1"
            />
          </div>
          <div
            onClick={() => {
              setData({ ...data, packageType: "select" });
            }}
          >
            <SelectCard
              id={2}
              selected={selected}
              onSelect={setSelected}
              text="text 2"
             />
          </div>
          <button onClick={() => setCurrent(1)}>Next</button>
        </div>
      );
   };
</code>```

second step Term file

```<code>   const Term = ({ setCurrent, data, setData, term, setTerm }) => {
      return (
        <div>
          <button onClick={() => setCurrent(0)}>Prev</button>
          <div
            onClick={() => {
              setData({ ...data, termType: "30 day" });
            }}
          >
            <SelectCard
              id={1}
              selected={term}
              onSelect={setTerm}
              text=" term text 1"
            />
         </div>
          <div
            onClick={() => {
              setData({ ...data, termType: "90 day" });
            }}
          >
            <SelectCard
              id={2}
              selected={term}
              onSelect={setTerm}
              text="term text 2"
            />
          </div>
          <button onClick={() => setCurrent(2)}>Next</button>
            </div>
      );
    };
</code>```

SelectCard file , in this file I am using onSelect

```<code>   const SelectCard = ({ id, selected, onSelect, text }) => {
      const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (
        <div className={classNames(myClassName)} onClick={() => onSelect(id)}>
          <div> {text} </div>
        </div>
      );
     };
</code>```

Please help me to understand how can I fix this problem in my code.

Thanks.

答:
You are passing the following to Term.jsx:

```<code>    <Term
      setCurrent={setCurrent}
      data={data}
      selected={term}
      setSelected={setTerm}
    />
</code>```

but then in Term you get:

```<code>const Term = ({ setCurrent, data, setData, term, setTerm }) => {
</code>```

setTerm is undefined because you pass it under the name setSelected. So change App.jsx as such:

```<code>    <Term
      setCurrent={setCurrent}
      data={data}
      selected={term}
      setTerm={setTerm}
    />
</code>```

Body:
I have following code.

I'm trying to store a value in my state and every time the user goes to the previous step he can see what he has selected and after that he can change and move on to the next step.

At the first step, everything works good. For example, the user selects the second text and proceeds to the next step, and when he returns to this step, he sees that the second text has already been selected...

The problem is with the second step, I write all the same, but it doesn't work for the second step.

The error says onSelect is not a function in src/component/SelectCard.js. Please help me solve this problem.

Here is my code.

App file

 export default function App() {
     const [selected, setSelected] = useState(1);
     const [term, setTerm] = useState(1);

     const [current, setCurrent] = useState(0);

     const [data, setData] = useState({
       firstName: "bob",
       lastName: "Forest",
       age: 47
     });
      const steps = [
        {
          title: "Package Choose",
          content: (
            <PackageChoose
              setCurrent={setCurrent}
              data={data}
              setData={setData}
              selected={selected}
              setSelected={setSelected}
            />
         ),
          id: 0
        },
        {
          title: "Term",
          content: (
            <Term
              setCurrent={setCurrent}
              data={data}
              selected={term}
              setSelected={setTerm}
            />
          ),
          id: 1
        },
        {
          title: "Last step",
          content: <LastStep setCurrent={setCurrent} data={data} />,
          id: 2
        }
      ];
      return (

{steps[current].content}

      );
    }

first step package choose file

    const PackageChoose = ({
      setCurrent,
      data,
      setData,
      setSelected,
      selected
    }) => {
      return (

 {
              setData({ ...data, packageType: "choice" });
            }}
          >
            <SelectCard
              id={1}
              selected={selected}
              onSelect={setSelected}
              text="text 1"
            />

 {
              setData({ ...data, packageType: "select" });
            }}
          >
            <SelectCard
              id={2}
              selected={selected}
              onSelect={setSelected}
              text="text 2"
             />

          <button onClick={() => setCurrent(1)}>Next</button>

      );
   };

second step Term file

   const Term = ({ setCurrent, data, setData, term, setTerm }) => {
      return (

          <button onClick={() => setCurrent(0)}>Prev</button>

 {
              setData({ ...data, termType: "30 day" });
            }}
          >
            <SelectCard
              id={1}
              selected={term}
              onSelect={setTerm}
              text=" term text 1"
            />

 {
              setData({ ...data, termType: "90 day" });
            }}
          >
            <SelectCard
              id={2}
              selected={term}
              onSelect={setTerm}
              text="term text 2"
            />

          <button onClick={() => setCurrent(2)}>Next</button>

      );
    };

SelectCard file , in this file I am using onSelect

   const SelectCard = ({ id, selected, onSelect, text }) => {
      const myClassName =
        id === selected
          ? Styles.selectCardWrapperActives
          : Styles.selectCardWrapper;

      return (

 onSelect(id)}>

 {text}

      );
     };

Please help me to understand how can I fix this problem in my code.

Thanks.

Body:
You are passing the following to Term.jsx:

    <Term
      setCurrent={setCurrent}
      data={data}
      selected={term}
      setSelected={setTerm}
    />

but then in Term you get:

const Term = ({ setCurrent, data, setData, term, setTerm }) => {

setTerm is undefined because you pass it under the name setSelected. So change App.jsx as such:

    <Term
      setCurrent={setCurrent}
      data={data}
      selected={term}
      setTerm={setTerm}
    />


来源: stackexchange

问:
Characters appearing different from API
I am trying to work with the Amazon Associates API, but whenever trying to get the information of a product, the characters come out in a weird way.

Example

Text on the Amazon page:
 【23800 mAh

Output of the JSON from the API: ðŸ”¥ ã€23800 mAh

Just like this, more weird characters are appearing, such as a dash transformation in a question mark.

I've used a code snippet in PHP that was provided by them, which contained the following line which determined the charset:

$awsv4->addHeader('content-type', 'application/json; charset=utf-8');

Does anyone have a pointer where I might be going wrong here, and what I could do to fix this weird conversion?

答:
I don't get what you are actually going to do with this. Assuming you are going to keep this in a database I am going to give you a solution.

You said these characters are changing into those weird symbols. What happening here is those imojis/symbols are converting into a UTF-8 encoded data form. And that is why you are seeing those symbols which are pure UTF-8 form.

Now if you want to keep those data you have to keep that data into some kind of text encode. It doesn't have to UTF-8 only . There are many encodings available.

If you want to decode those you have to write them in a system where it can be shown normally. Like I have kept imojis in my database as UTF-8 many years ago. The mobile phone I was using, gave me encoding for one emoji. I saved it and next time when I am seeing the data with my PC browser I am seeing some other symbols. The decoding system must be installed when you want to see them next time.

The point is you can not save the data as you can see in the Amazon.

ContentLicense: CC BY-SA 4.0

Title: Characters appearing different from API


问:
Simple array rotation
I'm trying to solve a simple array problem and I have encountered some bug.

I input {1, 2, 3, 4, 5, 6} and rotate left by 2, it should give me {3, 4, 5, 6, 1, 2}

I cannot find a reason why it gives me {0, 0, 0, 0, 1, 2}
I think my code is correct. I do not like looking at answers but I looked it up but then I still don't see why it is giving me this wrong answer.

I've looked it through more than 1 hour and I still cannot figure it out so I joined this community. Please help me out...

```<code>public int[] rotate(int[] arr, int shift, int size) {
    int[] output = new int[size];
    for(int i = 0; i < output.length;i++) {
        int newIndex = (arr.length-shift+i) % arr.length;
        output[newIndex] = arr[i];
        }
    return output;
}
</code>```

My output:

答:
Your code works well and I see that the output array has the right result, however I suspect that you are not printing/processing this output array in the right direction. See this answer on how to print the array output.

Adding code here for your understanding.

```<code>import java.util.Arrays;
public class ProcessArrays{

 public static void main(String []args){
    int[] arr = {1,2,3,4,5,6};
    int[] output = rotate(arr, 2 , 6);
    System.out.println(Arrays.toString(output));
 }

public static int[] rotate(int[] arr, int shift, int size) {
    int[] output = new int[size];
    for(int i = 0; i < output.length;i++) {
        int newIndex = (arr.length-shift+i) % arr.length;
        output[newIndex] = arr[i];
        }
    return output;
}
}
</code>```

Title: Simple array rotation

Body:
I'm trying to solve a simple array problem and I have encountered some bug.

I input {1, 2, 3, 4, 5, 6} and rotate left by 2, it should give me {3, 4, 5, 6, 1, 2}

I cannot find a reason why it gives me {0, 0, 0, 0, 1, 2}
I think my code is correct. I do not like looking at answers but I looked it up but then I still don't see why it is giving me this wrong answer.

I've looked it through more than 1 hour and I still cannot figure it out so I joined this community. Please help me out...

public int[] rotate(int[] arr, int shift, int size) {
    int[] output = new int[size];
    for(int i = 0; i < output.length;i++) {
        int newIndex = (arr.length-shift+i) % arr.length;
        output[newIndex] = arr[i];
        }
    return output;
}

My output:

Body:
Your code works well and I see that the output array has the right result, however I suspect that you are not printing/processing this output array in the right direction. See this answer on how to print the array output.

Adding code here for your understanding.

import java.util.Arrays;
public class ProcessArrays{

 public static void main(String []args){
    int[] arr = {1,2,3,4,5,6};
    int[] output = rotate(arr, 2 , 6);
    System.out.println(Arrays.toString(output));
 }

public static int[] rotate(int[] arr, int shift, int size) {
    int[] output = new int[size];
    for(int i = 0; i < output.length;i++) {
        int newIndex = (arr.length-shift+i) % arr.length;
        output[newIndex] = arr[i];
        }
    return output;
}
}


问:
Replacing words inside the string with that of dictionary without using any kind of replace function

expected output = "Hello. My name is $xyz$. I am from $abc$.

# code
string = 'Hi. My name is #something1#. I am from #something2#. My company is #something3#.'
toReplace = {'something1':'xyz', 'something2': 'abc', 'something3': 'ttl'}
modified = list(string)
arr=[]
for i in range(len(string)):
    if string[i]=='#':
        arr.append(i)
#print(arr)

indices = []
for i in range(len(arr)):
    if i%2 != 0:
        continue
    else:
        indices.append(arr[i]+1)
#print(indices)

sources = []
l = 0
while l<len(arr):
    sources.append(string[arr[l]+1:arr[l+1]])
    #print(l, sources)
    l+=2
#print(sources)

targets = toReplace.values()
#print(targets)

for index, source, target in zip(indices, sources, targets):
    #print(index, source, target)
    if not string[index:].startswith(source):
        continue
    else:
        modified[index] = target
        #print(modified)
        for i in range(index+1,len(source)+index):
            modified[i] = ''

print("".join(modified))```

should get this without using replace() or re.replace() functions. it should not remove placeholders. only word inside dictionary to be replace but to be done without replace functions. Any ideas??

答:
you're there. I'd suggest if instead of listing all characters in the sentence you can split() it with # delimiter, the solution becomes a lot simpler.

'$'.join([toReplace[k] if k in toReplace.keys() else k for k in string.split('#')])
# 'Hi. My name is $xyz$. I am from $abc$. My company is $ttl$.'
```

string.split('#') will generate a list of strings, broken at every '#'

The list comprehension will search for the list's strings in the dict's keys, and if found, it will pull the item from the dictionary

The resulting list after the comprehension can then be joined using the '#' delimiter as it was split. You could also update the join string to be '$'.

Body:
expected output = "Hello. My name is $xyz$. I am from $abc$.

# code
string = 'Hi. My name is #something1#. I am from #something2#. My company is #something3#.'
toReplace = {'something1':'xyz', 'something2': 'abc', 'something3': 'ttl'}
modified = list(string)
arr=[]
for i in range(len(string)):
    if string[i]=='#':
        arr.append(i)
#print(arr)

indices = []
for i in range(len(arr)):
    if i%2 != 0:
        continue
    else:
        indices.append(arr[i]+1)
#print(indices)

sources = []
l = 0
while l<len(arr):
    sources.append(string[arr[l]+1:arr[l+1]])
    #print(l, sources)
    l+=2
#print(sources)

targets = toReplace.values()
#print(targets)

for index, source, target in zip(indices, sources, targets):
    #print(index, source, target)
    if not string[index:].startswith(source):
        continue
    else:
        modified[index] = target
        #print(modified)
        for i in range(index+1,len(source)+index):
            modified[i] = ''

print("".join(modified))

should get this without using replace() or re.replace() functions. it should not remove placeholders. only word inside dictionary to be replace but to be done without replace functions. Any ideas??

Body:
you're there. I'd suggest if instead of listing all characters in the sentence you can split() it with # delimiter, the solution becomes a lot simpler.

'$'.join([toReplace[k] if k in toReplace.keys() else k for k in string.split('#')])
# 'Hi. My name is $xyz$. I am from $abc$. My company is $ttl$.'

string.split('#') will generate a list of strings, broken at every '#'

The list comprehension will search for the list's strings in the dict's keys, and if found, it will pull the item from the dictionary

The resulting list after the comprehension can then be joined using the '#' delimiter as it was split. You could also update the join string to be '$'.


问:
Get error swagger when change method private to public
This is my code in UserController and it runs well.

```<code>private Identifier GetCurrentUser()
        {
            var identity = HttpContext.User.Identity as ClaimsIdentity;
            if (identity != null)
            {
                var userClaims = identity.Claims;
                return new Identifier
                {
                    Id = userClaims.FirstOrDefault(o => o.Type == ClaimTypes.NameIdentifier)?.Value,
                    Role = userClaims.FirstOrDefault(o => o.Type == ClaimTypes.Role)?.Value,
                };
            }
            return null;
        }
</code>```

However when I change this method from private to public I got this error with swagger.

I do not understand why I get this error. Please tell me the reason and teach me how to fix it. Thank for your attention

答:
Like it has been pointed out in the comment, you have conflicting route names with api/GetUsers/{search} and api/GetUsers/{id}. It becomes difficult for the compiler to figure out which one you really want to use.

I recommend you change the GetUserById action method to this form so there's a distinction between the two routes.

```<code>[HttpGet("\GetUser\{id}")]
[Authorize(Roles = "Administrator,Staff")]
public IActionResult GetUser(string id)
</code>```

Alternatively you could place the search term for GetUsers in the same class as the paginationFilter like this

```<code>public class SearchAndPagination
{
    public PaginationFilter paginationFilter {get;set;}
    public string search {get;set;}
}
</code>```

Then pass as request body to GetUsers action

```<code>[HttpGet]
[Authorize(Roles = "Administrator,Staff")]
public IActionResult GetUsers([FromBody] SearchAndPagination paginationFilter)
{
    var users = _userRepository.GetUsers(paginationFilter.paginationFilter, paginationFilter.search);
    ...
}
</code>```

Body:
This is my code in UserController and it runs well.

private Identifier GetCurrentUser()
        {
            var identity = HttpContext.User.Identity as ClaimsIdentity;
            if (identity != null)
            {
                var userClaims = identity.Claims;
                return new Identifier
                {
                    Id = userClaims.FirstOrDefault(o => o.Type == ClaimTypes.NameIdentifier)?.Value,
                    Role = userClaims.FirstOrDefault(o => o.Type == ClaimTypes.Role)?.Value,
                };
            }
            return null;
        }

However when I change this method from private to public I got this error with swagger.

I do not understand why I get this error. Please tell me the reason and teach me how to fix it. Thank for your attention

Body:
Like it has been pointed out in the comment, you have conflicting route names with api/GetUsers/{search} and api/GetUsers/{id}. It becomes difficult for the compiler to figure out which one you really want to use.

I recommend you change the GetUserById action method to this form so there's a distinction between the two routes.

[HttpGet("\GetUser\{id}")]
[Authorize(Roles = "Administrator,Staff")]
public IActionResult GetUser(string id)

Alternatively you could place the search term for GetUsers in the same class as the paginationFilter like this

public class SearchAndPagination
{
    public PaginationFilter paginationFilter {get;set;}
    public string search {get;set;}
}

Then pass as request body to GetUsers action

[HttpGet]
[Authorize(Roles = "Administrator,Staff")]
public IActionResult GetUsers([FromBody] SearchAndPagination paginationFilter)
{
    var users = _userRepository.GetUsers(paginationFilter.paginationFilter, paginationFilter.search);
    ...
}


问:
Spring Cloud Stream - Testing consuming from and producing into a shared topic
I have been trying to implement the following solution:

My application is expecting to consume message A from all-messages, do some business logic and then producing
message B back into all-messages.

The reason why I am using StreamBridge instead of a Function is because I want the producing side to work with an arbitrary
number of produced messages, but for the sake of this example I am trying to simplify the scenario to just one.

Additionally, there is a custom router function in order to avoid an infinite loop, that dispatch the incoming messages
into the appropriate consumer, either incoming or discarded, would be great to have a way to effectively discard messages.

That being said I cannot quite get the implementation right using Spring Cloud Stream.

I'd like your help to understand what am I doing wrong and how to fix the current configure/setup in order to make the solution work as expected, specifically:

Is this solution supported by Spring cloud stream?

Is my application configuration correctly implementing the solution diagram above?

Which bindings exactly should I use inside the app when sending/receiving messages?

The major headache comes from the bindings, so I tried to write a test with different combinations of incoming and outgoing bindings to see what is what, something along these lines:

class ScsProblemTests {

    /* ... */

    @ParameterizedTest
    @MethodSource("bindings")
    void consumeFromAndProduceIntoSharedTopic(String incomingBinding, String outgoingBinding) {
        givenNoOutgoingMessages();
        whenAnIncomingMessageArrives(incomingBinding);
        thenEventuallyAnOutgoingMessageIsProduced(outgoingBinding);
    }

    public static Stream<Arguments> bindings() {
        return Stream.of(
            Arguments.of(null, null),
            Arguments.of(null, "outgoing-out-0"),
            Arguments.of(null, "all-messages"),
            Arguments.of("incoming-in-0", null),
            Arguments.of("incoming-in-0", "outgoing-out-0"),
            Arguments.of("incoming-in-0", "all-messages"),
            Arguments.of("all-messages", null),
            Arguments.of("all-messages", "outgoing-out-0"),
            Arguments.of("all-messages", "all-messages")
        );
    }

    /* ... */
}
```

I am running this set of tests with a overrides spring profile, where I setup the destination overrides as per the diagram, I am also testing the same set with a different spring profile with no overrides, again just for having a control group to compare with. Only 2 tests from the no-overrides profile pass, the rest fails.

The no-overrides profile does not match the design obviously, but I was curious to see how the overrides where affecting the results, specifically the no-overrides tests that passes are the one where:

incomingBinding=null, outgoingBinding=null

incomingBinding=null, outgoingBinding=outgoing-out-0

And for my understanding of Spring Cloud Stream, even in this no-overrides case, I'd expect also the following to pass (the are not):

incomingBinding=incoming-in-0, outgoingBinding=null

incomingBinding=incoming-in-0, outgoingBinding=outgoing-out-0

At this point I am starting to think I misunderstood some concepts behind Spring Cloud Stream, but I really hope
you can provide some useful advise.

I have shared my code into this repository for convenience.

Thanks in advance.

答:
It seems to me you are reusing the same queue for different type of messages which forces you to introduce the routing. Further more, the two functions appear to exist in the same runtime space, so why not just pass-by-reference (invoke one function from another), why do you need to introduce networking.

I don't know your use case, hence can only comment on what i see, but it appears there is a design issue here. Perhaps if you actually share the use case we can help with the appropriate solution.

Body:
I have been trying to implement the following solution:

My application is expecting to consume message A from all-messages, do some business logic and then producing
message B back into all-messages.

The reason why I am using StreamBridge instead of a Function is because I want the producing side to work with an arbitrary
number of produced messages, but for the sake of this example I am trying to simplify the scenario to just one.

Additionally, there is a custom router function in order to avoid an infinite loop, that dispatch the incoming messages
into the appropriate consumer, either incoming or discarded, would be great to have a way to effectively discard messages.

That being said I cannot quite get the implementation right using Spring Cloud Stream.

I'd like your help to understand what am I doing wrong and how to fix the current configure/setup in order to make the solution work as expected, specifically:

Is this solution supported by Spring cloud stream?

Is my application configuration correctly implementing the solution diagram above?

Which bindings exactly should I use inside the app when sending/receiving messages?

The major headache comes from the bindings, so I tried to write a test with different combinations of incoming and outgoing bindings to see what is what, something along these lines:

class ScsProblemTests {

    /* ... */

    @ParameterizedTest
    @MethodSource("bindings")
    void consumeFromAndProduceIntoSharedTopic(String incomingBinding, String outgoingBinding) {
        givenNoOutgoingMessages();
        whenAnIncomingMessageArrives(incomingBinding);
        thenEventuallyAnOutgoingMessageIsProduced(outgoingBinding);
    }

    public static Stream<Arguments> bindings() {
        return Stream.of(
            Arguments.of(null, null),
            Arguments.of(null, "outgoing-out-0"),
            Arguments.of(null, "all-messages"),
            Arguments.of("incoming-in-0", null),
            Arguments.of("incoming-in-0", "outgoing-out-0"),
            Arguments.of("incoming-in-0", "all-messages"),
            Arguments.of("all-messages", null),
            Arguments.of("all-messages", "outgoing-out-0"),
            Arguments.of("all-messages", "all-messages")
        );
    }

    /* ... */
}

I am running this set of tests with a overrides spring profile, where I setup the destination overrides as per the diagram, I am also testing the same set with a different spring profile with no overrides, again just for having a control group to compare with. Only 2 tests from the no-overrides profile pass, the rest fails.

The no-overrides profile does not match the design obviously, but I was curious to see how the overrides where affecting the results, specifically the no-overrides tests that passes are the one where:

incomingBinding=null, outgoingBinding=null

incomingBinding=null, outgoingBinding=outgoing-out-0

And for my understanding of Spring Cloud Stream, even in this no-overrides case, I'd expect also the following to pass (the are not):

incomingBinding=incoming-in-0, outgoingBinding=null

incomingBinding=incoming-in-0, outgoingBinding=outgoing-out-0

At this point I am starting to think I misunderstood some concepts behind Spring Cloud Stream, but I really hope
you can provide some useful advise.

I have shared my code into this repository for convenience.

Thanks in advance.


问:
How to handle null and NULL value in sql
So I have been facing this weird situation in mysql where somehow null values are inserted in my table.
I'm talking about null value not NULL value.

I have attached image for better understating

as you can see name column have null and mobile_no have NULL

So after using this query

```<code>select Case when t1.name IS NULL then 'NA'
            when t1.name= 'NA' or 'null' or NULL then 'NA'
            else t1.name end as 'Name',
       Case when t1.mobile_no IS NULL then 'NA'
            when t1.mobile_no= 'NA' or 'null' or NULL then 'NA'
            else t1.mobile_noend as 'Mobile no' from student;
</code>```

after this I'm getting this result

```<code>|Name|Mobile no|
----------------
|null|NA       |
</code>```

but I want below result

```<code>|Name|Mobile no|
----------------
|NA  |NA       |
</code>```

答:
To compare a column with multiple values use col IN (x, y, z), not col = x OR y OR z.

You also can't compare with NULL using = or IN, so that has to be a separate check.

```<code>select
    Case
        when t1.name IS NULL OR t1.name IN ('NA' or 'null') then 'NA'
        else t1.name
    end as 'Name'
</code>```

Body:
So I have been facing this weird situation in mysql where somehow null values are inserted in my table.
I'm talking about null value not NULL value.

I have attached image for better understating

as you can see name column have null and mobile_no have NULL

So after using this query

select Case when t1.name IS NULL then 'NA'
            when t1.name= 'NA' or 'null' or NULL then 'NA'
            else t1.name end as 'Name',
       Case when t1.mobile_no IS NULL then 'NA'
            when t1.mobile_no= 'NA' or 'null' or NULL then 'NA'
            else t1.mobile_noend as 'Mobile no' from student;

after this I'm getting this result

|Name|Mobile no|
----------------
|null|NA       |

but I want below result

|Name|Mobile no|
----------------
|NA  |NA       |

Body:
To compare a column with multiple values use col IN (x, y, z), not col = x OR y OR z.

You also can't compare with NULL using = or IN, so that has to be a separate check.

select
    Case
        when t1.name IS NULL OR t1.name IN ('NA' or 'null') then 'NA'
        else t1.name
    end as 'Name'


问:
Too many mysql db call issue with spring boot rest service
I am developing one rest application with spring boot and mysql. Currently I am still in development phase, hence I have not enabled any caching as such. I future as the load increases, I will use memcached(as we already use memcached for other apps in our org) or redis to cache the resulsts of db queries.
Right now I have not even enabled hibernate second level caching, so I am seeing too many db calls.
I would like to enable caching preferably ehcache to reduce the db calls.

Mine is a rest api, currently we are running it in 3 pods in aws.

What sort of caching should I enable (not memcached or redis)

Spring cache (ehcache)

Hibernate second level cache

My main objective right now is to reduce number of db calls.

should I use only hibernate second level cache or spring cache ?

Here is my default configs:

```<code>  jpa:
    open-in-view: false
    properties:
      hibernate.jdbc.time_zone: UTC
      hibernate.id.new_generator_mappings: true
      hibernate.connection.provider_disables_autocommit: true
      hibernate.cache.use_second_level_cache: false
      hibernate.cache.use_query_cache: true
      hibernate.generate_statistics: false
      # modify batch size as necessary
      hibernate.jdbc.batch_size: 25
      hibernate.order_inserts: true
      hibernate.order_updates: true
      hibernate.query.fail_on_pagination_over_collection_fetch: true
      hibernate.query.in_clause_parameter_padding: true
      hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
      spring.jpa.show-sql: true
</code>```

答:
It depends on your needs, if you want to cache an entity that is often accessed by your unique identifier (EntityManager.find()) and rarely edited, I think that it is a good candidate for L2C.

I tend to use Spring Cache when I build responses from other long service calls or projections from DB.

By the way you will need an implementation for L2C too (which can be EhCache).

Body:
I am developing one rest application with spring boot and mysql. Currently I am still in development phase, hence I have not enabled any caching as such. I future as the load increases, I will use memcached(as we already use memcached for other apps in our org) or redis to cache the resulsts of db queries.
Right now I have not even enabled hibernate second level caching, so I am seeing too many db calls.
I would like to enable caching preferably ehcache to reduce the db calls.

Mine is a rest api, currently we are running it in 3 pods in aws.

What sort of caching should I enable (not memcached or redis)

Spring cache (ehcache)

Hibernate second level cache

My main objective right now is to reduce number of db calls.

should I use only hibernate second level cache or spring cache ?

Here is my default configs:

  jpa:
    open-in-view: false
    properties:
      hibernate.jdbc.time_zone: UTC
      hibernate.id.new_generator_mappings: true
      hibernate.connection.provider_disables_autocommit: true
      hibernate.cache.use_second_level_cache: false
      hibernate.cache.use_query_cache: true
      hibernate.generate_statistics: false
      # modify batch size as necessary
      hibernate.jdbc.batch_size: 25
      hibernate.order_inserts: true
      hibernate.order_updates: true
      hibernate.query.fail_on_pagination_over_collection_fetch: true
      hibernate.query.in_clause_parameter_padding: true
      hibernate.dialect: org.hibernate.dialect.MySQL5Dialect
      spring.jpa.show-sql: true


问:
MongoDB Charts - Cumulative document growth over time
I have an atlas cluster and I connected charts to it. I have zero experience with data visualizations (or building dashboards) and I'd like to chart the number of documents in my database over time. E.g., if in January 10 documents were created, and in February another 10 were created, then the chart should display 10 for January and 20 for February.

I know the _id field has information when the document was created, but I have no idea how to display it in the chart. So far, all I have is document count using _id in the y-axis.

What is the best way to accomplish what I'm trying to do? Is using a bar chart the best visualization to use in this situation?

Also, for some reason whenever I'm creating a chart, I get alerts saying "Query Targeting: Scanned Objects / Returned has gone above 1000". Is there any way to stop this for happening?

答:
There are 2 parts to the question. I will answer each of them independently.

First Regarding Displaying The Cart

You are right that _id has all the information, it is encoded. So you will have to decode it to fetch those attributes. This might get very complicated very soon given we have to perform this in an aggregation pipeline.

I would rather recommend introducing a field called created_at which would be the timestamp generated when the document is inserted. Then all you need is a simple $group on created_at with count. And that would display data just fine (Bar Graph or Line Graph should suffice in the case).

Second - The alert received from Atlas regarding Query Targeting Ratio

We first need to understand what that Alert means. It essentially means that the ratio of no. of documents being scanned from the disk vs no. of documents returned from the disk is  going beyond 1000. This means you are scanning more than 1000 times extra records in the disk than you are required to - which can be interpreted as a poorly indexed query.

You can simply fix this by creating a supportive index for the $match filter you are using in the aggregation. If there is no $match then unfortunately you will have to live with the alert as no indexed will be picked in that case.


答:
Welcome to Stackoverflow and I think most likely there is something wrong with your output code.

Below is my test code:

```<code>public class Test {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6};
        int[] rotate = rotate(a, 2, 6);
        System.out.println(Arrays.toString(rotate));
    }

    public static int[] rotate(int[] arr, int shift, int size) {
        int[] output = new int[size];
        for (int i = 0; i < output.length; i++) {
            int newIndex = (arr.length - shift + i) % arr.length;
            output[newIndex] = arr[i];
        }
        return output;
    }
}
</code>```

Console output:

```<code>[3, 4, 5, 6, 1, 2]
</code>```

Title: Simple array rotation

Body:
Welcome to Stackoverflow and I think most likely there is something wrong with your output code.

Below is my test code:

public class Test {
    public static void main(String[] args) {
        int[] a = {1, 2, 3, 4, 5, 6};
        int[] rotate = rotate(a, 2, 6);
        System.out.println(Arrays.toString(rotate));
    }

    public static int[] rotate(int[] arr, int shift, int size) {
        int[] output = new int[size];
        for (int i = 0; i < output.length; i++) {
            int newIndex = (arr.length - shift + i) % arr.length;
            output[newIndex] = arr[i];
        }
        return output;
    }
}

Console output:

[3, 4, 5, 6, 1, 2]


问:
JAVA ThreadPoolExecutor workqueue with Callable
Java ExecutorService.newFixedThreadPool() internally using a LinkedBlockingQueue<Runnable>() as below:

```<code>public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}
</code>```

I am wondering when I call ExecutorService.submit(Callable<?>) with callable, how it is pushed into workQueue. As per docs, only Runnable are pushed to workQueue, then what happens to Callable when all threads are busy. Where these are kept for later processing.

As per docs

workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.

答: I believe that the callable is wrapped in a runnable when it is enqueued. Callables are definitely enqueue the same as runnables when all the workers are busy.</p>

Body:
Java ExecutorService.newFixedThreadPool() internally using a LinkedBlockingQueue<Runnable>() as below:

public static ExecutorService newFixedThreadPool(int nThreads) {
    return new ThreadPoolExecutor(nThreads, nThreads,
                                  0L, TimeUnit.MILLISECONDS,
                                  new LinkedBlockingQueue<Runnable>());
}

I am wondering when I call ExecutorService.submit(Callable<?>) with callable, how it is pushed into workQueue. As per docs, only Runnable are pushed to workQueue, then what happens to Callable when all threads are busy. Where these are kept for later processing.

As per docs

workQueue - the queue to use for holding tasks before they are executed. This queue will hold only the Runnable tasks submitted by the execute method.


问:
ImproperlyConfiguredError about app_name when using namespace in include()
I am currently trying out Django. I use the namespace argument in one of my include()s in urls.py. When I run the server and try to browse,
I get this error.

```<code>File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 39, in include
    'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.
</code>```

These are my urls.py files:

```<code>#project/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^reviews/', include('reviews.urls', namespace='reviews')),
    url(r'^admin/', include(admin.site.urls)),
]
</code>```

and

```<code>#app/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    # ex: /
    url(r'^$', views.review_list, name='review_list'),
    # ex: /review/5/
    url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),
    # ex: /wine/
    url(r'^wine$', views.wine_list, name='wine_list'),
    # ex: /wine/5/
    url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'),
]
</code>```

What do I pass the app_name as stated in the error message?

答:
In project level urls.py

```<code>path('',include('appname.urls'), namespace= 'test')
</code>```

Now in in your app level urls.py

```<code>app_name = 'test'
path('',views.index, name= 'home')
</code>```

Long story short is, You have to provide "app_name" in your app level urls and that same name should be your namespace name at project level url

Body:
I am currently trying out Django. I use the namespace argument in one of my include()s in urls.py. When I run the server and try to browse,
I get this error.

File "C:\Users\User\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\urls\conf.py", line 39, in include
    'Specifying a namespace in include() without providing an app_name '
django.core.exceptions.ImproperlyConfigured: Specifying a namespace in include() without providing an app_name is not supported. Set the app_name attribute in the included module, or pass a 2-tuple containing the list of patterns and app_name instead.

These are my urls.py files:

#project/urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^reviews/', include('reviews.urls', namespace='reviews')),
    url(r'^admin/', include(admin.site.urls)),
]

and

#app/urls.py

from django.conf.urls import url

from . import views

urlpatterns = [
    # ex: /
    url(r'^$', views.review_list, name='review_list'),
    # ex: /review/5/
    url(r'^review/(?P<review_id>[0-9]+)/$', views.review_detail, name='review_detail'),
    # ex: /wine/
    url(r'^wine$', views.wine_list, name='wine_list'),
    # ex: /wine/5/
    url(r'^wine/(?P<wine_id>[0-9]+)/$', views.wine_detail, name='wine_detail'),
]

What do I pass the app_name as stated in the error message?

Body:
In project level urls.py

path('',include('appname.urls'), namespace= 'test')

Now in in your app level urls.py

app_name = 'test'
path('',views.index, name= 'home')

Long story short is, You have to provide "app_name" in your app level urls and that same name should be your namespace name at project level url


问:
Why is there only a static/shared version of ForEach for arrays?
Could someone please be kind enough to explain why there is only a static/shared version of ForEach for arrays?

```<code>IE: ForEach<T>(T array[], System.Action(Of T) action[])
</code>```

I assume this has something to do with the type inference requirements of implementing an instance method, but when you declare your array you provide type right?

答:
One problem with arrays is that there's nowhere to document the instance methods which are available only on "vectors". A "vector" is a single-dimensional array with a base of 0 - so anything representable as T[] in C# is a vector, but a T[,] isn't, for example.

That means not every instance of Array should have the method - and even if it did, how would you represent the T? Each array type is separate, and there's no generic type in .NET which is a base class for all arrays. All we've got is Array.

So, given that we have to introduce the type parameter somewhere in the type system, and given that we're also restricting it to "vector" types, a static method seems an appropriate workaround.

Note how this is not the case with List<T>, where we already have the type parameter so can create a simple instance method.

It's also worth thinking about when using Array.ForEach actually ends up with cleaner code than just using a foreach loop. I would typically only use it when I'd already got a delegate to execute on each element. Otherwise the language construct feels cleaner, and it certainly more flexible in its ability to return or break out of the loop without an exception.

ContentLicense: CC BY-SA 3.0

Body:
Could someone please be kind enough to explain why there is only a static/shared version of ForEach for arrays?

IE: ForEach<T>(T array[], System.Action(Of T) action[])

I assume this has something to do with the type inference requirements of implementing an instance method, but when you declare your array you provide type right?


问:
what is the character code for ♥ and how to use it?
im creating a emoticon js script and i cant seem to get the character code for ♥ to work ive tried ♥ as the character code but dosen't work any help would be help ful

my script

```<code>jQuery.fn.emotion_func = function(icon_folder) {
var emotion_locate =  "emotions";
var key_stroke = { ....
         "heart": Array("♥")//it dosent work
                   ....
             };

function emotion_func(html){
for(var emotion in key_stroke){
    for(var i = 0; i < key_stroke[emotion].length; i++){
        var key = new RegExp(key_stroke[emotion][i],"g");//replace all occurenced
        html = html.replace(key,"<span style=\"background-image:url("+emotion_locate+"/"+emotion+".png); \" title="+emotion+" /></span>");
                }
            }
            return html;
        }
        return this.each(function(){
            $(this).html(emotion_func($(this).html()));
        });
    };
</code>```

Any Help would be appreciated

Also note that im using html 5

Sorry but only @hwnd's answer worked for me

答:
Red Heart Symbol Hex Code

If you want to use red heart variant you have to use two unicodes:

U+2764 - stands for heavy black heart

U+FE0F - is a variation selector

To insert ❤ symbol in html type it's hexcode

❤

Body:
im creating a emoticon js script and i cant seem to get the character code for ♥ to work ive tried ♥ as the character code but dosen't work any help would be help ful

my script

jQuery.fn.emotion_func = function(icon_folder) {
var emotion_locate =  "emotions";
var key_stroke = { ....
         "heart": Array("♥")//it dosent work
                   ....
             };

function emotion_func(html){
for(var emotion in key_stroke){
    for(var i = 0; i < key_stroke[emotion].length; i++){
        var key = new RegExp(key_stroke[emotion][i],"g");//replace all occurenced
        html = html.replace(key,"");
                }
            }
            return html;
        }
        return this.each(function(){
            $(this).html(emotion_func($(this).html()));
        });
    };

Any Help would be appreciated

Also note that im using html 5

Sorry but only @hwnd's answer worked for me

Body:
Red Heart Symbol Hex Code

If you want to use red heart variant you have to use two unicodes:

U+2764 - stands for heavy black heart

U+FE0F - is a variation selector

To insert ❤ symbol in html type it's hexcode
<p>&#x2764;&#xFE0F;</p>


问:
How plot and symbolize only selected columns from csv in plotting in d3?
How I can apply the same symbol format I have for Catan on Dominion too?
And also only keep Catan, Dixit and Dominion and dnt display the rest of them? I need to load and read all data because I would need them later but for this graph I need to only show three columns.
I have code snippets that I thought were relevant:

```<code>//-----------------------------DATA-----------------------------//
const timeConv = d3.timeParse("%m-%d-%Y");
const dataset = d3.csv("ratings.csv");

    dataset.then(function(data) {
        var slices = data.columns.slice(1).map(function(id) {
            return {
                id: id,
                values: data.map(function(d){
                    return {
                        date: timeConv(d.date),
                        measurement: +d[id]
                    };
                })
            };
        });

//----------------------------LINES-----------------------------//
const line = d3.line()
    .x(function(d) { return xScale(d.date); })
    .y(function(d) { return yScale(d.measurement); });

let id = 0;
const ids = function () {
    return "line-"+id++;
}

    //----------------------------LINES-----------------------------//
    const lines = svg.selectAll("lines")
        .data(slices)
        .enter()
        .append("g");

        lines.append("path")
        .attr("class", ids)
        .attr("d", function(d) { return line(d.values); });

        lines.append("text")
        .attr("class","serie_label")
        .datum(function(d) {
            return {
                id: d.id,
                value: d.values[d.values.length - 1]}; })
        .attr("transform", function(d) {
                return "translate(" + (xScale(d.value.date) + 10)
                + "," + (yScale(d.value.measurement) + 5 ) + ")"; })
        .attr("x", 5)
        .text(function(d) { return  d.id; });

//----------------------------Symbols-----------------------------//
    svg.selectAll("myDots")
      .data(slices)
      .enter()
        .append('g')
        .style("fill", "white")
      // Second we need to enter in the 'values' part of this group
      .selectAll("myPoints")
      .data(function(d){ return slices[0].values.filter(function(d,i) { return i%3 == 2})})
      .enter()
      .append("circle")
      .attr("class", ids)
        .attr("cx", function(d) { return xScale(d.date) } )
        .attr("cy", function(d) { return yScale(d.measurement);})
        .attr("r", 15)
        .attr("stroke", "black")
</code>```

this is the graph I have now:

and data sample:

```<code>date    Catan   Dominion    Codenames   Terraforming    Magic   Dixit
11/1/2016   213 46  20  69  138 141
12/1/2016   216 47  20  28  138 143
1/1/2017    219 50  20  24  141 146
2/1/2017    224 52  22  19  143 151
3/1/2017    226 54  22  17  144 155
4/1/2017    230 55  24  13  144 157
5/1/2017    234 55  28  9   145 158
6/1/2017    236 55  32  8   147 159
7/1/2017    239 55  32  8   145 160
8/1/2017    245 57  33  7   146 163
9/1/2017    250 57  34  7   149 166
10/1/2017   251 58  36  7   150 169
11/1/2017   255 60  36  6   151 170
12/1/2017   264 61  35  6   150 171
1/1/2018    270 61  36  6   152 173
2/1/2018    274 65  39  5   154 182

</code>```

答:
Map the data to filter out columns not included in keys:

```<code>d3.csv("ratings.csv").then(data => {
  const keys = ['date', 'Dixit', 'Dominion'];
  const filteredData = data.map(item =>
    keys.reduce((obj, key) => ({...obj, [key]: item[key]}), {}));
  ...
});
</code>```

Body:
How I can apply the same symbol format I have for Catan on Dominion too?
And also only keep Catan, Dixit and Dominion and dnt display the rest of them? I need to load and read all data because I would need them later but for this graph I need to only show three columns.
I have code snippets that I thought were relevant:

//-----------------------------DATA-----------------------------//
const timeConv = d3.timeParse("%m-%d-%Y");
const dataset = d3.csv("ratings.csv");

    dataset.then(function(data) {
        var slices = data.columns.slice(1).map(function(id) {
            return {
                id: id,
                values: data.map(function(d){
                    return {
                        date: timeConv(d.date),
                        measurement: +d[id]
                    };
                })
            };
        });

//----------------------------LINES-----------------------------//
const line = d3.line()
    .x(function(d) { return xScale(d.date); })
    .y(function(d) { return yScale(d.measurement); });

let id = 0;
const ids = function () {
    return "line-"+id++;
}

    //----------------------------LINES-----------------------------//
    const lines = svg.selectAll("lines")
        .data(slices)
        .enter()
        .append("g");

        lines.append("path")
        .attr("class", ids)
        .attr("d", function(d) { return line(d.values); });

        lines.append("text")
        .attr("class","serie_label")
        .datum(function(d) {
            return {
                id: d.id,
                value: d.values[d.values.length - 1]}; })
        .attr("transform", function(d) {
                return "translate(" + (xScale(d.value.date) + 10)
                + "," + (yScale(d.value.measurement) + 5 ) + ")"; })
        .attr("x", 5)
        .text(function(d) { return  d.id; });

//----------------------------Symbols-----------------------------//
    svg.selectAll("myDots")
      .data(slices)
      .enter()
        .append('g')
        .style("fill", "white")
      // Second we need to enter in the 'values' part of this group
      .selectAll("myPoints")
      .data(function(d){ return slices[0].values.filter(function(d,i) { return i%3 == 2})})
      .enter()
      .append("circle")
      .attr("class", ids)
        .attr("cx", function(d) { return xScale(d.date) } )
        .attr("cy", function(d) { return yScale(d.measurement);})
        .attr("r", 15)
        .attr("stroke", "black")

this is the graph I have now:

and data sample:

date    Catan   Dominion    Codenames   Terraforming    Magic   Dixit
11/1/2016   213 46  20  69  138 141
12/1/2016   216 47  20  28  138 143
1/1/2017    219 50  20  24  141 146
2/1/2017    224 52  22  19  143 151
3/1/2017    226 54  22  17  144 155
4/1/2017    230 55  24  13  144 157
5/1/2017    234 55  28  9   145 158
6/1/2017    236 55  32  8   147 159
7/1/2017    239 55  32  8   145 160
8/1/2017    245 57  33  7   146 163
9/1/2017    250 57  34  7   149 166
10/1/2017   251 58  36  7   150 169
11/1/2017   255 60  36  6   151 170
12/1/2017   264 61  35  6   150 171
1/1/2018    270 61  36  6   152 173
2/1/2018    274 65  39  5   154 182

Body:
Map the data to filter out columns not included in keys:

d3.csv("ratings.csv").then(data => {
  const keys = ['date', 'Dixit', 'Dominion'];
  const filteredData = data.map(item =>
    keys.reduce((obj, key) => ({...obj, [key]: item[key]}), {}));
  ...
});


问:
Monitor connectivity in a Sesam instance
We need to monitor connectivity of some systems to help figure out when and where outages occur, to help debug network and VPN issues.

What would a good approach to this be?

答:
You can do this using Sesams rest API and query sesam itself, when checking the network status it will attempt to create a network socket to the system and give back the status.

System config:

```<code>{
  "_id": "system-monitor",
  "type": "system:rest",
  "authentication": "jwt",
  "jwt_token": "$SECRET(jwt_token)",
  "operations": {
    "get": {
      "headers": {
        "Content-type": "application/xml"
      },
      "method": "GET",
      "payload-type": "json",
      "url": "systems/{{ _id }}/status"
    }
  },
  "rate_limiting_retries": 1000,
  "url_pattern": "https://datahub-83ac2aaa.sesam.cloud/api/%s",
  "verify_ssl": true
}
</code>```

Pipe config:

```<code>{
  "_id": "system-monitor-list",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "github-url"
    }, {
      "_id": "zoho-rest"
    }]
  },
  "transform": [{
    "type": "rest",
    "system": "system-monitor",
    "operation": "get"
  }, {
    "type": "dtl",
    "rules": {
      "default": [
        ["add", "_id", "_S._id"],
        ["add", "ts",
          ["now"]
        ],
        ["copy", "*"]
      ]
    }
  }],
  "pump": {
    "cron_expression": "*/15 * * * ?"
  },
  "compaction": {
    "keep_versions": 100
  }
}
</code>```

Body:
You can do this using Sesams rest API and query sesam itself, when checking the network status it will attempt to create a network socket to the system and give back the status.

System config:

{
  "_id": "system-monitor",
  "type": "system:rest",
  "authentication": "jwt",
  "jwt_token": "$SECRET(jwt_token)",
  "operations": {
    "get": {
      "headers": {
        "Content-type": "application/xml"
      },
      "method": "GET",
      "payload-type": "json",
      "url": "systems/{{ _id }}/status"
    }
  },
  "rate_limiting_retries": 1000,
  "url_pattern": "https://datahub-83ac2aaa.sesam.cloud/api/%s",
  "verify_ssl": true
}

Pipe config:

{
  "_id": "system-monitor-list",
  "type": "pipe",
  "source": {
    "type": "embedded",
    "entities": [{
      "_id": "github-url"
    }, {
      "_id": "zoho-rest"
    }]
  },
  "transform": [{
    "type": "rest",
    "system": "system-monitor",
    "operation": "get"
  }, {
    "type": "dtl",
    "rules": {
      "default": [
        ["add", "_id", "_S._id"],
        ["add", "ts",
          ["now"]
        ],
        ["copy", "*"]
      ]
    }
  }],
  "pump": {
    "cron_expression": "*/15 * * * ?"
  },
  "compaction": {
    "keep_versions": 100
  }
}


问:
How to check certificate revocation status in c#?
The certificate should be revoked if exists in the revocation list. There is an option in .net by which you'll be able to check the certificate revocation. I need to explore my certificate in the revocation list and revoke it, it exists in the revocation list. Therefore, I use the below one-line code to do that:

```<code>ServicePointManager.CheckCertificateRevocationList = true;
</code>```

The problem is that the above code does not work properly. I mean certificate revocation will never be checked. For example, If I revoke the certificate manually certificate is still working. Is there any help?

答:
You can use X509Certificate2.Verify as described here:

X509Certificate2.Verify

You can load your certificate and verify it by calling the verify method.

Body:
The certificate should be revoked if exists in the revocation list. There is an option in .net by which you'll be able to check the certificate revocation. I need to explore my certificate in the revocation list and revoke it, it exists in the revocation list. Therefore, I use the below one-line code to do that:

ServicePointManager.CheckCertificateRevocationList = true;

The problem is that the above code does not work properly. I mean certificate revocation will never be checked. For example, If I revoke the certificate manually certificate is still working. Is there any help?


问:
PHP - Load data from file with format X=Y
I have a file without any format called .env.

All the values are stored like this: X=Y

My supervisor told me to load this data into my PHP script, I need the values as array.
He said I can do it because the file is build like an ini file. But there are no sections.

I tried it like this:

```<code>$ini_array = parse_ini_file("../../.env");    // Output: false
$data = include("../../.env");                // Output: 1 -> prints the content of the file into the document
</code>```

```<code>APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:WVS0jXq4FBEOHEt2+K3AxyLCvTgq5L/dMhiFd5HZg7Q=
APP_DEBUG=true
APP_URL=http://api-konfigurator.local

JWT_SECRET=5PdNYddJuntDfbErQBg0vnUwwNCJiDy8hc1QMNAFaAWsdKJv2fe6m3ueLbYdYOk3

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=x
DB_USERNAME=y
DB_PASSWORD=z
</code>```

答:
It should be fairly straightforward to parse a file in the format mentioned but complicated slightly by some lines potentially including multiple = signs, such as for APP_KEY

That said, perhaps the following might help.

```<code>$filepath='c:/temp/fakeini.txt';

$data=array();
$lines=file( $filepath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
foreach( $lines as $index => $line ){
    if( !empty( $line ) ){
        $count=substr_count( $line, '=' );
        if( $count > 1 ){
            $pos=strpos($line,'=');
            $param=substr($line,0,$pos);
            $value=substr($line,$pos+1);
        }else{
            list( $param, $value )=explode( '=', trim( $line ) );
        }
        $data[ $param ]=$value;
    }
}
</code>```

which yields an array like this:

```<code>Array
(
    [APP_NAME] => Laravel
    [APP_ENV] => local
    [APP_KEY] => base64:WVS0jXq4FBEOHEt2+K3AxyLCvTgq5L/dMhiFd5HZg7Q=
    [APP_DEBUG] => true
    [APP_URL] => http://api-konfigurator.local
    [JWT_SECRET] => 5PdNYddJuntDfbErQBg0vnUwwNCJiDy8hc1QMNAFaAWsdKJv2fe6m3ueLbYdYOk3
    [LOG_CHANNEL] => stack
    [DB_CONNECTION] => mysql
    [DB_HOST] => localhost
    [DB_PORT] => 3306
    [DB_DATABASE] => x
    [DB_USERNAME] => y
    [DB_PASSWORD] => z
)
</code>```

Body:
I have a file without any format called .env.

All the values are stored like this: X=Y

My supervisor told me to load this data into my PHP script, I need the values as array.
He said I can do it because the file is build like an ini file. But there are no sections.

I tried it like this:

$ini_array = parse_ini_file("../../.env");    // Output: false
$data = include("../../.env");                // Output: 1 -> prints the content of the file into the document

APP_NAME=Laravel
APP_ENV=local
APP_KEY=base64:WVS0jXq4FBEOHEt2+K3AxyLCvTgq5L/dMhiFd5HZg7Q=
APP_DEBUG=true
APP_URL=http://api-konfigurator.local

JWT_SECRET=5PdNYddJuntDfbErQBg0vnUwwNCJiDy8hc1QMNAFaAWsdKJv2fe6m3ueLbYdYOk3

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=x
DB_USERNAME=y
DB_PASSWORD=z

Body:
It should be fairly straightforward to parse a file in the format mentioned but complicated slightly by some lines potentially including multiple = signs, such as for APP_KEY

That said, perhaps the following might help.

$filepath='c:/temp/fakeini.txt';

$data=array();
$lines=file( $filepath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES );
foreach( $lines as $index => $line ){
    if( !empty( $line ) ){
        $count=substr_count( $line, '=' );
        if( $count > 1 ){
            $pos=strpos($line,'=');
            $param=substr($line,0,$pos);
            $value=substr($line,$pos+1);
        }else{
            list( $param, $value )=explode( '=', trim( $line ) );
        }
        $data[ $param ]=$value;
    }
}

which yields an array like this:

Array
(
    [APP_NAME] => Laravel
    [APP_ENV] => local
    [APP_KEY] => base64:WVS0jXq4FBEOHEt2+K3AxyLCvTgq5L/dMhiFd5HZg7Q=
    [APP_DEBUG] => true
    [APP_URL] => http://api-konfigurator.local
    [JWT_SECRET] => 5PdNYddJuntDfbErQBg0vnUwwNCJiDy8hc1QMNAFaAWsdKJv2fe6m3ueLbYdYOk3
    [LOG_CHANNEL] => stack
    [DB_CONNECTION] => mysql
    [DB_HOST] => localhost
    [DB_PORT] => 3306
    [DB_DATABASE] => x
    [DB_USERNAME] => y
    [DB_PASSWORD] => z
)


问:
Rewriting URLs with .htaccess and mod_rewrite causes server error
I'm writing a website and I have a php file in the home directory that will grab the GET variables in the query string and open a video based on the query string id. The query string is: http://www.viewingtree.com/playlists.php?id=5914242 . I want to make that string look like http://www.viewingtree.com/playlists/5914242 . I'm using a .htaccess file on an Apache server with mod_rewrite installed, so I have this as my .htaccess file:

```<code>Options +FollowSymLinks
Options -MultiViews

RewriteEngine On
RewriteRule ^playlists/([0-9]+) /playlists.php?id=$1 [L]

RewriteCond %{REQUEST_URI} !(\.[^./]+)$
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule (.*) $1.php [L]
</code>```

When I enter the URL with the query string, the web page loads as it should. However, when I use the SEO-friendly URL, the page still loads but without any of the CSS formatting that I used. Is my .htaccess incorrect, or what?

答:
I recommend using absolute URLs for CSS and JavaScript.  The relative URL is causing this issue.

Try something like:

```<code><link media="screen" href="/style/defaultTheme.css" type="text/css" rel="stylesheet">
<link media="screen" href="/style/tablethemes.css" type="text/css" rel="stylesheet">
</code>```

Body:
I'm writing a website and I have a php file in the home directory that will grab the GET variables in the query string and open a video based on the query string id. The query string is: http://www.viewingtree.com/playlists.php?id=5914242 . I want to make that string look like http://www.viewingtree.com/playlists/5914242 . I'm using a .htaccess file on an Apache server with mod_rewrite installed, so I have this as my .htaccess file:

Options +FollowSymLinks
Options -MultiViews

RewriteEngine On
RewriteRule ^playlists/([0-9]+) /playlists.php?id=$1 [L]

RewriteCond %{REQUEST_URI} !(\.[^./]+)$
RewriteCond %{REQUEST_fileNAME} !-d
RewriteCond %{REQUEST_fileNAME} !-f
RewriteRule (.*) $1.php [L]

When I enter the URL with the query string, the web page loads as it should. However, when I use the SEO-friendly URL, the page still loads but without any of the CSS formatting that I used. Is my .htaccess incorrect, or what?

Body:
I recommend using absolute URLs for CSS and JavaScript.  The relative URL is causing this issue.

Try something like:

<link media="screen" href="/style/defaultTheme.css" type="text/css" rel="stylesheet">
<link media="screen" href="/style/tablethemes.css" type="text/css" rel="stylesheet">


问:
Disjoint Set Union with directed graph
I understand the DSU strictly works with undirected graphs from this stack overflow question - Can we detect cycles in directed graph using Union-Find data structure?

Nevertheless, I am currently working on a problem that involves 400000 queries and a graph with at most 400000 nodes, in which there are two possible queries:

Connect nodes a and b (directed, of course)

Output "true" if node "x" is reachable from node 1. Otherwise, print "false."

However, my original instinct was to use DSU; that obviously would not work. Any suggestions? Thank you.

答:
What you want is a data structure for a problem called 'incremental reachability'.
There are multiple ways to construct such a data structure, all have some different update/query time tradeoffs. A very simple way to achieve the goal is to use an adjacency list and use BFS every time a user queries if node "x" is reachable from 1.
This gets you update time: O(1) and query time: O(m).

A more complicated idea is 'even-shiloach' trees [1], here a BFS tree is maintained efficiently.
Total update time: O(nm) Query time: O(1).

An experimental analysis of similar algorithms can be found in [2].

[1] Shimon Even, Yossi Shiloach: An On-Line Edge-Deletion Problem. J. ACM 28(1): 1-4 (1981) https://dl.acm.org/doi/10.1145/322234.322235

[2] Fully Dynamic Single-Source Reachability in Practice: An Experimental Study, Kathrin Hanauer, Monika Henzinger and Christian Schulz https://arxiv.org/abs/1905.01216

Title: Disjoint Set Union with directed graph


问:
Get running instances of devops pipeline in Azure Devops
I need to get all the running instances of a particular pipeline.

The API in the docs,

This API allows us to get top 10K runs, but it does not seem to allow a filter where I can add a filter on the state of the pipeline, i.e. inProgress/running etc.

One way obviously is getting these top 10K runs and filtering them, which would be highly inefficient.

Is there a different API where I can get active runs of a pipeline or is this not possible?

答: Check this API: Builds - List. You can use statusFilter here:


问:
Is it possible to depend expected calls in gMock together?
Assume that I want to test following function:

template<typename Pack>
bool is_valid(const Pack& pack) {
  if (pack.a() > 0)
    return pack.b();
  return false;
};
```
<p>I will write a small mocker for <code>Pack</code> as follows:</p>
```class PackMock {
public:
    MOCK_METHOD(int, a, (), (const));
    MOCK_METHOD(bool, b, (), (const));
};
```
<p>and now I try to write test this method with in test function:</p>
```TEST(MyTests, IsValidTest) {
    PackMock p;
    EXPECT_CALL(p, a())
        .WillOnce(Return(0))
        .WillOnce(Return(1))
        .WillOnce(Return(20));
    EXPECT_CALL(p, b())
        .WillOnce(Return(true))
        .WillOnce(Return(false))
        .WillOnce(Return(true));

    EXPECT_FALSE(is_valid(p));
    EXPECT_FALSE(is_valid(p));
    EXPECT_TRUE(is_valid(p));
}
```

At the first sight, this code should be OK. I have 3 expectation and my mocker returns 3 different set of values and this is what happens in real application running (data-wise).

But if you run this code, you will get error that mocker expectations is not satisfied (it says that b() is expected to call 3 times while it is called twice). The reason is that when first test happens, a() returns 0, and because of if condition, b() is not called at all. So at the end, everything is messed up.

Now I wonder if there is a way to for example connect these expectations together or I should always set my expectations based on how code works rather than how my data works? I personally think that the later should be correct. For example, if a() in mocker called we make sure that at we always satisfy 1 expectation in b()? or for example we chain these expectations together in a way that b() is expected only if a() > 0?

答:
Firstly, you can use a testing::Sequence instance to keep track of mock calls in sequence. You can also directly define a InSequence for the test as in the docs.

Secondly, your first EXPECT_CALL does not call the b() mock call, because a() returns 0 which then never evaluates the return pack.b().

As an example found here, I've indicated how you can use a Sequence class in your example as follows:

TEST(MyTests, IsValidTest) {

    // Setup the mock object
    PackMock p;

    // Keep track of the sequence of events
    // using a sequence class
    testing::Sequence sequence;

    // # First is_valid() - a
    EXPECT_CALL(p, a())
        .InSequence(sequence)
        .WillOnce(Return(0));

    // # First is_valid() - b - not called
    // EXPECT_CALL(p, b())
    //     .InSequence(sequence)
    //     .WillOnce(Return(true));

    // # Second is_valid() - a
    EXPECT_CALL(p, a())
        .InSequence(sequence)
        .WillOnce(Return(1));

    // # Second is_valid() - b
    EXPECT_CALL(p, b())
        .InSequence(sequence)
        .WillOnce(Return(false));

    // # Third is_valid() - a
    EXPECT_CALL(p, a())
        .InSequence(sequence)
        .WillOnce(Return(20));

    // # Third is_valid() - b
    EXPECT_CALL(p, b())
        .InSequence(sequence)
        .WillOnce(Return(true));

    // Act - Initiate the calls and inject the
    // mock object as a dependency

    // # First call - a() returns 0,
    // thus returns false (but() b is not called)
    EXPECT_FALSE(is_valid(p));

    // # Second call - a() returns 1,
    // thus returns false, because b returns false
    EXPECT_FALSE(is_valid(p));

    // # Third call - a() returns 20,
    // thus returns true, because b returns true
    EXPECT_TRUE(is_valid(p));
}
```
<p>This will provide the following output:</p>
```Running main() from /opt/compiler-explorer/libs/googletest/release-1.10.0/googletest/src/gtest_main.cc
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from MyTests
[ RUN      ] MyTests.IsValidTest
[       OK ] MyTests.IsValidTest (0 ms)
[----------] 1 test from MyTests (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.
```

Thus, to answer your question:

Is it possible to depend expected calls in gMock together?

Yes, using a testing::Sequence class with or just using testing::InSequence()

Thus, if you have calls depending on each other in your test, use a sequence class instance(s) to link them.

Body:
Assume that I want to test following function:

template<typename Pack>
bool is_valid(const Pack& pack) {
  if (pack.a() > 0)
    return pack.b();
  return false;
};

I will write a small mocker for Pack as follows:

class PackMock {
public:
    MOCK_METHOD(int, a, (), (const));
    MOCK_METHOD(bool, b, (), (const));
};

and now I try to write test this method with in test function:

TEST(MyTests, IsValidTest) {
    PackMock p;
    EXPECT_CALL(p, a())
        .WillOnce(Return(0))
        .WillOnce(Return(1))
        .WillOnce(Return(20));
    EXPECT_CALL(p, b())
        .WillOnce(Return(true))
        .WillOnce(Return(false))
        .WillOnce(Return(true));

    EXPECT_FALSE(is_valid(p));
    EXPECT_FALSE(is_valid(p));
    EXPECT_TRUE(is_valid(p));
}

At the first sight, this code should be OK. I have 3 expectation and my mocker returns 3 different set of values and this is what happens in real application running (data-wise).

But if you run this code, you will get error that mocker expectations is not satisfied (it says that b() is expected to call 3 times while it is called twice). The reason is that when first test happens, a() returns 0, and because of if condition, b() is not called at all. So at the end, everything is messed up.

Now I wonder if there is a way to for example connect these expectations together or I should always set my expectations based on how code works rather than how my data works? I personally think that the later should be correct. For example, if a() in mocker called we make sure that at we always satisfy 1 expectation in b()? or for example we chain these expectations together in a way that b() is expected only if a() > 0?

Body:
Firstly, you can use a testing::Sequence instance to keep track of mock calls in sequence. You can also directly define a InSequence for the test as in the docs.

Secondly, your first EXPECT_CALL does not call the b() mock call, because a() returns 0 which then never evaluates the return pack.b().

As an example found here, I've indicated how you can use a Sequence class in your example as follows:

TEST(MyTests, IsValidTest) {

    // Setup the mock object
    PackMock p;

    // Keep track of the sequence of events
    // using a sequence class
    testing::Sequence sequence;

    // # First is_valid() - a
    EXPECT_CALL(p, a())
        .InSequence(sequence)
        .WillOnce(Return(0));

    // # First is_valid() - b - not called
    // EXPECT_CALL(p, b())
    //     .InSequence(sequence)
    //     .WillOnce(Return(true));

    // # Second is_valid() - a
    EXPECT_CALL(p, a())
        .InSequence(sequence)
        .WillOnce(Return(1));

    // # Second is_valid() - b
    EXPECT_CALL(p, b())
        .InSequence(sequence)
        .WillOnce(Return(false));

    // # Third is_valid() - a
    EXPECT_CALL(p, a())
        .InSequence(sequence)
        .WillOnce(Return(20));

    // # Third is_valid() - b
    EXPECT_CALL(p, b())
        .InSequence(sequence)
        .WillOnce(Return(true));

    // Act - Initiate the calls and inject the
    // mock object as a dependency

    // # First call - a() returns 0,
    // thus returns false (but() b is not called)
    EXPECT_FALSE(is_valid(p));

    // # Second call - a() returns 1,
    // thus returns false, because b returns false
    EXPECT_FALSE(is_valid(p));

    // # Third call - a() returns 20,
    // thus returns true, because b returns true
    EXPECT_TRUE(is_valid(p));
}

This will provide the following output:

Running main() from /opt/compiler-explorer/libs/googletest/release-1.10.0/googletest/src/gtest_main.cc
[==========] Running 1 test from 1 test suite.
[----------] Global test environment set-up.
[----------] 1 test from MyTests
[ RUN      ] MyTests.IsValidTest
[       OK ] MyTests.IsValidTest (0 ms)
[----------] 1 test from MyTests (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test suite ran. (0 ms total)
[  PASSED  ] 1 test.

Thus, to answer your question:

Is it possible to depend expected calls in gMock together?

Yes, using a testing::Sequence class with or just using testing::InSequence()

Thus, if you have calls depending on each other in your test, use a sequence class instance(s) to link them.


问:
i got error 500 on production when i read filefield in django
hello everyone please help me
i have recently maked a  website  but i got  500 error when i put it in production
but strangly all is working well in my computer
i am trying to read the buffer of a filefield inside a model and itson local but not in production

```<code>class post(models.Model):
titre=models.CharField(unique=True,null=True,max_length=100)
description=models.TextField(null=True,blank=True,max_length=400)
T=models.CharField(default="image",blank=True,max_length=50)
image=models.FileField(null=True)
cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True)
datepost=models.DateTimeField(auto_now_add=True,blank=True)
user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True)
vue=models.IntegerField(default=0,blank=True)
def __str__(self):
    return self.titre

def save(self, *args ,**kwargs):
    #cette partie permet de generer un identifiant unique
    f=self.image.readline()
    mime=magic.from_buffer(f,mime=True)
    if "video" in mime :
        self.T="short"
    super(post,self).save(*args,**kwargs)
</code>```

sorry for my english and thank you for your help

答:
i got its not the read method which have a problem
but i'm using cloudinary and cloudinary checks mimes types of files from buffer
so when i use read method the cursor is moved  after the file signature

i've used  file.seek(0) to resolve my problem

```<code>File=self.cleaned_data["image"]
    mime=magic.from_buffer(File.open("rb").read(1000),mime=True)
    File.seek(0)
</code>```

sorry  for my bad english ;)

Body:
hello everyone please help me
i have recently maked a  website  but i got  500 error when i put it in production
but strangly all is working well in my computer
i am trying to read the buffer of a filefield inside a model and itson local but not in production

class post(models.Model):
titre=models.CharField(unique=True,null=True,max_length=100)
description=models.TextField(null=True,blank=True,max_length=400)
T=models.CharField(default="image",blank=True,max_length=50)
image=models.FileField(null=True)
cat=models.ForeignKey(categorie,on_delete=models.CASCADE,null=True)
datepost=models.DateTimeField(auto_now_add=True,blank=True)
user=models.ForeignKey(myuser,on_delete=models.CASCADE,null=True)
vue=models.IntegerField(default=0,blank=True)
def __str__(self):
    return self.titre

def save(self, *args ,**kwargs):
    #cette partie permet de generer un identifiant unique
    f=self.image.readline()
    mime=magic.from_buffer(f,mime=True)
    if "video" in mime :
        self.T="short"
    super(post,self).save(*args,**kwargs)

sorry for my english and thank you for your help

Body:
i got its not the read method which have a problem
but i'm using cloudinary and cloudinary checks mimes types of files from buffer
so when i use read method the cursor is moved  after the file signature

i've used  file.seek(0) to resolve my problem

File=self.cleaned_data["image"]
    mime=magic.from_buffer(File.open("rb").read(1000),mime=True)
    File.seek(0)

sorry  for my bad english ;)


问:
Find list of empty indices in a javascript array
Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

```<code>["x", "", "", "x", "", "", ""]
</code>```

Would return something like:

```<code>[1,2,4,5,6]
</code>```

I have attempted something like this:

```<code>empty = roster.findIndex((obj) => Object.keys(obj).length === 0)
</code>```

However I can't come up with a way to iterate over the list.

答:
const arr = ['x', '', '', 'x', '', '', ''];
const emptyIndexes = arr.reduce((acc, curr, index) => {
  if (curr === '') {
    acc.push(index);
  }
  return acc;
}
  , []);
console.log(emptyIndexes);```

Body:
Is there a way in Javascript to find the indices where an array is empty or doesnt contain "x"?

["x", "", "", "x", "", "", ""]

Would return something like:

[1,2,4,5,6]

I have attempted something like this:

empty = roster.findIndex((obj) => Object.keys(obj).length === 0)

However I can't come up with a way to iterate over the list.


问:
Cursor with iteration to grab data from last row PL/SQL
I have a test script that I'm beggining to play with. I'm getting stuck with something that seems simple.
I want to iterate through rows to fetch data from last row of result set to use only it.

```<code>procedure e_test_send
is

cursor get_rec is
    select
    id,
    email_from,
    email_to,
    email_cc,
    email_subject,
    email_message
    from test_email_tab;

begin
    for rec_ in get_rec loop
    ifsapp.send_email_api.send_html_email(rec_.email_to,rec_.email_from, rec_.email_subject, rec_.email_message);
    end loop;

    end e_test_send;
</code>```

All I'm trying to do is send an email with a message and to a person from the last row only. This is a sample table that will grow in records. At the minute I have 2 rows of data in it, if I execute this procedure it will send 2 emails which is not the desired action.
I hope this makes sense.

Thanks

答:
Do you know which row is the last row? The one with the MAX(ID) value? If so, then you could base cursor on a straightforward

```<code>SELECT id,
       email_from,
       email_to,
       email_cc,
       email_subject,
       email_message
  FROM test_email_tab
 WHERE id = (SELECT MAX (id) FROM test_email_tab)
</code>```

As it scans the same table twice, its performance will drop as number of rows gets higher and higher. In that case, consider

```<code>WITH
   temp
   AS
      (SELECT id,
              email_from,
              email_to,
              email_cc,
              email_subject,
              email_message,
              ROW_NUMBER () OVER (ORDER BY id DESC) rn
         FROM test_email_tab)
SELECT t.id,
       t.email_from,
       t.email_to,
       t.email_cc,
       t.email_subject,
       t.email_message
  FROM temp t
 WHERE t.rn = 1
</code>```

which does it only once; sorts rows by ID in descending order and returns the one that ranks as the "highest" (i.e. the last).

Body:
I have a test script that I'm beggining to play with. I'm getting stuck with something that seems simple.
I want to iterate through rows to fetch data from last row of result set to use only it.

procedure e_test_send
is

cursor get_rec is
    select
    id,
    email_from,
    email_to,
    email_cc,
    email_subject,
    email_message
    from test_email_tab;

begin
    for rec_ in get_rec loop
    ifsapp.send_email_api.send_html_email(rec_.email_to,rec_.email_from, rec_.email_subject, rec_.email_message);
    end loop;

    end e_test_send;

All I'm trying to do is send an email with a message and to a person from the last row only. This is a sample table that will grow in records. At the minute I have 2 rows of data in it, if I execute this procedure it will send 2 emails which is not the desired action.
I hope this makes sense.

Thanks

Body:
Do you know which row is the last row? The one with the MAX(ID) value? If so, then you could base cursor on a straightforward

SELECT id,
       email_from,
       email_to,
       email_cc,
       email_subject,
       email_message
  FROM test_email_tab
 WHERE id = (SELECT MAX (id) FROM test_email_tab)

As it scans the same table twice, its performance will drop as number of rows gets higher and higher. In that case, consider

WITH
   temp
   AS
      (SELECT id,
              email_from,
              email_to,
              email_cc,
              email_subject,
              email_message,
              ROW_NUMBER () OVER (ORDER BY id DESC) rn
         FROM test_email_tab)
SELECT t.id,
       t.email_from,
       t.email_to,
       t.email_cc,
       t.email_subject,
       t.email_message
  FROM temp t
 WHERE t.rn = 1

which does it only once; sorts rows by ID in descending order and returns the one that ranks as the "highest" (i.e. the last).


问:
Getting null or empty error even though i controlled it
Though I controlled it with an if statement I'm getting ''Given string empty or null'' error and my app is closing.</p>
```<code>fun kayitOl ( view : View) {

    val email =findViewById<EditText>(R.id.emailText).text
    val password  = findViewById<EditText>(R.id.passwordText).text

        if (email != null && password != null ) {
            auth.createUserWithEmailAndPassword(email.toString(), password.toString())
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        val intent = Intent(this, haber_akisi::class.java)
                        startActivity(intent)
                        finish()

                    }
                }.addOnFailureListener { exception ->
                    Toast.makeText(this, exception.localizedMessage, Toast.LENGTH_LONG).show()
                }

        }else {
            Toast.makeText(this,"Lütfen E-mail ve Password alanlarını doldurunuz",Toast.LENGTH_LONG).show()
        }

}
</code>```

答:
You check just for null, but not for empty string ""

You can change your checking with email.isEmpty() or better email.isBlank() for checking strings like " "

Body:
Though I controlled it with an if statement I'm getting ''Given string empty or null'' error and my app is closing.

fun kayitOl ( view : View) {

    val email =findViewById<EditText>(R.id.emailText).text
    val password  = findViewById<EditText>(R.id.passwordText).text

        if (email != null && password != null ) {
            auth.createUserWithEmailAndPassword(email.toString(), password.toString())
                .addOnCompleteListener(this) { task ->
                    if (task.isSuccessful) {
                        val intent = Intent(this, haber_akisi::class.java)
                        startActivity(intent)
                        finish()

                    }
                }.addOnFailureListener { exception ->
                    Toast.makeText(this, exception.localizedMessage, Toast.LENGTH_LONG).show()
                }

        }else {
            Toast.makeText(this,"Lütfen E-mail ve Password alanlarını doldurunuz",Toast.LENGTH_LONG).show()
        }

}


问:
changing an images src value when the user scrolls jquery
I'm trying to attach an event handler to the scroll event that changes the value of the image tag's src value by returning a random value from an array of src values (titles)

$( function(titlemagic){

```<code>var titles =[
</code>```

//ive omitted the actual array contents in consideration of post length

```<code>            ];
</code>```

var rand = Math.ceil(100*Math.random())

$('#id').attr('src', function(){ return titles[(rand)] }).scroll();

});

答:
Try this</p>

```<code>$(document).scroll(function(){
  var rand = Math.ceil(100*Math.random())
  $('#id').attr('src', function(){ return titles[(rand)] }).scroll();
});
</code>```

Body:
I'm trying to attach an event handler to the scroll event that changes the value of the image tag's src value by returning a random value from an array of src values (titles)

$( function(titlemagic){

var titles =[

//ive omitted the actual array contents in consideration of post length

            ];

var rand = Math.ceil(100*Math.random())

$('#id').attr('src', function(){ return titles[(rand)] }).scroll();

});

Body:
Try this

$(document).scroll(function(){
  var rand = Math.ceil(100*Math.random())
  $('#id').attr('src', function(){ return titles[(rand)] }).scroll();
});


问:
Not able the hide content in of HTML page and show it at the time of print
Hi I try to hide one of the chart from main page and want to show it at the time of print.But it is not working for me.

HTML:

```<code><div class="bar-chart">
  <div class="canvas-holder3"><canvas id="resultsChart7"></canvas></div>
</div>
</code>```

CSS:

```<code>.bar-chart {
  display: none;
}

@media print {
  body,
  html,
  #wrapper {
    width: 100%;
  }

  .bar-chart {
    display: block;
    visibility: visible;
  }
}
</code>```

答:
It's working fine like this. you can just follow this pattern.

<!DOCTYPE html>

        <title>Show element at print</title>

This section would not appear on screen but only in print.

Show something during print.

 ```

Body:
Hi I try to hide one of the chart from main page and want to show it at the time of print.But it is not working for me.

HTML:

<canvas id="resultsChart7"></canvas>

CSS:

.bar-chart {
  display: none;
}

@media print {
  body,
  html,
  #wrapper {
    width: 100%;
  }

  .bar-chart {
    display: block;
    visibility: visible;
  }
}

Body:
It's working fine like this. you can just follow this pattern.

<!DOCTYPE html>
<html>
    <head>
        <title>Show element at print</title>
        <style>
            body {
                text-align:center;
            }
            h1 {
                color:green;
            }
            .print {
                  display: none;
            }
            @media print {
               .print {
                  display: block;
               }
            }
        </style>
    </head>
    <body>
        <h1 class = "print">This section would not appear on screen but only in print.</h1>

<p>Show something during print.</p>

    </body>
</html>


问:
Interactive stdin, stdout with subprocess
I've read some discussions about this but I couldn't find anything on how to correct the error I have.

I have a C program, for a device, that is interactive, user input gives out hardware status, measurement, etc. The program returns the asked data. Initialization takes a few seconds so I can't afford to re-run the program each time I want a measurement, as some sub-routine needs a few thousand samples a second. I want my data to be exported into python somehow to make all my calculations and graph displays. I could adapt the C program but I'd rather change the python script to accommodate for it.

For testing purposes I have this simple C program:

```<code>#include <stdio.h>

int main(int argc, char const *argv[])
{
    int command;
    printf("Line1\n");
    printf("Line2\n");

    while(1){
        scanf("%d", &command);
        if (command == 0) break;
        else if (command == 1) printf("result : s_0 = 1, s_1 = 0.05, s_0 = 0.5, s_0 = -0.85\n");
        else printf("Unknown\n");
    }
    return 0;
}
</code>```

And I have tried to run it inside a subprocess and use the stdin, stdout as communicate() ends the communication afterward :

```<code>import subprocess as sp
from subprocess import PIPE
import time

p = sp.Popen(["a.exe"], stdin=PIPE, stdout=PIPE)

# p.stdin.write(b'1\n') # Blocks here
print(p.stdout.readlines()) # Here too
p.stdout.flush()
p.stdin.write(b'0\n')
p.stdin.flush()
time.sleep(0.1)

print(p.stdout.readlines())

if not p.poll():p.kill()
</code>```

I tried a lot of things from what I've seen over my research. Should I use a queue or a thread ? Why am I not getting anything out, it looks like I got deadlock since the first time I try to either write or read the pipe first. Python froze (not responsive to Ctrl+C but my keys are still put in the buffer as they appear after python is killed) and I have to kill the Python process each time.

Is there something better to accommodate for my case?

EDIT

As I don't want to create a new post that is similar I post my new, related issue, here.
I implemented @Paul Cornelius solution and it worked. Hence I tried to make a command input to make the command transit throw python and go into the C program process :

```<code>p = sp.Popen(["a.exe"], stdin=PIPE, stdout=PIPE)

print("Line 1", p.stdout.readline())
print("Line 2", p.stdout.readline())

while(True):
    command = input("Command > ")
    p.stdin.write((command + '\n').encode())
    p.stdin.flush()
    if command == '0':
        break
    print("Answer : ", p.stdout.readline())

if not p.poll():
    p.kill()
</code>```

I have one issue (maybe more but I can't know) and a question.

The first two lines appear, no issue here, but once I reach the input I can't type anything, I'd like to know if that is normal and what is the fix.

I changed the C program like @Paul Cornelius made it with the flush of the stdout buffer.

My question is about the first two Line, I tried using p.stdout.readlines() instead of p.stdout.readline() twice but it didn't work (freeze like in my original question). Why doesn't it work here but work at the end of the script? EOF character?

答:
C programs buffer stdout.  So you need to flush stdout after each write or else the Python program won't see anything:

```<code>#include <stdio.h>

int main(int argc, char const *argv[])
{
    int command;
    printf("Line1\n");
    printf("Line2\n");
    fflush(stdout);

    while(1){
        scanf("%d", &command);
        if (command == 0) break;
        else if (command == 1) printf("result : s_0 = 1, s_1 = 0.05, s_0 = 0.5, s_0 = -0.85\n");
        else printf("Unknown\n");
        fflush(stdout);
    }
    return 0;
}
</code>```

In the Python program I rearranged a few things to get a better match to your C program logic.  (Perhaps some of it was unnecessary.)  The calls to p.stdin.flush are required.  This program works:

```<code>import subprocess as sp
from subprocess import PIPE
import time

p = sp.Popen([r"c:\gcc64proj\so\so1.exe"], stdout=PIPE, stdin=PIPE)

print("Line 1", p.stdout.readline())
print("Line 2", p.stdout.readline())
p.stdin.write(b'1\n')
p.stdin.flush()
print("Line 3", p.stdout.readline())
p.stdin.write(b'2\n')
p.stdin.write(b'0\n')
p.stdin.flush()
time.sleep(0.1)

print(p.stdout.readlines())

if not p.poll():
    p.kill()
</code>```

Body:
I've read some discussions about this but I couldn't find anything on how to correct the error I have.

I have a C program, for a device, that is interactive, user input gives out hardware status, measurement, etc. The program returns the asked data. Initialization takes a few seconds so I can't afford to re-run the program each time I want a measurement, as some sub-routine needs a few thousand samples a second. I want my data to be exported into python somehow to make all my calculations and graph displays. I could adapt the C program but I'd rather change the python script to accommodate for it.

For testing purposes I have this simple C program:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int command;
    printf("Line1\n");
    printf("Line2\n");

    while(1){
        scanf("%d", &command);
        if (command == 0) break;
        else if (command == 1) printf("result : s_0 = 1, s_1 = 0.05, s_0 = 0.5, s_0 = -0.85\n");
        else printf("Unknown\n");
    }
    return 0;
}

And I have tried to run it inside a subprocess and use the stdin, stdout as communicate() ends the communication afterward :

import subprocess as sp
from subprocess import PIPE
import time

p = sp.Popen(["a.exe"], stdin=PIPE, stdout=PIPE)

# p.stdin.write(b'1\n') # Blocks here
print(p.stdout.readlines()) # Here too
p.stdout.flush()
p.stdin.write(b'0\n')
p.stdin.flush()
time.sleep(0.1)

print(p.stdout.readlines())

if not p.poll():p.kill()

I tried a lot of things from what I've seen over my research. Should I use a queue or a thread ? Why am I not getting anything out, it looks like I got deadlock since the first time I try to either write or read the pipe first. Python froze (not responsive to Ctrl+C but my keys are still put in the buffer as they appear after python is killed) and I have to kill the Python process each time.

Is there something better to accommodate for my case?

EDIT

As I don't want to create a new post that is similar I post my new, related issue, here.
I implemented @Paul Cornelius solution and it worked. Hence I tried to make a command input to make the command transit throw python and go into the C program process :

p = sp.Popen(["a.exe"], stdin=PIPE, stdout=PIPE)

print("Line 1", p.stdout.readline())
print("Line 2", p.stdout.readline())

while(True):
    command = input("Command > ")
    p.stdin.write((command + '\n').encode())
    p.stdin.flush()
    if command == '0':
        break
    print("Answer : ", p.stdout.readline())

if not p.poll():
    p.kill()

I have one issue (maybe more but I can't know) and a question.

The first two lines appear, no issue here, but once I reach the input I can't type anything, I'd like to know if that is normal and what is the fix.

I changed the C program like @Paul Cornelius made it with the flush of the stdout buffer.

My question is about the first two Line, I tried using p.stdout.readlines() instead of p.stdout.readline() twice but it didn't work (freeze like in my original question). Why doesn't it work here but work at the end of the script? EOF character?

Body:
C programs buffer stdout.  So you need to flush stdout after each write or else the Python program won't see anything:

#include <stdio.h>

int main(int argc, char const *argv[])
{
    int command;
    printf("Line1\n");
    printf("Line2\n");
    fflush(stdout);

    while(1){
        scanf("%d", &command);
        if (command == 0) break;
        else if (command == 1) printf("result : s_0 = 1, s_1 = 0.05, s_0 = 0.5, s_0 = -0.85\n");
        else printf("Unknown\n");
        fflush(stdout);
    }
    return 0;
}

In the Python program I rearranged a few things to get a better match to your C program logic.  (Perhaps some of it was unnecessary.)  The calls to p.stdin.flush are required.  This program works:

import subprocess as sp
from subprocess import PIPE
import time

p = sp.Popen([r"c:\gcc64proj\so\so1.exe"], stdout=PIPE, stdin=PIPE)

print("Line 1", p.stdout.readline())
print("Line 2", p.stdout.readline())
p.stdin.write(b'1\n')
p.stdin.flush()
print("Line 3", p.stdout.readline())
p.stdin.write(b'2\n')
p.stdin.write(b'0\n')
p.stdin.flush()
time.sleep(0.1)

print(p.stdout.readlines())

if not p.poll():
    p.kill()