问:
JetBrains Rider C# Application Requiring Administrator Privileges
I'm trying to guess how to require administrator privileges for my application in JetBrains Rider. In Visual Studio there's the option to add "App.manifest" file, where you can set the property <requestedExecutionLevel level="requireAdministrator" uiAccess="false" /> and the application will require administrator privileges.

I find no way to do this in JetBrains Rider. How can I request administrator privileges using JetBrains Rider?

I'm developing a .NetFramework application using C# language. And this is my project structure:

Thanks in advance.

答:
I don't think there is a visual way for doing this on Rider, but you can manually do this by adding the ApplicationManifest tag to your .csproj file.

```<code><PropertyGroup>
    <ApplicationManifest>path/to/app/manifest/app.manifest</ApplicationManifest>
</PropertyGroup>
</code>```

Then, create your app.manifest file and configure it the way you want!
(The app.manifest is usually located at your app Properties folder)

Body:
I don't think there is a visual way for doing this on Rider, but you can manually do this by adding the ApplicationManifest tag to your .csproj file.

<PropertyGroup>
    <ApplicationManifest>path/to/app/manifest/app.manifest</ApplicationManifest>
</PropertyGroup>

Then, create your app.manifest file and configure it the way you want!
(The app.manifest is usually located at your app Properties folder)


来源: stackexchange

问:
Best way for passing string while including file
I'm having a trouble with passing string while using include() function. I have index.php which serves as template file and is including any other pages.

For example, if I want to go to the home page, the address is http://somethingsomething.com/index.php?page=home and included file is pages/home.php. Bellow you can find how the template system works. I want to change  of the page you're currently are but I don't know what is the best way to pass that string from the title of the page. So if I'm on the Catalogue page - http://somethingsomething.com/index.php?page=catalogue, it will include file pages/catalogue.php and I've tried to pass string as SESSION but it didn't worked. Could you please help me?

Source URL: http://somethingsomething.com/index.php?page=catalogue

index.php file

```<code><html>
    <head>
        <title><?php echo $title; ?></title>
    </head>
    <body>
        <h1>Welcome, world!</h1>
    <?php
        if (isset($_GET['page'])) {
            $page = $_GET['page'];
        } else {
            $page = 'home';
        }

        if (preg_match('/^[a-z0-9]+$/', $page)) {
            $insert = include('pages/' . $page . '.php');
            if (!$insert) {
                $insert = include('pages/error.php');
            }
        } else if (empty($page)) {
            $insert = include('pages/error.php');
        } else {
            $insert = include('pages/error.php');
        }
    ?>
    </body>
</html>
</code>```

pages/catalogue.php file

    <?php
        $title = "Catalogue";
    ?>
```

答:
Something like this?</p>

```<code><?php
    ob_start();
        if (isset($_GET['page'])) {
            $page = $_GET['page'];
        } else {
            $page = 'home';
        }

        if (preg_match('/^[a-z0-9]+$/', $page)) {
            $insert = include('pages/' . $page . '.php');
            if (!$insert) {
                $insert = include('pages/error.php');
            }
        } else if (empty($page)) {
            $insert = include('pages/error.php');
        } else {
            $insert = include('pages/error.php');
        }
    $output = ob_get_clean();
?>
<html>
    <head>
        <title><?php echo $title; ?></title>
    </head>
    <body>
        <h1>Welcome, world!</h1>
    <?php
        echo $output;
    ?>
    </body>
</html>
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm having a trouble with passing string while using include() function. I have index.php which serves as template file and is including any other pages.

For example, if I want to go to the home page, the address is http://somethingsomething.com/index.php?page=home and included file is pages/home.php. Bellow you can find how the template system works. I want to change  of the page you're currently are but I don't know what is the best way to pass that string from the title of the page. So if I'm on the Catalogue page - http://somethingsomething.com/index.php?page=catalogue, it will include file pages/catalogue.php and I've tried to pass string as SESSION but it didn't worked. Could you please help me?

Source URL: http://somethingsomething.com/index.php?page=catalogue

index.php file

        <title><?php echo $title; ?></title>

Welcome, world!

    <?php
        if (isset($_GET['page'])) {
            $page = $_GET['page'];
        } else {
            $page = 'home';
        }

        if (preg_match('/^[a-z0-9]+$/', $page)) {
            $insert = include('pages/' . $page . '.php');
            if (!$insert) {
                $insert = include('pages/error.php');
            }
        } else if (empty($page)) {
            $insert = include('pages/error.php');
        } else {
            $insert = include('pages/error.php');
        }
    ?>

pages/catalogue.php file

    <?php
        $title = "Catalogue";
    ?>

Body:
Something like this?

<?php
    ob_start();
        if (isset($_GET['page'])) {
            $page = $_GET['page'];
        } else {
            $page = 'home';
        }

        if (preg_match('/^[a-z0-9]+$/', $page)) {
            $insert = include('pages/' . $page . '.php');
            if (!$insert) {
                $insert = include('pages/error.php');
            }
        } else if (empty($page)) {
            $insert = include('pages/error.php');
        } else {
            $insert = include('pages/error.php');
        }
    $output = ob_get_clean();
?>
<html>
    <head>
        <title><?php echo $title; ?></title>
    </head>
    <body>
        <h1>Welcome, world!</h1>
    <?php
        echo $output;
    ?>
    </body>
</html>


问:
How to generate a download request from html page to controller of spring mvc

<title>Student Registration</title>

New Trainee Registration

       First Name
       ${traineeData.fName}

       Last Name
       ${traineeData.lName}

       Father's Name
       ${traineeData.fatherName}

       Mobile No.
       ${traineeData.mobile}

       Joining Date
       ${traineeData.joiningDate}>

       Grade
       ${traineeData.grade}

       Gender
       ${traineeData.gender}

       COURSES
APPLIED FOR

       ${traineeData.course}

       Joining Date
       ${traineeData.joiningDate}

    <button type="button" >Generate Certificate</button>

```
</div>
</div>
</p>

<p>Let's say, I have a download button on my HTML page. when clicking on this button a request goes through the controller of the spring MVC framework along with "enrollmentNo".</p>

<p>On Controller class, I will use this enrollmentNo.</p>

<p>I have a class which will generate a certificate for the student by fetching data using the student's enrollmentNo.</p>

<p>and response goes back and a file will download(which a pdf file generated by my pre-created class)</p>

<p>I have tried with many ways but not get what I want.</p>

```@RequestMapping(value = "/generateCertificate")
public void generateCertificate(@RequestParam("traineeData.enrollmentNo") int enrollmentNo) {

    System.out.println("you in /generateCertificate");

    // I don't know what should I return...
    // please change return type accordingly...
}
```

I want a button on my HTML page named "Generate certificate".  The code should be easy and normal, Ajax can be used here.

答:
Your button isn't actually doing anything, useful.

Try this code around your button...

```<code><tr>
    <td colspan="2" align="center">
        <form action="/generateCertificate" method="GET">
            <input type="hidden" name="enrollmentNo" value="${traineeData.enrollmentNo}"
            <button type="submit">Generate Certificate</button>
        </form>
    </td>
</tr>
</code>```

Then your controller will need to changed slightly...

```<code>@RequestMapping(value = "/generateCertificate")
public void generateCertificate(@RequestParam("enrollmentNo") int enrollmentNo) {

    // The @RequestParam was changed to the name of the param from the form and not the object/value.
}
</code>```

Body:
<title>Student Registration</title>

New Trainee Registration

       First Name
       ${traineeData.fName}

       Last Name
       ${traineeData.lName}

       Father's Name
       ${traineeData.fatherName}

       Mobile No.
       ${traineeData.mobile}

       Joining Date
       ${traineeData.joiningDate}>

       Grade
       ${traineeData.grade}

       Gender
       ${traineeData.gender}

       COURSES
APPLIED FOR

       ${traineeData.course}

       Joining Date
       ${traineeData.joiningDate}

    <button type="button" >Generate Certificate</button>

Let's say, I have a download button on my HTML page. when clicking on this button a request goes through the controller of the spring MVC framework along with "enrollmentNo".

On Controller class, I will use this enrollmentNo.

I have a class which will generate a certificate for the student by fetching data using the student's enrollmentNo.

and response goes back and a file will download(which a pdf file generated by my pre-created class)

I have tried with many ways but not get what I want.

@RequestMapping(value = "/generateCertificate")
public void generateCertificate(@RequestParam("traineeData.enrollmentNo") int enrollmentNo) {

    System.out.println("you in /generateCertificate");

    // I don't know what should I return...
    // please change return type accordingly...
}

I want a button on my HTML page named "Generate certificate".  The code should be easy and normal, Ajax can be used here.

Body:
Your button isn't actually doing anything, useful.

Try this code around your button...

<tr>
    <td colspan="2" align="center">
        <form action="/generateCertificate" method="GET">
            <input type="hidden" name="enrollmentNo" value="${traineeData.enrollmentNo}"
            <button type="submit">Generate Certificate</button>
        </form>
    </td>
</tr>

Then your controller will need to changed slightly...

@RequestMapping(value = "/generateCertificate")
public void generateCertificate(@RequestParam("enrollmentNo") int enrollmentNo) {

    // The @RequestParam was changed to the name of the param from the form and not the object/value.
}


问:
"index 1 is out of bounds for axis 0 with size 1" in python
I seem to be having an indexing problem? I do not know how to interpret this error... :/ I think it has to do with how I initialized u.

I have this 3x3 G matrix that I created using the variable u (a vector, x - y). I just made a zero matrix for now bc I'm not quite sure how to code it yet, there are lots of partials and norms involved haha. x_j = (x_1 (j), x_2 (j), x_3 (j)) and y_j = (y_1 (j), y_2 (j), y_3 (j)). x and y are nx3 vectors. alpha_j is a 3x3 matrix. The A matrix is block diagonal matrix of size 3nx3n. I am having trouble with the W matrix (size 3nx3n, where the (i,j)th block is the 3x3 matrix given by alpha_i*G_[ij]*alpha_j).

```<code>def G(u):

    u1 = u[0]
    u2 = u[1]
    u3 = u[2]
    g = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)

    return g

