问:
Apply trend of seasonal decompose to every column of a dask DataFrame, Python
As title says I can't run this code:

```<code>def simple_map(x):
    y = seasonal_decompose(x,model='additive',extrapolate_trend='freq',period=7,two_sided=False)
    return y.trend

b.map_partitions(simple_map,meta=b).compute()
</code>```

where b is a dask DataFrame with a datetime as index and some series of float as columns and seasonal_decompose is the statsmodel one.

This is what I get:

```<code>Index(...) must be called with a collection of some kind, 'seasonal' was passed
</code>```

If I do:

```<code>b.apply(simple_map,axis=0)
</code>```

Where b is a pandas DataFrame I get what I want.

Where I am wrong?

#

Reproducible example:

```<code>import pandas as pd
from statsmodels.tsa.seasonal import seasonal_decompose

d = {'Val1': [3, 2,7,5], 'Val2': [2, 4,8,6]}
b=pd.DataFrame(data=d)
b=b.set_index(pd.to_datetime(['25/12/1991','26/12/1991','27/12/1991','28/12/1991']))

def simple_map(x):
    y =seasonal_decompose(x,model='additive',extrapolate_trend='freq',period=2,two_sided=False)
    return y.trend

b.apply(simple_map,axis=0)

            Val1    Val2
1991-12-25  0.70    0.9
1991-12-26  2.10    2.7
1991-12-27  3.50    4.5
1991-12-28  5.25    6.5
</code>```

This is what i want do with dask but I cannot

In fact:

```<code>import dask.dataframe as dd

c=dd.from_pandas(b, npartitions=1)
c.map_partitions(simple_map,meta=c).compute()
</code>```

Produce the above appointed error.

答:
Thank you for the example!

From the docstring of apply

Objects passed to the function are Series objects whose index is
          either the DataFrame's index (axis=0)

However, map_partitions is going to work on the entire Dataframe.  I would suggest rewriting the function slightly:

 def simple_map_2(x):
     xVal1 = seasonal_decompose(x.Val1,model='additive',extrapolate_trend='freq',period=2,two_sided=False)
     xVal2 = seasonal_decompose(x.Val2,model='additive',extrapolate_trend='freq',period=2,two_sided=False)
     return pd.DataFrame({'Val1': xVal1.trend, 'Val2': xVal2.trend})

c.map_partitions(simple_map_2,meta=make_meta(c)).compute()

            Val1  Val2
1991-12-25  0.70   0.9
1991-12-26  2.10   2.7
1991-12-27  3.50   4.5
1991-12-28  5.25   6.5
```

Body:
As title says I can't run this code:

def simple_map(x):
    y = seasonal_decompose(x,model='additive',extrapolate_trend='freq',period=7,two_sided=False)
    return y.trend

b.map_partitions(simple_map,meta=b).compute()

where b is a dask DataFrame with a datetime as index and some series of float as columns and seasonal_decompose is the statsmodel one.

This is what I get:

Index(...) must be called with a collection of some kind, 'seasonal' was passed

If I do:

b.apply(simple_map,axis=0)

Where b is a pandas DataFrame I get what I want.

Where I am wrong?

#

Reproducible example:

import pandas as pd
from statsmodels.tsa.seasonal import seasonal_decompose

d = {'Val1': [3, 2,7,5], 'Val2': [2, 4,8,6]}
b=pd.DataFrame(data=d)
b=b.set_index(pd.to_datetime(['25/12/1991','26/12/1991','27/12/1991','28/12/1991']))

def simple_map(x):
    y =seasonal_decompose(x,model='additive',extrapolate_trend='freq',period=2,two_sided=False)
    return y.trend

b.apply(simple_map,axis=0)

            Val1    Val2
1991-12-25  0.70    0.9
1991-12-26  2.10    2.7
1991-12-27  3.50    4.5
1991-12-28  5.25    6.5

This is what i want do with dask but I cannot

In fact:

import dask.dataframe as dd

c=dd.from_pandas(b, npartitions=1)
c.map_partitions(simple_map,meta=c).compute()

Produce the above appointed error.


来源: stackexchange

问:
Using .zip files with Forge Design Automation for AutoCAD
I have a zip file containing several file types (.dwg,.xlsx,.pdf).  If I specify a .zip file as input, I've noticed they're all accepted by Forge, but only .dwg's come back out.  Is there anyway I can fix this?</p>

答:
Thanks to everyone who replied,
Ultimately, I create a project folder structure all my files are unzipped into (dwgs, pdfs, xlsx),beneath the working folder.  My localname for both my input and result are identical in both the Activity and the Workitem.  I recall Augusto telling me not to do this, but I have yet to run into an issue with it.  In the end, my files get cycled in AutoCAD Core and saved to same location. DA zips the changed files and sends them to my endpoint.  I took this approach, because if I save to changed files into a results folder, my modified dwg files and non-dwg files are now in two separate, adjacent locations.  If there's a side affect of working with files in a single location, I'd like to know what it is.</p>

ContentLicense: CC BY-SA 4.0


问:
Know if signal is triggered from django admin
I need to send a mail only when the model is saved from django admin, I was trying with sender.user.is_superuser but i couldn't find the specific method

答:
You can't do this with a signal, but you can do it with your ModelAdmin's save_model() method.

For example:

```<code>from django.contrib import admin
from django.core.mail import send_mail

class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        send_mail(...)
</code>```

Body:
You can't do this with a signal, but you can do it with your ModelAdmin's save_model() method.

For example:

from django.contrib import admin
from django.core.mail import send_mail

class MyModelAdmin(admin.ModelAdmin):
    def save_model(self, request, obj, form, change):
        super().save_model(request, obj, form, change)
        send_mail(...)


问:
Why cant Puppeteer find this link element on page?
^^UPDATE^^

Willing to pay someone to walk me through this, issue posted on codeMentor.io: https://www.codementor.io/u/dashboard/my-requests/9j42b83f0p

I've been looking to click on the element:

```<code><a id="isc_LinkItem_1$20j" href="javascript:void" target="javascript" tabindex="2"
onclick="if(window.isc_LinkItem_1) return isc_LinkItem_1.$30i(event);"
$9a="$9d">Reporting</a>
</code>```

In: https://stackblitz.com/edit/js-nzhhbk
(I haven't included the acutal page because its behind a username & pass)

seems easy enough

----------------------------------------------------------------------

solution1:

```<code>page.click('[id=isc_LinkItem_1$20j]') //not a valid selector
</code>```

solution2:

```<code>const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
} //link not found
</code>```

----------------------------------------------------------------------

I have looked at every which way to select and click it and it says it isn't in the document even though it clearly is (verified by inspecting the html in chrome dev tools and calling:page.evaluate(() => document.body.innerHTML))

**tried to see if it was in an iframe

**tried to select by id

**tried to select by inner text

**tried to console log the body in the browser (console logging not               working verified on the inspect _element) //nothing happens

**tried to create an alert with body text by using:
 _evaluate(() => alert(document)) // nothing happens

**tried to create an alert to test to see if javascript can be injected by:
 _evaluate(() => alert('works')) // nothing happens

**also tried this: How to select elements within an iframe element in Puppeteer // doesn't work

Here is the code I have built so far

```<code>const page = await browser.newPage();

const login1url =
    'https://np3.nextiva.com/NextOSPortal/ncp/landing/landing-platform';
