问:
JS Data filter and group not correct
I work with dictionary array, and I wanna group data by time period, I have a solution how to do it.

But now I found issues, for last hours data is not appear at the grouped array.

Code:

    // Dictionary array:
var array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];
// And I have time periods, for ex:
var time = ["05:45 - 06:00", "06:00 - 07:00",
     "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
     "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
     "13:00 - 14:00", "14:00 - 14:45"];

var formatedTime = time.map(function(val) {
    return val.split(" - ");
});

var grouped = formatedTime.reduce((groups, currentValue, cI) => {
    let min = parseInt(currentValue[0].substring(0,2));
    let max = parseInt(currentValue[1].substring(0,2));
    let filtered = array.filter(val => {
        let validDate = val.dateTime.replace(/\//g,'-').replace(' ','T').replace('19','2019');
        let date = new Date(validDate).getHours();
        let result = false;
        if(date >= min && date < max) {
            return true;
        } else {
            return false;
        }
    });

    let date = currentValue[0] + " - " + currentValue[1];
    groups.push({
        time: date,
        groupedData: filtered
    });
    return groups;

}, []);

console.log(grouped);```
</div>
</div>
</p>

<p>So as u can see at array I have data for <strong>time 14:00 - 14:45</strong> after filtering data does not appear correctly.</p>

<p>In my array i have two reccords:</p>

```{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
{ item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
```

<p>I try to found sollution, but i stuck.</p>

<p>Expected output: </p>

```{
    "time": "14:00 - 14:45",
    "groupedData": [{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
    { item: "item", category: "category", dateTime: "19/05/23 14:37:33" }]

 }
```

答:
    const array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];
    // And I have time periods, for ex:
    const times = ["05:45 - 06:00", "06:00 - 07:00",
        "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
        "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
        "13:00 - 14:00", "14:00 - 14:45"
    ];

    const result = [];

    times.forEach((time) => {

        const [min, max] = time.split(" - ");

        const groupedData = array.filter(({ dateTime }) => {
            return `${min}:00`.localeCompare(dateTime.slice(-8)) <= 0 && `${max}:00`.localeCompare(dateTime.slice(-8)) >= 0;
        })

        result.push({
            time,
            groupedData
        });
    });

    console.log('@>result', result)```

Title: JS Data filter and group not correct

Body:
I work with dictionary array, and I wanna group data by time period, I have a solution how to do it.

But now I found issues, for last hours data is not appear at the grouped array.

Code:

    // Dictionary array:
var array = [
        { item: "item", category: "category", dateTime: "19/05/23 05:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 05:21:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:31:33" },
        { item: "item", category: "category", dateTime: "19/05/23 06:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:34:33" },
        { item: "item", category: "category", dateTime: "19/05/23 07:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 08:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:16:33" },
        { item: "item", category: "category", dateTime: "19/05/23 09:46:33" },
        { item: "item", category: "category", dateTime: "19/05/23 10:36:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:47:33" },
        { item: "item", category: "category", dateTime: "19/05/23 11:55:33" },
        { item: "item", category: "category", dateTime: "19/05/23 12:37:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
        { item: "item", category: "category", dateTime: "19/05/23 14:37:33" },
    ];
// And I have time periods, for ex:
var time = ["05:45 - 06:00", "06:00 - 07:00",
     "07:00 - 08:00", "08:00 - 09:00", "09:00 - 10:00",
     "10:00 - 11:00", "11:00 - 12:00", "12:00 - 13:00",
     "13:00 - 14:00", "14:00 - 14:45"];

var formatedTime = time.map(function(val) {
    return val.split(" - ");
});

var grouped = formatedTime.reduce((groups, currentValue, cI) => {
    let min = parseInt(currentValue[0].substring(0,2));
    let max = parseInt(currentValue[1].substring(0,2));
    let filtered = array.filter(val => {
        let validDate = val.dateTime.replace(/\//g,'-').replace(' ','T').replace('19','2019');
        let date = new Date(validDate).getHours();
        let result = false;
        if(date >= min && date < max) {
            return true;
        } else {
            return false;
        }
    });

    let date = currentValue[0] + " - " + currentValue[1];
    groups.push({
        time: date,
        groupedData: filtered
    });
    return groups;

}, []);

console.log(grouped);

So as u can see at array I have data for time 14:00 - 14:45 after filtering data does not appear correctly.

In my array i have two reccords:

{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
{ item: "item", category: "category", dateTime: "19/05/23 14:37:33" },

I try to found sollution, but i stuck.

Expected output:

{
    "time": "14:00 - 14:45",
    "groupedData": [{ item: "item", category: "category", dateTime: "19/05/23 14:27:33" },
    { item: "item", category: "category", dateTime: "19/05/23 14:37:33" }]

 }


来源: stackexchange

问:
What should be the value of b in the following code snippet and why? '-6' or '-7'
I want so see the values of the four variables (Basically checking the precedence order of logical operators).

```<code>#include<stdio.h>
int main()
{
    int a=0, b=-7, c=0, d;
    d = ++c || ++a && ++b  ;
    printf("\n %d %d %d %d",a,b,c,d);
}
</code>```

I expect the result to be '0 -6 1 1', but the actual output is '0 -7 1 1'. Can anyone please give an explanation behind the output shown?

答:
First have a look at Operator Precedence.

Then, regarding the working of logical OR operator, from C11, chapter §6.5.14 (emphasis mine)

[...] the || operator guarantees left-to-right evaluation; if the
  second operand is evaluated, there is a sequence point between the evaluations of the first
  and second operands. If the first operand compares unequal to 0, the second operand is
  not evaluated.

and regarding the result:

The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it
  yields 0. The result has type int.

So, in your code

```<code> d = ++c || ++a && ++b  ;
</code>```

is the same as

```<code> d = (++c) || (++a && ++b);
</code>```

which evaluates to

```<code> d = 1 || (++a && ++b);         // short circuit, RHS not evaluated
</code>```

which is finally same as

```<code>d = 1;  // 1 is not the value computation of `++c`, rather result of the `||` operation.
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I want so see the values of the four variables (Basically checking the precedence order of logical operators).

#include<stdio.h>
int main()
{
    int a=0, b=-7, c=0, d;
    d = ++c || ++a && ++b  ;
    printf("\n %d %d %d %d",a,b,c,d);
}

I expect the result to be '0 -6 1 1', but the actual output is '0 -7 1 1'. Can anyone please give an explanation behind the output shown?

Body:
First have a look at Operator Precedence.

Then, regarding the working of logical OR operator, from C11, chapter §6.5.14 (emphasis mine)

[...] the || operator guarantees left-to-right evaluation; if the
  second operand is evaluated, there is a sequence point between the evaluations of the first
  and second operands. If the first operand compares unequal to 0, the second operand is
  not evaluated.

and regarding the result:

The || operator shall yield 1 if either of its operands compare unequal to 0; otherwise, it
  yields 0. The result has type int.

So, in your code

 d = ++c || ++a && ++b  ;

is the same as

 d = (++c) || (++a && ++b);

which evaluates to

 d = 1 || (++a && ++b);         // short circuit, RHS not evaluated

which is finally same as

d = 1;  // 1 is not the value computation of `++c`, rather result of the `||` operation.


问:
Map external directory outside tomcat installation in eclipse Dynamic Web Project
I want to map an external directory outside tomcat installation which stores images in eclipse Dynamic Web Project's tomcat server. I have done that in tomcat directly by adding context tag in server.xml file. But when I done that in eclipse Dynamic Web Project's tomcat server.xml file. It is not working. I am using Tomcat 6.

My question is:

How to map an external directory outside tomcat installation in eclipse Dynamic Web Project?

Is it the good way to map external directory outside tomcat installation?

Thanks

Brajesh

答:
Try a linked resource. Go to the folder in which you want your external directory to apprear. Now open the File menu -> New -> Folder.

Type in the name.

Click on "Advanced >>". Select "Link to alternate location (Linked Folder)". Browse to the external directory.

Click Finish.

That creates a link from your workspace to the external directory. It's possible that the plugin supports that.

ContentLicense: CC BY-SA 3.0


问:
Running time for a shortestP alg in unweighted undirected graph in python3
For this kind of problem I thought it would have been better make some BFS-like implementation. I don't know why, after some running time testing, it came out a plot that resembles an exponential function.

So I began to think of my code's correctness: is it really efficient? Can you help me to make a running time analysis for a good algorithm?

I've plotted the log in base 1.5 for the x-axis (since in the code I use a list of the first 30 powers of 1.5 as number of vertices input in a random graph generetor). Still looks exponential...

```<code>def bfs_short(graph, source, target):
    visited = set()
    queue = collections.deque([source])

    d={}
    d[source]=0

    while queue:
        u = queue.pop()
        if u==target:
            return d[target]
        if u not in visited:
            visited.add(u)
            for w in graph[u]:
                if w not in visited:
                    queue.appendleft(w)
                    d[w]=d[u]+1
</code>```

The thing is... I didn't posted also the benching input trials which also may cause problems but first of all I want to be sure that the code works fine... solving the problems related to testing is my final purpose.

答:
A problem in your code is that your queue does not take in account the distance to the origin in order to prioritize the next vertex it will pop.

Also, collections.deque is not a priority queue, and thus will not give you the closest unvisited vertex seen so far when you pop an element from it.

This should do it, using heapq, a built-in heap implementation:

```<code>import heapq

def bfs_short(graph, source, target):
    visited = set()
    queue = [(0, source)]
    heapq.heapify(queue)
    while not queue:
        dist, vertex = heapq.heappop(queue)
        if vertex == target:
            return dist
        if vertex not in visited:
            visited.add(vertex)
            for neighbor in graph[vertex]:
                if neighbor not in visited:
                    heapq.heappush(queue, (dist + 1, neighbor))
</code>```

In this version, pairs are pushed in the queue. To evaluate and compare tuples, Python tries to compare their first element, then the second in case of equality, and on and on.

So by pushing dist(vertex, origin) as first member of the tuple, the smallest couple (dist, vertex) in the heap will also be the closest to the origin vertex.

Body:
For this kind of problem I thought it would have been better make some BFS-like implementation. I don't know why, after some running time testing, it came out a plot that resembles an exponential function.

So I began to think of my code's correctness: is it really efficient? Can you help me to make a running time analysis for a good algorithm?

I've plotted the log in base 1.5 for the x-axis (since in the code I use a list of the first 30 powers of 1.5 as number of vertices input in a random graph generetor). Still looks exponential...

def bfs_short(graph, source, target):
    visited = set()
    queue = collections.deque([source])

    d={}
    d[source]=0

    while queue:
        u = queue.pop()
        if u==target:
            return d[target]
        if u not in visited:
            visited.add(u)
            for w in graph[u]:
                if w not in visited:
                    queue.appendleft(w)
                    d[w]=d[u]+1

The thing is... I didn't posted also the benching input trials which also may cause problems but first of all I want to be sure that the code works fine... solving the problems related to testing is my final purpose.

Body:
A problem in your code is that your queue does not take in account the distance to the origin in order to prioritize the next vertex it will pop.

Also, collections.deque is not a priority queue, and thus will not give you the closest unvisited vertex seen so far when you pop an element from it.

This should do it, using heapq, a built-in heap implementation:

import heapq

def bfs_short(graph, source, target):
    visited = set()
    queue = [(0, source)]
    heapq.heapify(queue)
    while not queue:
        dist, vertex = heapq.heappop(queue)
        if vertex == target:
            return dist
        if vertex not in visited:
            visited.add(vertex)
            for neighbor in graph[vertex]:
                if neighbor not in visited:
                    heapq.heappush(queue, (dist + 1, neighbor))

In this version, pairs are pushed in the queue. To evaluate and compare tuples, Python tries to compare their first element, then the second in case of equality, and on and on.

So by pushing dist(vertex, origin) as first member of the tuple, the smallest couple (dist, vertex) in the heap will also be the closest to the origin vertex.


问:
How is deque implemented in c++ stl
I just wanted to know how deque is implemented and how are the basic operations like push_front and random access operator are provided in that implementation.

Title: How is deque implemented in c++ stl

Body:
I just wanted to know how deque is implemented

It's always a good to have an excuse for doing ASCII art:

+-------------------------------------------------------------+
| std::deque<int>                                             |
|                                                             |
|  subarrays:                                                 |
| +---------------------------------------------------------+ |
| |           |           |           |         |           | |
| | int(*)[8] | int(*)[8] | int(*)[8] |int(*)[8]|int(*)[8]  | |
| |           |           |           |         |           | |
| +---------------------------------------------------------+ |
|                        /            \                       |
|                       /              \                      |
|                      /                \                     |
|                     /                  \                    |
|                    /                    \                   |
|                   /                      \                  |
|                  /                        \                 |
|                 /                          \                |
|                -                            -               |
|               +------------------------------+              |
|               | ?, ?, 42, 43, 50, ?, ?, ?, ? |              |
|               +------------------------------+              |
|                                                             |
| additional state:                                           |
|                                                             |
| - pointer to begin of the subarrays                         |
| - current capacity and size                                 |
| - pointer to current begin and end                          |
+-------------------------------------------------------------+

how are the basic operations like push_front and random access operator are provided in that implementation?

First, std::deque::push_front, from libcxx:

template <class _Tp, class _Allocator>
void
deque<_Tp, _Allocator>::push_front(const value_type& __v)
{
    allocator_type& __a = __base::__alloc();
    if (__front_spare() == 0)
        __add_front_capacity();
    __alloc_traits::construct(__a, _VSTD::addressof(*--__base::begin()), __v);
    --__base::__start_;
    ++__base::size();
}

This obviously checks whether the memory already allocated at the front can hold an additional element. If not, it allocates. Then, the main work is shifted to the iterator: _VSTD::addressof(*--__base::begin()) goes one location before the current front element of the container, and this address is passed to the allocator to construct a new element in place by copying v (the default allocator will definitely do a placement-new).

Now random access. Again from libcxx, std::deque::operator[] (the non-const version) is

template <class _Tp, class _Allocator>
inline
typename deque<_Tp, _Allocator>::reference
deque<_Tp, _Allocator>::operator[](size_type __i) _NOEXCEPT
{
    size_type __p = __base::__start_ + __i;
    return *(*(__base::__map_.begin() + __p / __base::__block_size) + __p % __base::__block_size);
}

This pretty much computes an index relative to some start index, and then determines the subarray and the index relative to the start of the subarray. __base::__block_size should be the size of one subarray here.


问:
ArchUnits layeredArchitecture rule doesn't include fields
We check our software architecture by some ArchUnit rules.

One of this is the test for our layered architecture.

This works fine for methods.
If we access a method of layer3 from layer1 we will get an exception.

But if the access a field declared in layer3 from layer1 this won't throw an exception.

```<code>   .layer("layer1").definedBy("com.acme.layer1")
   .layer("layer2").definedBy("com.acme.layer2")
   .layer("layer3").definedBy("com.acme.layer3")
   .whereLayer("layer3").mayNotBeAccessedByAnyLayer()
   .whereLayer("layer2").mayOnlyAccessedByLayers("layer3")
   .as("Respect the layered architecture");
</code>```

This won't throw an exception if we import a field from layer3 to a layer1 class:

```<code>package com.acme.layer1

import static com.acme.layer3.SOME_LABEL

public class x {
   ...
}
</code>```

Our expectation is that also accessing fields from layer3 in any other layer should throw an exception.
Or is there another way to check?

答:
My answer depends on the assumption that com.acme.layer3.SOME_LABEL is a constant expression like public static final String SOME_LABEL = "..."

Compile-time constants are inlined during compilation. If your code looks like

```<code>String label = SharedConstants.SOME_LABEL;
</code>```

then the compiled bytecode contains the exact value of SharedConstants.SOME_LABEL. There remains no reference to this field in the bytecode. (The Static Final Inline Trap)

ArchUnit gathers all information by analyzing the bytecode, see also the ArchUnit User Guide. Because there is no information about SharedConstants.SOME_LABEL in the bytecode, ArchUnit doesn't know about this access.

In summary: This is a limitation of ArchUnit and all other libraries which only depend on the bytecode.

Body:
We check our software architecture by some ArchUnit rules.

One of this is the test for our layered architecture.

This works fine for methods.
If we access a method of layer3 from layer1 we will get an exception.

But if the access a field declared in layer3 from layer1 this won't throw an exception.

   .layer("layer1").definedBy("com.acme.layer1")
   .layer("layer2").definedBy("com.acme.layer2")
   .layer("layer3").definedBy("com.acme.layer3")
   .whereLayer("layer3").mayNotBeAccessedByAnyLayer()
   .whereLayer("layer2").mayOnlyAccessedByLayers("layer3")
   .as("Respect the layered architecture");

This won't throw an exception if we import a field from layer3 to a layer1 class:

package com.acme.layer1

import static com.acme.layer3.SOME_LABEL

public class x {
   ...
}

Our expectation is that also accessing fields from layer3 in any other layer should throw an exception.
Or is there another way to check?

Body:
My answer depends on the assumption that com.acme.layer3.SOME_LABEL is a constant expression like public static final String SOME_LABEL = "..."

Compile-time constants are inlined during compilation. If your code looks like

String label = SharedConstants.SOME_LABEL;

then the compiled bytecode contains the exact value of SharedConstants.SOME_LABEL. There remains no reference to this field in the bytecode. (The Static Final Inline Trap)

ArchUnit gathers all information by analyzing the bytecode, see also the ArchUnit User Guide. Because there is no information about SharedConstants.SOME_LABEL in the bytecode, ArchUnit doesn't know about this access.

In summary: This is a limitation of ArchUnit and all other libraries which only depend on the bytecode.


问:
Is it possible to solve this situation with JavaScript/jQuery?
I have a code that checks if radio buttons are checked and if they are it set background color.  It's all working fine, my problem is when I want to select another radio button, result is that all my radio buttons are selected on click but it needs to be just one.

$("input[type='radio']").each(function () {
  if ($(this).is(":checked")) {
  $(this).css("background", "yellow");
   }
 });
 ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio">
<input type="radio" checked></code>```

You can test this out. Just try to select another radio button, you will see that radio buttons are selected (2 radio buttons).

What I want to achieve is that when you click on another radio button  it needs to remove this checked class or any other idea. I can't switch between radio buttons.

答:
To achieve the desired behavior with visible background color for each radio button, you could wrap each radio <input /> with a span element which would achieve the visual effect of a background color for the radio buttons:

/* Reusable selection of radio buttons */
const radioButtons = $("input[type='radio']");

/* Updates selected radio button parent backgrounds based on checked state */
function updateBackground() {
  radioButtons.each(function() {
    $(this).parent().css('background', $(this).is(":checked") ? 'yellow' : '');
  });
}

/* Attach click behavior to each causing the background colors to update */
radioButtons.click(updateBackground);

/* Initalise the backgrounds and */
updateBackground();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Wrap each radio button with a span, which will be used to show a colored background
when the radio button is checked -->
<span>
  <input type="radio" name="radio-group-name" checked>
</span>
<span>
  <input type="radio" name="radio-group-name">
</span></code>```

Body:
I have a code that checks if radio buttons are checked and if they are it set background color.  It's all working fine, my problem is when I want to select another radio button, result is that all my radio buttons are selected on click but it needs to be just one.

$("input[type='radio']").each(function () {
  if ($(this).is(":checked")) {
  $(this).css("background", "yellow");
   }
 });

<input type="radio">
<input type="radio" checked>

You can test this out. Just try to select another radio button, you will see that radio buttons are selected (2 radio buttons).

What I want to achieve is that when you click on another radio button  it needs to remove this checked class or any other idea. I can't switch between radio buttons.

Body:
To achieve the desired behavior with visible background color for each radio button, you could wrap each radio <input /> with a span element which would achieve the visual effect of a background color for the radio buttons:

/* Reusable selection of radio buttons */
const radioButtons = $("input[type='radio']");

/* Updates selected radio button parent backgrounds based on checked state */
function updateBackground() {
  radioButtons.each(function() {
    $(this).parent().css('background', $(this).is(":checked") ? 'yellow' : '');
  });
}

/* Attach click behavior to each causing the background colors to update */
radioButtons.click(updateBackground);

/* Initalise the backgrounds and */
updateBackground();

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<!-- Wrap each radio button with a span, which will be used to show a colored background
when the radio button is checked -->
<span>
  <input type="radio" name="radio-group-name" checked>
</span>
<span>
  <input type="radio" name="radio-group-name">
</span>


问:
Toast message doesn't show up on actual phone while it shows in emulator
I'm trying to create an android application. One part is to make sure that toast message shows. It works when I'm running the app on the android studio emulator, but it doesn't show when I'm running on actual Samsung phone

It's about a thousand line code, so I don't think it's helpful to copy all of it. So, I'd like to know if there is any common issues that can make toast messages to show in emulator but not in actual phone.

-- EDIT --

This is one of the parts where I want to toast message

```<code>private fun addListenerOnImageButtonHelper(intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(this,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}
</code>```

-- EDIT --

Phone's setting to show notification was turned off. Problem Solved... Thanks

答:
You need add ActivityName.this when you create toast

Because you want to show toast from ImageButton click

```<code>private fun addListenerOnImageButtonHelper(intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(ActivityName.this,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}
</code>```

Else you need to pass Context as parameter in your function

Like

```<code>private fun addListenerOnImageButtonHelper(context: Context,intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(context,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}
</code>```

Body:
I'm trying to create an android application. One part is to make sure that toast message shows. It works when I'm running the app on the android studio emulator, but it doesn't show when I'm running on actual Samsung phone

It's about a thousand line code, so I don't think it's helpful to copy all of it. So, I'd like to know if there is any common issues that can make toast messages to show in emulator but not in actual phone.

-- EDIT --

This is one of the parts where I want to toast message

private fun addListenerOnImageButtonHelper(intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(this,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}

-- EDIT --

Phone's setting to show notification was turned off. Problem Solved... Thanks

Body:
You need add ActivityName.this when you create toast

Because you want to show toast from ImageButton click

private fun addListenerOnImageButtonHelper(intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(ActivityName.this,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}

Else you need to pass Context as parameter in your function

Like

private fun addListenerOnImageButtonHelper(context: Context,intent: Intent, sensorId: Int, sensorType: Int, sensorTypeToString: String) {
    findViewById<ImageButton>(sensorId).setOnClickListener {
        if (sensorManager.getDefaultSensor(sensorType) != null) {
            intent.putExtra("sensor", sensorType)
            startActivity(intent)
        } else {
            Toast.makeText(context,
                "$sensorTypeToString sensor is not available on this device",
                Toast.LENGTH_LONG).show()
        }
    }
}


问:
Why does OnTime not execute when a userform is open?
I am attempting to use a self-activating OnTime sub to edit some text in a UF control. However, I find that an Application.OnTime event won't start working until  the UserForm is closed.

As per this SO thread, I have placed the self-activating sub in a public sub in a regular module. However, this is to no avail.

UF sub

```<code>Private Sub UserForm_Initialize
    TEST.loadingdots
End Sub
</code>```

Regular sub

```<code>Public Sub loadingdots
    Debug.Print 4
    Application.OnTime Now + TimeValue("00:00:02"), "loadingdots"
End Sub
</code>```

The first "4" gets printed, then nothing. When I close the UF, the procedure gets executed as expected.

How can I work around this?

答:
Answering my own question for future reference

When a UF holds a RefEdit control, an OnTime event won't be executed.

I created a new, blank UF, which caused no issues whatsoever.

Seems like RefEdits need to be approached with caution, similarly to how using a RefEdit control in a modeless userform forces the user to close the Excel application through task manager.

Body:
I am attempting to use a self-activating OnTime sub to edit some text in a UF control. However, I find that an Application.OnTime event won't start working until  the UserForm is closed.

As per this SO thread, I have placed the self-activating sub in a public sub in a regular module. However, this is to no avail.

UF sub

Private Sub UserForm_Initialize
    TEST.loadingdots
End Sub

Regular sub

Public Sub loadingdots
    Debug.Print 4
    Application.OnTime Now + TimeValue("00:00:02"), "loadingdots"
End Sub

The first "4" gets printed, then nothing. When I close the UF, the procedure gets executed as expected.

How can I work around this?


问:
How to `str.join` two list to strings of all combinations in Python3?
I want to get a list of ('A_1','A_2','B_1','B_2','C_1','C_2'), with something like '_'.join() and [(x, y) for x in ['A','B','C'] for y in [1,2]].

How to write this?

答:
Use itertools.product:

On python3.6+

```<code>import itertools
letters = ['A','B','C']
nums = [1, 2]
result = [f"{l}_{n}" for l, n in itertools.product(letters, nums)]
</code>```

Or in lower python versions:

```<code>result = ["{}_{}".format(l, n) for l, n in itertools.product(letters, nums)]
</code>```

Output:

```<code>>>> result
['A_1', 'A_2', 'B_1', 'B_2', 'C_1', 'C_2']
</code>```

Body:
Use itertools.product:

On python3.6+

import itertools
letters = ['A','B','C']
nums = [1, 2]
result = [f"{l}_{n}" for l, n in itertools.product(letters, nums)]

Or in lower python versions:

result = ["{}_{}".format(l, n) for l, n in itertools.product(letters, nums)]

Output:

>>> result
['A_1', 'A_2', 'B_1', 'B_2', 'C_1', 'C_2']


问:
What is the difference between different kernel sizes(1x1, 3x3, 5x5) in a convolution neural network?
I am working on cnn for image classification, i want to understand the difference between 1x1, 3x3, 5x5 size kernel in conv layer of cnn. Effect of each kernel, usages, advantage and disadvantage. When to use which kernel size. Does the size of kernel depends on the type of data, or size of data.</p>

答:
Lets divide the kernel sizes into 2 parts small and large, small being 1x1, 3x3 and large being 5x5.

Now the various comparisons between the 2 types of kernels could be as follows:

Receptive Field : The small kernel will have a smaller receptive field which means it will look at very few pixels at once whereas a  large kernel will look at a larger field view. This in turn would mean the the features extracted by a small kernel would be highly local whereas the features extracted from the  large kernel would be generic and spread across the image.

Amount of Information extracted : Small kernels would extract small complex features whereas the large kernel would extract simpler features . The amount of features extracted by large kernels would be considerably lesser than the small kernels.

With respect to Network :

Small kernels would lead to slow reduction of image dimensions making the network deep whereas large kernels would decrease the size of the image  really fast. Weight sharing is better in small kernels than large kernel. For example : Number of weights in two 3x3 kernels = 3x3 + 3x3 = 18 whereas the number of weights in 5x5 would be 25.

Memory : Since smaller kernels tend to make the network deeper it will require more memory whereas larger network tends to make the network smaller so requires less memory.

So 3x3 kernel is a popular choice among 1x1, 3x3 and 5x5 kernel for both reducing the dimensions of the images and capturing neighborhood information.  But this might not be applicable to all the datasets, for different datasets you will have to experiment with different kernel sizes and see which one performs the best for you. But yea to get an idea you consider the fact about complexity of features you want to capture in your image.

Notes that might be helpful :

 - 1x1 convolutions have their importance in dimensionality reduction for images. You can read about it here : https://iamaaditya.github.io/2016/03/one-by-one-convolution/

 - If you use an image sized kernel(large kernel) it will work just as a dense/fully connected layer.


问:
Angular 4 : Mega menu is not closed after clicked on a menu inside it
I am working in an angular 4 project ,In this I have a mega menu .What I want to do is when I clicked on a menu inside the mega menu I want to close it .

In my case it always open even after I clicked on a specific menu ,but closed if I remove the mouse focus in it .

Stackblitz : https://stackblitz.com/edit/angular-bootstrap-carousel-dynamic2-w1qhj4?file=app/app.component.html

can anyone help me to fix it .

答:
This Works  </p>

```<code>ngOnInit() {
    this.CartdataService.get_New_Products().subscribe(
      data => {
        this.storeData = data;
          console.log(this.storeData);
      });
  }

  categoryClick(event:Event, data,data2){
    alert(data2)
  }

  groupClick(event:Event, data,data2,data3, data4){
    //event.stopPropagation();
    //event.preventDefault();
  }

  subGroupClick(event:Event, data,data2,data3, data4, data5, data6){
    //event.stopPropagation();
    //event.preventDefault();
  }
}
</code>```

Body:
This Works

ngOnInit() {
    this.CartdataService.get_New_Products().subscribe(
      data => {
        this.storeData = data;
          console.log(this.storeData);
      });
  }

  categoryClick(event:Event, data,data2){
    alert(data2)
  }

  groupClick(event:Event, data,data2,data3, data4){
    //event.stopPropagation();
    //event.preventDefault();
  }

  subGroupClick(event:Event, data,data2,data3, data4, data5, data6){
    //event.stopPropagation();
    //event.preventDefault();
  }
}


问:
python openpyxl max_row counts all the rows instead of counting non-empty rows
I am using a excel sheet where it has 999 in total of rows and in which 20 rows are data filled rows and others are empty.

so when i print max_rows it gives me 999 numbers instead of 20 number! i am following this tutorial - openpyxl tutorial

```<code>wb = openpyxl.load_workbook(path)
s = wb.active
print(s.max_row)
</code>```

答:
That is expected. As per the docs max_row returns

The maximum row index containing data (1-based)

i.e. the maximum row index, not number of rows with data. If you have data just on e.g. row 100 you will get 100, not 1

Body:
I am using a excel sheet where it has 999 in total of rows and in which 20 rows are data filled rows and others are empty.

so when i print max_rows it gives me 999 numbers instead of 20 number! i am following this tutorial - openpyxl tutorial

wb = openpyxl.load_workbook(path)
s = wb.active
print(s.max_row)


问:
get object for all my documents in Cloud Firestore
I want to send a JSON of all my docuements in Firestore from my backend created with express

The Firestore docs says how to get all documents but the method is with forEach and express can send only once the response. So the problem is that I don't know how to render all forEach in a variable to send once for the headers

This is the code of Firestore docs:

```<code>  db.collection('users').get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });
</code>```

I hope somebody can help me.

答:
You could for example create and populate a JavaScript object of type array:</p>

```<code>  db.collection('users').get()
    .then((snapshot) => {
      var usersArray = [];
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
        usersArray.push(doc.data());
      });
      //do something with the usersArray
      //e.g. return usersArray;
      ///or return JSON.stringify(usersArray)
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });
</code>```

Body:
I want to send a JSON of all my docuements in Firestore from my backend created with express

The Firestore docs says how to get all documents but the method is with forEach and express can send only once the response. So the problem is that I don't know how to render all forEach in a variable to send once for the headers

This is the code of Firestore docs:

  db.collection('users').get()
    .then((snapshot) => {
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
      });
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });

I hope somebody can help me.

Body:
You could for example create and populate a JavaScript object of type array:

  db.collection('users').get()
    .then((snapshot) => {
      var usersArray = [];
      snapshot.forEach((doc) => {
        console.log(doc.id, '=>', doc.data());
        usersArray.push(doc.data());
      });
      //do something with the usersArray
      //e.g. return usersArray;
      ///or return JSON.stringify(usersArray)
    })
    .catch((err) => {
      console.log('Error getting documents', err);
    });


问:
How to Select between two periode of month and year eg: january 2018 - january 2019?
SQL query problem</p>

```<code>select *
from app_contract_hd
where year(created_datetime) between 2018 and 2018 and MONTH(created_datetime)between 4 and 4
</code>```

答:
if the data type is Datetime </p>

```<code>select * from app_contract_hd
where year(created_datetime) between cast('2018-01-01 00:00:00' as datetime) and  cast('2019-01-31 23:59:59'
as datetime)
</code>```

Body:
SQL query problem

select *
from app_contract_hd
where year(created_datetime) between 2018 and 2018 and MONTH(created_datetime)between 4 and 4

Body:
if the data type is Datetime

select * from app_contract_hd
where year(created_datetime) between cast('2018-01-01 00:00:00' as datetime) and  cast('2019-01-31 23:59:59'
as datetime)


问:
How do I exclude columns when exporting app engine data
I'm planning to do some data mining on my django app which uses appengine for storing data, however, one of my tables stores images in two of it's columns, and because of that, it is gigabytes in size so it's far too slow to download every time I want to analyse new data. For data mining, I only care about the plan text columns in that table, how do I exclude those columns while exporting data to an csv file?

I'm aware that there is a "column_list" for the csv connector for buildupload.yaml that you can specify to only include certain columns when exporting data, but it looks like it still downloads the entire table row before filtering out the columns when it's converting appengine's intermediate sqlite3 data file to csv.

For reference, I'm using the method described here to download my data http://code.google.com/appengine/docs/python/tools/uploadingdata.html, but I'm open to other solutions, preferably ones where I can automate this data export every few days.

答: You can't. The AppEngine datastore API, and the underlying GQL, only do two sorts of SELECT queries: __key__ only, and all fields. There's no way of getting a subset of fields.


问:
Suppose we had an algorithm that took in an array of strings, sorted each string, and then sorted the full array. What would the runtime be?
The questions is:

Suppose we had an algorithm that took in an array of strings, sorted each string, and then sorted the full array. What would the runtime be?

The solution is given as below:

What i find peculiar in the above solution is this: "You should also take into account that you need to compare the strings. Each string comparison takes O (s) time.There are O (a log a) comparisons, therefore this will take O (a*s log a) time."

What do we need the comparisons for?

It would take s log s time to sort a string. Say there a strings hence the total time taken would be a*s log s

Now the problem has shrunken down to simply sorting a given array which you can do in a log a time, hence the total time taken is a*s log s + a log a = a (s log s + log a)

Where did I go wrong in my thought process?

The question is taken from the book, Cracking The Coding Interview

答:
Sorting a list of numbers assumes that comparisons occur in O(1) constant time, giving the nlogn complexity, in terms of number of comparisons. However when we are sorting an enumerable whose members require a time x to compare,the run-time becomes xnlogn. This is because we are performing an action that requires x time, nlogn times.

But, I must also argue, that strings are a direct bijection to base 26. Since we consider comparison in base 10 to occur in constant time, there is no reason not to extend this to the strings which are essentially numbers in base 26. This really depends on the implementation of the string comparing mechanism. So, depending on how string comparison is done, we end up with two possible runtimes.

Yours is correct, if and only if we assume strings to be compared as numbers in base 26, and assuming that can be done in constant time.

Otherwise, sorting in general takes (Comparison time) x nlogn


问:
Merge-sorting a linked list
I'm required to sort a Linked list using merge sort. I've put together this code, but I'm running into a weird error.

My linked list is populated by random numbers. However, after sorting, it only displays numbers that are larger than the first element of the linked list, in sorted order.

Here is some of my code:

```<code>node* MergeSort(node *my_node)
{
    node *secondNode;

    if (my_node == NULL)
        return NULL;
    else if (my_node->next == NULL)
        return my_node;
    else
    {
        secondNode = Split(my_node);
        return Merge(MergeSort(my_node),MergeSort(secondNode));
    }
}

node* Merge(node* firstNode, node* secondNode)
{
    if (firstNode == NULL) return secondNode;
    else if (secondNode == NULL) return firstNode;
    else if (firstNode->number <= secondNode->number) //if I reverse the sign to >=, the behavior reverses
    {
        firstNode->next = Merge(firstNode->next, secondNode);
        return firstNode;
    }
    else
    {
        secondNode->next = Merge(firstNode, secondNode->next);
        return secondNode;
    }
}

node* Split(node* my_node)
{
    node* secondNode;

    if (my_node == NULL) return NULL;
    else if (my_node->next == NULL) return NULL;
    else {
        secondNode = my_node->next;
        my_node->next = secondNode->next;
        secondNode->next = Split(secondNode->next);
        return secondNode;
    }
}
</code>```

答:
I have tried your code and it works perfectly.

Have you looked at the right list in the end?
Your new head of the list is not the previous head, but the return value of
the Merge function.

```<code>printList(myList);
node* sortedList =  MergeSort(myList);
printList(sortedList); //whole list sorted
printList(myList); //list (of elements not smaller that first element) sorted
</code>```

and printList() is the obvious function:

```<code>void printList(node* my_node){
    if(my_node == NULL) return;
    else {
        std::cout<<my_node->number<<" "<<std::endl;
        printList(my_node->next);
    }
}
</code>```

Title: Merge-sorting a linked list

Body:
I'm required to sort a Linked list using merge sort. I've put together this code, but I'm running into a weird error.

My linked list is populated by random numbers. However, after sorting, it only displays numbers that are larger than the first element of the linked list, in sorted order.

Here is some of my code:

node* MergeSort(node *my_node)
{
    node *secondNode;

    if (my_node == NULL)
        return NULL;
    else if (my_node->next == NULL)
        return my_node;
    else
    {
        secondNode = Split(my_node);
        return Merge(MergeSort(my_node),MergeSort(secondNode));
    }
}

node* Merge(node* firstNode, node* secondNode)
{
    if (firstNode == NULL) return secondNode;
    else if (secondNode == NULL) return firstNode;
    else if (firstNode->number <= secondNode->number) //if I reverse the sign to >=, the behavior reverses
    {
        firstNode->next = Merge(firstNode->next, secondNode);
        return firstNode;
    }
    else
    {
        secondNode->next = Merge(firstNode, secondNode->next);
        return secondNode;
    }
}

node* Split(node* my_node)
{
    node* secondNode;

    if (my_node == NULL) return NULL;
    else if (my_node->next == NULL) return NULL;
    else {
        secondNode = my_node->next;
        my_node->next = secondNode->next;
        secondNode->next = Split(secondNode->next);
        return secondNode;
    }
}

Body:
I have tried your code and it works perfectly.

Have you looked at the right list in the end?
Your new head of the list is not the previous head, but the return value of
the Merge function.

printList(myList);
node* sortedList =  MergeSort(myList);
printList(sortedList); //whole list sorted
printList(myList); //list (of elements not smaller that first element) sorted

and printList() is the obvious function:

void printList(node* my_node){
    if(my_node == NULL) return;
    else {
        std::cout<<my_node->number<<" "<<std::endl;
        printList(my_node->next);
    }
}


问:
How to exclude non-numeric character in regex
I have a string which goes like this

```<code>Section 78(1) of the blabla
</code>```

These are my regex

```<code>\b\s(?!\b(\d{1,3}|\d{1,2}[a-zA-Z]|\d{5,})\b)\b\S*
</code>```

Expected output is: of the blabla

This regex works but it does not exclude "of" because of the (). Can anyone help me? Thank you

答:
It seems all you need to change is to remove the \b before \S* and replace the \S* with .+ or .* (if the match can be an empty string).

```<code>\s(?!\b(?:\d{1,3}|\d{1,2}[a-zA-Z]|\d{5,})\b)(.+)
</code>```

See the regex demo, grab Group 1 value. Note I turned the first group matching digits in the negative lookahead into a non-capturing group to avoid clutter in the resulting match list.

VB.NET demo:

```<code>Dim r As New Regex("\s(?!\b(?:\d{1,3}|\d{1,2}[a-zA-Z]|\d{5,})\b)(.+)")
Dim s As String
s = "Section 78(1) of the blabla"
For Each m As Match In r.Matches(s)
    Console.WriteLine(m.Groups(1).Value)
Next
</code>```

Result: of the blabla.

Body:
I have a string which goes like this

Section 78(1) of the blabla

These are my regex

\b\s(?!\b(\d{1,3}|\d{1,2}[a-zA-Z]|\d{5,})\b)\b\S*

Expected output is: of the blabla

This regex works but it does not exclude "of" because of the (). Can anyone help me? Thank you

Body:
It seems all you need to change is to remove the \b before \S* and replace the \S* with .+ or .* (if the match can be an empty string).

\s(?!\b(?:\d{1,3}|\d{1,2}[a-zA-Z]|\d{5,})\b)(.+)

See the regex demo, grab Group 1 value. Note I turned the first group matching digits in the negative lookahead into a non-capturing group to avoid clutter in the resulting match list.

VB.NET demo:

Dim r As New Regex("\s(?!\b(?:\d{1,3}|\d{1,2}[a-zA-Z]|\d{5,})\b)(.+)")
Dim s As String
s = "Section 78(1) of the blabla"
For Each m As Match In r.Matches(s)
    Console.WriteLine(m.Groups(1).Value)
Next

Result: of the blabla.


问:
does export_saved_model from TF2 save also weights?
I created, compiled and fitted a model with tf.keras using the latest TF2.0a.
Now I want to save this as a pb to be used later for inference.

I use :

```<code>import time
saved_model_path = "./models/pb/experimental/{}".format(int(time.time()))

tf.keras.experimental.export_saved_model(model, saved_model_path)
saved_model_path
</code>```

as nicely described here under point As a saved_model

The model is the model I previously created/compiled/fitted

Now my questions,

how does the export_saved_model know which weights to save? Or does it saves the weights from the last epoch?

following that logic, would be best to load the best model from your checkpoint and then use the export function?

Add on Question: Is there a callback which functions as modelcheckpoint from keras but with this export function? creating pb files of best model.

答:
you can have a look here: https://github.com/tensorflow/tensorflow/blob/master/tensorflow/python/keras/saving/saved_model.py

1) Keras saves the model with the last checkpoint, which are in fact the weights of the last epoch.

Cite from source:

The SavedModel contains:

a checkpoint containing the model weights.

a SavedModel proto containing the Tensorflow backend graph. Separate
  graphs are saved for prediction (serving), train, and evaluation. If
  the model has not been compiled, then only the graph computing predictions
  will be exported.

the model's json config. If the model is subclassed, this will only be
  included if the model's get_config() method is overwritten.

2) In my opinion the best way is to always seperate between model architecture and weights when saving and loading. In other terms: Yes, load the weights from the best model.

3) No, right now there is no callback that exports the whole model to pb. So either use the "ModelCheckpoint" Callback and load the optimal weights afterwards or build your own callback with "LambdaCallback".

I hope this helps!

Body:
I created, compiled and fitted a model with tf.keras using the latest TF2.0a.
Now I want to save this as a pb to be used later for inference.

I use :

import time
saved_model_path = "./models/pb/experimental/{}".format(int(time.time()))

tf.keras.experimental.export_saved_model(model, saved_model_path)
saved_model_path

as nicely described here under point As a saved_model

The model is the model I previously created/compiled/fitted

Now my questions,

how does the export_saved_model know which weights to save? Or does it saves the weights from the last epoch?

following that logic, would be best to load the best model from your checkpoint and then use the export function?

Add on Question: Is there a callback which functions as modelcheckpoint from keras but with this export function? creating pb files of best model.


问:
Subtract two numbers without using arithmetic operators
The problem that I am facing is :-

How does the logic of bitwise operators are working in the code below?

Code:

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

int subtract(int x, int y)
{
    while (y != 0)
    {
        int borrow = (~x) & y;
        x = x ^ y;
        y = borrow << 1;
    }
    return x;
}

int main()
{
    int x = 29, y = 13;
    printf("\nx - y is %d", subtract(x, y));
    return 0;
}
</code>```

How is the function subtract(x,y) is working?

答:
In binary,

```<code> x   y  | x-y
--- ---   ---
 0   0  |  0
 0   1  |  1 (with a borrow)
 1   0  |  1
 1   1  |  0
</code>```

which is to say

```<code> x   y  |       x-y
--- ---   ---------------
 0   0  |  0 - ( 0 << 1 )
 0   1  |  1 - ( 1 << 1 )
 1   0  |  1 - ( 0 << 1 )
 1   1  |  0 - ( 0 << 1 )
</code>```

That means that

```<code>x - y
</code>```

is equivalent to

```<code>( x ^ y ) - ( ( (~x) & y ) << 1 )
</code>```

because the result of the subtraction can be given by x ^ y

```<code> x   y  | x^y
--- ---   ---
 0   0  |  0
 0   1  |  1
 1   0  |  1
 1   1  |  0
</code>```

and the amount to borrow can be given by (~x) & y

```<code> x   y  | (~x) & y
--- ---   --------
 0   0  |     0
 0   1  |     1
 1   0  |     0
 1   1  |     0
</code>```

Checking what happens on (positive and negative) overflow is left to the user.

Body:
The problem that I am facing is :-

How does the logic of bitwise operators are working in the code below?

Code:

#include <stdio.h>

int subtract(int x, int y)
{
    while (y != 0)
    {
        int borrow = (~x) & y;
        x = x ^ y;
        y = borrow << 1;
    }
    return x;
}

int main()
{
    int x = 29, y = 13;
    printf("\nx - y is %d", subtract(x, y));
    return 0;
}

How is the function subtract(x,y) is working?

Body:
In binary,

 x   y  | x-y
--- ---   ---
 0   0  |  0
 0   1  |  1 (with a borrow)
 1   0  |  1
 1   1  |  0

which is to say

 x   y  |       x-y
--- ---   ---------------
 0   0  |  0 - ( 0 << 1 )
 0   1  |  1 - ( 1 << 1 )
 1   0  |  1 - ( 0 << 1 )
 1   1  |  0 - ( 0 << 1 )

That means that

x - y

is equivalent to

( x ^ y ) - ( ( (~x) & y ) << 1 )

because the result of the subtraction can be given by x ^ y

 x   y  | x^y
--- ---   ---
 0   0  |  0
 0   1  |  1
 1   0  |  1
 1   1  |  0

and the amount to borrow can be given by (~x) & y

 x   y  | (~x) & y
--- ---   --------
 0   0  |     0
 0   1  |     1
 1   0  |     0
 1   1  |     0

Checking what happens on (positive and negative) overflow is left to the user.


问:
To get column names from table having a particular value
Please tell me How to get column names where column value =123 for a particular row.Thanks in advance .</p>

答:
```<code>-- Test table
declare @T table(ID int, Col1 varchar(10), Col2 int, Col3 bit, Col4 varchar(max))
insert into @T values (1, '123', 123, 1, 'Some text long text')

-- ID to get one row
declare @ID int
set @ID = 1

-- Value to search for
declare @Val varchar(10)
set @Val = '123'

select
  Col.value('local-name(.)', 'varchar(max)') as ColName
from (select *
      from @T
      where ID = @ID
      for xml path(''), type) as T(XMLCol)
  cross apply
    T.XMLCol.nodes('*') as n(Col)
where Col.value('.', 'varchar(10)') = @Val
</code>```

Result

```<code>ColName
--------
Col1
Col2
</code>```

Body:
-- Test table
declare @T table(ID int, Col1 varchar(10), Col2 int, Col3 bit, Col4 varchar(max))
insert into @T values (1, '123', 123, 1, 'Some text long text')

-- ID to get one row
declare @ID int
set @ID = 1

-- Value to search for
declare @Val varchar(10)
set @Val = '123'

select
  Col.value('local-name(.)', 'varchar(max)') as ColName
from (select *
      from @T
      where ID = @ID
      for xml path(''), type) as T(XMLCol)
  cross apply
    T.XMLCol.nodes('*') as n(Col)
where Col.value('.', 'varchar(10)') = @Val

Result

ColName
--------
Col1
Col2


问:
sed: How to join the lines of a record with an empty line delimiting records
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

```<code>KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'
</code>```

I need to combine the lines like this:

```<code>KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'
</code>```

I'm a novice with sed but pieced together this ugly line.

```<code>sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'
</code>```

yea - there is a better way...

答:
I think awk is a way better for this job:

```<code>awk -v RS="\n\n" 'gsub(/\n/," ")' file
</code>```

this should give you the expected result.

Body:
I would like to use 'sed' to joins three lines that make up a record, with records separated by empty lines, and record fields separated by a space.

Here's a snip of data from the file:

KDFW
N 32°53.83'
W 097°02.26'

TOC
N 32°48.49'
W 097°01.39'

DART
N 32°17.15'
W 096°48.66'

I need to combine the lines like this:

KDFW N 32°53.83' W 097°02.26'
TOC N 32°48.49' W 097°01.39'
DART N 32°17.15' W 096°48.66'

I'm a novice with sed but pieced together this ugly line.

sed 'N;s/\n/ /' navlog.txt | sed 'N;s/\n/ /'

yea - there is a better way...

Body:
I think awk is a way better for this job:

awk -v RS="\n\n" 'gsub(/\n/," ")' file

this should give you the expected result.


答:
If your 'created_datetime' column is 'datetime' data type, you may try the next approach using DATEFROMPARTS() function:

```<code>SELECT *
FROM app_contract_hd
WHERE CONVERT(date, created_datetime) BETWEEN DATEFROMPARTS(2018, 1, 1) AND DATEFROMPARTS(2019, 1, 1)
</code>```

Additionally, if your want to filter your data with specific hour, use DATETIMEFROMPARTS():

```<code>SELECT *
FROM app_contract_hd
WHERE created_datetime BETWEEN DATEFROMPARTS(2018, 1, 1, 0, 0, 0, 0) AND DATEFROMPARTS(2019, 1, 1, 12, 0, 0, 0, 0)
</code>```

Title: How to Select between two periode of month and year eg: january 2018 - january 2019?

Body:
If your 'created_datetime' column is 'datetime' data type, you may try the next approach using DATEFROMPARTS() function:

SELECT *
FROM app_contract_hd
WHERE CONVERT(date, created_datetime) BETWEEN DATEFROMPARTS(2018, 1, 1) AND DATEFROMPARTS(2019, 1, 1)

Additionally, if your want to filter your data with specific hour, use DATETIMEFROMPARTS():

SELECT *
FROM app_contract_hd
WHERE created_datetime BETWEEN DATEFROMPARTS(2018, 1, 1, 0, 0, 0, 0) AND DATEFROMPARTS(2019, 1, 1, 12, 0, 0, 0, 0)


问:
Implement modal close on click outside
I've been trying to implement an onclick modal close in my system. I already implemented a modal onclick event using a close button but haven't done it successfully when clicking outside the modal

I already tried adding onclick listener on the div but the content is closing even clicking inside the modal window.

```<code><div
                className={"Overlay " + (this.state.hidden? "hidden": "show")}
                id={this.props.id + "-container"} onClick={() => {
                this.setState({ hidden: true })
            }}>
</code>```

here's my modal box rendering code so far

```<code> render() {
        const contentClassName = this.getContentClassName();

        if (this.props.show) {
            document.body.style.overflow = 'hidden';
        }

        const contentStyle = {
            width: this.props.width,
            height: this.props.height,
            position: "relative"
        };

        return (
            <div
                className={"Overlay " + (this.state.hidden? "hidden": "show")}
                id={this.props.id + "-container"} onClick={() => {
                this.setState({ hidden: true })
            }}>
                <div className={contentClassName}>
                    <div className={"Overlay-container"} style={contentStyle}>
                        <a id={this.props.id + '-closeButton'}
                           className="Overlay-closeBtn icon-close-zoom" onClick={() => {
                               this.setState({ hidden: true })
                        }}/>
                        {this.props.children}
                    </div>
                </div>
            </div>
        );
    }
</code>```

as expected i want the modal to be close when clicking outside the modal window. currently it's closing even after clicking the modal window.

答:
```<code><script>
$('html').click(function(e) {
        if(!$(e.target).hasClass("Overlay-container")) {
             document.getElementById('Overlay-container').style.display = "none"
        }
});
</script>
</code>```

your code switch the state show or hidden when you click on it(Of course you can't click closed one)

This function works when your click has no class element named "Overlay-container"

//add description

when you click your 'html', 'if' checks where you clicked and has class 'Overlay-container'.
And if there's no 'Overlay-container' on your click point, modal close.

Title: Implement modal close on click outside

Body:
I've been trying to implement an onclick modal close in my system. I already implemented a modal onclick event using a close button but haven't done it successfully when clicking outside the modal

I already tried adding onclick listener on the div but the content is closing even clicking inside the modal window.

 {
                this.setState({ hidden: true })
            }}>

here's my modal box rendering code so far

 render() {
        const contentClassName = this.getContentClassName();

        if (this.props.show) {
            document.body.style.overflow = 'hidden';
        }

        const contentStyle = {
            width: this.props.width,
            height: this.props.height,
            position: "relative"
        };

        return (

 {
                this.setState({ hidden: true })
            }}>

                         {
                               this.setState({ hidden: true })
                        }}/>
                        {this.props.children}

        );
    }

as expected i want the modal to be close when clicking outside the modal window. currently it's closing even after clicking the modal window.

Body:
<script>
$('html').click(function(e) {
        if(!$(e.target).hasClass("Overlay-container")) {
             document.getElementById('Overlay-container').style.display = "none"
        }
});
</script>

your code switch the state show or hidden when you click on it(Of course you can't click closed one)

This function works when your click has no class element named "Overlay-container"

//add description

when you click your 'html', 'if' checks where you clicked and has class 'Overlay-container'.
And if there's no 'Overlay-container' on your click point, modal close.


问:
Extract upwards pointing lane lines
We try to detect lane lines on a running track (and with this information the upcoming direction).

We currently use the following (simplified) steps:

Binary: transform the input with a binary threshold

Cropped: crop the region of interest (currently just the lower half of the image)

Canny: detect edges and group them with HoughLinesP

Upward Lines & Closing: only keep lines with an extreme slope - ignore horizontal lines

Result: find connected components and fit quadratic function through each line

This works in general (examples: straight.png, left.png) but has issues if for example a horizontal connection line wasn't removed (example: problems.png - bottom right & bottom left).
In such a case the two lines and the connection get interpreted as one connected component.

As our point of view can tilt a lot from left to right (camera mounted on a running person) it is quite hard to define a slope threshold for upwards pointing lines.

Is there a better way to get rid of non upwards pointing track lines?
As the current solution with canny, hough transform and slope filtering is not optimal for curves and sometimes doesn't work at all (as described above).

Would it be possible to get from the cropped image straight to the separated lines through morphology operations?
Similar to this example.
I know we have no strict horizontal lines which makes any fitting kernel a lot more complex (I assume).

Currently, we try to use perspective transformations to get a bird view on the track.
This should help to distinguish between horizontal and upward pointing lines.

Another small issue is too short lines which result in inaccurate approximated quadratic functions (most left line in problems.png and straight.png). This might be easily solvable (by requiring a minimal pixel count for a component to be counted as track line) and should not be part of this question.

EDIT (answer questions from vlad_tepesch)

What is with the curves? should they be part of your lane models or not?

We clearly want to detect curves of the running track - as this is needed for the direction estimation. But we want to ignore (remove) the horizontal connection curve on the bottom of the problems.png example.

4./6. rectification - camera distortion

I will take another look at rectification, until now I postponed it, as I thought it isn't that important.

7.3 how many pixel if overlap between segments is ignored (group pixel count)

Just draw all lines from a group and check the non zero pixel count?

10. lanes normally are not quadratic - look int clothoids instead - this may overkill so may be use a 3rd order polynomial instead

I get your point. Clothoids are out of scope at the moment, but I will keep them in mind.
How would you go with the direction estimation if we use more complex fitting?
Currently we just take the first coefficient of the 2nd oder polynomial to estimate the bending direction (and the degree of curvature to differentiate between curves and straight parts).

optional more advanced

Good point, we already thought about averaging results over multiple frames. I also keep that proposal in the back of my mind.

Straight

Left

Problems

答:
It seems that your real problem is the filtering and the connecting step. because you filter out a lot of horizontal components, then for connecting of the unfiltered nearly vertical lines only sub optimal segments are left.

What is with the curves? should they be part of your lane models or not?
At first I assume not, but it only has some influence during the grouping stage.

I would suggest the following steps

crop

binary (why wasting processing time on binarization of image parts that getting cropped)

canny (maybe try a vertical Sobel to get only horizontal edges)

consider rectification to correct the camera distortion

HoughLinesP

if you decided against a rectification of input image then rectify at least the coordinates of the output lines

From a processing time point of view this may be the more desirable option - however the hough line detector will be produce less optimal results depending on the strength of your cameras distortion

connect lines regardless of their directions

i would first try the following

for each segment calculate a line (point, direction)

find lines with similar parameters and check the distance of the segments

if close enough, group them into a line group

at the end you should have a few line groups with some properties you may calculate to estimate the quality

how many lines/segments belong to the group

how many pixel belong to the group (sum of length of all line segments)

how many pixel if overlap between segments is ignored (group pixel count)

the leftmost/rightmost pixel on the line group (some kind of group line segment)

fill ratio (group line length/group pixel count)

after that grouping the line segments and their assignment to the groups are not required any more, but i would keep the calculated properties.

if the bends should be part of the lane then i would try look for groups that continue the found groups at the end and merge them.

This should prevent merging of crossing lines.

filter the groups to your needs

fitting.

lanes normally are not quadratic

look int clothoids instead

this may overkill so may be use a 3rd order polynomial instead

optional more advanced

keep all the groups at the end

do filtering only at the output level

in the next frame match the old groups against the new one and do some tracking and plausibility checks of your models.

Title: Extract upwards pointing lane lines


问:
Qt - Why won't my widgets line up using a vertical layout inside a splitter?
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

```<code>/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H
</code>```

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.

答:
You are creating layout but never assign them.

If you want your widgets to be vertical aligned in your splitter, you need to set a vertical layout to the splitter and then add all your sub-widgets to the layout.

Body:
As per the screenshot below, why won't my widgets line up using a vertical layout inside a splitter?

/********************************************************************************
** Form generated from reading UI file 'test.ui'
**
** Created: Tue Apr 12 16:51:51 2011
**      by: Qt User Interface Compiler version 4.6.2
**
** WARNING! All changes made in this file will be lost when recompiling UI file!
********************************************************************************/

#ifndef UI_TEST_H
#define UI_TEST_H

#include <QtCore/QVariant>
#include <QtGui/QAction>
#include <QtGui/QApplication>
#include <QtGui/QButtonGroup>
#include <QtGui/QGridLayout>
#include <QtGui/QHeaderView>
#include <QtGui/QLineEdit>
#include <QtGui/QListWidget>
#include <QtGui/QMainWindow>
#include <QtGui/QSplitter>
#include <QtGui/QTreeWidget>
#include <QtGui/QVBoxLayout>
#include <QtGui/QWidget>

QT_BEGIN_NAMESPACE

class Ui_MainWindow
{
public:
    QWidget *centralwidget;
    QGridLayout *gridLayout;
    QSplitter *splitter;
    QTreeWidget *treeWidget;
    QWidget *widget;
    QVBoxLayout *verticalLayout;
    QLineEdit *lineEdit;
    QListWidget *listWidget;

    void setupUi(QMainWindow *MainWindow)
    {
    if (MainWindow->objectName().isEmpty())
        MainWindow->setObjectName(QString::fromUtf8("MainWindow"));
    MainWindow->resize(800, 600);
    centralwidget = new QWidget(MainWindow);
    centralwidget->setObjectName(QString::fromUtf8("centralwidget"));
    gridLayout = new QGridLayout(centralwidget);
    gridLayout->setObjectName(QString::fromUtf8("gridLayout"));
    splitter = new QSplitter(centralwidget);
    splitter->setObjectName(QString::fromUtf8("splitter"));
    splitter->setOrientation(Qt::Horizontal);
    treeWidget = new QTreeWidget(splitter);
    QTreeWidgetItem *__qtreewidgetitem = new QTreeWidgetItem();
    __qtreewidgetitem->setText(0, QString::fromUtf8("1"));
    treeWidget->setHeaderItem(__qtreewidgetitem);
    treeWidget->setObjectName(QString::fromUtf8("treeWidget"));
    splitter->addWidget(treeWidget);
    widget = new QWidget(splitter);
    widget->setObjectName(QString::fromUtf8("widget"));
    verticalLayout = new QVBoxLayout(widget);
    verticalLayout->setObjectName(QString::fromUtf8("verticalLayout"));
    verticalLayout->setContentsMargins(0, 0, 0, 0);
    lineEdit = new QLineEdit(widget);
    lineEdit->setObjectName(QString::fromUtf8("lineEdit"));

    verticalLayout->addWidget(lineEdit);

    listWidget = new QListWidget(widget);
    listWidget->setObjectName(QString::fromUtf8("listWidget"));

    verticalLayout->addWidget(listWidget);

    splitter->addWidget(widget);

    gridLayout->addWidget(splitter, 0, 0, 1, 1);

    MainWindow->setCentralWidget(centralwidget);

    retranslateUi(MainWindow);

    QMetaObject::connectSlotsByName(MainWindow);
    } // setupUi

    void retranslateUi(QMainWindow *MainWindow)
    {
    MainWindow->setWindowTitle(QApplication::translate("MainWindow", "MainWindow", 0, QApplication::UnicodeUTF8));
    } // retranslateUi

};

namespace Ui {
    class MainWindow: public Ui_MainWindow {};
} // namespace Ui

QT_END_NAMESPACE

#endif // UI_TEST_H

This is just a dummy ui uploaded here for the purpose of the question. In my real ui design I've tried every imaginable combination, but as soon as I start using splitters, it all goes out of alignment.


问:
I am using android studio and the mainactivity class is .kt type. I keep having this error: Expecting member declaration
I am using android studio and I have some issues with this piece of code. Could someone tell me what I am doing wrong?
The system keeps telling me "Expecting member declaration."

This is the code

```<code>class MainActivity: AppCompatActivity() {

   class TextView totalTextView;    //This is where I am having the error

        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)
</code>```

答:
```<code>This is not right way to create or define object of TextView.

1 > var totalTextView : TextView ? = null
1 > lateint var totalTextView : TextView

In kotlin, No need to define id of ViewGroup items , avoid to define the instance of view item  when you are using kotlin
</code>```

Body:
I am using android studio and I have some issues with this piece of code. Could someone tell me what I am doing wrong?
The system keeps telling me "Expecting member declaration."

This is the code

class MainActivity: AppCompatActivity() {

   class TextView totalTextView;    //This is where I am having the error

        override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)


问:
Next js dynamic API call with Express
I have an express server set up like so:

```<code>app.get('/', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    fetch('https://api.adzuna.com:443/v1/api/property/gb/search/1?app_id=1cd4129d&app_key=key&where=se16bx&distance=5&category=for-sale')
      .then(response => response.json())
      .then(data => {
          res.send(data) // Prints result from `response.json()` in getRequest
      })
      .catch(error => console.error(error))
  });
</code>```

I then have a Next.js page like so:

```<code>class About extends Component {
  state = {postcode: null}

  handleOnSubmit = e => {
      // calling the api passing the postcode
  }

  render() {
   return(
    <form>
      <input name="postcode" />
      <button onClick={this.handleOnSubmit}></button>
    </form>
   )
  }
}

About.getInitialProps = async function() {
  const res = await fetch('http://localhost:3001/');
  const data = await res.json();

  return {
    results: data
  }
}
</code>```

the API call in the Express server has a hard coded postcode in it.

where=se16bx

How can I pass that value in a dynamic way based on what the user will put into the form?

Thanks

答:
Yes you can create dynamic API call, for complete documentation you can see from here (Check /posts API).

In your case, you just need to add slug into your endpoint, then pass it to your fetcher function:

```<code>app.get('/:id*', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
    fetch(`https://api.adzuna.com:443/v1/api/property/gb/search/1?app_id=1cd4129d&app_key=key&where=${req.params.id}&distance=5&category=for-sale`)
      .then(response => response.json())
      .then(data => {
          res.send(data) // Prints result from `response.json()` in getRequest
      })
      .catch(error => console.error(error))
  });
</code>```

Title: Next js dynamic API call with Express

Body:
I have an express server set up like so:

app.get('/', (req, res) => {
    res.setHeader('Access-Control-Allow-Origin', '*');
    fetch('https://api.adzuna.com:443/v1/api/property/gb/search/1?app_id=1cd4129d&app_key=key&where=se16bx&distance=5&category=for-sale')
      .then(response => response.json())
      .then(data => {
          res.send(data) // Prints result from `response.json()` in getRequest
      })
      .catch(error => console.error(error))
  });

I then have a Next.js page like so:

class About extends Component {
  state = {postcode: null}

  handleOnSubmit = e => {
      // calling the api passing the postcode
  }

  render() {
   return(
    <form>
      <input name="postcode" />
      <button onClick={this.handleOnSubmit}></button>
    </form>
   )
  }
}

About.getInitialProps = async function() {
  const res = await fetch('http://localhost:3001/');
  const data = await res.json();

  return {
    results: data
  }
}

the API call in the Express server has a hard coded postcode in it.

where=se16bx

How can I pass that value in a dynamic way based on what the user will put into the form?

Thanks

Body:
Yes you can create dynamic API call, for complete documentation you can see from here (Check /posts API).

In your case, you just need to add slug into your endpoint, then pass it to your fetcher function:

app.get('/:id*', (req, res) => {
res.setHeader('Access-Control-Allow-Origin', '*');
    fetch(`https://api.adzuna.com:443/v1/api/property/gb/search/1?app_id=1cd4129d&app_key=key&where=${req.params.id}&distance=5&category=for-sale`)
      .then(response => response.json())
      .then(data => {
          res.send(data) // Prints result from `response.json()` in getRequest
      })
      .catch(error => console.error(error))
  });