def W(x, y, k, alpha, A):

    # initialization
    n = x.shape[0] # the number of x vextors
    result = np.zeros([3*n,3*n],complex)
    u = np.matlib.zeros((n, 3)) # u = x - y
    print(u)
    num_in_blocks = n

    # variables
    a_i = alpha_j(alpha, A)
    a_j = alpha_j(alpha, A)

    for i in range(0, 2):
        x1 = x[i] # each row of x
        y1 = y[i] # each row of y
        for j in range(0, n-1):
            u[i][j] = x1[j] - y1[j] # each row of x minus each row of y
        if i != j:
            block_result = a_i * G((u[i][j]), k) * a_j
            for k in range(num_in_blocks):
                for l in range(num_in_blocks):
                    result[3*i + k, 3*j + l] = block_result[i, j]

    return result

def alpha_j(a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    n = A.shape[0]
    rho = np.random.rand(n,1)
    for i in range(0, n-1):
        for j in range(0, n-1):
            alph[i,j] = (rho[i] * a * A[i,j])
    return alph

#------------------------------------------------------------------

# random case

def x(n):
    return np.random.randint(100, size=(n, 3))

def y(n):
    return np.random.randint(100, size=(n, 3))

# SYSTEM PARAMETERS

theta = 0 # can range from [0, 2pi)

chi = 10 + 1j

lam = 0.5 # microns (values between .4-.7)

k = (2 * np.pi)/lam # 1/microns

V_0 = (0.05)**3 # microns^3

K = k * np.array([[0], [np.sin(theta)], [np.cos(theta)]])

alpha = (V_0 * 3 * chi)/(chi + 3)

A = np.matlib.identity(3)

#------------------------------------------------------------------

# TEST FUNCTIONS

w = W(x(3), y(3), k, alpha, A)
print(w)
</code>```

I keep getting the error "invalid index to scalar variable." at the line u1 = u[0].

答:
np.matlib makes a np.matrix, a subclass of np.ndarray.  It's supposed to give a MATLAB feel, and (nearly) always produces a 2d array.  Its use in new code is being discouraged.

```<code>In [42]: U = np.matrix(np.arange(9).reshape(3,3))
In [43]: U
Out[43]:
matrix([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])
</code>```

Indexing with [0] picks the first row, but returns a 2d matrix.

```<code>In [44]: U[0]
Out[44]: matrix([[0, 1, 2]])
In [45]: U[0].shape
Out[45]: (1, 3)
</code>```

Adding another [1] still indexes the first dimension (which is now size 1):

```<code>In [46]: U[0][1]
---------------------------------------------------------------------------
IndexError: index 1 is out of bounds for axis 0 with size 1
</code>```

Normally we index numpy arrays with a composite index:

```<code>In [47]: U[0,1]
Out[47]: 1
</code>```

If we make an ndarray instead:

```<code>In [48]: U = np.arange(9).reshape(3,3)
In [49]: U
Out[49]:
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In [50]: U[0]
Out[50]: array([0, 1, 2])      # 1d
In [51]: U[0][1]               # works,
Out[51]: 1
In [52]: U[0,1]                # still preferable
Out[52]: 1
</code>```

Body:
I seem to be having an indexing problem? I do not know how to interpret this error... :/ I think it has to do with how I initialized u.

I have this 3x3 G matrix that I created using the variable u (a vector, x - y). I just made a zero matrix for now bc I'm not quite sure how to code it yet, there are lots of partials and norms involved haha. x_j = (x_1 (j), x_2 (j), x_3 (j)) and y_j = (y_1 (j), y_2 (j), y_3 (j)). x and y are nx3 vectors. alpha_j is a 3x3 matrix. The A matrix is block diagonal matrix of size 3nx3n. I am having trouble with the W matrix (size 3nx3n, where the (i,j)th block is the 3x3 matrix given by alpha_i*G_[ij]*alpha_j).

def G(u):

    u1 = u[0]
    u2 = u[1]
    u3 = u[2]
    g = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)

    return g

def W(x, y, k, alpha, A):

    # initialization
    n = x.shape[0] # the number of x vextors
    result = np.zeros([3*n,3*n],complex)
    u = np.matlib.zeros((n, 3)) # u = x - y
    print(u)
    num_in_blocks = n

    # variables
    a_i = alpha_j(alpha, A)
    a_j = alpha_j(alpha, A)

    for i in range(0, 2):
        x1 = x[i] # each row of x
        y1 = y[i] # each row of y
        for j in range(0, n-1):
            u[i][j] = x1[j] - y1[j] # each row of x minus each row of y
        if i != j:
            block_result = a_i * G((u[i][j]), k) * a_j
            for k in range(num_in_blocks):
                for l in range(num_in_blocks):
                    result[3*i + k, 3*j + l] = block_result[i, j]

    return result

def alpha_j(a, A):
    alph = np.array([[0,0,0],[0,0,0],[0,0,0]],complex)
    n = A.shape[0]
    rho = np.random.rand(n,1)
    for i in range(0, n-1):
        for j in range(0, n-1):
            alph[i,j] = (rho[i] * a * A[i,j])
    return alph

#------------------------------------------------------------------

# random case

def x(n):
    return np.random.randint(100, size=(n, 3))

def y(n):
    return np.random.randint(100, size=(n, 3))

# SYSTEM PARAMETERS

theta = 0 # can range from [0, 2pi)

chi = 10 + 1j

lam = 0.5 # microns (values between .4-.7)

k = (2 * np.pi)/lam # 1/microns

V_0 = (0.05)**3 # microns^3

K = k * np.array([[0], [np.sin(theta)], [np.cos(theta)]])

alpha = (V_0 * 3 * chi)/(chi + 3)

A = np.matlib.identity(3)

#------------------------------------------------------------------

# TEST FUNCTIONS

w = W(x(3), y(3), k, alpha, A)
print(w)

I keep getting the error "invalid index to scalar variable." at the line u1 = u[0].

Body:
np.matlib makes a np.matrix, a subclass of np.ndarray.  It's supposed to give a MATLAB feel, and (nearly) always produces a 2d array.  Its use in new code is being discouraged.

In [42]: U = np.matrix(np.arange(9).reshape(3,3))
In [43]: U
Out[43]:
matrix([[0, 1, 2],
        [3, 4, 5],
        [6, 7, 8]])

Indexing with [0] picks the first row, but returns a 2d matrix.

In [44]: U[0]
Out[44]: matrix([[0, 1, 2]])
In [45]: U[0].shape
Out[45]: (1, 3)

Adding another [1] still indexes the first dimension (which is now size 1):

In [46]: U[0][1]
---------------------------------------------------------------------------
IndexError: index 1 is out of bounds for axis 0 with size 1

Normally we index numpy arrays with a composite index:

In [47]: U[0,1]
Out[47]: 1

If we make an ndarray instead:

In [48]: U = np.arange(9).reshape(3,3)
In [49]: U
Out[49]:
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
In [50]: U[0]
Out[50]: array([0, 1, 2])      # 1d
In [51]: U[0][1]               # works,
Out[51]: 1
In [52]: U[0,1]                # still preferable
Out[52]: 1


问:
How to use Azure DevOps API to autocomplete a pull request for “rebase and fast-forward” merge type?
I have two main branches in my repo: master and production. The feature branches merge to master and there is a pipeline which uses REST API to create PRs to push changes from master to production. I want to keep history of master and production exact same, so I only allow "Rebase and fast-forward" merge type in production branch. Everything works fine except the fact that I cannot auto-complete the PR using Azure DevOps Rest API.

I am following the documentation to auto-complete the PR but there is only squashMerge option here. Is there support for other type of merges (Rebase and fase-forward or Rebase with merge commit) using REST APT?

答:
In the Rest API version 5.1 (in preview) you have the option to completionOptions, it's contains GitPullRequestCompletionOptions and there you have mergeStrategy:

noFastForward

rebase

rebaseMerge

squash

See the Docs here.

Put attention that you need to use this version in the URL: api-version=5.1


问:
Prevent duplicate keys in combined objects, reverse of { [K in keyof T]: T[K] }
In typescript I want to create a function which accepts 2 objects, and Object.assigns them to a new object, with type checking that ensures neither object has any of the same keys.

I tried using variaous forms of k in keyof T with no success.

function combine<T extends Object, U extends { [K in keyof T]: undefined }>(obj1: T, obj2: U) {
    return {
        ...obj1,
        ...obj2
    }
}
```

<p>The results have not resulted in proper type checking</p>

<pre class="lang-js prettyprint-override"><code>// setup objects
const test1 = { test: 1 }
const test2 = { something: 'string' }
const test3 = { test: {}}

//  I need this to only error when properties on test 2 exist in test 1

// should pass
const result = combine(test1, test2)

/* Resulting error:
Argument of type '{ something: string; }' is not assignable to parameter of type '{ test: undefined; }'.
  Property 'test' is missing in type '{ something: string; }' but required in type '{ test: undefined; }'.
 */

// should fail and does fail
const result2 = combine(test1, test3)

/* Resulting error:
Argument of type '{ test: {}; }' is not assignable to parameter of type '{ test: undefined; }'.
  Types of property 'test' are incompatible.
    Type '{}' is not assignable to type 'undefined'.
 */
</code>```

答:
Something like this also works:

```<code>function combine<T extends object, U extends object>(
  obj1: keyof T extends keyof U ? never : T,
  obj2: keyof U extends keyof T ? never : U,
) {
  return {
    ...obj1,
    ...obj2,
  }
}
</code>```

Playground here

Body:
In typescript I want to create a function which accepts 2 objects, and Object.assigns them to a new object, with type checking that ensures neither object has any of the same keys.

<a href="https://www.typescriptlang.org/play/#src=const%20test1%20%3D%20%7B%20test%3A%201%20%7D%0D%0Aconst%20test2%20%3D%20%7B%20something%3A%20'string'%20%7D%0D%0Aconst%20test3%20%3D%20%7B%20test%3A%20%7B%7D%7D%0D%0Afunction%20combine%3CT%20extends%20Object%2C%20U%20extends%20%7B%20%5BK%20in%20keyof%20T%5D%3A%20undefined%20%7D%3E(obj1%3A%20T%2C%20obj2%3A%20U)%20%7B%0D%0A%20%20%20%20return%20%7B%0D%0A%20%20%20%20%20%20%20%20...obj1%2C%0D%0A%20%20%20%20%20%20%20%20...obj2%0D%0A%20%20%20%20%7D%0D%0A%7D%0D%0A%0D%0A%2F%2F%20%20I%20need%20this%20to%20only%20error%20when%20properties%20on%20test%202%20exist%20in%20test%201%0D%0Aconst%20result%20%3D%20combine(test1%2C%20test2)%20%20%2F%2F%20should%20pass%0D%0Aconst%20result2%20%3D%20combine(test1%2C%20test3)%20%2F%2F%20should%20fail" rel="nofollow noreferrer">I tried using variaous forms of k in keyof T with no success.

function combine<T extends Object, U extends { [K in keyof T]: undefined }>(obj1: T, obj2: U) {
    return {
        ...obj1,
        ...obj2
    }
}

The results have not resulted in proper type checking

// setup objects
const test1 = { test: 1 }
const test2 = { something: 'string' }
const test3 = { test: {}}

//  I need this to only error when properties on test 2 exist in test 1

// should pass
const result = combine(test1, test2)

/* Resulting error:
Argument of type '{ something: string; }' is not assignable to parameter of type '{ test: undefined; }'.
  Property 'test' is missing in type '{ something: string; }' but required in type '{ test: undefined; }'.
 */

// should fail and does fail
const result2 = combine(test1, test3)

/* Resulting error:
Argument of type '{ test: {}; }' is not assignable to parameter of type '{ test: undefined; }'.
  Types of property 'test' are incompatible.
    Type '{}' is not assignable to type 'undefined'.
 */

Body:
Something like this also works:

function combine<T extends object, U extends object>(
  obj1: keyof T extends keyof U ? never : T,
  obj2: keyof U extends keyof T ? never : U,
) {
  return {
    ...obj1,
    ...obj2,
  }
}

Playground <a href="https://www.typescriptlang.org/play/#src=function%20combine%3CT%20extends%20object%2C%20U%20extends%20object%3E(%0D%0A%20%20obj1%3A%20keyof%20T%20extends%20keyof%20U%20%3F%20'arguments%20cannot%20have%20properties%20in%20common'%20%3A%20T%2C%0D%0A%20%20obj2%3A%20keyof%20U%20extends%20keyof%20T%20%3F%20'arguments%20cannot%20have%20properties%20in%20common'%20%3A%20U%2C%0D%0A)%20%7B%0D%0A%20%20return%20%7B%0D%0A%20%20%20%20...obj1%2C%0D%0A%20%20%20%20...obj2%2C%0D%0A%20%20%7D%0D%0A%7D%0D%0A%0D%0Aconst%20test1%20%3D%20%7B%20test%3A%201%20%7D%0D%0Aconst%20test2%20%3D%20%7B%20something%3A%20'string'%20%7D%0D%0Aconst%20test3%20%3D%20%7B%20test%3A%20%7B%7D%20%7D%0D%0A%0D%0A%0D%0Aconst%20result%20%3D%20combine(test1%2C%20test2)%0D%0A%0D%0Aconst%20result2%20%3D%20combine(test1%2C%20test3)%0D%0A" rel="nofollow noreferrer">here


问:
ImproperlyConfigured: The included URLconf 'buttonpython.urls' does not appear to have any patterns in it
The error im getting is

django.core.exceptions.ImproperlyConfigured: The included URLconf
  'buttonpython.urls' does not appear to have any patterns in it. If you
  see valid patterns in the file then the issue is probably caused by a
  circular import.

I am following an older django tutorial because those are literally all i can find and got his error.
Here is the urls.py:

```<code>from . import views
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.button)
]
</code>```

Settings.py (i included this because i found the buttonpython.urls variable in it):

```<code>INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'buttonpython.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'buttonpython.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'
</code>```

Views.py:

```<code>from django.shortcuts import render
from . import urls.py
import requests
from bs4 import BeautifulSoup