await page.goto(login1url);
await page.waitFor(1000);
await page.type('[name=loginUserName', 'itsaSecretLol');
await page.type('[name=loginPassword]', 'nopeHaha');
await page.click('[type=submit]');
await page.waitForNavigation();
const login3url = 'https://np3.nextiva.com/NextOSPortal/ncp/admin/dashboard';
await page.goto(login3url);
await page.click('[id=hdr_users]');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/manageUsers');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/garrettmrg');
await page.waitFor(2000);
await page.click('[id=loginAsUser]');
await page.waitFor(2000);
await page.click('[id=react-select-5--value');
await page.waitFor(1000);
await page.click('[id=react-select-5--option-0]');
await page.waitFor(20000);
const elementHandle = await page.$('iframe[id=callcenter]');
const frame = await elementHandle.contentFrame();
const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
}
</code>```

答:
On your solution1:

```<code>await page.click('a[id=isc_LinkItem_1\\$20j]');
</code>```

Or try to:

```<code>await page.click('#isc_LinkItem_1\\$20j]');
</code>```

I have the slight impression that you must provide what kind of element your trying to select before the brackets, in this case, an  element.

On the second solution, the # character means we're selecting an element by it's id

Body:
^^UPDATE^^

Willing to pay someone to walk me through this, issue posted on codeMentor.io: https://www.codementor.io/u/dashboard/my-requests/9j42b83f0p

I've been looking to click on the element:

Reporting

In: https://stackblitz.com/edit/js-nzhhbk
(I haven't included the acutal page because its behind a username & pass)

seems easy enough

----------------------------------------------------------------------

solution1:

page.click('[id=isc_LinkItem_1$20j]') //not a valid selector

solution2:

const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
} //link not found

----------------------------------------------------------------------

I have looked at every which way to select and click it and it says it isn't in the document even though it clearly is (verified by inspecting the html in chrome dev tools and calling:page.evaluate(() => document.body.innerHTML))

**tried to see if it was in an iframe

**tried to select by id

**tried to select by inner text

**tried to console log the body in the browser (console logging not               working verified on the inspect _element) //nothing happens

**tried to create an alert with body text by using:
 _evaluate(() => alert(document)) // nothing happens

**tried to create an alert to test to see if javascript can be injected by:
 _evaluate(() => alert('works')) // nothing happens

**also tried this: How to select elements within an iframe element in Puppeteer // doesn't work

Here is the code I have built so far

const page = await browser.newPage();

const login1url =
    'https://np3.nextiva.com/NextOSPortal/ncp/landing/landing-platform';
await page.goto(login1url);
await page.waitFor(1000);
await page.type('[name=loginUserName', 'itsaSecretLol');
await page.type('[name=loginPassword]', 'nopeHaha');
await page.click('[type=submit]');
await page.waitForNavigation();
const login3url = 'https://np3.nextiva.com/NextOSPortal/ncp/admin/dashboard';
await page.goto(login3url);
await page.click('[id=hdr_users]');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/manageUsers');
await page.goto('https://np3.nextiva.com/NextOSPortal/ncp/user/garrettmrg');
await page.waitFor(2000);
await page.click('[id=loginAsUser]');
await page.waitFor(2000);
await page.click('[id=react-select-5--value');
await page.waitFor(1000);
await page.click('[id=react-select-5--option-0]');
await page.waitFor(20000);
const elementHandle = await page.$('iframe[id=callcenter]');
const frame = await elementHandle.contentFrame();
const linkHandlers = await frame.$x("//a[contains(text(), 'Reporting')]");

if (linkHandlers.length > 0) {
    await linkHandlers[0].click();
} else {
    throw new Error('Link not found');
}

Body:
On your solution1:

await page.click('a[id=isc_LinkItem_1\\$20j]');

Or try to:

await page.click('#isc_LinkItem_1\\$20j]');

I have the slight impression that you must provide what kind of element your trying to select before the brackets, in this case, an < a > element.

On the second solution, the # character means we're selecting an element by it's id


问:
What's the difference between a mock & stub?
I've read various articles about mocking vs stubbing in testing, including Martin Fowler's Mocks Aren't Stubs, but still don't understand the difference.</p>

答:
Stub

A stub is an object used to fake a method that has pre-programmed behavior. You may want to use this instead of an existing method in order to avoid unwanted side-effects (e.g. a stub could make a fake fetch call that returns a pre-programmed response without actually making a request to a server).

Mock

A mock is an object used to fake a method that has pre-programmed behavior as well as pre-programmed expectations. If these expectations are not met then the mock will cause the test to fail (e.g. a mock could make a fake fetch call that returns a pre-programmed response without actually making a request to a server which would expect e.g. the first argument to be "http://localhost:3008/" otherwise the test would fail.)

Difference

Unlike mocks, stubs do not have pre-programmed expectations that could fail your test.

ContentLicense: CC BY-SA 3.0


问:
C# MySql ASP.NET Get items from rows in the database and put them in a gridview
I have a table in my database which contains the modules in a project. It is a many to many relationship with the module id which is a foreign to the modules table and the project key which is a foreign key to the projects table. I want to display the names for the modules associated with a project in a gridview. I have the first bit of code done but I don't know how to take in and store all the modules id and then how to get their names in the module table and put them in the gridview. Any help would be much appreciated.</p>

答:
there are several ways to do this...

1) read your module table into a Dictionary, and resolve the needed Names from there when you need them ...

2) let mysql handle that for you:

since you provided no table schema you will probably have to adapt the query...

```<code>    SELECT
    ProjectsTable.Name AS 'Project',
    GROUP_CONCAT(COALESCE(ModulesTable.Name,'None') SEPARATOR ', ') AS 'Modules'
    FROM ProjectsTable
    LEFT JOIN ProjectsModulesTable ON ProjectsTable.id = ProjectsModulesTable.projectId
    LEFT JOIN ModulesTable ON ProjectsModulesTable.moduleId = ModulesTable.id
</code>```

(query not tested)

3) use some framework (e.g. entity framework) and build objects for your database entities and access the names by those objects

Body:
there are several ways to do this...

1) read your module table into a Dictionary, and resolve the needed Names from there when you need them ...

2) let mysql handle that for you:

since you provided no table schema you will probably have to adapt the query...

    SELECT
    ProjectsTable.Name AS 'Project',
    GROUP_CONCAT(COALESCE(ModulesTable.Name,'None') SEPARATOR ', ') AS 'Modules'
    FROM ProjectsTable
    LEFT JOIN ProjectsModulesTable ON ProjectsTable.id = ProjectsModulesTable.projectId
    LEFT JOIN ModulesTable ON ProjectsModulesTable.moduleId = ModulesTable.id

(query not tested)

3) use some framework (e.g. entity framework) and build objects for your database entities and access the names by those objects


问:
Managing Tweepy API Search
Please forgive me if this is a gross repeat of a question previously answered elsewhere, but I am lost on how to use the tweepy API search function. Is there any documentation available on how to search for tweets using the api.search() function?

Is there any way I can control features such as number of tweets returned, results type etc.?

The results seem to max out at 100 for some reason.

the code snippet I use is as follows

searched_tweets = self.api.search(q=query,rpp=100,count=1000)

答:
I am working on extracting twitter data for around a location (in here, around India), for all tweets which include a special keyword or a list of keywords.

```<code>import tweepy
import credentials    ## all my twitter API credentials are in this file, this should be in the same directory as is this script

## set API connection
auth = tweepy.OAuthHandler(credentials.consumer_key,
                            credentials.consumer_secret)
auth.set_access_secret(credentials.access_token,
                        credentials.access_secret)

api = tweepy.API(auth, wait_on_rate_limit=True)    # set wait_on_rate_limit =True; as twitter may block you from querying if it finds you exceeding some limits

search_words = ["#covid19", "2020", "lockdown"]

date_since = "2020-05-21"

tweets = tweepy.Cursor(api.search, =search_words,
                       geocode="20.5937,78.9629,3000km",
                       lang="en", since=date_since).items(10)
## the geocode is for India; format for geocode="lattitude,longitude,radius"
## radius should be in miles or km

for tweet in tweets:
    print("created_at: {}\nuser: {}\ntweet text: {}\ngeo_location: {}".
            format(tweet.created_at, tweet.user.screen_name, tweet.text, tweet.user.location))
    print("\n")
## tweet.user.location will give you the general location of the user and not the particular location for the tweet itself, as it turns out, most of the users do not share the exact location of the tweet
</code>```

Results:

created_at: 2020-05-28 16:48:23
user: XXXXXXXXX
tweet text: RT @Eatala_Rajender: Media Bulletin on status of positive cases #COVID19 in Telangana. (Dated. 28.05.2020)
# TelanganaFightsCorona
# StayHom…
geo_location: Hyderabad, India
```

Title: Managing Tweepy API Search

Body:
I am working on extracting twitter data for around a location (in here, around India), for all tweets which include a special keyword or a list of keywords.

import tweepy
import credentials    ## all my twitter API credentials are in this file, this should be in the same directory as is this script

## set API connection
auth = tweepy.OAuthHandler(credentials.consumer_key,
                            credentials.consumer_secret)
auth.set_access_secret(credentials.access_token,
                        credentials.access_secret)

api = tweepy.API(auth, wait_on_rate_limit=True)    # set wait_on_rate_limit =True; as twitter may block you from querying if it finds you exceeding some limits

search_words = ["#covid19", "2020", "lockdown"]

date_since = "2020-05-21"

tweets = tweepy.Cursor(api.search, =search_words,
                       geocode="20.5937,78.9629,3000km",
                       lang="en", since=date_since).items(10)
## the geocode is for India; format for geocode="lattitude,longitude,radius"
## radius should be in miles or km

for tweet in tweets:
    print("created_at: {}\nuser: {}\ntweet text: {}\ngeo_location: {}".
            format(tweet.created_at, tweet.user.screen_name, tweet.text, tweet.user.location))
    print("\n")
## tweet.user.location will give you the general location of the user and not the particular location for the tweet itself, as it turns out, most of the users do not share the exact location of the tweet

Results:

created_at: 2020-05-28 16:48:23
user: XXXXXXXXX
tweet text: RT @Eatala_Rajender: Media Bulletin on status of positive cases #COVID19 in Telangana. (Dated. 28.05.2020)
# TelanganaFightsCorona
# StayHom…
geo_location: Hyderabad, India


问:
Where should I put free() in C?
I'm a bit new to C-programming and I can't seem to understand where should I free the int* array I initialized. I tried to put free(array) after I've got what I need but Valgrind still reports a memory leak and an invalid free at the location I proposed. Where should I put the free(array) call in this code?

Note: the actual code implementation is removed to make the code simpler while retaining the bug.

```<code>// C-language code (C99)
#include <stdio.h>
#include <stdlib.h>

int fib(int index, int *array, int initBlocks);
int processFib(int index);
int doubleStorage(int **array, int initialBlocks);

int main() {
    int ans = processFib(10);
    printf("ans = %d", ans);
    return 0;
}

// initialises an array and calls the fib(...) function
int processFib(int index) {
    int defaultInitBlocks = 10;
    int *array = calloc(defaultInitBlocks, sizeof(int));
    array[1] = 1;
    array[2] = 1;
    int ans = fib(index, array, defaultInitBlocks);
    free(array); /* Valgrind says InvalidFree here  ----------------------*/
    return ans;
}

// doubles storage of array using realloc
int doubleStorage(int **array, int initialBlocks) {
    int factor = 2;
    int *temp = realloc(*array, factor * initialBlocks * sizeof(int));
    /* Valgrind says the realloc here is a DefinitelyLost memory leak --------*/
    if (!temp) {
        free(*array);
        return -1;
    } else {
        *array = temp;
        for (int i = initialBlocks; i < factor * initialBlocks; i++) {
            (*array)[i] = 0;
        }
        return factor * initialBlocks;
    }
}

// doubles storage if 'index' is greater than array storage. Else, returns 1
int fib(int index, int *array, int initBlocks) {
    if (index >= initBlocks) {
        int newBlocks = doubleStorage(&array, initBlocks);
        return fib(index, array, newBlocks);
    }
    return 1;
}
</code>```

EDIT: SOLUTION MOVED TO ANSWERS

答:
SOLUTION

A double pointer is now used in the fib() function which cleared the Valgrind warning (code below). Heads up to @WhozCraig for his comment.

```<code>int fib(int index, int **array, int initBlocks) {
    if (index >= initBlocks) {
        int newBlocks = doubleStorage(array, initBlocks);
        return fib(index, array, newBlocks);
    }
    if (array[index] > 0) {
        return (*array)[index];
    } else {
        (*array)[index] = fib(index - 1, array, initBlocks)
                + fib(index - 2, array, initBlocks);
        return (*array)[index];
    }
}
</code>```