问:
Eloquent condition not detecting accented letters in where condition
In my web application I have locations and every location has company_id and I don't want to have same names of location in same company. So I made this:

```<code>$name = $request->get('name');
$location = Location::find($id);
if ($location->name != $name) {
    $old_location = Location::where('company_id', $location->company_id)
        ->where('name', $name)
        ->first();
    if ($old_location) {
        $errors = ['name' => trans('asset.location').' '.$name.'
        '.trans('message.already_exists')];
            return back()->withErrors($errors)->withInput();
    }
}
</code>```

The problem is that if I have Service location and want to change it's name to Šervice it will not let me to do it. I have no location that is named like that. If condition goes through but in eloquent search it fails. How is this possible?

答:
I found solution! and after reading the top answer I changed my code for $old_location to this:

```<code>$old_location = Location::where('company_id', $location->company_id)
    ->whereRaw('name COLLATE utf8mb4_bin', $name)
    ->first();
</code>```

I used different collation for my eloquent where condition, and it's working flawlessly.

Body:
In my web application I have locations and every location has company_id and I don't want to have same names of location in same company. So I made this:

$name = $request->get('name');
$location = Location::find($id);
if ($location->name != $name) {
    $old_location = Location::where('company_id', $location->company_id)
        ->where('name', $name)
        ->first();
    if ($old_location) {
        $errors = ['name' => trans('asset.location').' '.$name.'
        '.trans('message.already_exists')];
            return back()->withErrors($errors)->withInput();
    }
}

The problem is that if I have Service location and want to change it's name to Šervice it will not let me to do it. I have no location that is named like that. If condition goes through but in eloquent search it fails. How is this possible?

Body:
I found solution! and after reading the top answer I changed my code for $old_location to this:

$old_location = Location::where('company_id', $location->company_id)
    ->whereRaw('name COLLATE utf8mb4_bin', $name)
    ->first();

I used different collation for my eloquent where condition, and it's working flawlessly.