def button(request):
    return render(request, 'home.html')

def output(request):
    def trade_spider(max_pages):
        page = 1
        data = ''
        while(page <= max_pages):
                search = 'Ipad'
                url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
                src = requests.get(url)
                text = src.text
                soup = BeautifulSoup(text, features="html.parser")
                for link in soup.findAll('a', {'class': 's-item__link'}):
                        href = link.get('href')
                        title = link.string
                        if(title == None):
                            title = "Sorry the title was unavailable however you can check the price."
                        price = get_item_price(href)
                        data += href + '\n' + title + '\n' + price + '\n'

                page+=1
        return data

    def get_item_price(item_url):
        src = requests.get(item_url)
        text = src.text
        soup = BeautifulSoup(text, features="html.parser")
        for item_price in soup.findAll('span', {'class': 'notranslate'}):
                price = item_price.string
                return price

    data = trade_spider(1)
    return render(request, 'home.html', {'data':data})
</code>```

I am stumped any help would be appreciated.

答: As the error says, you have a circular import. For some reason your views.py is importing urls.py. There is no reason to do that, you should remove that import.</p>

Body:
The error im getting is

django.core.exceptions.ImproperlyConfigured: The included URLconf
  'buttonpython.urls' does not appear to have any patterns in it. If you
  see valid patterns in the file then the issue is probably caused by a
  circular import.

I am following an older django tutorial because those are literally all i can find and got his error.
Here is the urls.py:

from . import views
from django.contrib import admin
from django.urls import path

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', views.button)
]

Settings.py (i included this because i found the buttonpython.urls variable in it):

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'buttonpython.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': ['templates'],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'buttonpython.wsgi.application'

# Database
# https://docs.djangoproject.com/en/2.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
    }
}

# Password validation
# https://docs.djangoproject.com/en/2.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/2.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.2/howto/static-files/

STATIC_URL = '/static/'

Views.py:

from django.shortcuts import render
from . import urls.py
import requests
from bs4 import BeautifulSoup

def button(request):
    return render(request, 'home.html')

def output(request):
    def trade_spider(max_pages):
        page = 1
        data = ''
        while(page <= max_pages):
                search = 'Ipad'
                url = 'https://www.ebay.com/sch/i.html?_from=R40&_nkw=' + search + '&_sacat=0&_pgn=' + str(page)
                src = requests.get(url)
                text = src.text
                soup = BeautifulSoup(text, features="html.parser")
                for link in soup.findAll('a', {'class': 's-item__link'}):
                        href = link.get('href')
                        title = link.string
                        if(title == None):
                            title = "Sorry the title was unavailable however you can check the price."
                        price = get_item_price(href)
                        data += href + '\n' + title + '\n' + price + '\n'

                page+=1
        return data

    def get_item_price(item_url):
        src = requests.get(item_url)
        text = src.text
        soup = BeautifulSoup(text, features="html.parser")
        for item_price in soup.findAll('span', {'class': 'notranslate'}):
                price = item_price.string
                return price

    data = trade_spider(1)
    return render(request, 'home.html', {'data':data})

I am stumped any help would be appreciated.


问:
nHibernate ProxyFactory issues
I am setting up my first nHibernate project.  I have created a simple web form that accepts a name and an id however, I keep on getting the following error:

The ProxyFactoryFactory was not configured.
Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.
Example:
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
Example:
NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle

I have already added the references to both Castle and LinFu to my project.  I have also configured the web.config to the following:

```<code><section name="nhibernate" type="System.Configuration.NameValueSectionHandler, System, Version=1.0.5000.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" allowDefinition="Everywhere"/>
</code>```

Can you tell me what is going on?  I have tried everything.  Is it that I imported a lot of my mappings etc, from visualNHibernate?  Appreciate the help.

答:
You have to specify what proxy factory you intend to use, as for example:

```<code><property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>`
</code>```

And, furthermore, the cconfiguration you posted contains... nothing, please ensure to have a minimum configuration in place, without it you can't create the NH session factory.

ContentLicense: CC BY-SA 3.0

Title: nHibernate ProxyFactory issues

Body:
I am setting up my first nHibernate project.  I have created a simple web form that accepts a name and an id however, I keep on getting the following error:

The ProxyFactoryFactory was not configured.
Initialize 'proxyfactory.factory_class' property of the session-factory configuration section with one of the available NHibernate.ByteCode providers.
Example:
NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu
Example:
NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle

I have already added the references to both Castle and LinFu to my project.  I have also configured the web.config to the following:

Can you tell me what is going on?  I have tried everything.  Is it that I imported a lot of my mappings etc, from visualNHibernate?  Appreciate the help.

Body:
You have to specify what proxy factory you intend to use, as for example:

<property name="proxyfactory.factory_class">NHibernate.ByteCode.LinFu.ProxyFactoryFactory, NHibernate.ByteCode.LinFu</property>`

And, furthermore, the cconfiguration you posted contains... nothing, please ensure to have a minimum configuration in place, without it you can't create the NH session factory.


问:
Spring Maven reading from resources folder
I'm using Spring Boot. I want to read a json file in src/main/resources folder.

```<code>File file = new File(this.getClass().getClassLoader().getResource(inputFileName).getFile());
</code>```

Maven:

```<code><?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" output="target/classes" path="src/main/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="src" output="target/test-classes" path="src/test/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="test" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="output" path="target/classes"/>
</classpath>
</code>```

Now, when I run my Spring Boot application in Eclipse using Spring Tools (Run As -> Spring Boot App), I get NoSuchFileException and the application is trying to find the file in /target/classes/ instead of /src/main/resources folder.

Also, I cannot see the file in /target/classes/ folder. Why isn't maven copying it to target/classes?

What can I do to read from the resources folder?

答:
You don't have to use file to read the contents. You can just call

```<code>this.getClass().getResourceAsStream(inputFileName)
</code>```

This way it will work whether you have JAR/WAR file or running it in eclipse. As Yuan pointed out, resources will get copied and bundled in the files after the build. Eclipse manages the maven classpath and will add appropriate entries to classpath when application is executed.

Body:
I'm using Spring Boot. I want to read a json file in src/main/resources folder.

File file = new File(this.getClass().getClassLoader().getResource(inputFileName).getFile());

Maven:

<?xml version="1.0" encoding="UTF-8"?>
<classpath>
    <classpathentry kind="src" output="target/classes" path="src/main/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/resources">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="src" output="target/test-classes" path="src/test/java">
        <attributes>
            <attribute name="optional" value="true"/>
            <attribute name="maven.pomderived" value="true"/>
            <attribute name="test" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="con" path="org.eclipse.m2e.MAVEN2_CLASSPATH_CONTAINER">
        <attributes>
            <attribute name="maven.pomderived" value="true"/>
        </attributes>
    </classpathentry>
    <classpathentry kind="output" path="target/classes"/>
</classpath>

Now, when I run my Spring Boot application in Eclipse using Spring Tools (Run As -> Spring Boot App), I get NoSuchFileException and the application is trying to find the file in /target/classes/ instead of /src/main/resources folder.

Also, I cannot see the file in /target/classes/ folder. Why isn't maven copying it to target/classes?

What can I do to read from the resources folder?

Body:
You don't have to use file to read the contents. You can just call

this.getClass().getResourceAsStream(inputFileName)

This way it will work whether you have JAR/WAR file or running it in eclipse. As Yuan pointed out, resources will get copied and bundled in the files after the build. Eclipse manages the maven classpath and will add appropriate entries to classpath when application is executed.


问:
Ramdajs, group array with arguments
List to group:

```<code>const arr = [
  {
    "Global Id": "1231",
    "TypeID": "FD1",
    "Size": 160,
    "Flöde": 55,
  },
  {
    "Global Id": "5433",
    "TypeID": "FD1",
    "Size": 160,
    "Flöde": 100,
  },
  {
    "Global Id": "50433",
    "TypeID": "FD1",
    "Size": 120,
    "Flöde": 100,
  },
 {
    "Global Id": "452",
    "TypeID": "FD2",
    "Size": 120,
    "Flöde": 100,
  },
]
</code>```

Input to function which specifies what keys to group:

```<code>const columns = [
    {
      "dataField": "TypeID",
      "summarize": false,
    },
    {
      "dataField": "Size",
      "summarize": false,
    },
    {
      "dataField": "Flöde",
      "summarize": true,
    },
]
</code>```

Expected output:

```<code>const output = [
    {
      "TypeID": "FD1",
      "Size": 160,
      "Flöde": 155 // 55 + 100
      "nrOfItems": 2
    },
    {
       "TypeID": "FD1",
       "Size": 120,
       "Flöde": 100,
       "nrOfItems": 1
    },
    {
       "TypeID": "FD2",
       "Size": 120,
       "Flöde": 100,
       "nrOfItems": 1
    }
  ]

  // nrOfItems adds up 4. 2 + 1 +1. The totalt nr of items.