Title: Where should I put free() in C?

Body:
I'm a bit new to C-programming and I can't seem to understand where should I free the int* array I initialized. I tried to put free(array) after I've got what I need but Valgrind still reports a memory leak and an invalid free at the location I proposed. Where should I put the free(array) call in this code?

Note: the actual code implementation is removed to make the code simpler while retaining the bug.

// C-language code (C99)
#include <stdio.h>
#include <stdlib.h>

int fib(int index, int *array, int initBlocks);
int processFib(int index);
int doubleStorage(int **array, int initialBlocks);

int main() {
    int ans = processFib(10);
    printf("ans = %d", ans);
    return 0;
}

// initialises an array and calls the fib(...) function
int processFib(int index) {
    int defaultInitBlocks = 10;
    int *array = calloc(defaultInitBlocks, sizeof(int));
    array[1] = 1;
    array[2] = 1;
    int ans = fib(index, array, defaultInitBlocks);
    free(array); /* Valgrind says InvalidFree here  ----------------------*/
    return ans;
}

// doubles storage of array using realloc
int doubleStorage(int **array, int initialBlocks) {
    int factor = 2;
    int *temp = realloc(*array, factor * initialBlocks * sizeof(int));
    /* Valgrind says the realloc here is a DefinitelyLost memory leak --------*/
    if (!temp) {
        free(*array);
        return -1;
    } else {
        *array = temp;
        for (int i = initialBlocks; i < factor * initialBlocks; i++) {
            (*array)[i] = 0;
        }
        return factor * initialBlocks;
    }
}

// doubles storage if 'index' is greater than array storage. Else, returns 1
int fib(int index, int *array, int initBlocks) {
    if (index >= initBlocks) {
        int newBlocks = doubleStorage(&array, initBlocks);
        return fib(index, array, newBlocks);
    }
    return 1;
}

EDIT: SOLUTION MOVED TO ANSWERS

Body:
SOLUTION

A double pointer is now used in the fib() function which cleared the Valgrind warning (code below). Heads up to @WhozCraig for his comment.

int fib(int index, int **array, int initBlocks) {
    if (index >= initBlocks) {
        int newBlocks = doubleStorage(array, initBlocks);
        return fib(index, array, newBlocks);
    }
    if (array[index] > 0) {
        return (*array)[index];
    } else {
        (*array)[index] = fib(index - 1, array, initBlocks)
                + fib(index - 2, array, initBlocks);
        return (*array)[index];
    }
}


问:
Fill and edit List in Sharepoint online using powershell and http request
everyone,
I am new here and currently I am very busy with SharePoint Online and teams and Co. I would like to realize an idea and don't really know how to do that. I have found out how to bring a MessageCard via PowerShell in teams or on a SharePoint site. With incoming Webhooks this is very easy. Now I would like to change an existing card instead of creating new cards again and again. Alternatively, maybe create a list in which I can change list entries.

You probably already guessed it. I want to build a status page. From different servers I want to bring information from my Powershell scripts to a central office.

I can imagine that this is not that difficult. I just lack the right approach and after 2 days of wild googling and trying it out, I ended up here :D

答:
you can create a list in sharepoint, update list items with pnp powershell:

https://learn.microsoft.com/en-us/powershell/module/sharepoint-pnp/set-pnplistitem?view=sharepoint-ps

    Set-PnPListItem
   -List <ListPipeBind>
                  -Identity <ListItemPipeBind>
                  [-ContentType <ContentTypePipeBind>]
                  [-Values <Hashtable>]
                  [-SystemUpdate [<SwitchParameter>]]
                  [-Label <String>]
                  [-Web <WebPipeBind>]
                  [-Connection <SPOnlineConnection>]
```

<p>or ms graph:</p>

<p>https://learn.microsoft.com/en-us/graph/api/resources/listitem?view=graph-rest-1.0</p>

```PATCH https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items/{item-id}/fields
```

and then you could add a teams tab with the sharepoint list or create a powerapps-app

you can not delete or update channel messages with ms graph: https://learn.microsoft.com/en-us/graph/api/resources/chatmessage?view=graph-rest-beta

Body:
you can create a list in sharepoint, update list items with pnp powershell:

https://learn.microsoft.com/en-us/powershell/module/sharepoint-pnp/set-pnplistitem?view=sharepoint-ps

    Set-PnPListItem
   -List <ListPipeBind>
                  -Identity <ListItemPipeBind>
                  [-ContentType <ContentTypePipeBind>]
                  [-Values <Hashtable>]
                  [-SystemUpdate [<SwitchParameter>]]
                  [-Label <String>]
                  [-Web <WebPipeBind>]
                  [-Connection <SPOnlineConnection>]

or ms graph:

https://learn.microsoft.com/en-us/graph/api/resources/listitem?view=graph-rest-1.0

PATCH https://graph.microsoft.com/v1.0/sites/{site-id}/lists/{list-id}/items/{item-id}/fields

and then you could add a teams tab with the sharepoint list or create a powerapps-app

you can not delete or update channel messages with ms graph: https://learn.microsoft.com/en-us/graph/api/resources/chatmessage?view=graph-rest-beta


问:
Context Path with Webflux
I've been trying to find a way to set the context path for a webflux application. I know I can configure it using </p>

```<code>server.servlet.context-path
</code>```

<p>if I deploy a servlet, but I would like to achieve it with webflux, without having to explicitly add the path to every route or use MVC. </p>

答:
You can use web Filter, as mentioned in above answers, but you can do one more thing. Write a Base Controller and Extend every class to that Base Controller.
For example:

Base Controller.java

```<code>@RestController
@RequestMapping("/{base_url}")
public abstract class BaseController {
}
</code>```

NewController.java

```<code>@RestController
public class NewController extends BaseController{
  @Autowired
  DatabaseClient databaseClient;

  @GetMapping("/status")
  public Mono<Map<String, String>> status() {
    return databaseClient.execute("SELECT 'ok'").
      map(row -> singletonMap("status", row.get(0, String.class)))
      .one();
  }
}
</code>```

So now you can hit /{base_url}/status

Title: Context Path with Webflux

Body:
I've been trying to find a way to set the context path for a webflux application. I know I can configure it using

server.servlet.context-path

if I deploy a servlet, but I would like to achieve it with webflux, without having to explicitly add the path to every route or use MVC.

Body:
You can use web Filter, as mentioned in above answers, but you can do one more thing. Write a Base Controller and Extend every class to that Base Controller.
For example:

Base Controller.java

@RestController
@RequestMapping("/{base_url}")
public abstract class BaseController {
}

NewController.java

@RestController
public class NewController extends BaseController{
  @Autowired
  DatabaseClient databaseClient;

  @GetMapping("/status")
  public Mono<Map<String, String>> status() {
    return databaseClient.execute("SELECT 'ok'").
      map(row -> singletonMap("status", row.get(0, String.class)))
      .one();
  }
}

So now you can hit /{base_url}/status


问:
need help understanding this code
this code in book jQuery in action page 131

i don't understand

.trigger('adjustName');

what is adjustName

and Simple explanation for trigger()

thanks :)

```<code>$('#addFilterButton').click( function() {
    var filterItem = $('<div>')
    .addClass('filterItem')
    .appendTo('#filterPane')
    .data('suffix','.' + (filterCount++));
    $('div.template.filterChooser')
    .children().clone().appendTo(filterItem)
    .trigger('adjustName');
});
</code>```

答:
Maybe the original jQuery manual could be helpful?

Description: Execute all handlers and
  behaviors attached to the matched
  elements for the given event type.

Title: need help understanding this code

Body:
this code in book jQuery in action page 131

i don't understand

.trigger('adjustName');

what is adjustName

and Simple explanation for trigger()

thanks :)

$('#addFilterButton').click( function() {
    var filterItem = $('
')
    .addClass('filterItem')
    .appendTo('#filterPane')
    .data('suffix','.' + (filterCount++));
    $('div.template.filterChooser')
    .children().clone().appendTo(filterItem)
    .trigger('adjustName');
});


问:
Error build maven multi-module - jar file
Currently I have a multi module project with maven, in the super pom I have added the modules of the projects. From the SparkAppBuilder module I intend to build the jar project that contains the SparkDriver and SparkProcess projects.

To do this from the SparkAPPBuilder module, add the maven-assembly-plugin plugin, I see that it builds the project by adding my 2 modules, but the problem is that it is generating the jar with all the dependencies that are in my local repository, so the jar weighs more than 150MB.

This is my SparkAppBuilderPOM:

```<code><profile>
            <id>dev</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-assembly-plugin</artifactId>
                        <version>2.5</version>
                        <executions>
                            <execution>
                                <id>assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                                <configuration>
                                    <descriptorRefs>
                                        <descriptorRef>jar-with-dependencies</descriptorRef>
                                    </descriptorRefs>
                                    <archive>
                                        <manifest>
                                            <addClasspath>true</addClasspath>
                                            <classpathPrefix>lib/</classpathPrefix>
                                            <mainClass>com.streaming.example.DirectStreaming</mainClass>
                                        </manifest>
                                    </archive>
                                    <finalName>JavaStreamingDirect</finalName>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>3.1.1</version>
                        <configuration>
                            <archive>
                                <manifest>
                                    <addClasspath>true</addClasspath>
                                    <classpathPrefix>lib/</classpathPrefix>
                                    <mainClass>com.streaming.example.DirectStreaming</mainClass>
                                </manifest>
                            </archive>
                            <finalName>JavaStreamingDirect</finalName>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
...

<dependencies>
        <dependency>
            <groupId>com.spark.driver</groupId>
            <artifactId>SparkDriver</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.spark.streaming</groupId>
            <artifactId>SparkProcess</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>

    </dependencies>
