问:
Iteratively generate numeric values
I have a table, let's call it Foo, there is a field called Bar in the table, also, there is a field called LoremIpsum.

Bar is an nvarchar but I'm only interested in Bar values which are convertable to an integer number.

LoremIpsum is also a number.

I want to get the first n (value) numbers beginning with k from my Foo table where LoremIpsum has a specific value (LoremIpsum1) and (value) not in select Bar from Foo where LoremIpsum = LoremIpsum1

My input is: (LoremIpsum1, n, k)

where LoremIpsum1 is a particular value for LoremIpsum, n is the number of numbers to get and k is the offset.

My output should be a set of numbers which don't exist in the table as Bar values if LoremIpsum = LoremIpsum1. My current command:

```<code>WITH    q AS
        (
        SELECT convert(bigint, 50000) AS num
        UNION ALL
        SELECT  convert(bigint, num + 1)
        FROM    q
        )
SELECT  top 200 *
FROM    q
where convert(bigint, num) not in (select convert(bigint, Bar) from Foo where LoremIpsum = 68 and isnumeric(Bar + 'e0') = 1)
option (maxrecursion 365);
</code>```

This query doesn't always work, at a computer the problem was that an nvarchar couldn't be converted to a bigint, probably it was a problem with the settings, the other error occurs if the needed recursion is deeper than the given maxrecursion.

In this case n = 200, k = 50000, LoremIpsum1 = 68

The main problem is that this query is recursive and I would like to modify it to be an iterative query.

Any help is greatly appreciated.

Best regards,
Lajos Arpad.

答:
The following view will yield up to 2^32 numbers, and could be extended to give more if necessary:

```<code>create view numbers AS
with
  n as (select 0 as n union select 1)
, nn as (select 0 as n from n as n1, n as n2, n as n3, n as n4)
, nnn as (select 0 as n from nn as n1, nn as n2, nn as n3, nn as n4)
, nnnn as (select 0 as n from nnn as n1, nnn as n2)
select row_number() over (order by n) AS n from nnnn

go

select n from numbers where n <= 50000
</code>```

Regrettably there is a sort stage in the query plan, so it starts to slow down noticeably as n gets really large.  However, on my desktop machine the slowdown does not really become apparent until generating around 1,000,000 rows.

You may see better performance if you work the exhibited strategy directly into your full query (rather than as a standalone view) as the number of rows that need to be sorted would reduced to the minimum.

Title: Iteratively generate numeric values

Body:
I have a table, let's call it Foo, there is a field called Bar in the table, also, there is a field called LoremIpsum.

Bar is an nvarchar but I'm only interested in Bar values which are convertable to an integer number.

LoremIpsum is also a number.

I want to get the first n (value) numbers beginning with k from my Foo table where LoremIpsum has a specific value (LoremIpsum1) and (value) not in select Bar from Foo where LoremIpsum = LoremIpsum1

My input is: (LoremIpsum1, n, k)

where LoremIpsum1 is a particular value for LoremIpsum, n is the number of numbers to get and k is the offset.

My output should be a set of numbers which don't exist in the table as Bar values if LoremIpsum = LoremIpsum1. My current command:

WITH    q AS
        (
        SELECT convert(bigint, 50000) AS num
        UNION ALL
        SELECT  convert(bigint, num + 1)
        FROM    q
        )
SELECT  top 200 *
FROM    q
where convert(bigint, num) not in (select convert(bigint, Bar) from Foo where LoremIpsum = 68 and isnumeric(Bar + 'e0') = 1)
option (maxrecursion 365);

This query doesn't always work, at a computer the problem was that an nvarchar couldn't be converted to a bigint, probably it was a problem with the settings, the other error occurs if the needed recursion is deeper than the given maxrecursion.

In this case n = 200, k = 50000, LoremIpsum1 = 68

The main problem is that this query is recursive and I would like to modify it to be an iterative query.

Any help is greatly appreciated.

Best regards,
Lajos Arpad.

Body:
The following view will yield up to 2^32 numbers, and could be extended to give more if necessary:

create view numbers AS
with
  n as (select 0 as n union select 1)
, nn as (select 0 as n from n as n1, n as n2, n as n3, n as n4)
, nnn as (select 0 as n from nn as n1, nn as n2, nn as n3, nn as n4)
, nnnn as (select 0 as n from nnn as n1, nnn as n2)
select row_number() over (order by n) AS n from nnnn

go

select n from numbers where n <= 50000

Regrettably there is a sort stage in the query plan, so it starts to slow down noticeably as n gets really large.  However, on my desktop machine the slowdown does not really become apparent until generating around 1,000,000 rows.

You may see better performance if you work the exhibited strategy directly into your full query (rather than as a standalone view) as the number of rows that need to be sorted would reduced to the minimum.


来源: stackexchange

问:
MPLABX Project stopped compiling when I changed of computer
I'm writing firmware for a PIC18F4550 using the MPLABX and the XC8 compiler. The project was compiling with some warnings, but I was able to compile and use the hexa file to simulate. So I decided to advance the work at home. I zipped the folder where the MPLABX project was and sent it by email. When I got home, I downloaded it. I installed the MPLABX and the XC8 compiler. The version is the same one I originally used, the most recent until now, 2.05.I opened the project without making any changes, I compiled it, however, it did not compile. Errors were found, the first listing was:

error: unknown type name 'far'

This error did not occur before. What could have happened? Does anyone have any ideas ?

答:
You will encounter a lot more problems if you start using interrupts etc. Take a look at this summary for all the changes made in the latest version.

https://www.microforum.cc/topic/5-i-used-to-use-to-locate-variables-but-since-xc8-20-this-is-no-longer-working

ContentLicense: CC BY-SA 4.0


问:
Hilbert Transform in Python?
I am trying to write the Hilbert transform from scratch but not use any built in libraries other than for fft and ifft. I am not a mathematician by trade but I found these two algorithms online for the Hilbert transform, one in C and one in MATLAB. I tried to do implement them both but neither of them are giving me the same result as SciPy's Hilbert. I for sure have made something wrong in my implementation. Any insight would be greatly appreciated.

First implementation:
(From MATLAB Website)
Hilbert uses a four-step algorithm:

Calculate the FFT of the input sequence, storing the result in a vector x.

Create a vector h whose elements h(i) have the values:

1 for i = 1, (n/2)+1

2 for i = 2, 3, ... , (n/2)

0 for i = (n/2)+2, ... , n

Calculate the element-wise product of x and h.

Calculate the inverse FFT of the sequence obtained in step 3 and returns the first n elements of the result.

My attempt:

def generate_array(n):
    a = np.hstack((np.full(n//2+1, 2), np.zeros(n//2-1)))
    a[[0, n//2]] = 1
    return a

def hilbert_from_scratch_2(u):
    fft_result = fft(u) #scipy fft

    n = len(u)

    to_multiply = generate_array(n)

    result = np.multiply(n,to_multiply)

    return ifft(result) #scipy ifft
```

<hr>

<p>Second Implementation:
(https://www.cfa.harvard.edu/~spaine/am/download/src/transform.c)</p>

<pre class="lang-c prettyprint-override"><code>void hilbert(double *z, unsigned long n)
{
    double x;
    unsigned long i, n2;

    n2 = n << 1;
    /*
     * Compute the (bit-reversed) Fourier transform of z.
     */
    fft_dif(z, n);
    /*
     * Form the transform of the analytic sequence by zeroing
     * the transform for negative time, except for the (N/2)th.
     * element.  Since z is now in bit-reversed order, this means
     * zeroing every other complex element.  The array indices of
     * the elements to be zeroed are 6,7,10,11...etc. (The real
     * and imaginary parts of the (N/2)th element are in z[2] and
     * z[3], respectively.)
     */
    for (i = 6; i < n2; i += 4) {
        z[i] = 0.;
        z[i+1] = 0.;
    }
    /*
     * The 0th and (N/2)th elements get multiplied by 0.5.  Test
     * for the trivial 1-point transform, just in case.
     */
    z[0] *= 0.5;
    z[1] *= 0.5;
    if (n > 1) {
        z[2] *= 0.5;
        z[3] *= 0.5;
    }
    /*
     * Compute the inverse transform.
     */
    ifft_dit(z, n);
    /*
     * Normalize the array.  The factor of 2 is left over from
     * forming the transform in the time domain.
     */
    x = 2. / (double)n;
    for (i = 0; i < n2; ++i)
        z[i] *= x;
    return;
}   /* hilbert() */
</code>```

My attempt:

def hilbert_from_scratch(signal):
    fast_ft = fft(signal) #scipy fft
    for i in range(6,len(signal),4):
        fast_ft[i] = 0
        fast_ft[i+1] = 0

    fast_ft[0] = fast_ft[0]*.5
    fast_ft[1] = fast_ft[1]*.5

    if(len(fast_ft) > 1):
        fast_ft[2] = fast_ft[2]*.5
        fast_ft[3] = fast_ft[3]*.5

    inverse_fft = ifft(fast_ft) #scipy ifft

    x = 2 / len(signal)

    for i in range(0,len(signal),1):
        inverse_fft[i] = inverse_fft[i]*x

    return inverse_fft
```

Any insight on why neither of them give the same result as SciPy's hilbert would be greatly appreciated.

答:
I had a look at your code, made a couple edits, and compared it to the scipy and MATLAB Hilbert transforms. The function hilbert_from_scratch returns a complex sequence; the real components are the original signal and the complex components are the Hilbert transform. If you want just the Hilbert Transform, use np.imag on the returned array.

import math
from scipy.fftpack import *

def hilbert_from_scratch(u):
    # N : fft length
    # M : number of elements to zero out
    # U : DFT of u
    # v : IDFT of H(U)

    N = len(u)
    # take forward Fourier transform
    U = fft(u)
    M = N - N//2 - 1
    # zero out negative frequency components
    U[N//2+1:] = [0] * M
    # double fft energy except @ DC0
    U[1:N//2] = 2 * U[1:N//2]
    # take inverse Fourier transform
    v = ifft(U)
    return v

if __name__ == '__main__':
    N = 32
    f = 1
    dt = 1.0 / N
    y = []
    for n in range(N):
        x = 2*math.pi*f*dt*n
        y.append(math.sin(x))
    z1 = hilbert_from_scratch(y)
    z2 = hilbert(y)
    print(" n     y fromscratch scipy")
    for n in range(N):
        print('{:2d} {:+5.2f} {:+10.2f} {:+5.2f}'.format(n, y[n], z1[n], z2[n]))
```

<p>Outputs:</p>

``` n     y fromscratch scipy
 0 +0.00 +0.00-1.00j +1.00
 1 +0.38 +0.38-0.92j +0.92
 2 +0.71 +0.71-0.71j +0.71
 3 +0.92 +0.92-0.38j +0.38
 4 +1.00 +1.00-0.00j +0.00
 5 +0.92 +0.92+0.38j -0.38
 6 +0.71 +0.71+0.71j -0.71
 7 +0.38 +0.38+0.92j -0.92
 8 +0.00 +0.00+1.00j -1.00
 9 -0.38 -0.38+0.92j -0.92
10 -0.71 -0.71+0.71j -0.71
11 -0.92 -0.92+0.38j -0.38
12 -1.00 -1.00+0.00j -0.00
13 -0.92 -0.92-0.38j +0.38
14 -0.71 -0.71-0.71j +0.71
15 -0.38 -0.38-0.92j +0.92
```

<p>MATLAB:</p>

```>> y = sin(2*pi*linspace(0,1,17)); z = hilbert(y(1:end-1));
>> fprintf('%+2.2f %+2.2f\n',[real(z);imag(z)])
+0.00 -1.00
+0.38 -0.92
+0.71 -0.71
+0.92 -0.38
+1.00 -0.00
+0.92 +0.38
+0.71 +0.71
+0.38 +0.92
+0.00 +1.00
-0.38 +0.92
-0.71 +0.71
-0.92 +0.38
-1.00 +0.00
-0.92 -0.38
-0.71 -0.71
-0.38 -0.92
```

Title: Hilbert Transform in Python?

Body:
I am trying to write the Hilbert transform from scratch but not use any built in libraries other than for fft and ifft. I am not a mathematician by trade but I found these two algorithms online for the Hilbert transform, one in C and one in MATLAB. I tried to do implement them both but neither of them are giving me the same result as SciPy's Hilbert. I for sure have made something wrong in my implementation. Any insight would be greatly appreciated.

First implementation:
(From MATLAB Website)
Hilbert uses a four-step algorithm:

Calculate the FFT of the input sequence, storing the result in a vector x.

Create a vector h whose elements h(i) have the values:

1 for i = 1, (n/2)+1

2 for i = 2, 3, ... , (n/2)

0 for i = (n/2)+2, ... , n

Calculate the element-wise product of x and h.

Calculate the inverse FFT of the sequence obtained in step 3 and returns the first n elements of the result.

My attempt:

def generate_array(n):
    a = np.hstack((np.full(n//2+1, 2), np.zeros(n//2-1)))
    a[[0, n//2]] = 1
    return a

def hilbert_from_scratch_2(u):
    fft_result = fft(u) #scipy fft

    n = len(u)

    to_multiply = generate_array(n)

    result = np.multiply(n,to_multiply)

    return ifft(result) #scipy ifft

Second Implementation:
(https://www.cfa.harvard.edu/~spaine/am/download/src/transform.c)

void hilbert(double *z, unsigned long n)
{
    double x;
    unsigned long i, n2;

    n2 = n << 1;
    /*
     * Compute the (bit-reversed) Fourier transform of z.
     */
    fft_dif(z, n);
    /*
     * Form the transform of the analytic sequence by zeroing
     * the transform for negative time, except for the (N/2)th.
     * element.  Since z is now in bit-reversed order, this means
     * zeroing every other complex element.  The array indices of
     * the elements to be zeroed are 6,7,10,11...etc. (The real
     * and imaginary parts of the (N/2)th element are in z[2] and
     * z[3], respectively.)
     */
    for (i = 6; i < n2; i += 4) {
        z[i] = 0.;
        z[i+1] = 0.;
    }
    /*
     * The 0th and (N/2)th elements get multiplied by 0.5.  Test
     * for the trivial 1-point transform, just in case.
     */
    z[0] *= 0.5;
    z[1] *= 0.5;
    if (n > 1) {
        z[2] *= 0.5;
        z[3] *= 0.5;
    }
    /*
     * Compute the inverse transform.
     */
    ifft_dit(z, n);
    /*
     * Normalize the array.  The factor of 2 is left over from
     * forming the transform in the time domain.
     */
    x = 2. / (double)n;
    for (i = 0; i < n2; ++i)
        z[i] *= x;
    return;
}   /* hilbert() */

My attempt:

def hilbert_from_scratch(signal):
    fast_ft = fft(signal) #scipy fft
    for i in range(6,len(signal),4):
        fast_ft[i] = 0
        fast_ft[i+1] = 0

    fast_ft[0] = fast_ft[0]*.5
    fast_ft[1] = fast_ft[1]*.5

    if(len(fast_ft) > 1):
        fast_ft[2] = fast_ft[2]*.5
        fast_ft[3] = fast_ft[3]*.5

    inverse_fft = ifft(fast_ft) #scipy ifft

    x = 2 / len(signal)

    for i in range(0,len(signal),1):
        inverse_fft[i] = inverse_fft[i]*x

    return inverse_fft

Any insight on why neither of them give the same result as SciPy's hilbert would be greatly appreciated.

Body:
I had a look at your code, made a couple edits, and compared it to the scipy and MATLAB Hilbert transforms. The function hilbert_from_scratch returns a complex sequence; the real components are the original signal and the complex components are the Hilbert transform. If you want just the Hilbert Transform, use np.imag on the returned array.

import math
from scipy.fftpack import *

def hilbert_from_scratch(u):
    # N : fft length
    # M : number of elements to zero out
    # U : DFT of u
    # v : IDFT of H(U)

    N = len(u)
    # take forward Fourier transform
    U = fft(u)
    M = N - N//2 - 1
    # zero out negative frequency components
    U[N//2+1:] = [0] * M
    # double fft energy except @ DC0
    U[1:N//2] = 2 * U[1:N//2]
    # take inverse Fourier transform
    v = ifft(U)
    return v

if __name__ == '__main__':
    N = 32
    f = 1
    dt = 1.0 / N
    y = []
    for n in range(N):
        x = 2*math.pi*f*dt*n
        y.append(math.sin(x))
    z1 = hilbert_from_scratch(y)
    z2 = hilbert(y)
    print(" n     y fromscratch scipy")
    for n in range(N):
        print('{:2d} {:+5.2f} {:+10.2f} {:+5.2f}'.format(n, y[n], z1[n], z2[n]))

Outputs:

 n     y fromscratch scipy
 0 +0.00 +0.00-1.00j +1.00
 1 +0.38 +0.38-0.92j +0.92
 2 +0.71 +0.71-0.71j +0.71
 3 +0.92 +0.92-0.38j +0.38
 4 +1.00 +1.00-0.00j +0.00
 5 +0.92 +0.92+0.38j -0.38
 6 +0.71 +0.71+0.71j -0.71
 7 +0.38 +0.38+0.92j -0.92
 8 +0.00 +0.00+1.00j -1.00
 9 -0.38 -0.38+0.92j -0.92
10 -0.71 -0.71+0.71j -0.71
11 -0.92 -0.92+0.38j -0.38
12 -1.00 -1.00+0.00j -0.00
13 -0.92 -0.92-0.38j +0.38
14 -0.71 -0.71-0.71j +0.71
15 -0.38 -0.38-0.92j +0.92

MATLAB:

>> y = sin(2*pi*linspace(0,1,17)); z = hilbert(y(1:end-1));
>> fprintf('%+2.2f %+2.2f\n',[real(z);imag(z)])
+0.00 -1.00
+0.38 -0.92
+0.71 -0.71
+0.92 -0.38
+1.00 -0.00
+0.92 +0.38
+0.71 +0.71
+0.38 +0.92
+0.00 +1.00
-0.38 +0.92
-0.71 +0.71
-0.92 +0.38
-1.00 +0.00
-0.92 -0.38
-0.71 -0.71
-0.38 -0.92


问:
Convert from one date-time format to a different date-time format
I want to convert a time which is taken as an argument to the Perl script into a different format.

The input is of the form yyyyMMddHHmmss (e.g. 20190101235010).

The output should be of of the form yyyy-MM-dd-HH:mm:ss (e.g. 2019-01-01-23:50:10).

It would be better if solution doesn't use Perl Modules (except POSIX).

答:
The core module Time::Piece does this easily.</p>

```<code>use strict;
use warnings;
use Time::Piece;

# if input is the format you specified:
my $input = '20190101235010';
my $time = Time::Piece->strptime($input, '%Y%m%d%H%M%S');
print $time->strftime('%Y-%m-%d-%H:%M:%S'), "\n";

# if input is a unix epoch timestamp:
my $input = time;
my $time = gmtime $input;
print $time->strftime('%Y-%m-%d-%H:%M:%S'), "\n";
</code>```

Body:
The core module Time::Piece does this easily.

use strict;
use warnings;
use Time::Piece;

# if input is the format you specified:
my $input = '20190101235010';
my $time = Time::Piece->strptime($input, '%Y%m%d%H%M%S');
print $time->strftime('%Y-%m-%d-%H:%M:%S'), "\n";

# if input is a unix epoch timestamp:
my $input = time;
my $time = gmtime $input;
print $time->strftime('%Y-%m-%d-%H:%M:%S'), "\n";


问:
Is there an opposite to display:none?
The opposite of visibility: hidden is visibility: visible.  Similarly, is there any opposite for display: none?

Many people become confused figuring out how to show an element when it has display: none, since it's not as clear as using the visibility property.

I could just use visibility: hidden instead of display: none, but it does not give the same effect, so I am not going with it.

答:
You can use display: block

Example :

```<code><!DOCTYPE html>
<html>
<body>

<p id="demo">Lorem Ipsum</p>

<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

</body>
</html>
</code>```

ContentLicense: CC BY-SA 3.0

Title: Is there an opposite to display:none?

Body:
You can use display: block

Example :

<!DOCTYPE html>
<html>
<body>

<p id="demo">Lorem Ipsum</p>

<button type="button"
onclick="document.getElementById('demo').style.display='none'">Click Me!</button>
<button type="button"
onclick="document.getElementById('demo').style.display='block'">Click Me!</button>

</body>
</html>


问:
sharing ListView between classes
I have a ListView code in a class but I want to show the list into another class. How can I do it?

```<code>public class listar_teste extends ListActivity
{
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse",
            "Ubuntu", "Solaris", "Android", "iPhone" };
  setListAdapter(new ArrayAdapter<String>(this, R.layout.lista_categorias, names));

  ListView lv = getListView();
  lv.setTextFilterEnabled(true);
  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
      // When clicked, show a toast with the TextView text
      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
          Toast.LENGTH_SHORT).show();
    }
  });
}
</code>```

}

I want to put in a ListView from another class..

答: You should be able to instantiate your specialized version of ListActivity wherever you use a normal ListActivity. You can even use it in a layout by specifying the full package in the tag name.

Title: sharing ListView between classes

Body:
I have a ListView code in a class but I want to show the list into another class. How can I do it?

public class listar_teste extends ListActivity
{
@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse",
            "Ubuntu", "Solaris", "Android", "iPhone" };
  setListAdapter(new ArrayAdapter<String>(this, R.layout.lista_categorias, names));

  ListView lv = getListView();
  lv.setTextFilterEnabled(true);
  lv.setOnItemClickListener(new OnItemClickListener() {
    public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {
      // When clicked, show a toast with the TextView text
      Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
          Toast.LENGTH_SHORT).show();
    }
  });
}

}

I want to put in a ListView from another class..


问:
Laravel Using config() in request validation
I'm using laravel 5.8 and I want to use access global config() in Request validation class but it does not work

```<code>namespace App\Http\Requests;

use App\AppConstant;
use Illuminate\Foundation\Http\FormRequest;

class Something extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'url' => 'required',
            'category' => 'in:'.implode(",", config('app.categories').''
        ];
    }
}
</code>```

and here is part of my config/app.php

```<code>return [

    'name' => env('APP_NAME', 'Laravel'),
    'categories' => [
        'games',
        'entertainment'
    ],

</code>```

but the output is

```<code>Class App\\Http\\Requests\\Something does not exist
</code>```

```<code>when i remove config() from request file it works very well
</code>```

答:
your code is missing a close bracket ) after categories. it should be </p>

```<code>'category' => 'in:'.implode(",", config('app.categories')).''
</code>```

Body:
I'm using laravel 5.8 and I want to use access global config() in Request validation class but it does not work

namespace App\Http\Requests;

use App\AppConstant;
use Illuminate\Foundation\Http\FormRequest;

class Something extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'url' => 'required',
            'category' => 'in:'.implode(",", config('app.categories').''
        ];
    }
}

and here is part of my config/app.php

return [

    'name' => env('APP_NAME', 'Laravel'),
    'categories' => [
        'games',
        'entertainment'
    ],

but the output is

Class App\\Http\\Requests\\Something does not exist

when i remove config() from request file it works very well

Body:
your code is missing a close bracket ) after categories. it should be

'category' => 'in:'.implode(",", config('app.categories')).''


问:
making permutation from two list but not using full number
I want to create a list of all possible  permutation from two list. However, I do not want to make with full length.
For example, first list is ["a", "e", "i", "o" "u"] and second is [1, 2, 3, 4, 5]
then one of the outcome would be like [["a",1,"i",2],["u",4,"e",s].....]

```<code>listsOfPossibilitiesN ::[a] -> [a]  -> [[a]]
listsOfPossibilitiesN  a b = case a of
    _ -> (listMakerN [] a b (length a) (length b) 0)

-- | list = storage, and show at the end of loop, p1h = first list, p2h = second list,
-- | count(x) = count to stop loop when the thing is fully rotated, depthCount = count to stop all loop when the depth reached 10
listMakerN :: [a] -> [a]  -> [a] -> Integer  -> Integer -> Integer -> [[a]]
listMakerN list p1h  p2h count1 count2 depthCount
    | depthCount == 10 = [list]
    | count1 == 0 = []
    | otherwise = case p1h of
                    ((x:xs)) -> (listMaker2N (list ++ [x])  xs p2h (count2 - 1) count2 (depthCount + 1)) ++ listMakerN list (xs ++ [x]) p2h (count1 - 1) count2 depthCount

listMaker2N ::  [a] -> [a]  -> [a] -> Integer -> Integer  -> Integer -> [[a]]
listMaker2N list  p1h  p2h count1 count2 depthCount
    | depthCount == 10 = [list]
    | count2 == 0 = []
    | otherwise = case p2h of
                    ((x:xs)) -> (listMakerN (list ++ [x])  p1h xs count1 (count1 ) (depthCount + 1))  ++ listMaker2N list p1h (xs ++ [x]) count1 (count2 - 1) depthCount

</code>```

I made this function above (I am sorry for bad image. I finally could figure out how t put code in question), but it takes too long to get result.
How do i do better?(Just to remind you, I am a beginner of programming)

and, the output is:

```<code>> listsOfPossibilitiesN  [1,2,3,4,5,6,7,8,9,10] [100,200,300,400,500,600,700,800,900,1000]
[[1,100,2,200,3,300,4,400,5,500],[1,100,2,200,3,300,4,400,5,600],[1,100,2,200,3,300,4,400,5,700],[1,100,2,200,3,300,4,400,5,800],[1,100,2,200,3,300,4,400,5,900],[1,100,2,200,3,300,4,400,5,1000],[1,100,
2,200,3,300,4,400,6,500],[1,100,2,200,3,300,4,400,6,600],[1,100,2,200,3,300,4,400,6,700],[1,100,2,200,3,300,4,400,6,800],[1,100,2,200,3,300,4,400,6,900],[1,100,2,200,3,300,4,400,6,1000],[1,100,2,200,3,
300,4,400,7,500],[1,100,2,200,3,300,4,400,7,600],..]
</code>```

答:
Making a guess at what your current code does, here's a proposal for an algorithm:

nondeterministically pick a permutation of the vowels

assign indices to the permutation

use the standard tails trick to nondeterministically choose the appropriate number of elements from this list

In code:

```<code>import Data.List

choose :: Int -> [a] -> [[a]]
choose 0 xs = [[]]
choose n xs = do
    x:xs' <- tails xs
    (x:) <$> choose (n-1) xs'

assignments :: Int -> [a] -> [[(Int, a)]]
assignments n xs = do
    xs' <- permutations xs
    choose n (zip [1..] xs')
</code>```

In ghci:

```<code>> mapM_ print (assignments 2 "abc")
[(1,'a'),(2,'b')]
[(1,'a'),(3,'c')]
[(2,'b'),(3,'c')]
[(1,'b'),(2,'a')]
[(1,'b'),(3,'c')]
[(2,'a'),(3,'c')]
[(1,'c'),(2,'b')]
[(1,'c'),(3,'a')]
[(2,'b'),(3,'a')]
[(1,'b'),(2,'c')]
[(1,'b'),(3,'a')]
[(2,'c'),(3,'a')]
[(1,'c'),(2,'a')]
[(1,'c'),(3,'b')]
[(2,'a'),(3,'b')]
[(1,'a'),(2,'c')]
[(1,'a'),(3,'b')]
[(2,'c'),(3,'b')]
</code>```

Body:
I want to create a list of all possible  permutation from two list. However, I do not want to make with full length.
For example, first list is ["a", "e", "i", "o" "u"] and second is [1, 2, 3, 4, 5]
then one of the outcome would be like [["a",1,"i",2],["u",4,"e",s].....]

listsOfPossibilitiesN ::[a] -> [a]  -> [[a]]
listsOfPossibilitiesN  a b = case a of
    _ -> (listMakerN [] a b (length a) (length b) 0)

-- | list = storage, and show at the end of loop, p1h = first list, p2h = second list,
-- | count(x) = count to stop loop when the thing is fully rotated, depthCount = count to stop all loop when the depth reached 10
listMakerN :: [a] -> [a]  -> [a] -> Integer  -> Integer -> Integer -> [[a]]
listMakerN list p1h  p2h count1 count2 depthCount
    | depthCount == 10 = [list]
    | count1 == 0 = []
    | otherwise = case p1h of
                    ((x:xs)) -> (listMaker2N (list ++ [x])  xs p2h (count2 - 1) count2 (depthCount + 1)) ++ listMakerN list (xs ++ [x]) p2h (count1 - 1) count2 depthCount

listMaker2N ::  [a] -> [a]  -> [a] -> Integer -> Integer  -> Integer -> [[a]]
listMaker2N list  p1h  p2h count1 count2 depthCount
    | depthCount == 10 = [list]
    | count2 == 0 = []
    | otherwise = case p2h of
                    ((x:xs)) -> (listMakerN (list ++ [x])  p1h xs count1 (count1 ) (depthCount + 1))  ++ listMaker2N list p1h (xs ++ [x]) count1 (count2 - 1) depthCount

I made this function above (I am sorry for bad image. I finally could figure out how t put code in question), but it takes too long to get result.
How do i do better?(Just to remind you, I am a beginner of programming)

and, the output is:

> listsOfPossibilitiesN  [1,2,3,4,5,6,7,8,9,10] [100,200,300,400,500,600,700,800,900,1000]
[[1,100,2,200,3,300,4,400,5,500],[1,100,2,200,3,300,4,400,5,600],[1,100,2,200,3,300,4,400,5,700],[1,100,2,200,3,300,4,400,5,800],[1,100,2,200,3,300,4,400,5,900],[1,100,2,200,3,300,4,400,5,1000],[1,100,
2,200,3,300,4,400,6,500],[1,100,2,200,3,300,4,400,6,600],[1,100,2,200,3,300,4,400,6,700],[1,100,2,200,3,300,4,400,6,800],[1,100,2,200,3,300,4,400,6,900],[1,100,2,200,3,300,4,400,6,1000],[1,100,2,200,3,
300,4,400,7,500],[1,100,2,200,3,300,4,400,7,600],..]

Body:
Making a guess at what your current code does, here's a proposal for an algorithm:

nondeterministically pick a permutation of the vowels

assign indices to the permutation

use the standard tails trick to nondeterministically choose the appropriate number of elements from this list

In code:

import Data.List

choose :: Int -> [a] -> [[a]]
choose 0 xs = [[]]
choose n xs = do
    x:xs' <- tails xs
    (x:) <$> choose (n-1) xs'

assignments :: Int -> [a] -> [[(Int, a)]]
assignments n xs = do
    xs' <- permutations xs
    choose n (zip [1..] xs')

In ghci:

> mapM_ print (assignments 2 "abc")
[(1,'a'),(2,'b')]
[(1,'a'),(3,'c')]
[(2,'b'),(3,'c')]
[(1,'b'),(2,'a')]
[(1,'b'),(3,'c')]
[(2,'a'),(3,'c')]
[(1,'c'),(2,'b')]
[(1,'c'),(3,'a')]
[(2,'b'),(3,'a')]
[(1,'b'),(2,'c')]
[(1,'b'),(3,'a')]
[(2,'c'),(3,'a')]
[(1,'c'),(2,'a')]
[(1,'c'),(3,'b')]
[(2,'a'),(3,'b')]
[(1,'a'),(2,'c')]
[(1,'a'),(3,'b')]
[(2,'c'),(3,'b')]


问:
Wait for element to be clickable using python and Selenium
There are ways to wait for an object e.g. a button to be clickable in selenium python. I use time.sleep() and/or WebDriverWait...until, it works fine.

However, when there are hundreds of objects, is there a way to set a default time lag globally, instead of implementing it on each object?

The click() action should have a conditional wait time?

答:
You can do a few things...

Define a global default wait time and then use that in each wait you create.

```<code>default_wait_time = 10 # seconds
...
wait = WebDriverWait(driver, default_wait_time)
</code>```

Inside of a method where you will use the wait several times, you can instantiate a wait, store it in a variable, and then reuse it.

```<code>def my_method(self):
    wait = WebDriverWait(driver, 10)
    wait.until(EC.visibility_of_element_located((By.ID, "username")).send_keys("username")
    wait.until(EC.visibility_of_element_located((By.ID, "password")).send_keys("password")
    wait.until(EC.element_to_be_clickable((By.ID, "login")).click()
</code>```

Define a default WebDriverWait instance and then just repeatedly use that.

Note: if you are or will run your script(s) in parallel, you need to be very careful with this approach because an instance of WebDriverWait is tied to a specific driver.

```<code># some global location
wait = WebDriverWait(driver, 10)
...
# in your script, page object, helper method, etc.
wait.until(EC.element_to_be_clickable((By.ID, "login")).click()
</code>```

Body:
You can do a few things...

Define a global default wait time and then use that in each wait you create.

default_wait_time = 10 # seconds
...
wait = WebDriverWait(driver, default_wait_time)

Inside of a method where you will use the wait several times, you can instantiate a wait, store it in a variable, and then reuse it.

def my_method(self):
    wait = WebDriverWait(driver, 10)
    wait.until(EC.visibility_of_element_located((By.ID, "username")).send_keys("username")
    wait.until(EC.visibility_of_element_located((By.ID, "password")).send_keys("password")
    wait.until(EC.element_to_be_clickable((By.ID, "login")).click()

Define a default WebDriverWait instance and then just repeatedly use that.

Note: if you are or will run your script(s) in parallel, you need to be very careful with this approach because an instance of WebDriverWait is tied to a specific driver.

# some global location
wait = WebDriverWait(driver, 10)
...
# in your script, page object, helper method, etc.
wait.until(EC.element_to_be_clickable((By.ID, "login")).click()


问:
Express sendFile function
I am trying to write some API using node.js. I have a pdf file stored in Temp folder, and I want to send it using res.sendFile(). But when i try so, it just sends back empty file (not even pdf file), with no error.

I have already tried using both relative and absolute path.

```<code>res.sendFile(`${os.tmpdir}/download/something.pdf`);
</code>```

答:
It sounds like you may have an invalid file path. Try using the __dirname global to make the path to the file relative to the directory in which you are executing your node script.

```<code>res.sendFile(__dirname + "/download/something.pdf");
</code>```

Title: Express sendFile function

Body:
I am trying to write some API using node.js. I have a pdf file stored in Temp folder, and I want to send it using res.sendFile(). But when i try so, it just sends back empty file (not even pdf file), with no error.

I have already tried using both relative and absolute path.

res.sendFile(`${os.tmpdir}/download/something.pdf`);

Body:
It sounds like you may have an invalid file path. Try using the __dirname global to make the path to the file relative to the directory in which you are executing your node script.

res.sendFile(__dirname + "/download/something.pdf");


问:
Rails 5 Active Record - Query that determines if sibling record exists
The software I'm building helps plan events and contact people to attend events. We want to identify all Users who we have not yet invited to a specific event via a PhoneCall. To do this we want to query:

1) All Users for whom no ContactAttempt for any event exists

2) Users who for whom no ContactAttempt with event_id = this event.id and this attempted_type = PhoneCall. (this captures those who we contacted via a Text but not a PhoneCall)

```<code>User.includes(:contact_attempts).references(:contact_attempts)
.where('contact_attempts.id IS NULL OR (contact_attempts.event_id = ? AND contact_attempts.attempted_type != ?)', @event.id, "PhoneCall")
</code>```

But this query leaves out third group of Users I want to target, who I have been unable to include in the query:

The Users who have a ContactAttempt for a different event_id, but not for this event_id. At first I thought it could be done with contact_attempts.event_id != ?, but that included all Users who had an existing ContactAttempt even if they have been contacted for this event_id,

How can I construct the query to also target all Users who have no ContactAttempt for this particular event with attempted_type = PhoneCall, but may have a ContactAttempt for a previous event?

Is this something that requires Arel?

答:
```<code>User.joins('LEFT OUTER JOIN contact_attempts
            ON contact_attempts.user_id = users.id')
    .where('contact_attempts.id IS NULL
            OR (contact_attempts.event_id = ?
            AND contact_attempts.attempted_type != ?)',
            @event.id, "PhoneCall")
</code>```

I think the issue with the includes and references is it won't get users without the association, where as left join will return users both with and without contact attempts

Body:
The software I'm building helps plan events and contact people to attend events. We want to identify all Users who we have not yet invited to a specific event via a PhoneCall. To do this we want to query:

1) All Users for whom no ContactAttempt for any event exists

2) Users who for whom no ContactAttempt with event_id = this event.id and this attempted_type = PhoneCall. (this captures those who we contacted via a Text but not a PhoneCall)

User.includes(:contact_attempts).references(:contact_attempts)
.where('contact_attempts.id IS NULL OR (contact_attempts.event_id = ? AND contact_attempts.attempted_type != ?)', @event.id, "PhoneCall")

But this query leaves out third group of Users I want to target, who I have been unable to include in the query:

The Users who have a ContactAttempt for a different event_id, but not for this event_id. At first I thought it could be done with contact_attempts.event_id != ?, but that included all Users who had an existing ContactAttempt even if they have been contacted for this event_id,

How can I construct the query to also target all Users who have no ContactAttempt for this particular event with attempted_type = PhoneCall, but may have a ContactAttempt for a previous event?

Is this something that requires Arel?

Body:
User.joins('LEFT OUTER JOIN contact_attempts
            ON contact_attempts.user_id = users.id')
    .where('contact_attempts.id IS NULL
            OR (contact_attempts.event_id = ?
            AND contact_attempts.attempted_type != ?)',
            @event.id, "PhoneCall")

I think the issue with the includes and references is it won't get users without the association, where as left join will return users both with and without contact attempts


问:
Android click events acting strangely
I've been following these 2 tutorials to setup a list & click events:

http://mfarhan133.wordpress.com/2010/10/14/list-view-tutorial-for-android/
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/comment-page-3/#comments

Everything seems to have worked fine up until putting in the click events:

```<code>       view.setOnClickListener(new OnClickListener() {
       public void onClick(View arg0){...
</code>```

Clicking on an item in the list will operate the function normally, but it wont change the background colour as it used to. Also, scrolling the list manually and pressing enter / submit button doesn't seem to run the function, although it does change the background colour.

答: To handle such events you should implement AdapterView.OnItemClickListener interface and set its instance to a list view via list.setOnItemClickListener() method.</p>

Title: Android click events acting strangely

Body:
I've been following these 2 tutorials to setup a list & click events:

http://mfarhan133.wordpress.com/2010/10/14/list-view-tutorial-for-android/
http://www.softwarepassion.com/android-series-custom-listview-items-and-adapters/comment-page-3/#comments

Everything seems to have worked fine up until putting in the click events:

       view.setOnClickListener(new OnClickListener() {
       public void onClick(View arg0){...

Clicking on an item in the list will operate the function normally, but it wont change the background colour as it used to. Also, scrolling the list manually and pressing enter / submit button doesn't seem to run the function, although it does change the background colour.


问:
How do I hide the codes that appear in the sourcemap in the react application?
All codes are clearly visible in the "sources" section of the internet browser in an application made with react. Is there a method of concealing this?

I searched "Source map disable" and found a few results, but it didn't work.

Screenshot ;

http://serdarkaraca.com/react_serdarkaraca.png

package.json

"build": "rimraf ./build && react-scripts build && rimraf ./build/**/*.map",

答:
SOLVED ;</p>

```<code>SET GENERATE_SOURCEMAP=false
npm run build
</code>```

Body:
SOLVED ;

SET GENERATE_SOURCEMAP=false
npm run build


问:
Combine two objects in an array into a single object if the object properties are the same and convert the unique properties into an array
Input -

```<code>[
  {color:'red', shape:'circle', size:'medium'},
  {color:'red', shape:'circle', size:'small'}
]
</code>```

Output -

```<code>[
  {color:'red', shape:'circle', size:['medium','small']}
]
</code>```

How can this be achieved in Javascript?

答:
If you just want to group based on color and shape, you could use reduce. Create an accumulator object with each unique combination of those 2 properties separated by a | as key. And the object you want in the output as their value. Then use Object.values() to get those objects as an array.

const input = [
  {color:'red', shape:'circle', size :'medium'},
  {color:'red', shape:'circle', size:'small'},
  {color:'blue', shape:'square', size:'small'}
];

const merged = input.reduce((acc, { color, shape, size }) => {
  const key = color + "|" + shape;
  acc[key] = acc[key] || { color, shape, size: [] };
  acc[key].size.push(size);
  return acc
}, {})

console.log(Object.values(merged))```
</div>
</div>
</p>

<p>This is what the merged/accumulator looks like:</p>

```{
  "red|circle": {
    "color": "red",
    "shape": "circle",
    "size": [
      "medium",
      "small"
    ]
  },
  "blue|square": {
    "color": "blue",
    "shape": "square",
    "size": [
      "small"
    ]
  }
}
```

<p>You can make it dynamic by creating an array of keys you'd want to group by:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const input = [
      { color: 'red', shape: 'circle', size: 'medium' },
      { color: 'red', shape: 'circle', size: 'small' },
      { color: 'blue', shape: 'square', size: 'small' }
   ];
const groupKeys = ['color', 'shape'];

const merged = input.reduce((acc, o) => {
  const key = groupKeys.map(k => o[k]).join("|");

  if (!acc[key]) {
    acc[key] = groupKeys.reduce((r, k) => ({ ...r, [k]: o[k] }), {});
    acc[key].size = []
  }

  acc[key].size.push(o.size)
  return acc
}, {})

console.log(Object.values(merged))</code>```

Body:
Input -

[
  {color:'red', shape:'circle', size:'medium'},
  {color:'red', shape:'circle', size:'small'}
]

Output -

[
  {color:'red', shape:'circle', size:['medium','small']}
]

How can this be achieved in Javascript?

Body:
If you just want to group based on color and shape, you could use reduce. Create an accumulator object with each unique combination of those 2 properties separated by a | as key. And the object you want in the output as their value. Then use Object.values() to get those objects as an array.

const input = [
  {color:'red', shape:'circle', size :'medium'},
  {color:'red', shape:'circle', size:'small'},
  {color:'blue', shape:'square', size:'small'}
];

const merged = input.reduce((acc, { color, shape, size }) => {
  const key = color + "|" + shape;
  acc[key] = acc[key] || { color, shape, size: [] };
  acc[key].size.push(size);
  return acc
}, {})

console.log(Object.values(merged))

This is what the merged/accumulator looks like:

{
  "red|circle": {
    "color": "red",
    "shape": "circle",
    "size": [
      "medium",
      "small"
    ]
  },
  "blue|square": {
    "color": "blue",
    "shape": "square",
    "size": [
      "small"
    ]
  }
}

You can make it dynamic by creating an array of keys you'd want to group by:

const input = [
      { color: 'red', shape: 'circle', size: 'medium' },
      { color: 'red', shape: 'circle', size: 'small' },
      { color: 'blue', shape: 'square', size: 'small' }
   ];
const groupKeys = ['color', 'shape'];

const merged = input.reduce((acc, o) => {
  const key = groupKeys.map(k => o[k]).join("|");

  if (!acc[key]) {
    acc[key] = groupKeys.reduce((r, k) => ({ ...r, [k]: o[k] }), {});
    acc[key].size = []
  }

  acc[key].size.push(o.size)
  return acc
}, {})

console.log(Object.values(merged))


问:
How can I scrape Yahoo Finance by parsing through a text file containing a list of tickers?
I have a text file containing a list of company tickers.

My intention is to be able to scrape Yahoo Finance to get financial data for each of these tickers.

I do not know how to tell Python to go over each individual line in my text file, assign it to a variable and then scrape that particular Yahoo Finance page and retrieve its data and store it, repeating the process for how many tickers are contained in the text file.

I found some code online to be able to scrape data from Yahoo Finance.
Then I tried to add a for loop so that each ticker is added to a symbol variable (see code).

```<code>def scrape_table(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    table = tree.xpath('//table')
    assert len(table) == 1

    df = pd.read_html(lxml.etree.tostring(table[0], method='html'))[0]

    df = df.set_index(0)
    df = df.dropna()
    df = df.transpose()
    df = df.replace('-', '0')

    # The first column should be a date
    df[df.columns[0]] = pd.to_datetime(df[df.columns[0]])
    cols = list(df.columns)
    cols[0] = 'Date'
    df = df.set_axis(cols, axis='columns', inplace=False)

    numeric_columns = list(df.columns)[1::]
    df[numeric_columns] = df[numeric_columns].astype(np.float64)

    return df

symbol = []

tf = open("SMI_tickers.txt")
for line in tf.readlines():
   symbol.append(print(line))

balance_sheet_url = 'https://finance.yahoo.com/quote/' + symbol +
'/balance-sheet?p=' + symbol

df_balance_sheet = scrape_table(balance_sheet_url)
df_balance_sheet
</code>```

The error message I got was

TypeError: can only concatenate str (not "list") to str

My end goal is to be able to import financial data for each of these companies so that I can perform some calculations on each stock.

答:
I'm assuming your SMI_tickers.txt has a list of ticker symbols with one symbol per line. The erros comes when you build your url, you try to concatenate symbol, which is a list, not a string.

Change your code to below.

```<code>tf = open("SMI_tickers.txt")
for line in tf.readlines():
  symbol.append(line)
for symb in symbol:
    balance_sheet_url = 'https://finance.yahoo.com/quote/' + symb +
          '/balance-sheet?p=' + symb

    df_balance_sheet = scrape_table(balance_sheet_url)
    df_balance_sheet
</code>```

You don't actually need to read the symbols into a list, you could just use the symbol once you get it from the file without the list.

```<code>tf = open("SMI_tickers.txt")
for line in tf.readlines():
    balance_sheet_url = 'https://finance.yahoo.com/quote/' + line+
          '/balance-sheet?p=' + line

    df_balance_sheet = scrape_table(balance_sheet_url)
    df_balance_sheet
</code>```

In both cases df_balance_sheet will be your pandas datafram.

Body:
I have a text file containing a list of company tickers.

My intention is to be able to scrape Yahoo Finance to get financial data for each of these tickers.

I do not know how to tell Python to go over each individual line in my text file, assign it to a variable and then scrape that particular Yahoo Finance page and retrieve its data and store it, repeating the process for how many tickers are contained in the text file.

I found some code online to be able to scrape data from Yahoo Finance.
Then I tried to add a for loop so that each ticker is added to a symbol variable (see code).

def scrape_table(url):
    page = requests.get(url)
    tree = html.fromstring(page.content)
    table = tree.xpath('//table')
    assert len(table) == 1

    df = pd.read_html(lxml.etree.tostring(table[0], method='html'))[0]

    df = df.set_index(0)
    df = df.dropna()
    df = df.transpose()
    df = df.replace('-', '0')

    # The first column should be a date
    df[df.columns[0]] = pd.to_datetime(df[df.columns[0]])
    cols = list(df.columns)
    cols[0] = 'Date'
    df = df.set_axis(cols, axis='columns', inplace=False)

    numeric_columns = list(df.columns)[1::]
    df[numeric_columns] = df[numeric_columns].astype(np.float64)

    return df

symbol = []

tf = open("SMI_tickers.txt")
for line in tf.readlines():
   symbol.append(print(line))

balance_sheet_url = 'https://finance.yahoo.com/quote/' + symbol +
'/balance-sheet?p=' + symbol

df_balance_sheet = scrape_table(balance_sheet_url)
df_balance_sheet

The error message I got was

TypeError: can only concatenate str (not "list") to str

My end goal is to be able to import financial data for each of these companies so that I can perform some calculations on each stock.

Body:
I'm assuming your SMI_tickers.txt has a list of ticker symbols with one symbol per line. The erros comes when you build your url, you try to concatenate symbol, which is a list, not a string.

Change your code to below.

tf = open("SMI_tickers.txt")
for line in tf.readlines():
  symbol.append(line)
for symb in symbol:
    balance_sheet_url = 'https://finance.yahoo.com/quote/' + symb +
          '/balance-sheet?p=' + symb

    df_balance_sheet = scrape_table(balance_sheet_url)
    df_balance_sheet

You don't actually need to read the symbols into a list, you could just use the symbol once you get it from the file without the list.

tf = open("SMI_tickers.txt")
for line in tf.readlines():
    balance_sheet_url = 'https://finance.yahoo.com/quote/' + line+
          '/balance-sheet?p=' + line

    df_balance_sheet = scrape_table(balance_sheet_url)
    df_balance_sheet

In both cases df_balance_sheet will be your pandas datafram.


问:
Using case-when in aggregate function in Sequelize.js
Is it possible to build the below query on a Model instead of using sequilize.query() for raw sql

select
  queue,
  count(*) total,
  sum(case when type = 'Proactive' then 1 else 0 end) proactive,
  sum(case when type = 'Reactive' then 1 else 0 end) reactive
from "OpenIncidents"
group by queue
order by total DESC;
```

<p>I tired using sequelize.fn() for aggregate function, but found nothing in the docs regarding CASE WHEN support in aggregate function.</p>

<p>I currently using raw query </p>

```return sequelize.query(
    `
    SELECT
      queue,
      COUNT(*) total,
      SUM(CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END) proactive,
      SUM(CASE WHEN type = 'Reactive' THEN 1 ELSE 0 END) reactive
    FROM "OpenIncidents"
    GROUP BY queue
    ORDER BY total DESC;
    `,
    { type: sequelize.QueryTypes.SELECT })
  .then(queues => res.json(queues))
  .catch(err => res.status(400).json(err));
```

<p>Is there any way to do it directly on a Sequelize Model, like below</p>

```return OpenIncident.findAll({
  attributes:[
    'queue',
    [sequelize.fn('COUNT', sequelize.col('id')), 'total'],
    [sequelize.fn('SUM', CASE_WHEN_STATEMENT, 'proactive'],
    [sequelize.fn('SUM', CASE_WHEN_STATEMENT), 'reactive']
  ],
  group: ['queue'],
  order: [sequelize.fn('COUNT', sequelize.col('id')), 'DESC']
})
```

答:
One solution is to use `Sequelize.literal()', as shown below:</p>

```<code>[Sequelize.fn('SUM', Sequelize.literal('CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END')), 'proactive']
</code>```

Body:
Is it possible to build the below query on a Model instead of using sequilize.query() for raw sql

select
  queue,
  count(*) total,
  sum(case when type = 'Proactive' then 1 else 0 end) proactive,
  sum(case when type = 'Reactive' then 1 else 0 end) reactive
from "OpenIncidents"
group by queue
order by total DESC;

I tired using sequelize.fn() for aggregate function, but found nothing in the docs regarding CASE WHEN support in aggregate function.

I currently using raw query

return sequelize.query(
    `
    SELECT
      queue,
      COUNT(*) total,
      SUM(CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END) proactive,
      SUM(CASE WHEN type = 'Reactive' THEN 1 ELSE 0 END) reactive
    FROM "OpenIncidents"
    GROUP BY queue
    ORDER BY total DESC;
    `,
    { type: sequelize.QueryTypes.SELECT })
  .then(queues => res.json(queues))
  .catch(err => res.status(400).json(err));

Is there any way to do it directly on a Sequelize Model, like below

return OpenIncident.findAll({
  attributes:[
    'queue',
    [sequelize.fn('COUNT', sequelize.col('id')), 'total'],
    [sequelize.fn('SUM', CASE_WHEN_STATEMENT, 'proactive'],
    [sequelize.fn('SUM', CASE_WHEN_STATEMENT), 'reactive']
  ],
  group: ['queue'],
  order: [sequelize.fn('COUNT', sequelize.col('id')), 'DESC']
})

Body:
One solution is to use `Sequelize.literal()', as shown below:

[Sequelize.fn('SUM', Sequelize.literal('CASE WHEN type = 'Proactive' THEN 1 ELSE 0 END')), 'proactive']


问:
Adding notes to a data file (csv) in python
I am trying to capture data from an oscilloscope using a python script. The script saves it as in csv format. I need to add few lines of text describing the data at the beginning.

I looked at existing threads to see if there was a possible solution. I just started learning Python. I am using code that came with the instrument.

This is part of the script that saves the data as csv.

```<code>NewD = (np.insert(Wav_Data, 0, DataTime, axis = 0)).T
filename = BASE_DIRECTORY + BASE_FILE_NAME + ".csv"
now = time.time() # Only to show how long it takes to save
with open(filename, 'w') as filehandle:
   np.savetxt(filename, NewD, delimiter = ',', header = column_titles)
</code>```

I tried to use the section below from another code but am not sure how to append this to the csv file.

```<code>with open("notes.txt") as f:
    NOTES = f.readlines()
NOTES = "".join(NOTES)
</code>```

It is unable to find notes.txt which is located in the same directory as the script.
Eager to hear your feedback. Thanks in advance.

Updated to:

```<code># Save data
NewD = (np.insert(Wav_Data, 0, DataTime, axis = 0)).T
filename = BASE_DIRECTORY + BASE_FILE_NAME + ".csv"

with open("notes.txt") as f:
    NOTES = f.readlines()
NOTES = "".join(NOTES)

with open(filename, "a") as fh:
    fh.write(NOTES)

now = time.time() # Only to show how long it takes to save
with open(filename, 'w') as filehandle:
    np.savetxt(filename, NewD, delimiter = ',', header = column_titles)
</code>```

答:
Just open the file for appending or write

If you want to write CSV first then notes:

```<code>with open("notes.txt") as f:
    NOTES = f.readlines()
NOTES = "".join(NOTES)

with open(filename, "w") as fh:
    fh.write(NOTES)
    # this time we give np the opened filehandle, not the filename
    np.savetxt(fh, NewD, delimiter = ',', header = column_titles)
</code>```

Body:
I am trying to capture data from an oscilloscope using a python script. The script saves it as in csv format. I need to add few lines of text describing the data at the beginning.

I looked at existing threads to see if there was a possible solution. I just started learning Python. I am using code that came with the instrument.

This is part of the script that saves the data as csv.

NewD = (np.insert(Wav_Data, 0, DataTime, axis = 0)).T
filename = BASE_DIRECTORY + BASE_FILE_NAME + ".csv"
now = time.time() # Only to show how long it takes to save
with open(filename, 'w') as filehandle:
   np.savetxt(filename, NewD, delimiter = ',', header = column_titles)

I tried to use the section below from another code but am not sure how to append this to the csv file.

with open("notes.txt") as f:
    NOTES = f.readlines()
NOTES = "".join(NOTES)

It is unable to find notes.txt which is located in the same directory as the script.
Eager to hear your feedback. Thanks in advance.

Updated to:

# Save data
NewD = (np.insert(Wav_Data, 0, DataTime, axis = 0)).T
filename = BASE_DIRECTORY + BASE_FILE_NAME + ".csv"

with open("notes.txt") as f:
    NOTES = f.readlines()
NOTES = "".join(NOTES)

with open(filename, "a") as fh:
    fh.write(NOTES)

now = time.time() # Only to show how long it takes to save
with open(filename, 'w') as filehandle:
    np.savetxt(filename, NewD, delimiter = ',', header = column_titles)

Body:
Just open the file for appending or write

If you want to write CSV first then notes:

with open("notes.txt") as f:
    NOTES = f.readlines()
NOTES = "".join(NOTES)

with open(filename, "w") as fh:
    fh.write(NOTES)
    # this time we give np the opened filehandle, not the filename
    np.savetxt(fh, NewD, delimiter = ',', header = column_titles)


问:
Are non-generic collections in .NET obsolete?
Put differently:

Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility?

As far as I understand, generic collections not only are type-safe, but their performance is better.

Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0.

答: Going forward only generic collections should be used. There is also the benefit of avoiding boxing/unboxing of types in the collection. This is ineffecient, especially when you have a collection of value types that are converted to System.Object when stored on the collection, hence storing the values on the heap instead of the callstack.</p>

OwnerDisplayName: guillermooo

LastEditorDisplayName: guillermooo

OwnerDisplayName: Sean Chambers

ContentLicense: CC BY-SA 2.5


问:
How to properly develop for the iPhone on a PowerPC Mac?
I'm doing iPhone development on a PowerPC Mac. How do I get code signing to work properly so that I can build to my iPhone?

The iPhone SDK doesn't officially support PowerPC, but with some fidgeting, it can be installed. See here. I've got the SDK installed and running fine in Xcode and the iPhone simulator works fine.

However, I can't build to my iPhone in Xcode -- the code signing is fubar. Some clever people have created workarounds here. Namely, I used the codesign script that Tiku posted along with some of the corrections. This has helped me make some progress. The code compiles now, but I still get an 0xE800003A error when it tries to deploy.

I think I have all my keys and provisioning profiles set up properly. My iPhone is registered for development, I've got the provisioning profile created. The AppID listed in the dev portal says MagicNumber.com.website.* and in my project, I have the Bundle ID set as com.website.${PRODUCT_NAME:identifier}. In project settings, product name is HelloWord, and the code signing identity is my developer certificate.

The console log of the iPhone says:
Wed Feb 18 14:57:55 unknown afcd[180] : user mobile has uid 501

Wed Feb 18 14:57:55 unknown afcd[180] : mode is 0x41e8
Wed Feb 18 14:57:55 unknown mobile_installation_proxy[182] : install_embedded_profile: Skipping the installation of the embedded profile
Wed Feb 18 14:57:55 unknown mobile_installation_proxy[182] : verify_executable: Could not validate signature: e800800e
Wed Feb 18 14:57:55 unknown mobile_installation_proxy[182] : preflight_application_install: Could not verify /var/tmp/install_staging.QNk2sD/HelloWorld.app/HelloWorld
Wed Feb 18 14:57:55 unknown mobile_installation_proxy[182] : install_application: Could not preflight application install
Wed Feb 18 14:57:55 unknown mobile_installation_proxy[182] : handle_install: Installation failed

Any help is appreciated!

答:
What does your codesign script look like? I used to use this one when I was working on a G4: (The original "/usr/bin/codesign" should be renamed "/usr/bin/codesign.orig" and then save this script as "/usr/bin/codesign". You would have to do it with "sudo". Also this script doesn't work if your path names have spaces in them.)</p>

```<code>#!/usr/bin/perl
#
$appDir=$ARGV[$#ARGV];
@tmpAry=split(/\//,$appDir);
$baseAppName=$tmpAry[$#tmpAry];
$baseAppName=~s/\.app$//;
$realAppName="$appDir"."/$baseAppName";

$sign=0;
for($b=0;$b<$#ARGV;$b++) {
if($ARGV[$b] eq "-s") {
$sign=1;
}
}

$mums=`file $realAppName`;
if($sign==1 && $mums=~/executable arm/) {
#print "Signing armv6..\n";
$dev="/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/";
$tmp="$appDir"."/tmpbin";
`$dev/lipo -create $realAppName -output $tmp`;
`mv $tmp $realAppName`;
system("/usr/bin/codesign.orig",@ARGV);
`$dev/lipo -thin armv6 $realAppName -output $tmp`;
`mv $tmp $realAppName`;
system("rm $appDir"."/CodeResources");
system("cp $appDir"."/_CodeSignature/CodeResources $appDir"."/CodeResources");
exit 0;
} else {
exec '/usr/bin/codesign.orig',@ARGV;
}
</code>```

OwnerDisplayName: Mike Welsh

LastEditorDisplayName: Mike Welsh

Body:
What does your codesign script look like? I used to use this one when I was working on a G4: (The original "/usr/bin/codesign" should be renamed "/usr/bin/codesign.orig" and then save this script as "/usr/bin/codesign". You would have to do it with "sudo". Also this script doesn't work if your path names have spaces in them.)

#!/usr/bin/perl
#
$appDir=$ARGV[$#ARGV];
@tmpAry=split(/\//,$appDir);
$baseAppName=$tmpAry[$#tmpAry];
$baseAppName=~s/\.app$//;
$realAppName="$appDir"."/$baseAppName";

$sign=0;
for($b=0;$b<$#ARGV;$b++) {
if($ARGV[$b] eq "-s") {
$sign=1;
}
}

$mums=`file $realAppName`;
if($sign==1 && $mums=~/executable arm/) {
#print "Signing armv6..\n";
$dev="/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/";
$tmp="$appDir"."/tmpbin";
`$dev/lipo -create $realAppName -output $tmp`;
`mv $tmp $realAppName`;
system("/usr/bin/codesign.orig",@ARGV);
`$dev/lipo -thin armv6 $realAppName -output $tmp`;
`mv $tmp $realAppName`;
system("rm $appDir"."/CodeResources");
system("cp $appDir"."/_CodeSignature/CodeResources $appDir"."/CodeResources");
exit 0;
} else {
exec '/usr/bin/codesign.orig',@ARGV;
}

OwnerDisplayName: Boot To The Head


问:
How can I combine numeric values of similar strings?
I have a list of licenses and associated license counts, for example:

```<code>1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
3 Station
3 Station
3 Station
20 Station
</code>```

The lists are never in the same order and I simply need to add the totals for each license type so in the example I would want the return:

```<code>3 Third Party SIP Device Seat
29 Station
</code>```

The data is being entered into unsaved notepad and later moved into a database. Using excel isn't applicable as it's spaces between the numbers and names, not tabs.

What would be the easiest way to accomplish this task?

答:
A complete solution with data in a "saved notepad file" named licences.txt:

```<code>from collections import Counter
counter=Counter()
with open ('licences.txt','r') as f:
    for line in f:
        count,*words = line.split()
        counter[" ".join(words)] += int(count)

with open('grouped_licences.txt','w') as f:
    for licence,total in counter.items():
        f.write(str(total) + " " + licence + "\n")
</code>```

Then result is in file grouped_licences.txt:

```<code>    3 Third Party SIP Device Seat
    29 Station
</code>```

Another solution with pandas :

```<code>df=pandas.read_csv('licences.txt', sep=" ",header=None).fillna("")
df["licence"]=df.iloc[:,1:].apply(" ".join,axis=1)
print(df.groupby("licence")[0].sum())
</code>```

For :

```<code>licence
Station                           29
Third Party SIP Device Seat        3
</code>```

Body:
I have a list of licenses and associated license counts, for example:

1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
1 Third Party SIP Device Seat
3 Station
3 Station
3 Station
20 Station

The lists are never in the same order and I simply need to add the totals for each license type so in the example I would want the return:

3 Third Party SIP Device Seat
29 Station

The data is being entered into unsaved notepad and later moved into a database. Using excel isn't applicable as it's spaces between the numbers and names, not tabs.

What would be the easiest way to accomplish this task?

Body:
A complete solution with data in a "saved notepad file" named licences.txt:

from collections import Counter
counter=Counter()
with open ('licences.txt','r') as f:
    for line in f:
        count,*words = line.split()
        counter[" ".join(words)] += int(count)

with open('grouped_licences.txt','w') as f:
    for licence,total in counter.items():
        f.write(str(total) + " " + licence + "\n")

Then result is in file grouped_licences.txt:

    3 Third Party SIP Device Seat
    29 Station

Another solution with pandas :

df=pandas.read_csv('licences.txt', sep=" ",header=None).fillna("")
df["licence"]=df.iloc[:,1:].apply(" ".join,axis=1)
print(df.groupby("licence")[0].sum())

For :

licence
Station                           29
Third Party SIP Device Seat        3


问:
Rename a jar file removing the version number
I am trying to rename a jar file name with a version embedded in it like
test-java-1.0.0.jar to test-java.jar

Tried below approach but this will not workout if the version is changed to something like

test-java-11.0.0.jar or test-compile-1.0.12.jar

```<code>Set test=test-java-1.0.0.jar
set test1=%test:~0,-10%
rename %test% %test1%.jar
</code>```

Looking for something like:

Input string: test-java-1.0.0.jar

Expected output: test-java.jar

答:
To strip any characters 0-9.-_ from the back of the file name without extension:

```<code>:: Q:\Test\2019\05\30\SO_56380430.cmd
@Echo off
for %%A in (
    "test java-1.0.0.jar"
    compile-java-1.11.1.jar
    poc-java-1.2.22.jar
    some-thing-1.2.32.jar
) do call :StripVer "%%~A"

Goto :Eof

:StripVer
set "Name=%~n1"
:loop
Echo %Name:~-1%|findstr "[0-9._-]" >Nul && (set "Name=%Name:~0,-1%"&Goto :loop)
Echo Original name : %~1
Echo w/o version   : %Name%%~x1
Echo:
</code>```

Sample output:

```<code>> Q:\Test\2019\05\30\SO_56380430.cmd
Original name : test java-1.0.0.jar
w/o version   : test java.jar

Original name : compile-java-1.11.1.jar
w/o version   : compile-java.jar

Original name : poc-java-1.2.22.jar
w/o version   : poc-java.jar

Original name : some-thing-1.2.32.jar
w/o version   : some-thing.jar
</code>```

This method is quite slow.

A one liner in PowerShell will be a lot faster.

```<code>Get-ChildItem *.jar|Rename-Item -NewName {$_.Basename.trimend('0123456789.-_')+$_.Extension} -WhatIf
</code>```

Remove the trailing -WhatIf if the output looks OK.

That could be wrapped in cmd line /batch file

```<code>powershell -Nop -C "Get-ChildItem *.jar|Rename-Item -NewName {$_.Basename.trimend('0123456789.-_')+$_.Extension} -WhatIf"
</code>```

Body:
I am trying to rename a jar file name with a version embedded in it like
test-java-1.0.0.jar to test-java.jar

Tried below approach but this will not workout if the version is changed to something like

test-java-11.0.0.jar or test-compile-1.0.12.jar

Set test=test-java-1.0.0.jar
set test1=%test:~0,-10%
rename %test% %test1%.jar

Looking for something like:

Input string: test-java-1.0.0.jar

Expected output: test-java.jar

Body:
To strip any characters 0-9.-_ from the back of the file name without extension:

:: Q:\Test\2019\05\30\SO_56380430.cmd
@Echo off
for %%A in (
    "test java-1.0.0.jar"
    compile-java-1.11.1.jar
    poc-java-1.2.22.jar
    some-thing-1.2.32.jar
) do call :StripVer "%%~A"

Goto :Eof

:StripVer
set "Name=%~n1"
:loop
Echo %Name:~-1%|findstr "[0-9._-]" >Nul && (set "Name=%Name:~0,-1%"&Goto :loop)
Echo Original name : %~1
Echo w/o version   : %Name%%~x1
Echo:

Sample output:

> Q:\Test\2019\05\30\SO_56380430.cmd
Original name : test java-1.0.0.jar
w/o version   : test java.jar

Original name : compile-java-1.11.1.jar
w/o version   : compile-java.jar

Original name : poc-java-1.2.22.jar
w/o version   : poc-java.jar

Original name : some-thing-1.2.32.jar
w/o version   : some-thing.jar

This method is quite slow.

A one liner in PowerShell will be a lot faster.

Get-ChildItem *.jar|Rename-Item -NewName {$_.Basename.trimend('0123456789.-_')+$_.Extension} -WhatIf

Remove the trailing -WhatIf if the output looks OK.

That could be wrapped in cmd line /batch file

powershell -Nop -C "Get-ChildItem *.jar|Rename-Item -NewName {$_.Basename.trimend('0123456789.-_')+$_.Extension} -WhatIf"


问:
What's wrong with this template
I am doing c++ 6th edition the 6th exercise of 8th chapter. I have questions on this template. I don't know why it always shows the last string not shows the string that has the max length.  </p>

```<code>#include <iostream>
#include <cstring>

//8.6

using namespace std;

template <typename T> T Maxn(T *,int);

template <>  char * Maxn<>(char **,int );

int main()
{
    double arr_1[5] = { 0.0,3.0,1.0,4.0,5.0 };
    cout << "double max: " << Maxn(arr_1,5) << endl;

    int arr_2[4] = { 3,4,1,0 };
    cout << "int max: " << Maxn(arr_2, 4) << endl;

    const char *arr_3[4] = { "sdf","tttq","ttttrrsdss" ,"q12221"};
    cout << "char max:" << Maxn(arr_3, 4) << endl;

    return 0;
}

template <typename T>
T Maxn(T *p,int n)
{
    T max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (p[i] > max)
            max = p[i];
    }

    return max;
}

template <> char * Maxn<>(char **p, int n)
{
    char * max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (strlen(p[i]) > strlen(max))
        {
            max = p[i];
        }
    }
    return max;
}
</code>```

答:
You should simply start using a debugger or at minimum you could visit your code by using printf debugging. You will see, that your char* specialization is never used!

Reason:

Your data type for the "strings" is const char* which matches better for the first template than to your specialization and so simply the first template version is called. And this compares now the address of the strings. If your compiler puts the strings in the order presented in the source, you will always see the last string as result, as it has the highest address.

Simply use:

```<code>template <> const char * Maxn<>(const char **p, int n)
{
    const char * max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (strlen(p[i]) > strlen(max))
        {
            max = p[i];
        }
    }
    return max;
}
</code>```

BTW: Your code has some efficiency flows. You compare in the first step two times the same value which is not needed.

Title: What's wrong with this template

Body:
I am doing c++ 6th edition the 6th exercise of 8th chapter. I have questions on this template. I don't know why it always shows the last string not shows the string that has the max length.

#include <iostream>
#include <cstring>

//8.6

using namespace std;

template <typename T> T Maxn(T *,int);

template <>  char * Maxn<>(char **,int );

int main()
{
    double arr_1[5] = { 0.0,3.0,1.0,4.0,5.0 };
    cout << "double max: " << Maxn(arr_1,5) << endl;

    int arr_2[4] = { 3,4,1,0 };
    cout << "int max: " << Maxn(arr_2, 4) << endl;

    const char *arr_3[4] = { "sdf","tttq","ttttrrsdss" ,"q12221"};
    cout << "char max:" << Maxn(arr_3, 4) << endl;

    return 0;
}

template <typename T>
T Maxn(T *p,int n)
{
    T max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (p[i] > max)
            max = p[i];
    }

    return max;
}

template <> char * Maxn<>(char **p, int n)
{
    char * max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (strlen(p[i]) > strlen(max))
        {
            max = p[i];
        }
    }
    return max;
}

Body:
You should simply start using a debugger or at minimum you could visit your code by using printf debugging. You will see, that your char* specialization is never used!

Reason:

Your data type for the "strings" is const char* which matches better for the first template than to your specialization and so simply the first template version is called. And this compares now the address of the strings. If your compiler puts the strings in the order presented in the source, you will always see the last string as result, as it has the highest address.

Simply use:

template <> const char * Maxn<>(const char **p, int n)
{
    const char * max = p[0];
    for (int i = 0; i < n; i++)
    {
        if (strlen(p[i]) > strlen(max))
        {
            max = p[i];
        }
    }
    return max;
}

BTW: Your code has some efficiency flows. You compare in the first step two times the same value which is not needed.


问:
Creating lib of mongoose models not working on import
I've been trying to create a library of mongo models and helper class that is then shared as an npm module we the rest of my team. The problem I having is the main code I import from lib MongoConnector which process config information and connects to mongo, I also import Model1 and do a find all that call works. But when I import Poller from the same lib and pass it Model1, when it does the find the promise never returns.

Library has 4 files

Model1.ts:

import mongoose from 'mongoose';

export interface IModel1 {
    draftId: string;
    [k:string]: any;
}

export interface IModel1DocumnetAttrs {
    draftId: string;
    data: string;
    createdBy?: String;
}

export interface IModel1Document extends mongoose.Document {
    draftId: String;
    createdBy: String;
    data: string;
}

export type IModel1Model = mongoose.Model<IModel1Document>;

const schema = new mongoose.Schema(
    {
        draftId: {type: String, index: {unique: true }},
        createdBy: String,
        data: String,
    },
    { versionKey: false, strict: false, timestamps: true, },
);

export const Model1: IModel1Model = mongoose.model<IModel1Document, IModel1Model>('Model1', schema);
```

<p>MongoPoller.ts:</p>

<pre class="lang-js prettyprint-override"><code>import * as Logger from 'bunyan';
import * as _ from 'lodash';
import mongoose from 'mongoose';

export type IMongoPollerCallback<T extends mongoose.Document> = (error: Error | undefined, docs?: T[]) => void;

export class MongoPoller<T extends mongoose.Document> {
    private query: any;
    private callback: IMongoPollerCallback<T>;
    private intervalId: any;
    private readonly log: Logger;
    constructor(private readonly pollingTime: number, private readonly model: typeof mongoose.Model, baseLogger: Logger) {
        this.callback = _.noop;
        this.log = baseLogger.child({ component: 'MongoPoller' });
    }

    public start(query: any, callback: IMongoPollerCallback<T>) {
        this.query = query;
        this.callback = callback;

        this.intervalId = setInterval(() => this.workFunction(), this.pollingTime);
    }

    public stop() {
        clearInterval(this.intervalId);
    }

    public async initial(query: any, callback: IMongoPollerCallback<T>) {
        this.query = query;
        this.callback = callback;
        this.log.info(`Mongo Poller started with initial, ${JSON.stringify(query)}`);

        return this.workFunction();
    }

    public continue() {
        this.log.info(`Mongo Poller told to continue, ${JSON.stringify(this.query)}`);
        this.intervalId = setTimeout(() => this.workFunction(), this.pollingTime);
    }

    private async workFunction() {
        try{
            this.log.info(`Mongo Poller executing workFunction, ${JSON.stringify(this.query)}`);
            const docsp =  this.model.find(this.query).exec();
            const docs = await docsp;
            this.log.info(`Mongo Poller executing workFunction callback with ${docs.length} docs, ${JSON.stringify(this.query)}`);

            this.callback(undefined, docs)

        }
        catch (e){
            this.log.info(`Mongo Poller executing workFunction callback with ERROR ${e.message}, ${JSON.stringify(this.query)}`);
            this.callback(undefined)
        }

    }
}
</code>```

MongoDBConnector.ts:

import Promise = require('bluebird');
import * as Logger from 'bunyan';
import mongoose from 'mongoose';
import { decrypt, IKeyData } from './cryptoUtils';

interface IMongoDatabaseConfig {
    uri?: string;
    fullUri?: string;
    options?: object;
    username?: string;
    password?: string;
    initialDelayMSec?: number;
    finalDelayMSec?: number;
    triesBeforeFinalDelay?: number;
    autoIndex?: boolean;
    debug?:boolean
}

export class MongoDBConnector {
    private readonly mongoConfig: IMongoDatabaseConfig = {};
    private connectionPromise: Promise<any> | undefined;
    private readonly log: Logger;
    constructor(config: IMongoDatabaseConfig, baseLogger: Logger, keyData: IKeyData) {
        this.mongoConfig = config;
        mongoose.set('debug', this.mongoConfig.debug);
        mongoose.set('autoCreate', true);
        this.log = baseLogger.child({ component: 'MongoDBConnector' });
        Object.assign(this.mongoConfig, config);
        if (
            !this.mongoConfig.username ||
            this.mongoConfig.username.trim() === '' ||
            !this.mongoConfig.password ||
            this.mongoConfig.password.trim() === ''
        ) {
            this.mongoConfig.fullUri = `mongodb://${this.mongoConfig.uri}`;
        } else {
            this.mongoConfig.fullUri = `mongodb://${this.mongoConfig.username}:${decrypt(
                this.mongoConfig.password,keyData
            )}@${this.mongoConfig.uri}`;
        }
        this.mongoConfig.autoIndex = true;

        mongoose.Promise = global.Promise;
    }

    private connectToMongo(numTries: number = 1): any {
        return mongoose
            .connect(<string>this.mongoConfig.fullUri, this.mongoConfig.options)
            .then(() => {
                this.log.info('MongoDB Connected!');

                return mongoose.connection;
            })
            .catch((error: any) => {
                const timeoutDelayMSec =
                    numTries < <number>this.mongoConfig.triesBeforeFinalDelay
                        ? this.mongoConfig.initialDelayMSec
                        : this.mongoConfig.finalDelayMSec;
                this.log.error(`Issue connecting to MongoDB: ${error.message}`);
                this.log.info(
                    `Retrying connection to MongoDB (attempt #${numTries}). Reconnecting in ${timeoutDelayMSec} ms...`,
                );

                return Promise.delay(<number>timeoutDelayMSec).then(() => {
                    return this.connectToMongo(numTries + 1);
                });
            });
    }

    public connect() {
        if (!this.connectionPromise) {
            this.log.info(`Attempting to connect to MongoDB on ${this.mongoConfig.fullUri}`);
            this.connectionPromise = this.connectToMongo().catch((error: any) => {
                this.connectionPromise = undefined;
                throw error;
            });
        }

        return this.connectionPromise;
    }
}
```

<p>index.ts:</p>

<pre class="lang-js prettyprint-override"><code>export { Model1 } from './Model1';
export { MongoDBConnector} from './MongoDBConnector';
export {IMongoPollerCallback, MongoPoller}  from './MongoPoller';
</code>```

The Main App :

index.ts:

import * as config from './config/config.json';
import * as keyEventLogger from './logging/keyEventLogger';
import { loggerFactory } from './logging/loggerFactory';

import {
    DraftJudgment,
    IDraftDocument,
    IMongoPollerCallback,
    MongoDBConnector,
    MongoPoller
} from 'exploitmongomodels';

import mongoose from 'mongoose';

import { Promise as bluebird } from 'bluebird';
import * as keyData from './key.json';

global.Promise = bluebird;

const log = loggerFactory('main');

async function main() {
    // adding better logging for uncaught rejected promises
    process.on('unhandledRejection', err => {
        log.fatal({ err }, 'uncaught rejection');
    });

    process.on('uncaughtException', err => {
        log.fatal({ err }, 'uncaught exception');
    });

    const mongo = new MongoDBConnector(config.database.mongo, log, keyData);

    await mongo.connect();

    keyEventLogger.logKeyEvent(keyEventLogger.keyEvents.heartBeat, '');

    const d = await DraftJudgment.find({}).exec();
    console.log(d.length); //<- this prints 3
    //const j2 = mongoose.model('DraftJudgment');  <-- this throws an error

    //Set up heart beat for log files
    setInterval(
        () => keyEventLogger.logKeyEvent(keyEventLogger.keyEvents.heartBeat, ''),
        config.logger.heartbeatInterval,
    );

    const judgmentSubmitPoller = new MongoPoller<IDraftDocument>(config.pollingDurationInSec, DraftJudgment, log);

    const judgmentSubmitPollingCB: IMongoPollerCallback<IDraftDocument> = (
        error: Error | undefined,
        docs?: IDraftDocument[],
    ) => {
        if (error) {
            log.error(error, 'Error during judgment mongo polling');
            judgmentSubmitPoller.continue();

            return;
        }
        log.info(`Submit poller triggered submitted judgments`);
        if (!docs) {
            return;
        }
        //do something with the docs object

        log.info(`Submit poller triggered with ${docs.length} submitted judgments`);

        judgmentSubmitPoller.continue();
    };
    judgmentSubmitPoller.initial({ status: 'submitted' }, judgmentSubmitPollingCB);

    const judgmentPendingPoller = new MongoPoller<IDraftDocument>(config.pollingDurationInSec, DraftJudgment, log);

    const judgmentPendingPollingCB: IMongoPollerCallback<IDraftDocument> = (
        error: Error | undefined,
        docs?: IDraftDocument[],
    ) => {
        if (error) {
            log.error(error, 'Error during judgment mongo polling');
            judgmentSubmitPoller.continue();

            return;
        }
        if (!docs) {
            return;
        }

        //do something with the docs object

        log.info(`Pending poller triggered with ${docs.length} submitted judgments`);

        judgmentPendingPoller.continue();
    };
    //judgmentPendingPoller.initial({ $query: { status: 'pending' } }, judgmentPendingPollingCB);

    //tslint:disable-next-line
    while (true) {}
}

main();
```

In MongoPoller#workFunction , docsp promise never resolves.

答:
So this was a bit embarrassing, the problem was the while loop at the bottom of main. Added by another dev; we both assumed it was needed to prevent node from exiting. Well it is not, and because the loop was so tight it never allowed time for the promise to resolve. </p>

<p>Live and learn. </p>

Body:
I've been trying to create a library of mongo models and helper class that is then shared as an npm module we the rest of my team. The problem I having is the main code I import from lib MongoConnector which process config information and connects to mongo, I also import Model1 and do a find all that call works. But when I import Poller from the same lib and pass it Model1, when it does the find the promise never returns.

Library has 4 files

Model1.ts:

import mongoose from 'mongoose';

export interface IModel1 {
    draftId: string;
    [k:string]: any;
}

export interface IModel1DocumnetAttrs {
    draftId: string;
    data: string;
    createdBy?: String;
}

export interface IModel1Document extends mongoose.Document {
    draftId: String;
    createdBy: String;
    data: string;
}

export type IModel1Model = mongoose.Model<IModel1Document>;

const schema = new mongoose.Schema(
    {
        draftId: {type: String, index: {unique: true }},
        createdBy: String,
        data: String,
    },
    { versionKey: false, strict: false, timestamps: true, },
);

export const Model1: IModel1Model = mongoose.model<IModel1Document, IModel1Model>('Model1', schema);

MongoPoller.ts:

import * as Logger from 'bunyan';
import * as _ from 'lodash';
import mongoose from 'mongoose';

export type IMongoPollerCallback<T extends mongoose.Document> = (error: Error | undefined, docs?: T[]) => void;

export class MongoPoller<T extends mongoose.Document> {
    private query: any;
    private callback: IMongoPollerCallback<T>;
    private intervalId: any;
    private readonly log: Logger;
    constructor(private readonly pollingTime: number, private readonly model: typeof mongoose.Model, baseLogger: Logger) {
        this.callback = _.noop;
        this.log = baseLogger.child({ component: 'MongoPoller' });
    }

    public start(query: any, callback: IMongoPollerCallback<T>) {
        this.query = query;
        this.callback = callback;

        this.intervalId = setInterval(() => this.workFunction(), this.pollingTime);
    }

    public stop() {
        clearInterval(this.intervalId);
    }

    public async initial(query: any, callback: IMongoPollerCallback<T>) {
        this.query = query;
        this.callback = callback;
        this.log.info(`Mongo Poller started with initial, ${JSON.stringify(query)}`);

        return this.workFunction();
    }

    public continue() {
        this.log.info(`Mongo Poller told to continue, ${JSON.stringify(this.query)}`);
        this.intervalId = setTimeout(() => this.workFunction(), this.pollingTime);
    }

    private async workFunction() {
        try{
            this.log.info(`Mongo Poller executing workFunction, ${JSON.stringify(this.query)}`);
            const docsp =  this.model.find(this.query).exec();
            const docs = await docsp;
            this.log.info(`Mongo Poller executing workFunction callback with ${docs.length} docs, ${JSON.stringify(this.query)}`);

            this.callback(undefined, docs)

        }
        catch (e){
            this.log.info(`Mongo Poller executing workFunction callback with ERROR ${e.message}, ${JSON.stringify(this.query)}`);
            this.callback(undefined)
        }

    }
}

MongoDBConnector.ts:

import Promise = require('bluebird');
import * as Logger from 'bunyan';
import mongoose from 'mongoose';
import { decrypt, IKeyData } from './cryptoUtils';

interface IMongoDatabaseConfig {
    uri?: string;
    fullUri?: string;
    options?: object;
    username?: string;
    password?: string;
    initialDelayMSec?: number;
    finalDelayMSec?: number;
    triesBeforeFinalDelay?: number;
    autoIndex?: boolean;
    debug?:boolean
}

export class MongoDBConnector {
    private readonly mongoConfig: IMongoDatabaseConfig = {};
    private connectionPromise: Promise<any> | undefined;
    private readonly log: Logger;
    constructor(config: IMongoDatabaseConfig, baseLogger: Logger, keyData: IKeyData) {
        this.mongoConfig = config;
        mongoose.set('debug', this.mongoConfig.debug);
        mongoose.set('autoCreate', true);
        this.log = baseLogger.child({ component: 'MongoDBConnector' });
        Object.assign(this.mongoConfig, config);
        if (
            !this.mongoConfig.username ||
            this.mongoConfig.username.trim() === '' ||
            !this.mongoConfig.password ||
            this.mongoConfig.password.trim() === ''
        ) {
            this.mongoConfig.fullUri = `mongodb://${this.mongoConfig.uri}`;
        } else {
            this.mongoConfig.fullUri = `mongodb://${this.mongoConfig.username}:${decrypt(
                this.mongoConfig.password,keyData
            )}@${this.mongoConfig.uri}`;
        }
        this.mongoConfig.autoIndex = true;

        mongoose.Promise = global.Promise;
    }

    private connectToMongo(numTries: number = 1): any {
        return mongoose
            .connect(<string>this.mongoConfig.fullUri, this.mongoConfig.options)
            .then(() => {
                this.log.info('MongoDB Connected!');

                return mongoose.connection;
            })
            .catch((error: any) => {
                const timeoutDelayMSec =
                    numTries < <number>this.mongoConfig.triesBeforeFinalDelay
                        ? this.mongoConfig.initialDelayMSec
                        : this.mongoConfig.finalDelayMSec;
                this.log.error(`Issue connecting to MongoDB: ${error.message}`);
                this.log.info(
                    `Retrying connection to MongoDB (attempt #${numTries}). Reconnecting in ${timeoutDelayMSec} ms...`,
                );

                return Promise.delay(<number>timeoutDelayMSec).then(() => {
                    return this.connectToMongo(numTries + 1);
                });
            });
    }

    public connect() {
        if (!this.connectionPromise) {
            this.log.info(`Attempting to connect to MongoDB on ${this.mongoConfig.fullUri}`);
            this.connectionPromise = this.connectToMongo().catch((error: any) => {
                this.connectionPromise = undefined;
                throw error;
            });
        }

        return this.connectionPromise;
    }
}

index.ts:

export { Model1 } from './Model1';
export { MongoDBConnector} from './MongoDBConnector';
export {IMongoPollerCallback, MongoPoller}  from './MongoPoller';

The Main App :

index.ts:

import * as config from './config/config.json';
import * as keyEventLogger from './logging/keyEventLogger';
import { loggerFactory } from './logging/loggerFactory';

import {
    DraftJudgment,
    IDraftDocument,
    IMongoPollerCallback,
    MongoDBConnector,
    MongoPoller
} from 'exploitmongomodels';

import mongoose from 'mongoose';

import { Promise as bluebird } from 'bluebird';
import * as keyData from './key.json';

global.Promise = bluebird;

const log = loggerFactory('main');

async function main() {
    // adding better logging for uncaught rejected promises
    process.on('unhandledRejection', err => {
        log.fatal({ err }, 'uncaught rejection');
    });

    process.on('uncaughtException', err => {
        log.fatal({ err }, 'uncaught exception');
    });

    const mongo = new MongoDBConnector(config.database.mongo, log, keyData);

    await mongo.connect();

    keyEventLogger.logKeyEvent(keyEventLogger.keyEvents.heartBeat, '');

    const d = await DraftJudgment.find({}).exec();
    console.log(d.length); //<- this prints 3
    //const j2 = mongoose.model('DraftJudgment');  <-- this throws an error

    //Set up heart beat for log files
    setInterval(
        () => keyEventLogger.logKeyEvent(keyEventLogger.keyEvents.heartBeat, ''),
        config.logger.heartbeatInterval,
    );

    const judgmentSubmitPoller = new MongoPoller<IDraftDocument>(config.pollingDurationInSec, DraftJudgment, log);

    const judgmentSubmitPollingCB: IMongoPollerCallback<IDraftDocument> = (
        error: Error | undefined,
        docs?: IDraftDocument[],
    ) => {
        if (error) {
            log.error(error, 'Error during judgment mongo polling');
            judgmentSubmitPoller.continue();

            return;
        }
        log.info(`Submit poller triggered submitted judgments`);
        if (!docs) {
            return;
        }
        //do something with the docs object

        log.info(`Submit poller triggered with ${docs.length} submitted judgments`);

        judgmentSubmitPoller.continue();
    };
    judgmentSubmitPoller.initial({ status: 'submitted' }, judgmentSubmitPollingCB);

    const judgmentPendingPoller = new MongoPoller<IDraftDocument>(config.pollingDurationInSec, DraftJudgment, log);

    const judgmentPendingPollingCB: IMongoPollerCallback<IDraftDocument> = (
        error: Error | undefined,
        docs?: IDraftDocument[],
    ) => {
        if (error) {
            log.error(error, 'Error during judgment mongo polling');
            judgmentSubmitPoller.continue();

            return;
        }
        if (!docs) {
            return;
        }

        //do something with the docs object

        log.info(`Pending poller triggered with ${docs.length} submitted judgments`);

        judgmentPendingPoller.continue();
    };
    //judgmentPendingPoller.initial({ $query: { status: 'pending' } }, judgmentPendingPollingCB);

    //tslint:disable-next-line
    while (true) {}
}

main();

In MongoPoller#workFunction , docsp promise never resolves.

Body:
So this was a bit embarrassing, the problem was the while loop at the bottom of main. Added by another dev; we both assumed it was needed to prevent node from exiting. Well it is not, and because the loop was so tight it never allowed time for the promise to resolve.

Live and learn.


问:
Is it possible to access the character after matched position (&) in sed?
I have a text like:

... - hi- 12-

my desired output is to have a space between alphanumeric values that end with - :

... - hi - 12 -

notice that the first hyphen stayed at place since it's preceded by space - not alphanemuric.

also words like multi-line should not be modified.

here's what I'm using:

echo " - hi- 12-" | sed -E 's/[[:alnum:]]-($|[^[:alnum:]])/ &/g'

which outputs:

" - h i- 1 2-"

is there a way I could use &+1 position?

答:
You may use

```<code>sed -E 's/([[:alnum:]])-($|[^[:alnum:]])/\1 -\2/g' <<< " - hi- 12-"
#         ^-- Group1--^ ^-- Group 2 ---^
</code>```

See the online demo

Details

([[:alnum:]]) - Capturing group #1: an alphanumeric char

- - a hyphen

($|[^[:alnum:]]) - Capturing group #2: end of string or any char but alphanumeric.

In the RHS (replacement pattern), \1 and \2 placeholders (or numeric backreferences) refer to the text captured with the corresponding groups.

Body:
You may use

sed -E 's/([[:alnum:]])-($|[^[:alnum:]])/\1 -\2/g' <<< " - hi- 12-"
#         ^-- Group1--^ ^-- Group 2 ---^

See the online demo

Details

([[:alnum:]]) - Capturing group #1: an alphanumeric char

- - a hyphen

($|[^[:alnum:]]) - Capturing group #2: end of string or any char but alphanumeric.

In the RHS (replacement pattern), \1 and \2 placeholders (or numeric backreferences) refer to the text captured with the corresponding groups.


问:
Display all data in the model and use checkbox to bulk edit all the data
I am trying to create a page that can allow user to use check boxes edit multiple row of data. I know js can finish the job but I only have limited knowledge about js.. Is there a way to use Django Form and Widgets to accomplish this?</p>

答:
It's certainly possible to use Django-filters (or just a ListView with a fixed QuerySet) to generate a multi-row HTML form complete with checkboxes. Once the user has filtered out what he wants to update, he'll click checkboxes, fill in some fields on the rows, and click on the form-submit button (which you'll have to code in the template) instead of the filter button.

The form data gets POSTed back to the URL you code, and your view then has to loop over the rows represented as raw request.POST data. If the checkbox is checked, you can gather the rest of the submitted raw data for that row from request.POST into a dict with the right keys  for feeding into a Django form. Validate and save in the usual way.

In other words, you are using your form purely to validate. not to generate any html at all. You need greater HTML skill to write that the view template that renders as a form, but no JS is involved (other than appropriate classes and divs for Bootstrap or whatever overall scheme you are using).

It's not the same as a Django form, in that it's pretty hard to re-display the form with what the user typed pre-filled for fixing up  after validation fails. Best if the user is updating stuff that "can't be wrong" such as Yes/No options or comment fields.

You need to consider your database integrity, should the N'th row fails to validate. If the rows are all independent it may be sufficient to tell the user which updates failed. Otherwise you may want to make it a transaction that you can completely roll back on failure.


问:
changing control source in access report textbox
I have an access report where I wanted to make a textbox control source dynamic based on the current date using this to limit data returned to the last 5 years based on the current date.
I'm bring back the number of claims for the past 5 years based on the accident year.

Working:  =Sum(IIf([accidYr]>(Year()-6),[numClaims],0))

It works just fine but............
When I click off or save and reopen the properties box it changes to:
=Sum(IIf([accidYr]>2013,[numClaims],0))

The issue is that 2013 is now hard-coded and is no longer dynamic so it will lead to problems down the road.

Any suggestions?
Thank you.

Tried several variations with no luck.

Working:  =Sum(IIf([accidYr]>(Year()-6),[numClaims],0))

Changes to:  =Sum(IIf([accidYr]>2013,[numClaims],0))

No error messages, just an Access "feature" I presume.

答:
Try with:</p>

```<code>=Sum(IIf([accidYr]>(Year(Date())-6),[numClaims],0))
</code>```

Body:
Try with:

=Sum(IIf([accidYr]>(Year(Date())-6),[numClaims],0))


答:
Here is a simple groupBy function which accepts an array of objects and array of props to group on:

let data = [
  {color:'red', shape:'circle', size:'medium'},
  {color:'red', shape:'circle', size:'small'}
]

let groupBy = (arr, props) => Object.values(arr.reduce((r,c) => {
  let key = props.reduce((a,k) => `${a}${c[k]}`, '')
  let otherKeys = Object.keys(c).filter(k => !props.includes(k))
  r[key] = r[key] || {...c, ...otherKeys.reduce((a,k) => (a[k] = [], a),{})}
  otherKeys.forEach(k => r[key][k].push(c[k]))
  return r
}, {}))

console.log(groupBy(data, ['color','shape']))```

The idea is to use Array.reduce and basically create a string key of the passed in props. For the other fields create an array and keep pushing values there on each iteration.

Title: Combine two objects in an array into a single object if the object properties are the same and convert the unique properties into an array

Body:
Input -

[
  {color:'red', shape:'circle', size:'medium'},
  {color:'red', shape:'circle', size:'small'}
]

Output -

[
  {color:'red', shape:'circle', size:['medium','small']}
]

How can this be achieved in Javascript?

Body:
Here is a simple groupBy function which accepts an array of objects and array of props to group on:

let data = [
  {color:'red', shape:'circle', size:'medium'},
  {color:'red', shape:'circle', size:'small'}
]

let groupBy = (arr, props) => Object.values(arr.reduce((r,c) => {
  let key = props.reduce((a,k) => `${a}${c[k]}`, '')
  let otherKeys = Object.keys(c).filter(k => !props.includes(k))
  r[key] = r[key] || {...c, ...otherKeys.reduce((a,k) => (a[k] = [], a),{})}
  otherKeys.forEach(k => r[key][k].push(c[k]))
  return r
}, {}))

console.log(groupBy(data, ['color','shape']))

The idea is to use Array.reduce and basically create a string key of the passed in props. For the other fields create an array and keep pushing values there on each iteration.