</code>```

Function:

```<code>const groupArr = (columns) => R.pipe(...);
</code>```

The "summarize" property tells if the property should summarize or not.

The dataset is very large, +100k items. So I don't want to iterate more than necessary.

I've looked at the R.group but I'm not sure it can be applied here?

Maybe something with R.reduce? Store the group in the accumulator, summarize values and add to count if the group already exists? Need to find the group fast so maybe store the group as a key?

Or is it better to use vanilla javascript in this case?

答:
Here's my initial approach.  Everything but summarize is a helper function which I suppose could be inlined if you really wanted.  I find it cleaner with this separation.

const getKeys = (val) => pipe (
  filter (propEq ('summarize', val) ),
  pluck ('dataField')
)

const keyMaker = (columns, keys = getKeys (false) (columns)) => pipe (
  pick (keys),
  JSON .stringify
)

const makeReducer = (
  columns,
  toSum = getKeys (true) (columns),
  toInclude = getKeys (false) (columns),
) => (a, b) => ({
  ...mergeAll (map (k => ({ [k]: b[k] }), toInclude ) ),
  ...mergeAll (map (k => ({ [k]: (a[k] || 0) + b[k] }), toSum ) ),
  nrOfItems: (a .nrOfItems || 0) + 1
})

const summarize = (columns) => pipe (
  groupBy (keyMaker (columns) ),
  values,
  map (reduce (makeReducer (columns), {} ))
)

const arr = [{"Flöde": 55, "Global Id": "1231", "Size": 160, "TypeID": "FD1"}, {"Flöde": 100, "Global Id": "5433", "Size": 160, "TypeID": "FD1"}, {"Flöde": 100, "Global Id": "50433", "Size": 120, "TypeID": "FD1"}, {"Flöde": 100, "Global Id": "452", "Size": 120, "TypeID": "FD2"}]
const columns = [{"dataField": "TypeID", "summarize": false}, {"dataField": "Size", "summarize": false}, {"dataField": "Flöde", "summarize": true}]

console .log (
  summarize (columns) (arr)
)```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://bundle.run/ramda@0.26.1"></script><script>
const {pipe, filter, propEq, pluck, pick, mergeAll, map, groupBy, values, reduce} = ramda</script></code>```

There is a lot of overlap with the solution from Joe, but also some real differences.  His was already posted when I saw the question, but I wanted my own approach not to be influenced, so I didn't look until I wrote the above.  Note the difference in our hash functions.  Mine does JSON.stringify on values like {TypeID: "FD1", Size: 160} while Joe's creates "GROUPKEY___FD1___160".  I think I like mine better for the simplicity.  On the other hand, Joe's solution is definitely better than mine in handling nrOfItems.  I updated it on each reduce iteration and have to use an || 0 to handle the initial case.  Joe simply starts the fold with the already-known value.  But overall, the solutions are quite similar.

You mention wanting to reduce the number of passes through the data.  The way I write Ramda code tends not to help with this.  This code iterates the whole list to group it into like items then iterates through each of those groups to fold down to individual values.  (Also there is a perhaps a minor iteration in values.)  These could certainly be changed to combine those two iterations.  It might even make for shorter code.  But to my mind, it would become harder to understand.

Update

I was curious about the single-pass approach, and found that I could use all the infrastructure I built for the multi-pass one, rewriting only the main function:

const summarize2 = (columns) => (
  arr,
  makeKey = keyMaker (columns),
  reducer = makeReducer (columns)
) => values (reduce (
  (a, item, key = makeKey (item) ) => assoc (key, reducer (key in a ? a[key]: {}, item), a),
  {},
  arr
))

console .log (
  summarize2 (columns) (arr)
)
```

I wouldn't choose this over the original unless testing showed that this code was a bottleneck in my application.  But it's not as much more complex as I thought it would be, and it does everything in one iteration (well, except for whatever values does.)  Interestingly, it makes me change my mind a bit about the handling of nrOfItems.  My helper code just worked in this version, and I never had to know the total size of the group.  That wouldn't have happened if I used Joe's approach.

Title: Ramdajs, group array with arguments

Body:
List to group:

const arr = [
  {
    "Global Id": "1231",
    "TypeID": "FD1",
    "Size": 160,
    "Flöde": 55,
  },
  {
    "Global Id": "5433",
    "TypeID": "FD1",
    "Size": 160,
    "Flöde": 100,
  },
  {
    "Global Id": "50433",
    "TypeID": "FD1",
    "Size": 120,
    "Flöde": 100,
  },
 {
    "Global Id": "452",
    "TypeID": "FD2",
    "Size": 120,
    "Flöde": 100,
  },
]

Input to function which specifies what keys to group:

const columns = [
    {
      "dataField": "TypeID",
      "summarize": false,
    },
    {
      "dataField": "Size",
      "summarize": false,
    },
    {
      "dataField": "Flöde",
      "summarize": true,
    },
]

Expected output:

const output = [
    {
      "TypeID": "FD1",
      "Size": 160,
      "Flöde": 155 // 55 + 100
      "nrOfItems": 2
    },
    {
       "TypeID": "FD1",
       "Size": 120,
       "Flöde": 100,
       "nrOfItems": 1
    },
    {
       "TypeID": "FD2",
       "Size": 120,
       "Flöde": 100,
       "nrOfItems": 1
    }
  ]

  // nrOfItems adds up 4. 2 + 1 +1. The totalt nr of items.

Function:

const groupArr = (columns) => R.pipe(...);

The "summarize" property tells if the property should summarize or not.

The dataset is very large, +100k items. So I don't want to iterate more than necessary.

I've looked at the R.group but I'm not sure it can be applied here?

Maybe something with R.reduce? Store the group in the accumulator, summarize values and add to count if the group already exists? Need to find the group fast so maybe store the group as a key?

Or is it better to use vanilla javascript in this case?

Body:
Here's my initial approach.  Everything but summarize is a helper function which I suppose could be inlined if you really wanted.  I find it cleaner with this separation.

const getKeys = (val) => pipe (
  filter (propEq ('summarize', val) ),
  pluck ('dataField')
)

const keyMaker = (columns, keys = getKeys (false) (columns)) => pipe (
  pick (keys),
  JSON .stringify
)

const makeReducer = (
  columns,
  toSum = getKeys (true) (columns),
  toInclude = getKeys (false) (columns),
) => (a, b) => ({
  ...mergeAll (map (k => ({ [k]: b[k] }), toInclude ) ),
  ...mergeAll (map (k => ({ [k]: (a[k] || 0) + b[k] }), toSum ) ),
  nrOfItems: (a .nrOfItems || 0) + 1
})

const summarize = (columns) => pipe (
  groupBy (keyMaker (columns) ),
  values,
  map (reduce (makeReducer (columns), {} ))
)

const arr = [{"Flöde": 55, "Global Id": "1231", "Size": 160, "TypeID": "FD1"}, {"Flöde": 100, "Global Id": "5433", "Size": 160, "TypeID": "FD1"}, {"Flöde": 100, "Global Id": "50433", "Size": 120, "TypeID": "FD1"}, {"Flöde": 100, "Global Id": "452", "Size": 120, "TypeID": "FD2"}]
const columns = [{"dataField": "TypeID", "summarize": false}, {"dataField": "Size", "summarize": false}, {"dataField": "Flöde", "summarize": true}]

console .log (
  summarize (columns) (arr)
)

<script src="https://bundle.run/ramda@0.26.1"></script><script>
const {pipe, filter, propEq, pluck, pick, mergeAll, map, groupBy, values, reduce} = ramda</script>

There is a lot of overlap with the solution from Joe, but also some real differences.  His was already posted when I saw the question, but I wanted my own approach not to be influenced, so I didn't look until I wrote the above.  Note the difference in our hash functions.  Mine does JSON.stringify on values like {TypeID: "FD1", Size: 160} while Joe's creates "GROUPKEY___FD1___160".  I think I like mine better for the simplicity.  On the other hand, Joe's solution is definitely better than mine in handling nrOfItems.  I updated it on each reduce iteration and have to use an || 0 to handle the initial case.  Joe simply starts the fold with the already-known value.  But overall, the solutions are quite similar.

You mention wanting to reduce the number of passes through the data.  The way I write Ramda code tends not to help with this.  This code iterates the whole list to group it into like items then iterates through each of those groups to fold down to individual values.  (Also there is a perhaps a minor iteration in values.)  These could certainly be changed to combine those two iterations.  It might even make for shorter code.  But to my mind, it would become harder to understand.

Update

I was curious about the single-pass approach, and found that I could use all the infrastructure I built for the multi-pass one, rewriting only the main function:

const summarize2 = (columns) => (
  arr,
  makeKey = keyMaker (columns),
  reducer = makeReducer (columns)
) => values (reduce (
  (a, item, key = makeKey (item) ) => assoc (key, reducer (key in a ? a[key]: {}, item), a),
  {},
  arr
))

console .log (
  summarize2 (columns) (arr)
)

I wouldn't choose this over the original unless testing showed that this code was a bottleneck in my application.  But it's not as much more complex as I thought it would be, and it does everything in one iteration (well, except for whatever values does.)  Interestingly, it makes me change my mind a bit about the handling of nrOfItems.  My helper code just worked in this version, and I never had to know the total size of the group.  That wouldn't have happened if I used Joe's approach.


问:
Get data from future function to text widget
I am trying to implement a Column with a Text:

```<code>Column(
        children: <Widget>[
        Text('data from future function')
      ],
    ),
</code>```

I can't get the data from initState() cause initState() it's only void
If I get data directly from the function

```<code>Text(function)
</code>```

I get

instance of function

The function:

```<code>Future<double> calculate(int index) async {
    LocData _getUser = await getLoc();
    double uLat = _getUser.latitude;
    double uLng = _getUser.latitude;
    double pLat = parks[data].loc.lat;
    double pLng = parks[data].loc.lng;

    double dis = await Geolocator()
        .distanceBetween(uLat , uLng, uLng , pLat );
    return dis ;
  }
</code>```

Any idea what can i do to get this data from the function directly to the text wigdet?

答:
There 2 ways to get data from a future.

Option #1:

(with 2 suboptions)

class MyWidgetState extends State<MyWidget> {

  String _someAsyncData;

  @override
  void initState() {
    super.initState();

    // opt 1.
    aDataFuture.then((val) {
      setState(() {
        _someAsyncdata = val;
      });
    });

    // opt 2.
    _setAsyncData(aDataFuture);
  }

  void _setAsyncData(Future<String> someFuture) async {
    // void + async is considered a "fire and forget" call
    // part of opt. 2
    _someAsyncData = await someFuture;
    // must trigger rebuild with setState
    setState((){});
  }

  Widget build(BuildContext context) {
    return _someAsyncData == null ? Container() : Text('$_someAsyncData');
  }
}
```

<p><strong>Option #2</strong></p>

<p>Use FutureBuilder</p>

<pre class="lang-dart prettyprint-override"><code>class MyWidget extends StatelessWidget {

  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: _someFuture,
      builder: (ctx, snapshot) {
        // can also check for snapshot.hasData or snapshot.hasError to
        // provide more user feedback eg.
        if(snapshot.connectionState == ConnectionState.done)
          return Text('${snapshot.data}');
        return Text('No data available yet...');
      }
    );
  }

}
</code>```

Body:
I am trying to implement a Column with a Text:

Column(
        children: <Widget>[
        Text('data from future function')
      ],
    ),

I can't get the data from initState() cause initState() it's only void
If I get data directly from the function

Text(function)

I get

instance of function

The function:

Future<double> calculate(int index) async {
    LocData _getUser = await getLoc();
    double uLat = _getUser.latitude;
    double uLng = _getUser.latitude;
    double pLat = parks[data].loc.lat;
    double pLng = parks[data].loc.lng;

    double dis = await Geolocator()
        .distanceBetween(uLat , uLng, uLng , pLat );
    return dis ;
  }

Any idea what can i do to get this data from the function directly to the text wigdet?

Body:
There 2 ways to get data from a future.

Option #1:

(with 2 suboptions)

class MyWidgetState extends State<MyWidget> {

  String _someAsyncData;

  @override
  void initState() {
    super.initState();

    // opt 1.
    aDataFuture.then((val) {
      setState(() {
        _someAsyncdata = val;
      });
    });

    // opt 2.
    _setAsyncData(aDataFuture);
  }

  void _setAsyncData(Future<String> someFuture) async {
    // void + async is considered a "fire and forget" call
    // part of opt. 2
    _someAsyncData = await someFuture;
    // must trigger rebuild with setState
    setState((){});
  }

  Widget build(BuildContext context) {
    return _someAsyncData == null ? Container() : Text('$_someAsyncData');
  }
}

Option #2

Use FutureBuilder

class MyWidget extends StatelessWidget {

  Widget build(BuildContext context) {
    return FutureBuilder<String>(
      future: _someFuture,
      builder: (ctx, snapshot) {
        // can also check for snapshot.hasData or snapshot.hasError to
        // provide more user feedback eg.
        if(snapshot.connectionState == ConnectionState.done)
          return Text('${snapshot.data}');
        return Text('No data available yet...');
      }
    );
  }

}


问:
Set Width and Height of Element Screenshot in Puppeteer
If I have this code:

```<code>const puppeteer = require('puppeteer');

var test = async () => {
  const browser = await puppeteer.launch({args: ["--no-sandbox", "--disable-setuid-sandbox"]});
  const page = await browser.newPage();
  await page.goto('https://community.wikia.com/wiki/Special:WikiActivity');
  let element =  await page.$('#WikiaMainContent');
  await page.setViewport({ width: 800, height: 1000}); // This is ignored
  await element.screenshot({path: "./wiki.png"});
  await browser.close();
}

test();
</code>```

The screenshot is larger than the viewport.

How can I make it so that the screenshot has a width of 800px and height of 1000px?

答:
I have a better solution using html2canvas in the front:

https://gist.github.com/homam/3162383c8b22e7af691085e77cdbb414

or using it with puppeteer and html2canvas in the Backend:

```<code>const screenshot = await page.evaluate(async () => {
   const canvasElement = await html2canvas($("div")[0], {
        // useCORS: true,
   });

   let image = Canvas2Image.convertToImage(
        canvasElement,
        $(canvasElement).width(),
        $(canvasElement).height(),
        "png"
    );
    console.log(image.src)
    return image.src;
})
var fs = require('fs');
// strip off the data: url prefix to get just the base64-encoded bytes
var data = screenshot.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile(`./screenshots/div-${Date.now()}-.png`, buf);
</code>```

full code here:
https://github.com/davidtorroija/screenshot-of-div-e2e/blob/master/README.md

this is better because is easy to take a screenshot of a huge div, and no need to scroll, and you are not going to lose any part of the div

Body:
If I have this code:

const puppeteer = require('puppeteer');

var test = async () => {
  const browser = await puppeteer.launch({args: ["--no-sandbox", "--disable-setuid-sandbox"]});
  const page = await browser.newPage();
  await page.goto('https://community.wikia.com/wiki/Special:WikiActivity');
  let element =  await page.$('#WikiaMainContent');
  await page.setViewport({ width: 800, height: 1000}); // This is ignored
  await element.screenshot({path: "./wiki.png"});
  await browser.close();
}

test();

The screenshot is larger than the viewport.

How can I make it so that the screenshot has a width of 800px and height of 1000px?

Body:
I have a better solution using html2canvas in the front:

https://gist.github.com/homam/3162383c8b22e7af691085e77cdbb414

or using it with puppeteer and html2canvas in the Backend:

const screenshot = await page.evaluate(async () => {
   const canvasElement = await html2canvas($("div")[0], {
        // useCORS: true,
   });

   let image = Canvas2Image.convertToImage(
        canvasElement,
        $(canvasElement).width(),
        $(canvasElement).height(),
        "png"
    );
    console.log(image.src)
    return image.src;
})
var fs = require('fs');
// strip off the data: url prefix to get just the base64-encoded bytes
var data = screenshot.replace(/^data:image\/\w+;base64,/, "");
var buf = new Buffer(data, 'base64');
fs.writeFile(`./screenshots/div-${Date.now()}-.png`, buf);

full code here:
https://github.com/davidtorroija/screenshot-of-div-e2e/blob/master/README.md

this is better because is easy to take a screenshot of a huge div, and no need to scroll, and you are not going to lose any part of the div


问:
ReactJS vs NodeJS - Why do I need to create both?
I understand that React is frontend, and NodeJS is the backend that allows Javascript code to function outside of a browser. What I don't understand (and this is after following tutorials online on setting up a React project and a NodeJS project) is why I have to create an instance of each.

For example, in my React project, I managed to create a website. But because I needed a backend, I decided to use NodeJS. But I'm doing NodeJS tutorials, and I can create a website using NodeJS too. I'm confused because right now, it's appearing to be that React and NodeJS do the SAME THING.

I have never worked with NodeJS before so I am a bit confused. I was under the impression that I would just use NodeJS to host the backend, but after seeing that I'm literally having to create an entire website with NodeJS, I don't understand how I'm supposed to use React and NodeJS together.

How do the two, React and NodeJS, integrate together to create a fully-functioning web app? I have yet to see something online that clearly breaks down how the two interact.

答:
NodeJS is a javascript framework that allows you to create a server to serve up websites using Express or the built in libraries. It also is capable of building a website with just NodeJS.

You can take advantage of the ability to do server side rendering with a NodeJS server.
https://reactjs.org/docs/react-dom-server.html

There is a ReactJS framework called NextJS tha has server side rendering of ReactJS component.
https://nextjs.org/#features

You could potentially have some areas of your website that are built solely with NodeJS and other pages that use ReactJS and a NodeJS backend. But it is cleaner to use ReactJS for the front-end and NodeJS for the backend.


问:
Is it possible to declare a string / int as numer?
I want to parse JSON in Java, but my JSON lookslike this:

```<code>...
{
    "total_count": 16,
    "entries": [
        {
            "2": "1788",
            "3": "Yes",
            "id": "2009131"
         },
         {
            "2": "956",
            "3": "No",
            "id": "1381"
         }
...
</code>```

I already figured out to "extract" the entries by:

```<code>if(jsonTree.isJsonObject()){
            System.out.println("True");
            JsonObject jsonObject = jsonTree.getAsJsonObject();

            JsonElement f2 = jsonObject.get("entries");
</code>```

Now I've a JSON array. For parsing with gson, I would need a class with variables like this (at least I think so):

```<code>int 2;
String 3;
</code>```

which isn't declarable as far as I know.

Is there a way (prefix, syntax?) to implement anyways? Or another way to extract and assign the values with the right id?

答: You can create an object "Entries" and have all possible variables there.  There are JSON libraries that can do the transformation for you.</p>

Body:
I want to parse JSON in Java, but my JSON lookslike this:

...
{
    "total_count": 16,
    "entries": [
        {
            "2": "1788",
            "3": "Yes",
            "id": "2009131"
         },
         {
            "2": "956",
            "3": "No",
            "id": "1381"
         }
...

I already figured out to "extract" the entries by:

if(jsonTree.isJsonObject()){
            System.out.println("True");
            JsonObject jsonObject = jsonTree.getAsJsonObject();

            JsonElement f2 = jsonObject.get("entries");

Now I've a JSON array. For parsing with gson, I would need a class with variables like this (at least I think so):

int 2;
String 3;

which isn't declarable as far as I know.

Is there a way (prefix, syntax?) to implement anyways? Or another way to extract and assign the values with the right id?


问:
Exchange web services Error - The Autodiscover service couldn't be located
I am using Exchange Web Services(EWS) to create outlook meeting invite in SharePoint Visual Web Part. Following is the code snippet to get the instance of EWS.

```<code>ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.UseDefaultCredentials = true;
service.AutodiscoverUrl("firstName.Lastname@xxxxxxxx.com", RedirectionUrlValidationCallback);
</code>```

When I use it in test console application, it is working properly. But if I use it in Visual Web Part on same server with same user account, then it gives following error.

Microsoft.Exchange.WebServices.Data.AutodiscoverLocalException: The Autodiscover service couldn't be located.
     at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.InternalGetLegacyUserSettings[TSettings](String emailAddress, List`1 redirectionEmailAddresses, Int32& currentHop)
     at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.GetLegacyUserSettings[TSettings](String emailAddress)
     at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.InternalGetLegacyUserSettings(String emailAddress, List`1 requestedSettings)
     at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.GetUserSettings(String userSmtpAddress, UserSettingName[] userSettingNames)
     at Microsoft.Exchange.WebServices.Data.ExchangeService.GetAutodiscoverUrl(String emailAddress, ExchangeVersion requestedServerVersion, AutodiscoverRedirectionUrlValidationCallback validateRedirectionUrlCallback)
     at Microsoft.Exchange.WebServices.Data.ExchangeService.AutodiscoverUrl(String emailAddress, AutodiscoverRedirectionUrlValidationCallback validateRedirectionUrlCallback)

答:
Not that familiar with Visual Web Part, so I'm not sure exactly what the user context is that you are running under there.  As an experiment, can you specify actual credentials in the program above (rather than UseDefaultCredentials) and see if it successfully runs?  If so, then you either need to specify the creds in your code or find a way to change the user context of Visual Web Part.

If that doesn't work, then you might have to enable tracing on the ExchangeService object and see what's happening under the covers.  My experience has been that AD error reporting is very limited until you see what's coming back on the HTTP layer.

Body:
I am using Exchange Web Services(EWS) to create outlook meeting invite in SharePoint Visual Web Part. Following is the code snippet to get the instance of EWS.

ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013);
service.UseDefaultCredentials = true;
service.AutodiscoverUrl("firstName.Lastname@xxxxxxxx.com", RedirectionUrlValidationCallback);

When I use it in test console application, it is working properly. But if I use it in Visual Web Part on same server with same user account, then it gives following error.

Microsoft.Exchange.WebServices.Data.AutodiscoverLocalException: The Autodiscover service couldn't be located.
     at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.InternalGetLegacyUserSettings[TSettings](String emailAddress, List`1 redirectionEmailAddresses, Int32& currentHop)
     at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.GetLegacyUserSettings[TSettings](String emailAddress)
     at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.InternalGetLegacyUserSettings(String emailAddress, List`1 requestedSettings)
     at Microsoft.Exchange.WebServices.Autodiscover.AutodiscoverService.GetUserSettings(String userSmtpAddress, UserSettingName[] userSettingNames)
     at Microsoft.Exchange.WebServices.Data.ExchangeService.GetAutodiscoverUrl(String emailAddress, ExchangeVersion requestedServerVersion, AutodiscoverRedirectionUrlValidationCallback validateRedirectionUrlCallback)
     at Microsoft.Exchange.WebServices.Data.ExchangeService.AutodiscoverUrl(String emailAddress, AutodiscoverRedirectionUrlValidationCallback validateRedirectionUrlCallback)


问:
Shell script finds file in directory, how to pass into python script
I have a shell script that looks through a directory and returns the most recent CVS file; I then want to pass this file into a python script.

I'm not very familiar with UNIX, am I supposed to be using arguments for the files in my shell script and how would I go about it?

This is the shell code:

file = ls -t | $path-n 2 | head -n1
```

<p>In python:</p>

<pre class="lang-py prettyprint-override"><code>import pandas as pd
data = pd.read_excel(file, sep='delimiter',skiprows = 3, header=None, names = colnames)
</code>```

答:
If your python file is named test.py, it should look like:

```<code>import sys
import pandas as pd

data = pd.read_excel(sys.argv[1], sep='delimiter',skiprows = 3, header=None, names = colnames)
</code>```

Then the command would be ./test.py $file in the shell script.

sys.argv[0] is the python file name (ex test.py), and sys.argv[1] is the first argument after the file name.

Body:
I have a shell script that looks through a directory and returns the most recent CVS file; I then want to pass this file into a python script.

I'm not very familiar with UNIX, am I supposed to be using arguments for the files in my shell script and how would I go about it?

This is the shell code:

file = ls -t | $path-n 2 | head -n1

In python:

import pandas as pd
data = pd.read_excel(file, sep='delimiter',skiprows = 3, header=None, names = colnames)

Body:
If your python file is named test.py, it should look like:

import sys
import pandas as pd

data = pd.read_excel(sys.argv[1], sep='delimiter',skiprows = 3, header=None, names = colnames)

Then the command would be ./test.py $file in the shell script.

sys.argv[0] is the python file name (ex test.py), and sys.argv[1] is the first argument after the file name.


问:
iText pdfReader Not Releasing File in ColdFusion 2018
I am upgrading to ColdFusion 2018.  iText routines that I use to convert and rotate PDFs,  the pdfReader puts locks on the file that do not release when the page is done.

I have tried adding a close() method to my code.  (It was not needed on the pdfReader in Release 11.)

```<code><cfscript>

reader = createObject("java", "com.lowagie.text.pdf.PdfReader").init( "test.pdf" );

reader.close();

inStream = createObject("java", "java.io.FileReader").init("test2.pdf");

inStream.close();

</cfscript>
</code>```

I would expect to be able to rename or delete both files when the supplied script is ran, but only the inStream file (test2.pdf) can be.  The reader file (test.pdf) is locked by the system.

答:
Rather than using an older Java plugin, just use the native cfpdf.

```<code><cfpdf action="transform" source="myPDF.pdf" rotation="90" name="outPDF">
</code>```

There is a ton of other functionality available to this tag. https://cfdocs.org/cfpdf

https://cffiddle.org/app/file?filepath=eca41ba2-22f2-41f2-a205-0c2d3aafe91c/ca3873c8-4d4b-4cfc-8e64-6c4ceb825717/9861993d-7db3-43ee-882f-681a1aa498d4.cfm

Body:
I am upgrading to ColdFusion 2018.  iText routines that I use to convert and rotate PDFs,  the pdfReader puts locks on the file that do not release when the page is done.

I have tried adding a close() method to my code.  (It was not needed on the pdfReader in Release 11.)

<cfscript>

reader = createObject("java", "com.lowagie.text.pdf.PdfReader").init( "test.pdf" );

reader.close();

inStream = createObject("java", "java.io.FileReader").init("test2.pdf");

inStream.close();

</cfscript>

I would expect to be able to rename or delete both files when the supplied script is ran, but only the inStream file (test2.pdf) can be.  The reader file (test.pdf) is locked by the system.

Body:
Rather than using an older Java plugin, just use the native cfpdf.

<cfpdf action="transform" source="myPDF.pdf" rotation="90" name="outPDF">

There is a ton of other functionality available to this tag. https://cfdocs.org/cfpdf

https://cffiddle.org/app/file?filepath=eca41ba2-22f2-41f2-a205-0c2d3aafe91c/ca3873c8-4d4b-4cfc-8e64-6c4ceb825717/9861993d-7db3-43ee-882f-681a1aa498d4.cfm


问:
How access event listeners of an object instantiated on runtime in java swing
I have a custom made JPanel itemSmallCard(String prodID, String productName, String price, String retailer), using this I created multiple instances of it in another JPanel with different parameters on the ActionPerformed event of a button as follows:

JPanel iC = new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");
        mainContentPane.add(iC);
        mainContentPane.revalidate();
        mainContentPane.repaint();
```

However as all the new JPanels were created with this same code using the same variable iC,  I don't know how to access a particular JPanel variable from them, thus also unable to access its event listeners.
How can I achieve that?

答:
Perhaps create an ArrayList (if you don't need to access specific ones not based on location).

ArrayList<JPanel> panels = new ArrayList<JPanel>();
```

<p>Or, if you need to access them, you could make a "HashMap" and store the ID you have in there.</p>

<pre class="lang-java prettyprint-override"><code>WeakHashMap<String, JPanel> panels = new WeakHashMap<String, JPanel>();

panels.put("123456789ab", new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");// Adds a product with that info

panels.get("123456789ab"); // Returns the panel with that ID.
</code>```

Hope this helps.

Body:
I have a custom made JPanel itemSmallCard(String prodID, String productName, String price, String retailer), using this I created multiple instances of it in another JPanel with different parameters on the ActionPerformed event of a button as follows:

JPanel iC = new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");
        mainContentPane.add(iC);
        mainContentPane.revalidate();
        mainContentPane.repaint();

However as all the new JPanels were created with this same code using the same variable iC,  I don't know how to access a particular JPanel variable from them, thus also unable to access its event listeners.
How can I achieve that?

Body:
Perhaps create an ArrayList (if you don't need to access specific ones not based on location).

ArrayList<JPanel> panels = new ArrayList<JPanel>();

Or, if you need to access them, you could make a "HashMap" and store the ID you have in there.

WeakHashMap<String, JPanel> panels = new WeakHashMap<String, JPanel>();

panels.put("123456789ab", new itemSmallCard("123456789ab", "Inspiron 7567 Intel Core i5 DELL Laptop", "48957", "Cloudtail Pvt. Ltd.");// Adds a product with that info

panels.get("123456789ab"); // Returns the panel with that ID.

Hope this helps.


问:
Where does initscript come from?
I am just curious about where the initscript method of init.gradle script comes from.

according to the gradle official documents, a initscript method can be used to configure init.gradle script and a init.gradle script configure against a Gradle object. And we also know every gradle script implementing Script. So I guess initscript must be a method of Gradle or Script. I refered to the official gradle dsl reference to search the definition of initscript but no definition was found in Gradle or Script. So, where are the definition of initscript? Is it a method of Gradle of Script?

答:
Why not find out for yourself?

```<code>initscript {
   throw new Exception("foo")
}
</code>```

Then run something like

```<code>gradle tasks --stacktrace
</code>```

Title: Where does initscript come from?

Body:
Why not find out for yourself?

initscript {
   throw new Exception("foo")
}

Then run something like

gradle tasks --stacktrace


问:
Android In-App update API return 0 as availableVersionCode & updateAvailability as 1 (UPDATE_NOT_AVAILABLE)
I'm trying to implement the in-app update API, followed in-app-update-api, when debugging the app with lower version than play store version, AppUpdateInfo return availableVersionCode as 0 and updateAvailability as 1 (UPDATE_NOT_AVAILABLE),
Note: I've used the same package name & same signing key to run a  build

Thanks in advance!

答:
The most likely reason is that the Play Store on your device hasn't learnt about the new update yet.

After you release your update in the Play Developer Console, the information about this update does not reach immediately all devices; some Play Store background job on the device is responsible for periodically checking for updates for installed apps and refresh the on-device cached information.

"But I want to test the behaviour on my device now, I don't want to wait for a background job to complete before I can test. Can I force the refresh of this cache?"

Yes, take a look at the last item of the Troubleshooting section here: https://developer.android.com/guide/app-bundle/in-app-updates#troubleshoot
To refresh the cache you need to: close the Play Store; reopen it; navigate to the "My Apps & Games" app.

"Will my users need to do this too?"

No: your users can just wait for the background job to run.


问:
How to populate java map on creation
Is there a short and handy way to create pre-populated java map?

E.g. a new list can be easily created from an array using Arrays.asList("A", "B", "C") but there is no such method like Arrays.toMap({"key1", "value1"}, {"key2", "value2"}, ...) or

If there is no such method in JDK, is there a utility lib which I can use?

Thank you!

答:
You can use Map<String, String> map = Map.of(key1, value1, key2, value2) for the most easy to use way.

(Map<String, String> is just an example. You can use the types you want)

Note that this creates immutable maps.

For mutable maps you can pass this map to a HashMap

```<code>Map<String, String> map = new HashMap<String, String>(
    Map.of(...)
);
</code>```

Title: How to populate java map on creation

Body:
You can use Map<String, String> map = Map.of(key1, value1, key2, value2) for the most easy to use way.

(Map<String, String> is just an example. You can use the types you want)

Note that this creates immutable maps.

For mutable maps you can pass this map to a HashMap

Map<String, String> map = new HashMap<String, String>(
    Map.of(...)
);


问:
How to speed up a data file import in Excel VBA
Update as of June 11, 2019: I still haven’t figured out why practically all of my delay happens in those two lines, but current status is that I put up with the delay. So far, I have about 6000 rows of data in the master document, and an import process takes about 20 seconds regardless of how many rows I import.

—

I have a "master document" and I import data from lots and lots of little documents all day long. I admit I'm not a super-genius here, and a lot of my coding habits come from doing it "old school" so there may be "Excel ways" that I don't know (but want to learn!).

The issue I'm seeing is how much time a data file import can take.

When I started the tool out, data imports took only a few seconds.

Now that I have about 3500 rows of data, data imports take about 15-20 seconds. It doesn't matter if I am importing one row or a hundred rows. I expect this to keep going up. By the time I get to 7000 rows or 10,000 rows, I expect it to become unbearable.

By using message boxes (remember: "old school"), I've been able to narrow the speed bottleneck down to two lines of code. Between "Step 1" and "Step 2" is about 30% of my delay, and between "Step 2" and "Step 3" is about 70% of my delay.

I've included the whole sub below to make sure I'm not missing something obvious, but I made sure to UNINDENT my message boxes so you can go r-i-g-h-t to the code I suspect. Also, I included the entire sub because usually one of the first responses is “can you show the whole sub so I have better context?”

Thank you kindly for any thoughts or suggestions you might have. :)

```<code>Private Sub Btn_ImportDataFiles_Click()
  ' Search the current worksheet and assign the next TransactionID
    Dim TransactionCounter As Integer
    Dim TransactionID As Long ' This is the next available Transaction ID
    TransactionID = Application.WorksheetFunction.Max(Range("a:a")) + 1
  ' open the file and import the data
    Dim customerBook As Workbook
    Dim filter As String
    Dim caption As String
    Dim customerFilename As String
    Dim customerWorkbook As Workbook
    Dim targetWorkbook As Workbook

    ' make weak assumption that active workbook is the target
      Set targetWorkbook = Application.ActiveWorkbook

    ' get the customer workbook
      filter = "Text files (*.xlsx),*.xlsx"
      caption = "Please Select an input file "
      customerFilename = Application.GetOpenFilename(filter, , caption)

    If customerFilename <> "False" Then
    ' If they have uploaded the file before, let them know.
    ' If they want to keep uploading it, no harm done,
    ' but no need to stupidly add data that is already present.
    ' Select the archive sheet
      Sheets("Upload_Archive").Select
      Dim FileNameHunt As String
      Dim cell As Range
      Dim ContinueUpload As Boolean
      ContinueUpload = True
      FileNameHunt = Mid(customerFilename, InStrRev(customerFilename, "\") + 1)
      Columns("A:A").Select
      Set cell = Selection.Find(what:=FileNameHunt, after:=ActiveCell, LookIn:=xlFormulas, lookat:=xlWhole, searchorder:=xlByRows, searchdirection:=xlNext, MatchCase:=False, searchformat:=False)
      If cell Is Nothing Then ' Add the new filename to the archive
        Sheets("Upload_Archive").Select
        Rows(1).Insert shift:=xlDown
        Range("a1:a1").Value = FileNameHunt
        Sheets("MasterSheet").Select
        Application.Cells.Font.Name = "Calibri Light"
        Application.Cells.Font.Size = "8"
        Application.Cells.Font.Bold = False
      Else
        response = MsgBox("This data file has previously been uploaded. " & vbCrLf & "Do you want to cancel this upload?" & vbCrLf & vbCrLf & "Pressing [yes] will cancel the process." & vbCrLf & "Pressing [no] will continue with the file upload" & vbCrLf & "and add the data to the tracking sheet.", vbYesNo)
        If response = vbYes Then
          ContinueUpload = False
          Sheets("MasterSheet").Select
          Exit Sub
        End If
      End If ' If cell Is Nothing Then...

      If ContinueUpload = True Then
        ' Continue with data upload procedure
          Sheets("MasterSheet").Select
          Set customerWorkbook = Application.Workbooks.Open(customerFilename)
        ' Copy data from customer to target workbook
          Dim targetSheet As Worksheet
          Set targetSheet = targetWorkbook.Worksheets(1)
          Dim sourceSheet As Worksheet
          Set sourceSheet = customerWorkbook.Worksheets(1)
          Dim ImportRecordCount As Integer
          ImportRecordCount = sourceSheet.Range("B1")
          Dim ReconciliationID As String
          ReconciliationID = ""
          If sourceSheet.Range("E3") = "Removed from Depot" Then ReconciliationID = "1"
MsgBox ("Step 1")
          targetSheet.Range("A1").EntireRow.Offset(1).Resize(ImportRecordCount).Insert shift:=xlDown ' Add the blank rows
MsgBox ("Step 2")
          targetSheet.Range("B2:AB" & ImportRecordCount + 1).Value = sourceSheet.Range("A3:AA" & ImportRecordCount + 2).Value ' Bring in the big pile of data
MsgBox ("Step 3")
          targetSheet.Range("AJ2:AJ" & ImportRecordCount + 1).Value = ReconciliationID ' To help with reconciling shipments
          targetSheet.Range("AK2:AK" & ImportRecordCount + 1).Value = ReconciliationID ' To help with deployment timing
          'targetSheet.Range("AI2:AI" & ImportRecordCount + 1).Value = "=COUNTIFS($D:$D, D2, $F:$F, F2)" ' This is the helper formula for identifying duplicates (deprecated, but I'm saving the code)
          For TransactionCounter = 2 To ImportRecordCount + 1 ' Create and add the new Transaction ID values
            targetSheet.Range("a" & TransactionCounter) = TransactionID + ImportRecordCount - TransactionCounter + 1
          Next
        ' Close customer workbook
          customerWorkbook.Close
        ' Format the sheet properly
          Application.Cells.Font.Name = "Calibri Light"
          Application.Cells.Font.Size = "8"
          Application.Cells.Font.Bold = False
          Application.Range("1:1").Font.Size = "10"
          Application.Range("1:1").Font.Bold = True
        ' Query the User -- delete the file?
          If MsgBox("Delete the local client-generated data file?" & vbCrLf & vbCrLf & "(this will NOT affect your email)", vbYesNo, "Confirm") = vbYes Then
            Kill customerFilename
            ' MsgBox ("File: " & vbCrLf & customerFilename & vbCrLf & "has been deleted.")
          End If
      End If ' If ContinueUpload = True Then
    End If ' If customerFilename <> "False" Then

End Sub

</code>```

edit

I edited your original question to highlight things I found as suspect. These are things I felt are worth pointing out to you. I shaved everything else out as to focus on these particular issue. Review them and do soem research to see if you can find yourself in a better situation.

```<code>    MsgBox ("Step 2")

        'Ive never moved large amounts of data using this method. Ive always just used arrays. I have moved smaller bits of data though.
        ' I suspect that this might take a moment if the data set is large. Again use arrays to grab the data and move it.
        ' Edward says “This step takes about 70% of my delay — even if bringing in only a single line of data.”

        targetSheet.Range("B2:AB" & ImportRecordCount + 1).Value = sourceSheet.Range("A3:AA" & ImportRecordCount + 2).Value ' Bring in the big pile of data

    MsgBox ("Step 3")

      ' this loop is probably your main culprit of your performance issue.
      ' Edward says “Nope, this flies by. It is not the issue at all. I have verified this already.”
      ' Learn how to construct an array of data on the fly and then learn how to dump the entire array to
      ' sheet using a simple method.

        For TransactionCounter = 2 To ImportRecordCount + 1 ' Create and add the new Transaction ID values
            targetSheet.Range("a" & TransactionCounter) = TransactionID + ImportRecordCount - TransactionCounter + 1
        Next
</code>```

答:
Try adding this at the beginning and end of your script. Just be sure to set everything back to TRUE!!</p>

```<code>Application.ScreenUpdating = False
Application.DisplayAlerts = False

...CODE HERE...

Application.ScreenUpdating = True
Application.DisplayAlerts = True
</code>```

Body:
Update as of June 11, 2019: I still haven’t figured out why practically all of my delay happens in those two lines, but current status is that I put up with the delay. So far, I have about 6000 rows of data in the master document, and an import process takes about 20 seconds regardless of how many rows I import.

—

I have a "master document" and I import data from lots and lots of little documents all day long. I admit I'm not a super-genius here, and a lot of my coding habits come from doing it "old school" so there may be "Excel ways" that I don't know (but want to learn!).

The issue I'm seeing is how much time a data file import can take.

When I started the tool out, data imports took only a few seconds.

Now that I have about 3500 rows of data, data imports take about 15-20 seconds. It doesn't matter if I am importing one row or a hundred rows. I expect this to keep going up. By the time I get to 7000 rows or 10,000 rows, I expect it to become unbearable.

By using message boxes (remember: "old school"), I've been able to narrow the speed bottleneck down to two lines of code. Between "Step 1" and "Step 2" is about 30% of my delay, and between "Step 2" and "Step 3" is about 70% of my delay.

I've included the whole sub below to make sure I'm not missing something obvious, but I made sure to UNINDENT my message boxes so you can go r-i-g-h-t to the code I suspect. Also, I included the entire sub because usually one of the first responses is “can you show the whole sub so I have better context?”

Thank you kindly for any thoughts or suggestions you might have. :)

Private Sub Btn_ImportDataFiles_Click()
  ' Search the current worksheet and assign the next TransactionID
    Dim TransactionCounter As Integer
    Dim TransactionID As Long ' This is the next available Transaction ID
    TransactionID = Application.WorksheetFunction.Max(Range("a:a")) + 1
  ' open the file and import the data
    Dim customerBook As Workbook
    Dim filter As String
    Dim caption As String
    Dim customerFilename As String
    Dim customerWorkbook As Workbook
    Dim targetWorkbook As Workbook

    ' make weak assumption that active workbook is the target
      Set targetWorkbook = Application.ActiveWorkbook

    ' get the customer workbook
      filter = "Text files (*.xlsx),*.xlsx"
      caption = "Please Select an input file "
      customerFilename = Application.GetOpenFilename(filter, , caption)

    If customerFilename <> "False" Then
    ' If they have uploaded the file before, let them know.
    ' If they want to keep uploading it, no harm done,
    ' but no need to stupidly add data that is already present.
    ' Select the archive sheet
      Sheets("Upload_Archive").Select
      Dim FileNameHunt As String
      Dim cell As Range
      Dim ContinueUpload As Boolean
      ContinueUpload = True
      FileNameHunt = Mid(customerFilename, InStrRev(customerFilename, "\") + 1)
      Columns("A:A").Select
      Set cell = Selection.Find(what:=FileNameHunt, after:=ActiveCell, LookIn:=xlFormulas, lookat:=xlWhole, searchorder:=xlByRows, searchdirection:=xlNext, MatchCase:=False, searchformat:=False)
      If cell Is Nothing Then ' Add the new filename to the archive
        Sheets("Upload_Archive").Select
        Rows(1).Insert shift:=xlDown
        Range("a1:a1").Value = FileNameHunt
        Sheets("MasterSheet").Select
        Application.Cells.Font.Name = "Calibri Light"
        Application.Cells.Font.Size = "8"
        Application.Cells.Font.Bold = False
      Else
        response = MsgBox("This data file has previously been uploaded. " & vbCrLf & "Do you want to cancel this upload?" & vbCrLf & vbCrLf & "Pressing [yes] will cancel the process." & vbCrLf & "Pressing [no] will continue with the file upload" & vbCrLf & "and add the data to the tracking sheet.", vbYesNo)
        If response = vbYes Then
          ContinueUpload = False
          Sheets("MasterSheet").Select
          Exit Sub
        End If
      End If ' If cell Is Nothing Then...

      If ContinueUpload = True Then
        ' Continue with data upload procedure
          Sheets("MasterSheet").Select
          Set customerWorkbook = Application.Workbooks.Open(customerFilename)
        ' Copy data from customer to target workbook
          Dim targetSheet As Worksheet
          Set targetSheet = targetWorkbook.Worksheets(1)
          Dim sourceSheet As Worksheet
          Set sourceSheet = customerWorkbook.Worksheets(1)
          Dim ImportRecordCount As Integer
          ImportRecordCount = sourceSheet.Range("B1")
          Dim ReconciliationID As String
          ReconciliationID = ""
          If sourceSheet.Range("E3") = "Removed from Depot" Then ReconciliationID = "1"
MsgBox ("Step 1")
          targetSheet.Range("A1").EntireRow.Offset(1).Resize(ImportRecordCount).Insert shift:=xlDown ' Add the blank rows
MsgBox ("Step 2")
          targetSheet.Range("B2:AB" & ImportRecordCount + 1).Value = sourceSheet.Range("A3:AA" & ImportRecordCount + 2).Value ' Bring in the big pile of data
MsgBox ("Step 3")
          targetSheet.Range("AJ2:AJ" & ImportRecordCount + 1).Value = ReconciliationID ' To help with reconciling shipments
          targetSheet.Range("AK2:AK" & ImportRecordCount + 1).Value = ReconciliationID ' To help with deployment timing
          'targetSheet.Range("AI2:AI" & ImportRecordCount + 1).Value = "=COUNTIFS($D:$D, D2, $F:$F, F2)" ' This is the helper formula for identifying duplicates (deprecated, but I'm saving the code)
          For TransactionCounter = 2 To ImportRecordCount + 1 ' Create and add the new Transaction ID values
            targetSheet.Range("a" & TransactionCounter) = TransactionID + ImportRecordCount - TransactionCounter + 1
          Next
        ' Close customer workbook
          customerWorkbook.Close
        ' Format the sheet properly
          Application.Cells.Font.Name = "Calibri Light"
          Application.Cells.Font.Size = "8"
          Application.Cells.Font.Bold = False
          Application.Range("1:1").Font.Size = "10"
          Application.Range("1:1").Font.Bold = True
        ' Query the User -- delete the file?
          If MsgBox("Delete the local client-generated data file?" & vbCrLf & vbCrLf & "(this will NOT affect your email)", vbYesNo, "Confirm") = vbYes Then
            Kill customerFilename
            ' MsgBox ("File: " & vbCrLf & customerFilename & vbCrLf & "has been deleted.")
          End If
      End If ' If ContinueUpload = True Then
    End If ' If customerFilename <> "False" Then

End Sub

edit

I edited your original question to highlight things I found as suspect. These are things I felt are worth pointing out to you. I shaved everything else out as to focus on these particular issue. Review them and do soem research to see if you can find yourself in a better situation.

    MsgBox ("Step 2")

        'Ive never moved large amounts of data using this method. Ive always just used arrays. I have moved smaller bits of data though.
        ' I suspect that this might take a moment if the data set is large. Again use arrays to grab the data and move it.
        ' Edward says “This step takes about 70% of my delay — even if bringing in only a single line of data.”

        targetSheet.Range("B2:AB" & ImportRecordCount + 1).Value = sourceSheet.Range("A3:AA" & ImportRecordCount + 2).Value ' Bring in the big pile of data

    MsgBox ("Step 3")

      ' this loop is probably your main culprit of your performance issue.
      ' Edward says “Nope, this flies by. It is not the issue at all. I have verified this already.”
      ' Learn how to construct an array of data on the fly and then learn how to dump the entire array to
      ' sheet using a simple method.

        For TransactionCounter = 2 To ImportRecordCount + 1 ' Create and add the new Transaction ID values
            targetSheet.Range("a" & TransactionCounter) = TransactionID + ImportRecordCount - TransactionCounter + 1
        Next

Body:
Try adding this at the beginning and end of your script. Just be sure to set everything back to TRUE!!

Application.ScreenUpdating = False
Application.DisplayAlerts = False

...CODE HERE...

Application.ScreenUpdating = True
Application.DisplayAlerts = True


问:
Passing Observable to another component in Angular
I have two components details and details-view.

In the details I have to pass obserwable by @Input() into second component.

Details Component

```<code> res$: (id: number, type: string) => Observable<DetailsResponse[]>;
 constructor(private service: Service) {
  this.res$ = service.getData;
 }
</code>```

Service

```<code> getData(id: number, type: string): Observable<DetailsResponse[]>{
   const params = new HttpParams().append('typename', type);
   return this.http.get<any>('api/id', {params: params});
 }
</code>```

Detalis-View HTML

<dwtalis-view [resources$]="res$"></dwtalis-view>

Detalis-Viev TS Component

```<code>@Input()
resouces$: Observable<DetailsResponse[]>
</code>```

My question is how to subscribe and get the data from resources$ observable in the detalis view component. Subscribing this object retunrs error "resources$ is not a finction can not subscribe"

答:
You can change the DetailsViewComponent like the following code

```<code>export class DetailsViewComponent implements OnInit, OnChanges {

  @Input() resouces$: (id: number, type: string) => Observable<DetailsResponse[]>;

  constructor(
  ) {}

  ngOnInit() {
  }

  ngOnChanges(data) {
    if (data.resouces$ && this.resouces$) {
      this.resouces$(this.id, this.type).subscibe(res => {});
    }
  }

}
</code>```

Body:
I have two components details and details-view.

In the details I have to pass obserwable by @Input() into second component.

Details Component

 res$: (id: number, type: string) => Observable<DetailsResponse[]>;
 constructor(private service: Service) {
  this.res$ = service.getData;
 }

Service

 getData(id: number, type: string): Observable<DetailsResponse[]>{
   const params = new HttpParams().append('typename', type);
   return this.http.get<any>('api/id', {params: params});
 }

Detalis-View HTML

<dwtalis-view [resources$]="res$"></dwtalis-view>

Detalis-Viev TS Component

@Input()
resouces$: Observable<DetailsResponse[]>

My question is how to subscribe and get the data from resources$ observable in the detalis view component. Subscribing this object retunrs error "resources$ is not a finction can not subscribe"

Body:
You can change the DetailsViewComponent like the following code

export class DetailsViewComponent implements OnInit, OnChanges {

  @Input() resouces$: (id: number, type: string) => Observable<DetailsResponse[]>;

  constructor(
  ) {}

  ngOnInit() {
  }

  ngOnChanges(data) {
    if (data.resouces$ && this.resouces$) {
      this.resouces$(this.id, this.type).subscibe(res => {});
    }
  }

}