</code>```

Do you know why you add my entire local repository in the assmbly phase?

Thanks so much.

Regards

答:
A jar-with-dependencies also contains all transitive dependencies. Those are usually needed to run the project because they are the dependencies of your dependencies.

So it is not unusual that this jar is large. You should look in your mvn dependency:tree where most of the stuff comes from -- then you might be able to reduce the amount by changing the dependencies of your modules.

So: The jar-with-dependencies does not contain the whole local repository, just the whole dependency tree.

Body:
Currently I have a multi module project with maven, in the super pom I have added the modules of the projects. From the SparkAppBuilder module I intend to build the jar project that contains the SparkDriver and SparkProcess projects.

To do this from the SparkAPPBuilder module, add the maven-assembly-plugin plugin, I see that it builds the project by adding my 2 modules, but the problem is that it is generating the jar with all the dependencies that are in my local repository, so the jar weighs more than 150MB.

This is my SparkAppBuilderPOM:

<profile>
            <id>dev</id>
            <build>
                <plugins>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-assembly-plugin</artifactId>
                        <version>2.5</version>
                        <executions>
                            <execution>
                                <id>assembly</id>
                                <phase>package</phase>
                                <goals>
                                    <goal>single</goal>
                                </goals>
                                <configuration>
                                    <descriptorRefs>
                                        <descriptorRef>jar-with-dependencies</descriptorRef>
                                    </descriptorRefs>
                                    <archive>
                                        <manifest>
                                            <addClasspath>true</addClasspath>
                                            <classpathPrefix>lib/</classpathPrefix>
                                            <mainClass>com.streaming.example.DirectStreaming</mainClass>
                                        </manifest>
                                    </archive>
                                    <finalName>JavaStreamingDirect</finalName>
                                </configuration>
                            </execution>
                        </executions>
                    </plugin>
                    <plugin>
                        <groupId>org.apache.maven.plugins</groupId>
                        <artifactId>maven-jar-plugin</artifactId>
                        <version>3.1.1</version>
                        <configuration>
                            <archive>
                                <manifest>
                                    <addClasspath>true</addClasspath>
                                    <classpathPrefix>lib/</classpathPrefix>
                                    <mainClass>com.streaming.example.DirectStreaming</mainClass>
                                </manifest>
                            </archive>
                            <finalName>JavaStreamingDirect</finalName>
                        </configuration>
                    </plugin>
                </plugins>
            </build>
        </profile>
...

<dependencies>
        <dependency>
            <groupId>com.spark.driver</groupId>
            <artifactId>SparkDriver</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>

        <dependency>
            <groupId>com.spark.streaming</groupId>
            <artifactId>SparkProcess</artifactId>
            <version>0.0.2-SNAPSHOT</version>
        </dependency>

    </dependencies>

Do you know why you add my entire local repository in the assmbly phase?

Thanks so much.

Regards


问:
Python: Remove character only from end of string if character is ="/"
I add different Values to the Houdini Variables with Python.

Some of these Variables are file pathes and end with an "/" - others are just names and do not end with an "/".

In my current code I use [:-1] to remove the last character of the filepath, so I dont have the "/".
The problem is, that if I add a Value like "Var_ABC", the result will be "Var_AB" since it also removes the last character.

How can i remove the last character only if the last character is a "/"?

Thats what I have and it works so far:

```<code>def set_vars():

count = hou.evalParm('vars_names')
user_name = hou.evalParm('user_name')

for idx in range( 1,count+1):
    output = hou.evalParm('vars_' + str(idx))
    vars_path_out = hou.evalParm('vars_path_' + str(idx))
    vars_path = vars_path_out[:-1]

    hou.hscript("setenv -g " + output + "=" + vars_path)

    final_vars = hou.hscript("setenv -g " + output + "=" + vars_path)

    hou.ui.displayMessage(user_name +", " + "all variables are set.")
</code>```

Thank you

答:
Try this in your code:

```<code>vars_path_out = hou.evalParm('vars_path_' + str(idx))
if vars_path_out[-1] == '/':
 vars_path = vars_path_out[:-1]
</code>```

or

based on the comment of jasonharper

```<code>vars_path = vars_path_out.rstrip('/')
</code>```

This is much better than the first

Body:
I add different Values to the Houdini Variables with Python.

Some of these Variables are file pathes and end with an "/" - others are just names and do not end with an "/".

In my current code I use [:-1] to remove the last character of the filepath, so I dont have the "/".
The problem is, that if I add a Value like "Var_ABC", the result will be "Var_AB" since it also removes the last character.

How can i remove the last character only if the last character is a "/"?

Thats what I have and it works so far:

def set_vars():

count = hou.evalParm('vars_names')
user_name = hou.evalParm('user_name')

for idx in range( 1,count+1):
    output = hou.evalParm('vars_' + str(idx))
    vars_path_out = hou.evalParm('vars_path_' + str(idx))
    vars_path = vars_path_out[:-1]

    hou.hscript("setenv -g " + output + "=" + vars_path)

    final_vars = hou.hscript("setenv -g " + output + "=" + vars_path)

    hou.ui.displayMessage(user_name +", " + "all variables are set.")

Thank you

Body:
Try this in your code:

vars_path_out = hou.evalParm('vars_path_' + str(idx))
if vars_path_out[-1] == '/':
 vars_path = vars_path_out[:-1]

or

based on the comment of jasonharper

vars_path = vars_path_out.rstrip('/')

This is much better than the first


问:
Inno Setup: Overwrite existing installation or show dir prompt
It would be nice if I have this in my setup:

If there is no previous installation, then an edit field for the destination directory should be shown.

If there is a previous installation, than the user should should be asked if he wants to overwrite the existing installation (no directory
prompt should be visible) or if he wants to install this version in a
different directory as a separate installation (two entries in the uninstall list). If this option is chosen, than the edit field
for the destination directory should be shown.

Is it possible to use existing Inno Setup options to achieve this? Or do I have to build a custom dialog page?

答: I solved this problem by putting the responsibility on the user (the one installing the application) to explicitly specify that they want to install a separate instance of the application by specifying a /instancename parameter on the installer's command line (the AppId directive uses a scripted constant).


问:
Print items in array with increasing times
I have an array and I want every element in this array printed on the screen. But the time to print to the screen will be multiplied by 2 every time.

Example: a printed: 1 sec, b printed: 2sec, c printed: 4 sec...

How can I do that? This is my code. Can you help?

let exampleArray = ['a', 'b', 'c', 'd'];

const writeArray = (arr) => {
    let time = 1000;
    for (i = 0; i < arr.length; i++) {
        console.log(arr[i])
    }
}

writeArray(exampleArray)```

答:
I think you are looking for this:

Edit:
It prints to console every 2^i seconds. Have in mind, that i starts at 0, so you may want to use Math.pow(2,i+1)*1000 instead...

let exampleArray = ['a', 'b', 'c', 'd'];

const writeArray = (arr) => {
    for (let i = 0; i < arr.length; i++) {
        setTimeout(() => {
          console.log(arr[i]);
        }, Math.pow(2,i)*1000);
    }
}

writeArray(exampleArray)```


问:
Python Program - Use a while loop to calculate the amount of letter grades from user input
I wrote some code for the following problem:

"Write a program to continuously asks the user an exam score given as integer percentages in the range 0 to 100. Calculate the total number of grades in each letter-grade category as follows: 90 to 100 is an A, 80 to 89 is a B, 70 to 79 is a C, 60 to 69 is a D, and 0 to 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is used only to end the loop, so do not use it in the calculations.)"

Here is my code:

```<code>count = 0
gradeA = 0
gradeB = 0
gradeC = 0
gradeD = 0
gradeF = 0

score = int(input("Enter an exam score: "))
while score != -1:
    count = count + 1
    score = int(input("Enter an exam score: "))

if score >= 90 and score <= 100:
    gradeA = gradeA + 1
elif score >= 80 and score <= 89:
    gradeB = gradeB + 1
elif score >= 70 and score <= 79:
    gradeC = gradeC + 1
elif score >= 60 and score <= 69:
    gradeD = gradeD + 1
elif score >= 0 and score <= 59:
    gradeF = gradeF + 1

print ("You entered " + str(count) + " exam scores.")
print ("Number of A's = " + str(gradeA))
print ("Number of B's = " + str(gradeB))
print ("Number of C's = " + str(gradeC))
print ("Number of D's = " + str(gradeD))
print ("Number of F's = " + str(gradeF))
</code>```

The issue is that when I run the code, the number of grades in each letter-grade category are all showing up as 0.
How could I fix this so that the correct numbers are shown?

答:
You forgot to indent your if statements.</p>

```<code>count = 0
gradeA = 0
gradeB = 0
gradeC = 0
gradeD = 0
gradeF = 0

score = int(input("Enter an exam score: "))
while score != -1:
    count = count + 1
    score = int(input("Enter an exam score: "))

    if score >= 90 and score <= 100:
        gradeA = gradeA + 1
    elif score >= 80 and score <= 89:
        gradeB = gradeB + 1
    elif score >= 70 and score <= 79:
        gradeC = gradeC + 1
    elif score >= 60 and score <= 69:
        gradeD = gradeD + 1
    elif score >= 0 and score <= 59:
        gradeF = gradeF + 1

print ("You entered " + str(count) + " exam scores.")
print ("Number of A's = " + str(gradeA))
print ("Number of B's = " + str(gradeB))
print ("Number of C's = " + str(gradeC))
print ("Number of D's = " + str(gradeD))
print ("Number of F's = " + str(gradeF))
</code>```

Body:
I wrote some code for the following problem:

"Write a program to continuously asks the user an exam score given as integer percentages in the range 0 to 100. Calculate the total number of grades in each letter-grade category as follows: 90 to 100 is an A, 80 to 89 is a B, 70 to 79 is a C, 60 to 69 is a D, and 0 to 59 is an F. Use a negative score as a sentinel value to indicate the end of the input. (The negative value is used only to end the loop, so do not use it in the calculations.)"

Here is my code:

count = 0
gradeA = 0
gradeB = 0
gradeC = 0
gradeD = 0
gradeF = 0

score = int(input("Enter an exam score: "))
while score != -1:
    count = count + 1
    score = int(input("Enter an exam score: "))

if score >= 90 and score <= 100:
    gradeA = gradeA + 1
elif score >= 80 and score <= 89:
    gradeB = gradeB + 1
elif score >= 70 and score <= 79:
    gradeC = gradeC + 1
elif score >= 60 and score <= 69:
    gradeD = gradeD + 1
elif score >= 0 and score <= 59:
    gradeF = gradeF + 1

print ("You entered " + str(count) + " exam scores.")
print ("Number of A's = " + str(gradeA))
print ("Number of B's = " + str(gradeB))
print ("Number of C's = " + str(gradeC))
print ("Number of D's = " + str(gradeD))
print ("Number of F's = " + str(gradeF))

The issue is that when I run the code, the number of grades in each letter-grade category are all showing up as 0.
How could I fix this so that the correct numbers are shown?

Body:
You forgot to indent your if statements.

count = 0
gradeA = 0
gradeB = 0
gradeC = 0
gradeD = 0
gradeF = 0

score = int(input("Enter an exam score: "))
while score != -1:
    count = count + 1
    score = int(input("Enter an exam score: "))

    if score >= 90 and score <= 100:
        gradeA = gradeA + 1
    elif score >= 80 and score <= 89:
        gradeB = gradeB + 1
    elif score >= 70 and score <= 79:
        gradeC = gradeC + 1
    elif score >= 60 and score <= 69:
        gradeD = gradeD + 1
    elif score >= 0 and score <= 59:
        gradeF = gradeF + 1

print ("You entered " + str(count) + " exam scores.")
print ("Number of A's = " + str(gradeA))
print ("Number of B's = " + str(gradeB))
print ("Number of C's = " + str(gradeC))
print ("Number of D's = " + str(gradeD))
print ("Number of F's = " + str(gradeF))


问:
Loop over a List getting an increasing number of elements each time
Let's say I have a list that looks like

```<code>{A, B, C, D, E}
</code>```

And I want to loop over this list, getting an increasing number of elements each time, so each iteration would look like:

```<code>Iteration 1: {A}
Iteration 2: {A, B}
Iteration 3: {A, B, C}
Iteration 4: {A, B, C, D}
Iteration 5: {A, B, C, D, E}
</code>```

Currently I am accomplishing this with:

```<code>(1 to list.size).foreach( n => {
  val elements = list.take(n)
  // Do something with elements
})
</code>```

But that feels messy. Is there a more 'scala' way of accomplishing this behavior?

答:
You could use list.inits :

```<code>scala> List(1,2,3,4,5).inits.foreach(println)
List(1, 2, 3, 4, 5)
List(1, 2, 3, 4)
List(1, 2, 3)
List(1, 2)
List(1)
List()
</code>```

To get your desired out put you would need to create a list from the iterator, reverse it and take the tail to omit the empty list:

```<code>scala> List(1,2,3,4,5).inits.toList.reverse.tail.foreach(println)
List(1)
List(1, 2)
List(1, 2, 3)
List(1, 2, 3, 4)
List(1, 2, 3, 4, 5)
</code>```

Body:
Let's say I have a list that looks like

{A, B, C, D, E}

And I want to loop over this list, getting an increasing number of elements each time, so each iteration would look like:

Iteration 1: {A}
Iteration 2: {A, B}
Iteration 3: {A, B, C}
Iteration 4: {A, B, C, D}
Iteration 5: {A, B, C, D, E}

Currently I am accomplishing this with:

(1 to list.size).foreach( n => {
  val elements = list.take(n)
  // Do something with elements
})

But that feels messy. Is there a more 'scala' way of accomplishing this behavior?

Body:
You could use list.inits :

scala> List(1,2,3,4,5).inits.foreach(println)
List(1, 2, 3, 4, 5)
List(1, 2, 3, 4)
List(1, 2, 3)
List(1, 2)
List(1)
List()

To get your desired out put you would need to create a list from the iterator, reverse it and take the tail to omit the empty list:

scala> List(1,2,3,4,5).inits.toList.reverse.tail.foreach(println)
List(1)
List(1, 2)
List(1, 2, 3)
List(1, 2, 3, 4)
List(1, 2, 3, 4, 5)


问:
Set a global var in jenkins
How can I set a variable in maven project in jenkins and use it across all non dependent jobs. This variable is not static and I can only set it via executing a job based on some conditions</p>

答:
You can set global variable programmatically through custom script.
Though I haven't tried/tested this personally, you can custom script on this google groups discussion.

https://groups.google.com/forum/#!topic/jenkinsci-users/KgCGuDmED1Q

Note what it says :

That code is a global configuration script which needs to be executed
  from the "Groovy console" of the Jenkins server.

It can't be used from a Jenkinsfile.

So, you might have to execute it outside the job. Once done, you can consume the global variable in downstream job(s).

Title: Set a global var in jenkins


问:
How to design and develop a financial transactions app in Spring Boot?
I try to make an app for a test and I need some help. The app is about financial transactions and could be 4 transactions type. And I need to do 2 microservices.

The MS2 will have 2 entities:

User entity:

```<code>public class User {

    private int id;
    private String name;
    private String tin;
    private String iban;
    private String pocketNo;
    private List<Transaction> transactions;
}
</code>```

Transaction entity:

```<code>public class Transaction {

    private int id;
    private enum TransactionType {
        IBAN_TO_IBAN, IBAN_TO_POCKET, POCKET_TO_IBAN, POCKET_TO_POCKET;
    }

    private int noOfTransactions;
    private BigDecimal sum;
}
</code>```

Any feedback will be appreciated, Thank you!

答:
Multiple endpoints for multiple transaction types is a better idea as opposed to a single one because it will lead to cleaner code that is much easier to maintain and write tests for.

If you use only one endpoint, you may have to write some parsing logic and add conditions (either if or switch, both are not ideal) to determine how to handle the transaction in your RestController. This additional complexity can introduce bugs and add to your development time, whereas writing 4 separate endpoints removes the unnecessary logic and allows you to focus on writing only what you need.

Having a REST API for report generation is fine too. Just be cautious on what you want the required arguments to be- you might want id to be required for report generation, but your API might need to be flexible enough to generate reports from the iban or pocketNo properties. The annotation @RequestParam(required = false) can help with this.

For additional information, the book Clean Code has a good chapter on writing functions.

Body:
I try to make an app for a test and I need some help. The app is about financial transactions and could be 4 transactions type. And I need to do 2 microservices.

The MS2 will have 2 entities:

User entity:

public class User {

    private int id;
    private String name;
    private String tin;
    private String iban;
    private String pocketNo;
    private List<Transaction> transactions;
}

Transaction entity:

public class Transaction {

    private int id;
    private enum TransactionType {
        IBAN_TO_IBAN, IBAN_TO_POCKET, POCKET_TO_IBAN, POCKET_TO_POCKET;
    }

    private int noOfTransactions;
    private BigDecimal sum;
}

Any feedback will be appreciated, Thank you!


问:
Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)
Hi i'm trying to run this code on Angular 6 after updating from angular2-modal to ngx-modialog

```<code>this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
            .open()
            .then(( d ) => d.result
            .then(( r ) => {...});
</code>```

but after compiling i get this error :

```<code>Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)
</code>```

I tried this but same error

```<code>...
dialog: DialogRef<TwoButtonPreset>;
...
let dialog = this.modal.confirm() .showClose(true)
.title(this.translator.instant('common.message.confirm.delete'))
.keyboard(27)
.okBtn(this.translator.instant('common.text.yes'))
.cancelBtn(this.translator.instant('common.text.no'))
.message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
.open()
.then(( d ) => d.result
...
</code>```

I also tried that but getting ; expected

```<code>this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("<h5>" + this.translator.instant('common.message.confirm.deleteAll') + "</h5>")
            .open()
            .result => {...};
</code>```

Here's my package.json :

```<code>{
  "name": "frontend6",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "@ngx-translate/core": "^12.1.2",
    "@ngx-translate/http-loader": "^4.0.0",
    "@types/alertify": "^0.3.29",
    "@types/file-saver": "0.0.1",
    "@types/highcharts": "^5.0.25",
    "@types/jquery": "2.0.47",
    "@types/openlayers": "4.6.9",
    "ag-grid": "7.1.0",
    "ag-grid-ng2": "7.1.2",
    "angular-tree-component": "^3.7.3",
    "angular2-google-maps": "0.17.0",
    "angular2-infinite-scroll": "^0.3.4",
    "angular2-text-mask": "2.1.0",
    "angular2-toaster": "^8.0.0",
    "angular2-tree-component": "2.0.0",
    "animate.css": "^3.7.2",
    "bootstrap": "3.3.7",
    "chart.js": "^2.7.3",
    "chroma-js": "^1.3.7",
    "codemirror": "5.22.0",
    "core-js": "^2.5.4",
    "easy-pie-chart": "2.1.7",
    "file-saver": "1.3.3",
    "flot": "0.8.0-alpha",
    "font-awesome": "4.7.0",
    "fullcalendar": "3.1.0",
    "highcharts": "^6.2.0",
    "highcharts-stock": "^0.1.7",
    "jqcloud2": "2.0.2",
    "jquery": "^3.5.1",
    "jquery-slimscroll": "1.3.8",
    "jquery-sparkline": "2.4.0",
    "jquery.browser": "0.1.0",
    "jquery.flot.tooltip": "0.9.0",
    "jspdf": "1.3.5",
    "jspdf-autotable": "2.3.2",
    "lodash": "^4.17.15",
    "modernizr": "^3.11.1",
    "moment": "^2.25.3",
    "mydatepicker": "1.10.2",
    "ng2-bootstrap": "1.1.16-11",
    "ng2-charts": "^1.6.0",
    "ng2-data-table": "1.0.0",
    "ng2-dnd": "2.1.1",
    "ng2-file-upload": "1.1.4-2",
    "ng2-img-cropper": "0.7.7",
    "ng2-select": "1.1.2",
    "ng2-table": "1.3.2",
    "ng2-tag-input": "0.7.0",
    "ng2-validation": "3.1.3",
    "ngx-modialog": "^5.0.1",
    "openlayers": "3.20.1",
    "rxjs": "~6.2.0",
    "rxjs-tslint": "^0.1.8",
    "screenfull": "3.0.2",
    "simple-line-icons": "2.4.1",
    "spinkit": "1.2.5",
    "summernote": "0.8.2",
    "ts-helpers": "1.1.1",
    "weather-icons": "1.3.2",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-builders/jest": "^7.2.3",
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.9",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/codemirror": "0.0.37",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/moment": "2.13.0",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-read-json": "1.1.0",
    "karma-remap-istanbul": "0.2.1",
    "loaders.css": "0.1.2",
    "napa": "2.3.0",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.0.2",
    "typescript": "^2.4.2",
    "webdriver-manager": "10.2.5",
    "webpack": "^4.11.1",
    "webpack-dev-server": "2.1.0-beta.9"
  }
}
</code>```

The base app was on Angular 2 i was able to upgrade it to Angular 4 now I'm going for Angular 6

答:
I guess open() does not return a Promise. Try to add .result like this:

...
.open().result => alert(`The result is: ${result}`) );
...
```

(This is for v4)

Body:
Hi i'm trying to run this code on Angular 6 after updating from angular2-modal to ngx-modialog

this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
            .open()
            .then(( d ) => d.result
            .then(( r ) => {...});

but after compiling i get this error :

Property 'then' does not exist on type 'DialogRef<TwoButtonPreset>'.ts(2339)

I tried this but same error

...
dialog: DialogRef<TwoButtonPreset>;
...
let dialog = this.modal.confirm() .showClose(true)
.title(this.translator.instant('common.message.confirm.delete'))
.keyboard(27)
.okBtn(this.translator.instant('common.text.yes'))
.cancelBtn(this.translator.instant('common.text.no'))
.message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
.open()
.then(( d ) => d.result
...

I also tried that but getting ; expected

this.modal.confirm()
            .showClose(true)
            .title(this.translator.instant('common.message.confirm.delete'))
            .keyboard(27)
            .okBtn(this.translator.instant('common.text.yes'))
            .cancelBtn(this.translator.instant('common.text.no'))
            .message("
" + this.translator.instant('common.message.confirm.deleteAll') + "
")
            .open()
            .result => {...};

Here's my package.json :

{
  "name": "frontend6",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  "private": true,
  "dependencies": {
    "@angular/animations": "^6.1.0",
    "@angular/common": "^6.1.0",
    "@angular/compiler": "^6.1.0",
    "@angular/core": "^6.1.0",
    "@angular/forms": "^6.1.0",
    "@angular/http": "^6.1.0",
    "@angular/platform-browser": "^6.1.0",
    "@angular/platform-browser-dynamic": "^6.1.0",
    "@angular/router": "^6.1.0",
    "@ngx-translate/core": "^12.1.2",
    "@ngx-translate/http-loader": "^4.0.0",
    "@types/alertify": "^0.3.29",
    "@types/file-saver": "0.0.1",
    "@types/highcharts": "^5.0.25",
    "@types/jquery": "2.0.47",
    "@types/openlayers": "4.6.9",
    "ag-grid": "7.1.0",
    "ag-grid-ng2": "7.1.2",
    "angular-tree-component": "^3.7.3",
    "angular2-google-maps": "0.17.0",
    "angular2-infinite-scroll": "^0.3.4",
    "angular2-text-mask": "2.1.0",
    "angular2-toaster": "^8.0.0",
    "angular2-tree-component": "2.0.0",
    "animate.css": "^3.7.2",
    "bootstrap": "3.3.7",
    "chart.js": "^2.7.3",
    "chroma-js": "^1.3.7",
    "codemirror": "5.22.0",
    "core-js": "^2.5.4",
    "easy-pie-chart": "2.1.7",
    "file-saver": "1.3.3",
    "flot": "0.8.0-alpha",
    "font-awesome": "4.7.0",
    "fullcalendar": "3.1.0",
    "highcharts": "^6.2.0",
    "highcharts-stock": "^0.1.7",
    "jqcloud2": "2.0.2",
    "jquery": "^3.5.1",
    "jquery-slimscroll": "1.3.8",
    "jquery-sparkline": "2.4.0",
    "jquery.browser": "0.1.0",
    "jquery.flot.tooltip": "0.9.0",
    "jspdf": "1.3.5",
    "jspdf-autotable": "2.3.2",
    "lodash": "^4.17.15",
    "modernizr": "^3.11.1",
    "moment": "^2.25.3",
    "mydatepicker": "1.10.2",
    "ng2-bootstrap": "1.1.16-11",
    "ng2-charts": "^1.6.0",
    "ng2-data-table": "1.0.0",
    "ng2-dnd": "2.1.1",
    "ng2-file-upload": "1.1.4-2",
    "ng2-img-cropper": "0.7.7",
    "ng2-select": "1.1.2",
    "ng2-table": "1.3.2",
    "ng2-tag-input": "0.7.0",
    "ng2-validation": "3.1.3",
    "ngx-modialog": "^5.0.1",
    "openlayers": "3.20.1",
    "rxjs": "~6.2.0",
    "rxjs-tslint": "^0.1.8",
    "screenfull": "3.0.2",
    "simple-line-icons": "2.4.1",
    "spinkit": "1.2.5",
    "summernote": "0.8.2",
    "ts-helpers": "1.1.1",
    "weather-icons": "1.3.2",
    "zone.js": "~0.8.26"
  },
  "devDependencies": {
    "@angular-builders/jest": "^7.2.3",
    "@angular-devkit/build-angular": "~0.8.0",
    "@angular/cli": "~6.2.9",
    "@angular/compiler-cli": "^6.1.0",
    "@angular/language-service": "^6.1.0",
    "@types/codemirror": "0.0.37",
    "@types/jasmine": "~2.8.8",
    "@types/jasminewd2": "~2.0.3",
    "@types/moment": "2.13.0",
    "@types/node": "~8.9.4",
    "codelyzer": "~4.3.0",
    "jasmine-core": "~2.99.1",
    "jasmine-spec-reporter": "~4.2.1",
    "karma": "~3.0.0",
    "karma-chrome-launcher": "~2.2.0",
    "karma-cli": "1.0.1",
    "karma-coverage-istanbul-reporter": "~2.0.1",
    "karma-jasmine": "~1.1.2",
    "karma-jasmine-html-reporter": "^0.2.2",
    "karma-read-json": "1.1.0",
    "karma-remap-istanbul": "0.2.1",
    "loaders.css": "0.1.2",
    "napa": "2.3.0",
    "protractor": "4.0.13",
    "ts-node": "1.2.1",
    "tslint": "4.0.2",
    "typescript": "^2.4.2",
    "webdriver-manager": "10.2.5",
    "webpack": "^4.11.1",
    "webpack-dev-server": "2.1.0-beta.9"
  }
}

The base app was on Angular 2 i was able to upgrade it to Angular 4 now I'm going for Angular 6

Body:
I guess open() does not return a Promise. Try to add .result like this:

...
.open().result => alert(`The result is: ${result}`) );
...

(This is for v4)


问:
Local Dynamodb Console
As the title speaks, is there a way to visualize data in local dynamodb like how it is on AWS Console? This seems to be one of the drawback to me because using localhost:8000/shell (default endpoint) and doing scans requiring the setup of the attributes and etc.</p>

答:
https://www.npmjs.com/package/dynamodb-admin

I have then came across with this webapp that visualize dynamodb data across platform. Working quite well especially if you're developing on Serverless Framework.

tldr;

```<code>npm i dynamodb-admin
DYNAMO_ENDPOINT=http://localhost:8000 dynamodb-admin
</code>```

(assume you are running local dynamodb on default port 8000)

Browse http://localhost:8001

Title: Local Dynamodb Console

Body:
https://www.npmjs.com/package/dynamodb-admin

I have then came across with this webapp that visualize dynamodb data across platform. Working quite well especially if you're developing on Serverless Framework.

tldr;

npm i dynamodb-admin
DYNAMO_ENDPOINT=http://localhost:8000 dynamodb-admin

(assume you are running local dynamodb on default port 8000)

Browse http://localhost:8001


问:
Output razor string inside a string literal quotations
How do I do this:

```<code><tr id="paymentId_@item.ItemId">
</code>```

I want the output to look like:

```<code><tr id="paymentId_0">
</code>```

when item.ItemId is 0.

Body:
How do I do this:

I want the output to look like:

when item.ItemId is 0.

Body: <tr id="paymentId_@(item.ItemId)">


问:
How to identify the element using Selenium and Python
I've been tinkering with Selenium (Python) for the day working on a project. I'm stuck trying to click on a link of the webpage because I'm unable to retrieve the element by any of the ways I've found until now.

The link is this:

```<code><p>
<a href="0_fr.asp?contenido=0actunor.asp" target="mainFrame"><font size="3" face="Arial" color="#CC9900">
<b>Base de datos de Disposiciones Vigentes</b></font></a>
</font>
</p>
</code>```

Now, I've tried these things so far, and all give me NoSuchElementException:

driver.find_element_by_css_selector("a[href=0_fr.asp?contenido=0actunor.asp]")

driver.find_element_by_css_selector('div:contains("Base de datos de Disposiciones Vigentes")')

same as 1) but copying and pasting CSS selector alone as a String

by link text and partial link text using the content between  and

by using id just in case it does something.

And several more found across other StackOverflow questions and online guides to build my own css selectors and such, but I don't know any HTML or CSS so it's been a bit difficult to follow them.
I can provide more information if needed, but i'm unable to link the webpage as you would have to log in and it's a job thing.

Any help or places to search for more information are greatly welcome!

SOLVED: The problem was that the link was inside a frame, which was inside another frame. I just hade to use driver.switch_to.frame("frameName") twice, then use css_selector normally and works as it should.

答:
The element is  element and by all possible means you will interact i.e. click on it. Ideally to invoke click() on any element using Selenium you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href*='contenido'][href*='actunor'][target='mainFrame'] b"))).click()
</code>```

Using XPATH:

```<code>WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href, 'contenido') and contains(@href, 'actunor')][@target='mainFrame']//b[text()='Base de datos de Disposiciones Vigentes']"))).click()
</code>```

Note : You have to add the following imports :

```<code>from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
</code>```

Update

As you are observing TimeoutException inducing WebDriverWait you need to address NoSuchElementException first following the discussion in Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome

Body:
I've been tinkering with Selenium (Python) for the day working on a project. I'm stuck trying to click on a link of the webpage because I'm unable to retrieve the element by any of the ways I've found until now.

The link is this:

Base de datos de Disposiciones Vigentes

Now, I've tried these things so far, and all give me NoSuchElementException:

driver.find_element_by_css_selector("a[href=0_fr.asp?contenido=0actunor.asp]")

driver.find_element_by_css_selector('div:contains("Base de datos de Disposiciones Vigentes")')

same as 1) but copying and pasting CSS selector alone as a String

by link text and partial link text using the content between  and

by using id just in case it does something.

And several more found across other StackOverflow questions and online guides to build my own css selectors and such, but I don't know any HTML or CSS so it's been a bit difficult to follow them.
I can provide more information if needed, but i'm unable to link the webpage as you would have to log in and it's a job thing.

Any help or places to search for more information are greatly welcome!

SOLVED: The problem was that the link was inside a frame, which was inside another frame. I just hade to use driver.switch_to.frame("frameName") twice, then use css_selector normally and works as it should.

Body:
The element is <a> element and by all possible means you will interact i.e. click on it. Ideally to invoke click() on any element using Selenium you have to induce WebDriverWait for the element_to_be_clickable() and you can use either of the following Locator Strategies:

Using CSS_SELECTOR:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.CSS_SELECTOR, "a[href*='contenido'][href*='actunor'][target='mainFrame'] b"))).click()

Using XPATH:

WebDriverWait(driver, 20).until(EC.element_to_be_clickable((By.XPATH, "//a[contains(@href, 'contenido') and contains(@href, 'actunor')][@target='mainFrame']//b[text()='Base de datos de Disposiciones Vigentes']"))).click()

Note : You have to add the following imports :

from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC

Update

As you are observing TimeoutException inducing WebDriverWait you need to address NoSuchElementException first following the discussion in Selenium “selenium.common.exceptions.NoSuchElementException” when using Chrome


问:
How to check if a node contains relation with other node with 2 specific codes in it but not a particular code in Neo4j Cypher Query
I tried as below

```<code>Match(A)-[r1]->(B) where B.Code IN ['aaa', 'bbb'] and B.Code <> 'ccc'
return A, B
</code>```

seems to be incorrect. This returns  records of B with 'aaa' and 'bbb' ignoring 'ccc'.
I dont want to return B at all if it has 'ccc'. Not just ignore that relation.

Other tries: same result as above

```<code>Match(A)->[r1]->(B) where B.Code <> 'ccc'
With *
Match(A)->[r1]->(B) where B.Code IN ['aaa', 'bbb']
return A, B
</code>```

Its is returning me A with aaa, A with bbb and X with aaa and X with bbb. I am expecting only X. Could you please correct where I am doing it incorrectly.

答:
Something like this should work:</p>

```<code>MATCH (A)-->(B)
WHERE B.Code IN ['aaa', 'bbb', 'ccc']
WITH A, COLLECT(B) AS bs, COLLECT(B.Code) AS codes
WHERE 'ccc' NOT IN codes
RETURN A, bs
</code>```

Body:
I tried as below

Match(A)-[r1]->(B) where B.Code IN ['aaa', 'bbb'] and B.Code <> 'ccc'
return A, B

seems to be incorrect. This returns  records of B with 'aaa' and 'bbb' ignoring 'ccc'.
I dont want to return B at all if it has 'ccc'. Not just ignore that relation.

Other tries: same result as above

Match(A)->[r1]->(B) where B.Code <> 'ccc'
With *
Match(A)->[r1]->(B) where B.Code IN ['aaa', 'bbb']
return A, B

Its is returning me A with aaa, A with bbb and X with aaa and X with bbb. I am expecting only X. Could you please correct where I am doing it incorrectly.

Body:
Something like this should work:

MATCH (A)-->(B)
WHERE B.Code IN ['aaa', 'bbb', 'ccc']
WITH A, COLLECT(B) AS bs, COLLECT(B.Code) AS codes
WHERE 'ccc' NOT IN codes
RETURN A, bs


问:
The SELECT statement includes a reserved word
So when I try to run my code I get a Runtime Error '3141' "The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect."

Here is my code

```<code>    strSQL5 = " SELECT DatePart('m',[gs_MultiList_Daily/monthly]![Test_Date]) AS Char, MonthName(DatePart('m',[Test_Date])) AS [Month], DatePart('yyyy',[Test_Date]) AS [Year], Sum([gs_MultiList_Daily/monthly].LeaksLogged) AS LeaksLogged, Sum([gs_MultiList_Daily/monthly].[ME Samples]) AS [ME Samples], Sum([gs_MultiList_Daily/monthly].MSampleLogged) AS MSampleLogged, Sum([gs_MultiList_Daily/monthly].Saddle) AS Saddle, Sum([gs_MultiList_Daily/monthly].EntranceDia) AS EntranceDia, Sum([gs_MultiList_Daily/monthly].TappingTee) AS TappingTee, [gs_MultiList_Daily/monthly].LDIW, [gs_MultiList_Daily/monthly].[X-Ray], [gs_MultiList_Daily/monthly].[ETSP Inspection], [gs_MultiList_Daily/monthly].DFT, [gs_MultiList_Daily/monthly].CDT, Sum([gs_MultiList_Daily/monthly].[Mount Photos]) AS [Mount Photos], Sum([gs_MultiList_Daily/monthly].[Melt Index]) AS [Melt Index], Sum([gs_MultiList_Daily/monthly].PSampleLogged) AS PSampleLogged, Sum([gs_MultiList_Daily/monthly].Density) AS Density, " & _
 " Sum([gs_MultiList_Daily/monthly].PE_WT) AS PE_WT, Sum([gs_MultiList_Daily/monthly].OOR) AS OOR, " & _
 " Sum([gs_MultiList_Daily/monthly].Poly_OD) AS Poly_OD, Sum([gs_MultiList_Daily/monthly].[WaterBath Out]) AS [WaterBath Out], Sum([gs_MultiList_Daily/monthly].[WaterBath In]) AS [WaterBath In], Sum([gs_MultiList_Daily/monthly].FTIR) AS FTIR, Sum([gs_MultiList_Daily/monthly].OIT) AS OIT, Sum([gs_MultiList_Daily/monthly].[Steel WT]) AS [Steel WT], Sum([gs_MultiList_Daily/monthly].[Steel Hardness]) AS [Steel Hardness], Sum([gs_MultiList_Daily/monthly].[Steel OD]) AS [Steel OD], Sum([gs_MultiList_Daily/monthly].[TIMP Corrosion]) AS [TIMP Corrosion], Sum([gs_MultiList_Daily/monthly].[Chem Analysis]) AS [Chem Analysis], Sum([gs_MultiList_Daily/monthly].[Steel Mounts]) AS [Steel Mounts], Sum([gs_MultiList_Daily/monthly].[Mounts Polished]) AS [Mounts Polished], Sum([gs_MultiList_Daily/monthly].Etch) AS Etch FROM [gs_MultiList_Daily/monthly] " & _
 " GROUP BY DatePart('m',[gs_MultiList_Daily/monthly]![Test_Date]), MonthName(DatePart('m',[Test_Date])), DatePart('yyyy',[Test_Date]) " & _
 " ORDER BY DatePart('yyyy',[Test_Date]) "
</code>```

This is exactly how it is displayed on the window. The SELECT statement is really long and did not fit in a single line so I broke it up into 3 using " & _ " I also have spaces at both ends of the " so im clueless to where the error is coming from. Can someone please direct me to the correct path ? thank you!

答:
CHAR is a reserved word, don't use it as an alias (or add [] brackets, but really, don't use it).

Generally, when you encounter this error, run each field name through the list of reserved words.

Body:
So when I try to run my code I get a Runtime Error '3141' "The SELECT statement includes a reserved word or an argument name that is misspelled or missing, or the punctuation is incorrect."

Here is my code

    strSQL5 = " SELECT DatePart('m',[gs_MultiList_Daily/monthly]![Test_Date]) AS Char, MonthName(DatePart('m',[Test_Date])) AS [Month], DatePart('yyyy',[Test_Date]) AS [Year], Sum([gs_MultiList_Daily/monthly].LeaksLogged) AS LeaksLogged, Sum([gs_MultiList_Daily/monthly].[ME Samples]) AS [ME Samples], Sum([gs_MultiList_Daily/monthly].MSampleLogged) AS MSampleLogged, Sum([gs_MultiList_Daily/monthly].Saddle) AS Saddle, Sum([gs_MultiList_Daily/monthly].EntranceDia) AS EntranceDia, Sum([gs_MultiList_Daily/monthly].TappingTee) AS TappingTee, [gs_MultiList_Daily/monthly].LDIW, [gs_MultiList_Daily/monthly].[X-Ray], [gs_MultiList_Daily/monthly].[ETSP Inspection], [gs_MultiList_Daily/monthly].DFT, [gs_MultiList_Daily/monthly].CDT, Sum([gs_MultiList_Daily/monthly].[Mount Photos]) AS [Mount Photos], Sum([gs_MultiList_Daily/monthly].[Melt Index]) AS [Melt Index], Sum([gs_MultiList_Daily/monthly].PSampleLogged) AS PSampleLogged, Sum([gs_MultiList_Daily/monthly].Density) AS Density, " & _
 " Sum([gs_MultiList_Daily/monthly].PE_WT) AS PE_WT, Sum([gs_MultiList_Daily/monthly].OOR) AS OOR, " & _
 " Sum([gs_MultiList_Daily/monthly].Poly_OD) AS Poly_OD, Sum([gs_MultiList_Daily/monthly].[WaterBath Out]) AS [WaterBath Out], Sum([gs_MultiList_Daily/monthly].[WaterBath In]) AS [WaterBath In], Sum([gs_MultiList_Daily/monthly].FTIR) AS FTIR, Sum([gs_MultiList_Daily/monthly].OIT) AS OIT, Sum([gs_MultiList_Daily/monthly].[Steel WT]) AS [Steel WT], Sum([gs_MultiList_Daily/monthly].[Steel Hardness]) AS [Steel Hardness], Sum([gs_MultiList_Daily/monthly].[Steel OD]) AS [Steel OD], Sum([gs_MultiList_Daily/monthly].[TIMP Corrosion]) AS [TIMP Corrosion], Sum([gs_MultiList_Daily/monthly].[Chem Analysis]) AS [Chem Analysis], Sum([gs_MultiList_Daily/monthly].[Steel Mounts]) AS [Steel Mounts], Sum([gs_MultiList_Daily/monthly].[Mounts Polished]) AS [Mounts Polished], Sum([gs_MultiList_Daily/monthly].Etch) AS Etch FROM [gs_MultiList_Daily/monthly] " & _
 " GROUP BY DatePart('m',[gs_MultiList_Daily/monthly]![Test_Date]), MonthName(DatePart('m',[Test_Date])), DatePart('yyyy',[Test_Date]) " & _
 " ORDER BY DatePart('yyyy',[Test_Date]) "

This is exactly how it is displayed on the window. The SELECT statement is really long and did not fit in a single line so I broke it up into 3 using " & _ " I also have spaces at both ends of the " so im clueless to where the error is coming from. Can someone please direct me to the correct path ? thank you!


问:
How to pass string paramter in Jenkins pipeline to customize emailext?
I am trying to use the env parameters to customize the email body. But i not able to achieve it.

String parameter1 : NAMESPACE = abcd

Jenkins pipeline :

```<code>  agent{ label 'apps' }
  stages {
    stage("Checkout Sourcecode") {
                                xxxxxx
                    }
    stage('Create namespace'){
                                steps {
                                    sh """kubectl create namespace ${env.NAMESPACE}"""
                                        }
                                    }
    stage ("Clearing Workspace"){
                                steps{
                                    cleanWs()
                                }
                            }
    }
    post {
    success {
        emailext body: '''Hi,
${env.NAMESPACE} is created.
Build is ${currentBuild.currentResult}
Regards,
DT''', subject: 'Build ${BUILD_STATUS} - Build #${BUILD_NUMBER}', to: 'abc@xyz.com'
    }
}
}
</code>```

Email output:

```<code>Subject: Build Success - Build #8

Hi,
${env.NAMESPACE} is created.
Build is ${currentBuild.currentResult}

Regards,
DT
</code>```

Expected output is getting the value of NAMESPACE and currentBuild.currentResult.
What am i doing wrong?

答: You need to use double-quotes (triple double-quotes) to use string interpolation. See here for more info. https://stackoverflow.com/a/37465198/10531450</p>

Body:
I am trying to use the env parameters to customize the email body. But i not able to achieve it.

String parameter1 : NAMESPACE = abcd

Jenkins pipeline :

  agent{ label 'apps' }
  stages {
    stage("Checkout Sourcecode") {
                                xxxxxx
                    }
    stage('Create namespace'){
                                steps {
                                    sh """kubectl create namespace ${env.NAMESPACE}"""
                                        }
                                    }
    stage ("Clearing Workspace"){
                                steps{
                                    cleanWs()
                                }
                            }
    }
    post {
    success {
        emailext body: '''Hi,
${env.NAMESPACE} is created.
Build is ${currentBuild.currentResult}
Regards,
DT''', subject: 'Build ${BUILD_STATUS} - Build #${BUILD_NUMBER}', to: 'abc@xyz.com'
    }
}
}

Email output:

Subject: Build Success - Build #8

Hi,
${env.NAMESPACE} is created.
Build is ${currentBuild.currentResult}

Regards,
DT

Expected output is getting the value of NAMESPACE and currentBuild.currentResult.
What am i doing wrong?


答: It looks like the if/elif statements arent included in the while loop so the variables arent actually getting updated. Try indenting that block so its inside the loop and see if that works!</p>

Title: Python Program - Use a while loop to calculate the amount of letter grades from user input


问:
Pattern in a Numpy Series
I have a Python Numpy array:

```<code>a = np.array([1,0,5,6,0,1,2,5,0,1,2,8,0,0,0,0,1,1,2,3,0,0,10,0])
</code>```

I am trying to find the following:

a) Between each zero, return any sequential set of numbers where sum is equal or greater than 10

```<code>5,6
1,2,8
10
</code>```

b) Between every set of sequential 5 numbers, return sequential set of numbers where sum is equal or greater than 10

```<code>1,0,5,6,0
0,5,6,0,1
5,6,0,1,2
6,0,1,2,5
2,5,0,1,2
5,0,1,2,8
0,1,2,8,0
1,2,8,0,0
2,8,0,0,0
2,3,0,0,10
3,0,0,10,0
</code>```

答:
You can take slices inside a list comprehension to do this.</p>

```<code>idxs = np.where(a==0)[0]
group1 = [a[idxs[i-1]+1:idxs[i]] for i in range(1,len(idxs)) if a[idxs[i-1]+1:idxs[i]].sum()>=10]
group2 = [a[i:i+5] for i in range(len(a)-4) if a[i:i+5].sum()>=10]
</code>```

Title: Pattern in a Numpy Series

Body:
I have a Python Numpy array:

a = np.array([1,0,5,6,0,1,2,5,0,1,2,8,0,0,0,0,1,1,2,3,0,0,10,0])

I am trying to find the following:

a) Between each zero, return any sequential set of numbers where sum is equal or greater than 10

5,6
1,2,8
10

b) Between every set of sequential 5 numbers, return sequential set of numbers where sum is equal or greater than 10

1,0,5,6,0
0,5,6,0,1
5,6,0,1,2
6,0,1,2,5
2,5,0,1,2
5,0,1,2,8
0,1,2,8,0
1,2,8,0,0
2,8,0,0,0
2,3,0,0,10
3,0,0,10,0

Body:
You can take slices inside a list comprehension to do this.

idxs = np.where(a==0)[0]
group1 = [a[idxs[i-1]+1:idxs[i]] for i in range(1,len(idxs)) if a[idxs[i-1]+1:idxs[i]].sum()>=10]
group2 = [a[i:i+5] for i in range(len(a)-4) if a[i:i+5].sum()>=10]


问:
Why do undefined constants evaluate to true?
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

```<code><?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>
</code>```

The above example prints 'Huh?'

Thanks so much for your help! :)

答:
Note that constant name must always be quoted when defined.

e.g.

define('MY_CONST','blah') - correct

define(MY_CONST,'blah') - incorrect

also

```<code><?php
 if (DEBUG) {
    // echo some sensitive data.
 }
 ?>
 and saw this warning:
 "Use of undefined constant DEBUG - assumed 'DEBUG'"

A clearer workaround is to use
 <?php
 if (defined('DEBUG')) {
    // echo some sensitive data.
 }
 ?>
</code>```

See http://php.net/manual/en/language.constants.php

Body:
Stupid question - I'm surprised this one has bitten me.  Why do undefined constants in PHP evaluate to true?

Test case:

<?php
    if(WHATEVER_THIS_ISNT_DEFINED)
        echo 'Huh?';
?>

The above example prints 'Huh?'

Thanks so much for your help! :)

Body:
Note that constant name must always be quoted when defined.

e.g.

define('MY_CONST','blah') - correct

define(MY_CONST,'blah') - incorrect

also

<?php
 if (DEBUG) {
    // echo some sensitive data.
 }
 ?>
 and saw this warning:
 "Use of undefined constant DEBUG - assumed 'DEBUG'"

A clearer workaround is to use
 <?php
 if (defined('DEBUG')) {
    // echo some sensitive data.
 }
 ?>

See http://php.net/manual/en/language.constants.php


问:
What's the difference between a 302 and a 307 redirect?
What's the difference between a 302 FOUND and a 307 TEMPORARY REDIRECT HTTP response?

The W3 spec seems to indicate that they're both used for temporary redirects, and neither can be cached unless the response specifically allows it.

答:
302 is temporary redirect, which is generated by the server whereas 307 is internal redirect response generated by the browser. Internal redirect means that redirect is done automatically by browser internally, basically the browser alters the entered url from http to https in get request by itself before making the request so request for unsecured connection is never made to the internet. Whether browser will alter the url to https or not depends upon the hsts preload list that comes preinstalled with the browser. You can also add any site which support https to the list by entering the domain in the hsts preload list of your own browser which is at chrome://net-internals/#hsts.One more thing website domains can be added by their owners to preload list by filling up the form at https://hstspreload.org/ so that it comes preinstalled in browsers for every user even though I mention you can do particularly for yourself also.

Let me explain with an example:

I made a get request to http://www.pentesteracademy.com which supports only https and I don't have that domain in my hsts preload list on my browser as site owner has not registered for it to come with preinstalled hsts preload list.

GET request for unsecure version of the site is redirected to secure version(see http header named location for that in response in above image).

Now I add the site to my own browser preload list by adding its domain in Add hsts domain form at chrome://net-internals/#hsts, which modifies my personal preload list on my chrome browser.Be sure to select include subdomains for STS option there.

Let's see the request and response for the same website now after adding it to hsts preload list.

 you can see the internal redirect 307 there in response headers, actually this response is generated by your browser not by server.

Also HSTS preload list can help prevent users reach the unsecure version of site as 302 redirect are prone to mitm attacks.

Hope I somewhat helped you understand more about redirects.