问:
VBA code to Sum using subtotal for different columns
I am having the code in VBA that will sum the entire column that i filtered and that sum count is copying  it in another sheet for calculation. I have different columns each time am writing the code separate.

Can some one help me out write in a single line so that i can reduce the lines of code.

Please find the code.

```<code>worksheets("Sheet2").Range("B10") = WorksheetFunction.Subtotal(9, Range("AP2:AP" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("C10") = WorksheetFunction.Subtotal(9, Range("BT2:BT" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("D10") = WorksheetFunction.Subtotal(9, Range("CZ2:CZ" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("E10") = WorksheetFunction.Subtotal(9, Range("EE2:EE" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("F10") = WorksheetFunction.Subtotal(9, Range("FK2:FK" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("G10") = WorksheetFunction.Subtotal(9, Range("GP2:GP" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("H10") = WorksheetFunction.Subtotal(9, Range("HV2:HV" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("I10") = WorksheetFunction.Subtotal(9, Range("JB2:JB" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("J10") = WorksheetFunction.Subtotal(9, Range("KG2:KG" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("K10") = WorksheetFunction.Subtotal(9, Range("LM2:LM" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("L10") = WorksheetFunction.Subtotal(9, Range("MR2:MR" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("M10") = WorksheetFunction.Subtotal(9, Range("NX2:NX" & Rows(Rows.Count).End(xlUp).Row))
</code>```

答:
Here is my attempt to parametrize the code, so that you can enter columns and output range and eventually turn it into a function if needed. Note, if number of output cells differ than number of columns totalled, an error will be produced. Should be wiser to check if these arrays differ and stop the code with a warning.

Issue found: Using Debug.Print() and a section of the original formula related to finding last row I found it returns 1 for all columns. After the change the original formula would look like:

```<code>Sub populateTotals()
        Dim sht As Worksheet: Set sht = Worksheets("Sheet2")
        Dim mycols As String: mycols = "G,H,I,J"
        Set Rng = sht.Range("B10:E10")

        SplitCatcher = Split(mycols, ",")

        Dim i As Integer: i = 0

        For Each Cell In Rng
            Cell.Value = WorksheetFunction.Subtotal(9, Range(SplitCatcher(i) & "2:" & SplitCatcher(i) & Cells(sht.Rows.Count, SplitCatcher(i)).End(xlUp).Row))
            i = i + 1
        Next Cell

End Sub
</code>```

I tested it with a subtotal function and filtered out one row. It returns correct results.

Body:
I am having the code in VBA that will sum the entire column that i filtered and that sum count is copying  it in another sheet for calculation. I have different columns each time am writing the code separate.

Can some one help me out write in a single line so that i can reduce the lines of code.

Please find the code.

worksheets("Sheet2").Range("B10") = WorksheetFunction.Subtotal(9, Range("AP2:AP" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("C10") = WorksheetFunction.Subtotal(9, Range("BT2:BT" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("D10") = WorksheetFunction.Subtotal(9, Range("CZ2:CZ" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("E10") = WorksheetFunction.Subtotal(9, Range("EE2:EE" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("F10") = WorksheetFunction.Subtotal(9, Range("FK2:FK" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("G10") = WorksheetFunction.Subtotal(9, Range("GP2:GP" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("H10") = WorksheetFunction.Subtotal(9, Range("HV2:HV" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("I10") = WorksheetFunction.Subtotal(9, Range("JB2:JB" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("J10") = WorksheetFunction.Subtotal(9, Range("KG2:KG" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("K10") = WorksheetFunction.Subtotal(9, Range("LM2:LM" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("L10") = WorksheetFunction.Subtotal(9, Range("MR2:MR" & Rows(Rows.Count).End(xlUp).Row))
worksheets("Sheet2").Range("M10") = WorksheetFunction.Subtotal(9, Range("NX2:NX" & Rows(Rows.Count).End(xlUp).Row))

Body:
Here is my attempt to parametrize the code, so that you can enter columns and output range and eventually turn it into a function if needed. Note, if number of output cells differ than number of columns totalled, an error will be produced. Should be wiser to check if these arrays differ and stop the code with a warning.

Issue found: Using Debug.Print() and a section of the original formula related to finding last row I found it returns 1 for all columns. After the change the original formula would look like:

Sub populateTotals()
        Dim sht As Worksheet: Set sht = Worksheets("Sheet2")
        Dim mycols As String: mycols = "G,H,I,J"
        Set Rng = sht.Range("B10:E10")

        SplitCatcher = Split(mycols, ",")

        Dim i As Integer: i = 0

        For Each Cell In Rng
            Cell.Value = WorksheetFunction.Subtotal(9, Range(SplitCatcher(i) & "2:" & SplitCatcher(i) & Cells(sht.Rows.Count, SplitCatcher(i)).End(xlUp).Row))
            i = i + 1
        Next Cell

End Sub

I tested it with a subtotal function and filtered out one row. It returns correct results.


来源: stackexchange

问:
Override PHP base dependency in composer
I try  to install Laravel 5.1 on a host which only has PHP 5.5.6. While I asked the customer to upgrade, this might be not possible/feasible.

So I am getting:

```<code>- This package requires php >=5.5.9 but your PHP version (5.5.6)
   does not satisfy that requirement.
</code>```

on composer.phar install.

Is there a way to do a composer install which ignores this dependency?

I think it should be safe, as there are only bug-fixes from 5.5.6 to 5.5.9.

答:
Just add these lines in composer.json file

```<code>  "config": {
    "platform": {
      "php": "5.5.9"
    }
  },
</code>```

Then run command,

```<code>composer update or install
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I try  to install Laravel 5.1 on a host which only has PHP 5.5.6. While I asked the customer to upgrade, this might be not possible/feasible.

So I am getting:

- This package requires php >=5.5.9 but your PHP version (5.5.6)
   does not satisfy that requirement.

on composer.phar install.

Is there a way to do a composer install which ignores this dependency?

I think it should be safe, as there are only bug-fixes from 5.5.6 to 5.5.9.

Body:
Just add these lines in composer.json file

  "config": {
    "platform": {
      "php": "5.5.9"
    }
  },

Then run command,

composer update or install

ContentLicense: CC BY-SA 4.0


问:
Why can't I execute system("xxx.Py -yyy -zzz...") on Ruby?
My OS is Win7

I have a python file(xxx.py), and I need execute it on ruby

my ruby code:

```<code>system("xxx.py -yyy -zzz");
</code>```

and run it no result, but it can run on cmd(xxx.py -yyy -zzz)

and ruby can run system("java -h"); or system("python -h"); success.

What's problem with me???

答:
Just to fill out Dogberts answer in full

Using system("python xxx.py -yyy -zzz") should prrovide you with what you want. This is because your python script is probably not +777 or is missing its shebang line.

Body:
My OS is Win7

I have a python file(xxx.py), and I need execute it on ruby

my ruby code:

system("xxx.py -yyy -zzz");

and run it no result, but it can run on cmd(xxx.py -yyy -zzz)

and ruby can run system("java -h"); or system("python -h"); success.

What's problem with me???


问:
How to always run a service in the background?
I am in the process of creating an app that is similar to the built-in SMS app.

What I need:

a service that is always running in the background

every 5 min. the service checks the current location of the device and calls a web service

if certain criteria are met, the service should generate a notification (just like the SMS app)

when the notification is clicked, the user is taken to the app (just like the SMS app)

when the app is installed the service should be started

when the device is rebooted, the service should be started

What I have tried:

- running a regular service which worked just fine until Android kills the service

- using the AlarmManager to make the 5 min. interval call to a service. But I was not able to make this work.

答:
According to me when you want your service to run always means that it shouldn't get stopped when the app is killed, because if your app is running or is in the background anyways your service will be running. When you kill the app while a service is running the onTaskRemoved function is triggered.

```<code>@Override
        public void onTaskRemoved(Intent rootIntent) {
            Log.d(TAG, "onTaskRemoved: removed");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis() + 10000);
((AlarmManager) getSystemService(Context.ALARM_SERVICE)).setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), PendingIntent.getService(getApplicationContext(), 0, new Intent(getApplicationContext(), RegisterReceiverService.class), 0));
            super.onTaskRemoved(rootIntent);
        }
</code>```

So basically once you kill the app the service will be started after 10 seconds.
Note: In case you want to use

```<code>AlarmManager.ELAPSED_REALTIME_WAKEUP
</code>```

the minimum time after which you'll be able to restart the service will be 15 minutes.

Remember you also need to start the service on reboot using BroadcastReceiver.

Body:
According to me when you want your service to run always means that it shouldn't get stopped when the app is killed, because if your app is running or is in the background anyways your service will be running. When you kill the app while a service is running the onTaskRemoved function is triggered.

@Override
        public void onTaskRemoved(Intent rootIntent) {
            Log.d(TAG, "onTaskRemoved: removed");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis() + 10000);
((AlarmManager) getSystemService(Context.ALARM_SERVICE)).setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), PendingIntent.getService(getApplicationContext(), 0, new Intent(getApplicationContext(), RegisterReceiverService.class), 0));
            super.onTaskRemoved(rootIntent);
        }

So basically once you kill the app the service will be started after 10 seconds.
Note: In case you want to use

AlarmManager.ELAPSED_REALTIME_WAKEUP

the minimum time after which you'll be able to restart the service will be 15 minutes.

Remember you also need to start the service on reboot using BroadcastReceiver.


问:
Change the color of the SAS window in the taskbar
Hello to all the experts,

I would like to know if it was possible to change the color of the SAS window in the taskbar when the request is finished.
This can be very practical when you have several open SAS windows, rather than clicking on each of them to verify that the request is complete, you will click directly on the correct window.

Here's what it will look like (not on SAS):
enter image description here

I know that in older versions of SAS it was possible to do this (probably a default option).

Win 10
Sas Guide 7.1

A big thank you to you,

答:
SAS would have to update it's Windows clients (EG 7, EG 8, DMS) to utilize the Windows API classes Microsoft.WindowsAPICodePack.Shell.Taskbar, ProgressBar, and OverlayIcon to communicate the running task(s) progress states.

From a customized perspective a custom task might be able to be written that would be manipulate the task bar icon of the EG process it is running in.

Or a task bar manipulating powershell script could be invoked from the System Command example custom task.

Other custom task resources: 11 super-useful custom tasks for SAS Enterprise Guide article includes information about and download links for:

SAS Catalog Explorer

SAS System Options Viewer

Macro Variable Viewer

Project Reviewer

Task Property Viewer

Copy Files to/from SAS Session

Message Prompt

System Command

DATA Step from Data Set

Compress SAS Data

Calculate Data Cardinalities


问:
How to update Bokeh source with CustomJS
I am having some troubles while trying to update my Bokeh source when using a Select widget and CustomJS. CustomJS is a mandatory requirement in this case, so no def: function can be used.
The below code returns the data visualisation but it does not refresh as, I guess, the JS code is not properly written and I got no way to debug it (if someone knows how, please its indeed the best answer I could get).

The main idea is to filter my source based on the value selected on the Select widget.

Any ideas??

```<code>
source = ColumnDataSource(data=dict(
    x=gx,
    y=gy,
    recty=recty,
    colors=colors,
    filter_info= filter_info))

select = Select(title="Option:", value="All", options=["All", "1", "2", "3", "4", "5", "6+"])

renderer_source = source

# Add the slider
code = """
    var value_filter_info = cb_obj.value;

    if value_assignments == 'All' {
      new_source_data['x'] =  source.data['x'];
      new_source_data['y'] =  source.data['y'];
      new_source_data['recty'] =  source.data['recty'];
      new_source_data['colors'] =  source.data['colors'];
    } else {
      new_source_data['x'] =  source.data['x'][source.data['filter_info']==value_filter_info];
      new_source_data['y'] =  source.data['y'][source.data['filter_info']==value_filter_info];
      new_source_data['recty'] =  source.data['recty'][source.data['filter_info']==value_filter_info];
      new_source_data['colors'] =  source.data['colors'][source.data['filter_info']==value_filter_info];

    }

    renderer_source.data= new_source_data;
    renderer_source.change.emit();

"""

callback = CustomJS(args=dict(source=source, renderer_source=renderer_source), code=code)
select.js_on_change('value', callback)

p = figure(plot_width=1200, plot_height=400, x_range=(0,100), y_range=(0,1000))

p.rect(x='x', y='recty',  width=1, height=1, color='colors', source=renderer_source, line_color=None, fill_alpha=1, width_units="data", height_units="data")

plot_layout = column(select,p)
show(plot_layout)
output_notebook()
</code>```

Many thanks!

答:
So I found a solution that can be aesthetically, programatically, and visually improved but at least the outcome is shown.

Following the advice by @bigreddot on indexing and overwriting, I managed to write the current CustomJS code:

```<code>code = """
    var render=renderer_source.data;
    var data=source.data;
    var data_assignment = data['assignments'];
    var value_assignments = cb_obj.value;

    var data_x=data['x'];
    var data_y=data['y'];
    var data_recty=data['recty'];
    var data_colors=data['colors'];

    var render_x=render['x'];
    var render_y=render['y'];
    var render_recty=render['recty'];
    var render_colors=render['colors'];

    var x = [];
    var y = [];
    var recty = [];
    var colors = [];

    render_x=[];
    render_y=[];
    render_recty=[];
    render_colors=[];

    for (var i=0;i<data_assignment.length; i++){

        if (value_assignments == 'All') {
          x.push(data_x[i]);
          y.push(data_y[i]);
          recty.push(data_recty[i]);
          colors.push(data_colors[i]);
        } else if (data_assignment[i]==value_assignments) {
          x.push(data_x[i]);
          y.push(data_y[i]);
          recty.push(data_recty[i]);
          colors.push(data_colors[i]);

        }
    }

    renderer_source.data['x']=x;
    renderer_source.data['y']=y;
    renderer_source.data['recty']=recty;
    renderer_source.data['colors']=colors;

    renderer_source.change.emit();

"""
</code>```

Body:
I am having some troubles while trying to update my Bokeh source when using a Select widget and CustomJS. CustomJS is a mandatory requirement in this case, so no def: function can be used.
The below code returns the data visualisation but it does not refresh as, I guess, the JS code is not properly written and I got no way to debug it (if someone knows how, please its indeed the best answer I could get).

The main idea is to filter my source based on the value selected on the Select widget.

Any ideas??

source = ColumnDataSource(data=dict(
    x=gx,
    y=gy,
    recty=recty,
    colors=colors,
    filter_info= filter_info))

select = Select(title="Option:", value="All", options=["All", "1", "2", "3", "4", "5", "6+"])

renderer_source = source

# Add the slider
code = """
    var value_filter_info = cb_obj.value;

    if value_assignments == 'All' {
      new_source_data['x'] =  source.data['x'];
      new_source_data['y'] =  source.data['y'];
      new_source_data['recty'] =  source.data['recty'];
      new_source_data['colors'] =  source.data['colors'];
    } else {
      new_source_data['x'] =  source.data['x'][source.data['filter_info']==value_filter_info];
      new_source_data['y'] =  source.data['y'][source.data['filter_info']==value_filter_info];
      new_source_data['recty'] =  source.data['recty'][source.data['filter_info']==value_filter_info];
      new_source_data['colors'] =  source.data['colors'][source.data['filter_info']==value_filter_info];

    }

    renderer_source.data= new_source_data;
    renderer_source.change.emit();

"""

callback = CustomJS(args=dict(source=source, renderer_source=renderer_source), code=code)
select.js_on_change('value', callback)

p = figure(plot_width=1200, plot_height=400, x_range=(0,100), y_range=(0,1000))

p.rect(x='x', y='recty',  width=1, height=1, color='colors', source=renderer_source, line_color=None, fill_alpha=1, width_units="data", height_units="data")

plot_layout = column(select,p)
show(plot_layout)
output_notebook()

Many thanks!

Body:
So I found a solution that can be aesthetically, programatically, and visually improved but at least the outcome is shown.

Following the advice by @bigreddot on indexing and overwriting, I managed to write the current CustomJS code:

code = """
    var render=renderer_source.data;
    var data=source.data;
    var data_assignment = data['assignments'];
    var value_assignments = cb_obj.value;

    var data_x=data['x'];
    var data_y=data['y'];
    var data_recty=data['recty'];
    var data_colors=data['colors'];

    var render_x=render['x'];
    var render_y=render['y'];
    var render_recty=render['recty'];
    var render_colors=render['colors'];

    var x = [];
    var y = [];
    var recty = [];
    var colors = [];

    render_x=[];
    render_y=[];
    render_recty=[];
    render_colors=[];

    for (var i=0;i<data_assignment.length; i++){

        if (value_assignments == 'All') {
          x.push(data_x[i]);
          y.push(data_y[i]);
          recty.push(data_recty[i]);
          colors.push(data_colors[i]);
        } else if (data_assignment[i]==value_assignments) {
          x.push(data_x[i]);
          y.push(data_y[i]);
          recty.push(data_recty[i]);
          colors.push(data_colors[i]);

        }
    }

    renderer_source.data['x']=x;
    renderer_source.data['y']=y;
    renderer_source.data['recty']=recty;
    renderer_source.data['colors']=colors;

    renderer_source.change.emit();

"""


问:
Intuit QuickBooks Merchant Service + php
I try integrate my web applacation with Intuit QuickBooks Merchant Service.
I found this https://idnforums.intuit.com/messageview.aspx?catid=50&threadid=11829

But I don't understand what is it $connection_ticket, where I can get it?

Thanks.

答:
I went through the same hazzle a few years ago.  It is not an obvious issue.  A connection ticket is actually an approval from the Intuit Payment underwriting to allow your app integtration with the Payment gateway. In my particular situation, I was a merchant account holder which allowed me to accept credit card using  sent QuickBooks Online invoices and the use of a virtual terminal at the Intuit Merchant Solution website.

But to my surprise, this does not mean that you get automatic authority to develop apps to do the same thing.  In my particular scenario, I want to link my website shopping cart to Intuit Payments.  But at the end of hundreds of hours invested in this development work, I was decnied a connection ticket.

Again, this happened about 4 years ago. I am not sure if now days there are flexible about these things or have finally come to trust their own SKD or API tools issue to developers.


问:
Google Mock and override keyword
Is there a macro in Google Mock to ensure compile time check of the signature of f() by appending the override keyword to the macro substitution:

```<code>struct I
{
    virtual void f() = 0;
};

struct MockI
{
    MOCK_METHOD0(f, void()); // this will define another function if f signature changes
                             // leading to weird runtime test failures
};
</code>```

答:
Simply derive your mock from base pure virtual class.

```<code>struct MockI : I
{
    MOCK_METHOD0(f, void());
};
</code>```

And you will get compile error if signature of f is changed in base class only. No upgrade or manual change of gmock is needed.

Title: Google Mock and override keyword

Body:
Is there a macro in Google Mock to ensure compile time check of the signature of f() by appending the override keyword to the macro substitution:

struct I
{
    virtual void f() = 0;
};

struct MockI
{
    MOCK_METHOD0(f, void()); // this will define another function if f signature changes
                             // leading to weird runtime test failures
};

Body:
Simply derive your mock from base pure virtual class.

struct MockI : I
{
    MOCK_METHOD0(f, void());
};

And you will get compile error if signature of f is changed in base class only. No upgrade or manual change of gmock is needed.


问:
Selenium can't find element until element is inspected
I ran into a similar problem described here:
Selenium - can't find visible element until HTML is inspected?
But the solution indicated there did not help me.

There's a website that has the following dropbox (I can see them when I inspect the page):

No error is raised when I attempt to switch to the desired frame, no elements are found with id = UIFormControl-5.

So after inspecting the dropbox (id = UIFormControl-5) and doing no other change whatsoever, the elements are there, as if the mere act of looking at the source code of the webpage changed the outcome of the result. What could possibly be happening here?

I'm using the java selenium code

```<code>            driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.flex-grow-1")));
            wait.until(ExpectedConditions.presenceOfElementLocated(By.id("UIFormControl-5")));
            driver.findElement(By.id("UIFormControl-5")).click();
</code>```

答:
Induce WebDriverWait() and wait for frameToBeAvailableAndSwitchToIt()

Induce WebDriverWait() and wait for elementToBeClickable() and then click.

```<code>new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe.flex-grow-1")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("UIFormControl-5"))).click();
</code>```

Body:
I ran into a similar problem described here:
Selenium - can't find visible element until HTML is inspected?
But the solution indicated there did not help me.

There's a website that has the following dropbox (I can see them when I inspect the page):

No error is raised when I attempt to switch to the desired frame, no elements are found with id = UIFormControl-5.

So after inspecting the dropbox (id = UIFormControl-5) and doing no other change whatsoever, the elements are there, as if the mere act of looking at the source code of the webpage changed the outcome of the result. What could possibly be happening here?

I'm using the java selenium code

            driver.switchTo().frame(driver.findElement(By.cssSelector("iframe.flex-grow-1")));
            wait.until(ExpectedConditions.presenceOfElementLocated(By.id("UIFormControl-5")));
            driver.findElement(By.id("UIFormControl-5")).click();

Body:
Induce WebDriverWait() and wait for frameToBeAvailableAndSwitchToIt()

Induce WebDriverWait() and wait for elementToBeClickable() and then click.

new WebDriverWait(driver, 20).until(ExpectedConditions.frameToBeAvailableAndSwitchToIt(By.cssSelector("iframe.flex-grow-1")));
new WebDriverWait(driver, 20).until(ExpectedConditions.elementToBeClickable(By.id("UIFormControl-5"))).click();


问:
React Navigation 5 - Native Stack Navigator with custom header which has a searchbar
I'm currently in a project for which we are using React Navigation 5 with the native stack navigator due to its increased performance. We are needing to add a searchbar to the header cause the client isn't gonna like it to be somewhere else. Is there any way to make a custom header?
using options={{ headerShown: false }} is not an option cause inside the native stack navigator we have a bottom stack navigator and inside this bottom tab navigator we have a top stack navigator with the screens inside it. So using headerShown: false and a custom header inside the screens would only render it below the top tabs and that would not be acceptable.
Any ideas on how to make this? is using the common stack navigator with a custom react element as the header prop the only solution?

Greatly appreciate any ideas on how to solve this.

答:
pass navigationOptions in your component

export default class Test extends Component{

    static navigationOptions = ({ navigation }) => ({
        headerTitle: "Test",
        headerStyle: {
          backgroundColor: #f1f1f1,
          elevation: 0
        },
        headerTintColor: "#000",
      });

    render(){
        return(<View><Text>Test App</Text></View>);
    }
}
```


问:
JS: async function
I'am new in JS and had some problems with async function.
I have a function, that return data from MongoDB. I create a promise, and get collection with empty object.

```<code>async function getRating(item, applicant) {
let arr = await Applicant.find({ proff: item }).sort({ ball: "desc" });
let rating = arr.findIndex(item => item._id.equals(applicant._id));
let spec = await Spec.findById(item);
const el = { spec, rating };
return el;}

router.get("/test", auth, async (req, res) => {
let applicant = await Applicant.findOne({ user: req.user.id });
let ratings = [];
applicant.proff.forEach(item => {
    const rating = getRating(item, applicant)
    .then(rating => ratings.push(rating))
    .catch(err => console.log(err));
     ratings.push(rating);
});
await res.json(ratings);
});
</code>```

When I check in Postman, this return me array: [{},{},{}]

Please help.

答: Async Functions returns promise so you need to use await before getRating.</p>

Title: JS: async function

Body:
I'am new in JS and had some problems with async function.
I have a function, that return data from MongoDB. I create a promise, and get collection with empty object.

async function getRating(item, applicant) {
let arr = await Applicant.find({ proff: item }).sort({ ball: "desc" });
let rating = arr.findIndex(item => item._id.equals(applicant._id));
let spec = await Spec.findById(item);
const el = { spec, rating };
return el;}

router.get("/test", auth, async (req, res) => {
let applicant = await Applicant.findOne({ user: req.user.id });
let ratings = [];
applicant.proff.forEach(item => {
    const rating = getRating(item, applicant)
    .then(rating => ratings.push(rating))
    .catch(err => console.log(err));
     ratings.push(rating);
});
await res.json(ratings);
});

When I check in Postman, this return me array: [{},{},{}]

Please help.


问:
.NET Core API -> Updating an object also update previously loaded object
I have implemented a system to log every create/update/delete actions on all controllers.
Basically, the idea is simple as when I update an object in the Update controller, I first do a Get then Update so I have access to original object and updated object as follow.

```<code>public async Task<IActionResult> Update([FromRoute] Guid groupId, [FromRoute] Guid licenseId, [FromBody] UpdateLicenseRequest request)
    {
        var cLicense = await _licenseService.GetAsync(groupId, licenseId);

        if (cLicense == null)
            return BadRequest(_localizer["LicenseNotExist"]);

        var uLicense = await _licenseService.UpdateAsync(cLicense, _mapper.Map<License>(request));

        if (uLicense == null)
            return BadRequest();

        await _auditService.CreateAsync(AuditTypeEnum.SVAULT_LICENSE_UPDATE, cLicense, uLicense);

        return Ok(_mapper.Map<LicenseResponse>(uLicense));
    }
</code>```

Here is the detail of the GetAsync method :

```<code>public async Task<License> GetAsync(Guid groupId, Guid licenseId)
    {
        RSUser cRSUser = await _cloudService.GetCloudAsync(groupId);

        var rxLicense = await Task.Run(() =>
        {
            return cRSUser.getLicense(licenseId.ToString());
        });

        List<LicenseState> lstStates = await _context.LicenseStates.ToListAsync();
        List<LicenseType> lstTypes = await _context.LicenseTypes.ToListAsync();
        List<LicenseStatus> lstStatus = await _context.LicenseStatus.ToListAsync();
        List<LicenseProduct> lstProducts = await _context.LicenseProducts.ToListAsync();
        Dictionary<string, Group> dcGroups = _context.GroupProperties.AsNoTracking().Where(w => w.Name == GroupProperties.community_id.ToString() && (w.Value == rxLicense.P_community_id || w.Value == rxLicense.P_community_customer_id || w.Value == rxLicense.P_community_reseller_id)).Include(w => w.Group).ToDictionary(w => w.Value, w => w.Group);

        if (rxLicense == null)
            return null;

        return License.ToObject(rxLicense, dcGroups, lstStates, lstTypes, lstStatus, lstProducts);
    }
</code>```

Also find the detail of the Update method :

```<code>public async Task<License> UpdateAsync(License cLicense, License nLicense)
    {
        RSUser cRSUser = await _cloudService.GetCloudAsync(cLicense.Group.Id);

        var result = await Task.Run(() =>
        {
            cLicense.TypeId = nLicense.TypeId;
            cLicense.DataLimit = nLicense.DataLimit;
            cLicense.Email = nLicense.Email;
            cLicense.Notes = nLicense.Notes;

            if (cLicense.TypeId == 8)
                cLicense.DataLimit = 0;

            return cRSUser.updateLicense(cLicense.ToRSUserClass(), new List<RX_licensemode>() { new RX_licensemode() { P_id = nLicense.ProductId.ToString().ToUpper() } }); ;
        });

        if (result != RSC_errorcode.success)
            return null;

        return await GetAsync(cLicense.Group.Id, cLicense.Id);
    }
</code>```

When I do debug and make a stop on cLicense, I see that this object is the current License (which is what I want) but as soon as the UpdateAsync method runs, cLicense is also updated while I want it to remain as the original object.

Does anyone has already had same behavior ? I'm sure this is a normal process but I don't know how to have it working as I wish.

Feel free to ask if anything is not clear enough.
Regards,

答: When you pass cLicense to UpdateAsync, you aren't passing a copy, you are passing THE cLicence.  In UpdateAsync you are setting the properties of cLicense to the values of nLicense, which is why you are seeing the values change.

Body:
I have implemented a system to log every create/update/delete actions on all controllers.
Basically, the idea is simple as when I update an object in the Update controller, I first do a Get then Update so I have access to original object and updated object as follow.

public async Task<IActionResult> Update([FromRoute] Guid groupId, [FromRoute] Guid licenseId, [FromBody] UpdateLicenseRequest request)
    {
        var cLicense = await _licenseService.GetAsync(groupId, licenseId);

        if (cLicense == null)
            return BadRequest(_localizer["LicenseNotExist"]);

        var uLicense = await _licenseService.UpdateAsync(cLicense, _mapper.Map<License>(request));

        if (uLicense == null)
            return BadRequest();

        await _auditService.CreateAsync(AuditTypeEnum.SVAULT_LICENSE_UPDATE, cLicense, uLicense);

        return Ok(_mapper.Map<LicenseResponse>(uLicense));
    }

Here is the detail of the GetAsync method :

public async Task<License> GetAsync(Guid groupId, Guid licenseId)
    {
        RSUser cRSUser = await _cloudService.GetCloudAsync(groupId);

        var rxLicense = await Task.Run(() =>
        {
            return cRSUser.getLicense(licenseId.ToString());
        });

        List<LicenseState> lstStates = await _context.LicenseStates.ToListAsync();
        List<LicenseType> lstTypes = await _context.LicenseTypes.ToListAsync();
        List<LicenseStatus> lstStatus = await _context.LicenseStatus.ToListAsync();
        List<LicenseProduct> lstProducts = await _context.LicenseProducts.ToListAsync();
        Dictionary<string, Group> dcGroups = _context.GroupProperties.AsNoTracking().Where(w => w.Name == GroupProperties.community_id.ToString() && (w.Value == rxLicense.P_community_id || w.Value == rxLicense.P_community_customer_id || w.Value == rxLicense.P_community_reseller_id)).Include(w => w.Group).ToDictionary(w => w.Value, w => w.Group);

        if (rxLicense == null)
            return null;

        return License.ToObject(rxLicense, dcGroups, lstStates, lstTypes, lstStatus, lstProducts);
    }

Also find the detail of the Update method :

public async Task<License> UpdateAsync(License cLicense, License nLicense)
    {
        RSUser cRSUser = await _cloudService.GetCloudAsync(cLicense.Group.Id);

        var result = await Task.Run(() =>
        {
            cLicense.TypeId = nLicense.TypeId;
            cLicense.DataLimit = nLicense.DataLimit;
            cLicense.Email = nLicense.Email;
            cLicense.Notes = nLicense.Notes;

            if (cLicense.TypeId == 8)
                cLicense.DataLimit = 0;

            return cRSUser.updateLicense(cLicense.ToRSUserClass(), new List<RX_licensemode>() { new RX_licensemode() { P_id = nLicense.ProductId.ToString().ToUpper() } }); ;
        });

        if (result != RSC_errorcode.success)
            return null;

        return await GetAsync(cLicense.Group.Id, cLicense.Id);
    }

When I do debug and make a stop on cLicense, I see that this object is the current License (which is what I want) but as soon as the UpdateAsync method runs, cLicense is also updated while I want it to remain as the original object.

Does anyone has already had same behavior ? I'm sure this is a normal process but I don't know how to have it working as I wish.

Feel free to ask if anything is not clear enough.
Regards,


问:
SQL Select where values in List<string>
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

```<code>Select * from Table where RecordID in (RecordIDList)
</code>```

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

答:
You can write a table-valued user-defined function that takes a list of IDs and creates a table, then join agains the result of this function. This article by Erland Sommarskog describes how to do it.

Or, you could use table parameters, new in SQL server 2008 (I think).

Or, as Manu said, you can use XML.

However, I advice against using the IN String.Join approach in the accepted answer since it is like asking for SQL injection.

OwnerDisplayName: JoelHess

ContentLicense: CC BY-SA 2.5

Title: SQL Select where values in List<string>

Body:
Is there a way that I can create query against a data source (could be sql, oracle or access) that has a where clause that points to an ArrayList or List?

example:

Select * from Table where RecordID in (RecordIDList)

I've seen some ways to do it with Linq, but I'd rather not resort to it if it's avoidable.

LastEditorDisplayName: Andrew Hare


问:
How to store bulk images using ASP.NET and C#
What is the most efficient way to store and retrieve images?

To Store:

Store in Database as a column

Store in Application File system

Write the Binarydata of the image to Xml and read it from there

To Retrieve:

Generic Handler

I am planning to do it for a social networking site, please advise me.

答:
For social network site you should store images in database as binary data.
Here is good article: http://www.dotnetspider.com/resources/460-Store-Retrieve-SQL-Server-database.aspx</p>


问:
How can we sum only the most recent values of a quantity computed in each stratum of a datastream using Flink?
I have a datastream (from a csv file) which contains strings and a specific value (a double) in every row. I use keyBy() in Flink to group these values by a specific attribute (country), so I have a different group of tuples (stratum) for every distinct country. I compute the mean and the variance for each group (stratum) in the datastream and I return the quantity mean/variance (μ/σ) for every stratum. In my Flink program I need to sum all the last values of this quantity (mean/variance), i.e. the most recent values, coming from each stratum, as my algorithm runs. In other words, if a quantity γ (mean/variance) results from each stratum, I want to sum all the last values of γ resulting from the computation of γ in every stratum. Can anyone help me to solve this maybe using a specific Flink operator? </p>

答:
When you perform computations on streams, you never know if or when more data may arrive, so the typical approach is to treat every event as though it might be the last, and so go ahead and produce a result for every event. Which is then made obsolete, or updated, by the result produced in response to the next event.

Unless you are doing windowing, in which case each window can be treated as a finite batch.

In your case, since the input is a CSV file, why not treat this as a batch computation?

But regardless of whether you want batch or streaming, I would suggest looking at Flink's Table and SQL APIs, which have support for computing mean and variance as built-in aggregate functions. You can use the filesystem connector with the old csv format.

Could you do this with the DataStream API? Yes, but ...

If you are doing this computation in windows, then yes, this is straightforward. Just implement your business logic in a ProcessWindowFunction. Its process method will be passed an Iterable containing all of the events assigned to the window, and from there you can compute the mean, variance, etc.

But, without windowing (or batching), no, not really. Computing variance in a purely streaming fashion on unbounded inputs doesn't scale. You must store all of the events in state, and after each event, update the mean and then recompute all of the squared differences between each event and the mean.


问:
How to start with Edge webdriver with python 2.7 and Robot framework 2.9
I have downloaded and installed edge webdriver from Microsoft website. I see the Edge driver folder in the "C:\Python27\Lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\edge".

Whenever I try to execute the below Robot Test case:

```<code>*** Settings ***
Documentation       Test Edge Browser

*** Test Case ***
Test Edge browser
    open browser    http://www.google.in    Edge
</code>```

Though I have set the environment path for "Mircrosoftwebdriver.exe". I see the "WebDriverException: Message: The EdgeDriver executable needs to be available in the path. Please download from http://go.microsoft.com/fwlink/?LinkId=619687"

Please let me know if anyone has the same issue and resolved.

答: Not sure if this is still relevant, however I was having the same problems even though it was in my path correctly. What I noticed was when I unpacked the driver after downloading from MS the name was all in lowercase 'microsoftwebdriver.exe'. Changed name in path so it was the same as the error message 'MicrosoftWebDriver.exe' and low and behold it now works.</p>

Body:
I have downloaded and installed edge webdriver from Microsoft website. I see the Edge driver folder in the "C:\Python27\Lib\site-packages\selenium-2.48.0-py2.7.egg\selenium\webdriver\edge".

Whenever I try to execute the below Robot Test case:

*** Settings ***
Documentation       Test Edge Browser

*** Test Case ***
Test Edge browser
    open browser    http://www.google.in    Edge

Though I have set the environment path for "Mircrosoftwebdriver.exe". I see the "WebDriverException: Message: The EdgeDriver executable needs to be available in the path. Please download from http://go.microsoft.com/fwlink/?LinkId=619687"

Please let me know if anyone has the same issue and resolved.


问:
C- What is the matter of my mergesort algorithm?
I made a code of mergesort algorithm that have two inputs: the number of digits, and digits

And I want to print array sorted by my mergesort function.

But only i can see is run time error.

I think my Merge() function made runtime error. but I cant find the exception of my while loop in Merge function..

How can I fix this error and run mergesort function properly?

Here is my code

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

void Merge(int *arr, int s, int e, int m);
void MergeSort(int *arr, int s, int e);

int main(void) {
    int N;
    scanf("%d", &N);
    int arr[N];
    for (int i = 0; i < N; i++) {
        scanf("%d", &arr[i]);
    }
    MergeSort(arr, 0, N - 1);
    for (int i = 0; i < N; i++) {
        printf("%d", arr[i]);
    }
}

void MergeSort(int *arr, int s, int e) {
    printf("hi\n");
    int m;
    if (e - s > 0) {
        m = (s + e) / 2;
        MergeSort(arr, s, m);
        MergeSort(arr, m + 1, e);
        Merge(arr, s, e, m);
    } else {
        return;
    }
}

void Merge(int *arr, int s, int e, int m) {
    int arr_t[e - s + 1];
    int i = s, j = m + 1, idx = s;
    while (1) {
        if (i != m && j != s) {
            if (i <= m && arr[i] <= arr[j]) {
                arr_t[idx] = arr[i];
                i++;
                idx++;
            } else
            if (j <= e) {
                arr_t[idx] = arr[j];
                j++;
                idx++;
            }
        } else
        if (i == m && j != e) {
            arr_t[idx] = arr[j];
            j++;
            idx++;
        } else
        if (i != m && j == e) {
            arr_t[idx] = arr[i];
            i++;
            idx++;
        } else {
            if (arr[i] <= arr[j]) {
                arr_t[idx] = arr[i];
                idx++;
                arr_t[idx] = arr[j];
            } else {
                arr_t[idx] = arr[j];
                idx++;
                arr_t[idx] = arr[i];
            }
            break;
        }
    }
    for (int k = s; k <= e; k++) {
        arr[k] = arr_t[k];
    }
}
</code>```

答:
The error in your part of code may be due to:

You are probably going out of bounds of one of your array as stated by @Some programmer dude

Instead of while(1) you may use while(i<=mid && j<=end) which loops until the merge runs out of one or both parts

N even instead of using so many else if in your merge function, you can use while() loop that will simplify your code.You shouldn't append two values to the temporary array in your last else clause either

Even if(i!=m && j!=s) this condition in your code looks a bit weird.

So I wrote this sample mergesort for your reference. Hope this helps!!

```<code>#include<stdio.h>
void merge(int a[],int start,int mid,int end){
int i=start,j=mid+1,k=0;
int temp[end-start+1];
while(i<=mid && j<=end){
    if(a[i]<a[j]){
        temp[k]=a[i];
        k+=1;
        i+=1;
    }
    else{
        temp[k]=a[j];
        k+=1;
        j+=1;
    }
}
while(i<=mid){
    temp[k]=a[i];
    i+=1;k+=1;
}
while(j<=end){
    temp[k]=a[j];
    j+=1;k+=1;
}
for(int i=end;i>=start;i--){
    a[i]=temp[--k];
}

}

void mergesort(int a[],int start,int end){
if(start<end){
int mid=(start+end)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);

}
}

void display(int a[],int n){
for(int i=0;i<n;i++)
printf("%d ",a[i]);

}

int main()

{
    int a[5]={5,4,6,2,1};
    int n=sizeof(a)/sizeof(a[0]);
    mergesort(a,0,n-1);
    display(a,n);
}
</code>```

With the worst-case time complexity being Ο(n log n)

Body:
I made a code of mergesort algorithm that have two inputs: the number of digits, and digits

And I want to print array sorted by my mergesort function.

But only i can see is run time error.

I think my Merge() function made runtime error. but I cant find the exception of my while loop in Merge function..

How can I fix this error and run mergesort function properly?

Here is my code

 #include <stdio.h>

void Merge(int *arr, int s, int e, int m);
void MergeSort(int *arr, int s, int e);

int main(void) {
    int N;
    scanf("%d", &N);
    int arr[N];
    for (int i = 0; i < N; i++) {
        scanf("%d", &arr[i]);
    }
    MergeSort(arr, 0, N - 1);
    for (int i = 0; i < N; i++) {
        printf("%d", arr[i]);
    }
}

void MergeSort(int *arr, int s, int e) {
    printf("hi\n");
    int m;
    if (e - s > 0) {
        m = (s + e) / 2;
        MergeSort(arr, s, m);
        MergeSort(arr, m + 1, e);
        Merge(arr, s, e, m);
    } else {
        return;
    }
}

void Merge(int *arr, int s, int e, int m) {
    int arr_t[e - s + 1];
    int i = s, j = m + 1, idx = s;
    while (1) {
        if (i != m && j != s) {
            if (i <= m && arr[i] <= arr[j]) {
                arr_t[idx] = arr[i];
                i++;
                idx++;
            } else
            if (j <= e) {
                arr_t[idx] = arr[j];
                j++;
                idx++;
            }
        } else
        if (i == m && j != e) {
            arr_t[idx] = arr[j];
            j++;
            idx++;
        } else
        if (i != m && j == e) {
            arr_t[idx] = arr[i];
            i++;
            idx++;
        } else {
            if (arr[i] <= arr[j]) {
                arr_t[idx] = arr[i];
                idx++;
                arr_t[idx] = arr[j];
            } else {
                arr_t[idx] = arr[j];
                idx++;
                arr_t[idx] = arr[i];
            }
            break;
        }
    }
    for (int k = s; k <= e; k++) {
        arr[k] = arr_t[k];
    }
}

Body:
The error in your part of code may be due to:

You are probably going out of bounds of one of your array as stated by @Some programmer dude

Instead of while(1) you may use while(i<=mid && j<=end) which loops until the merge runs out of one or both parts

N even instead of using so many else if in your merge function, you can use while() loop that will simplify your code.You shouldn't append two values to the temporary array in your last else clause either

Even if(i!=m && j!=s) this condition in your code looks a bit weird.

So I wrote this sample mergesort for your reference. Hope this helps!!

#include<stdio.h>
void merge(int a[],int start,int mid,int end){
int i=start,j=mid+1,k=0;
int temp[end-start+1];
while(i<=mid && j<=end){
    if(a[i]<a[j]){
        temp[k]=a[i];
        k+=1;
        i+=1;
    }
    else{
        temp[k]=a[j];
        k+=1;
        j+=1;
    }
}
while(i<=mid){
    temp[k]=a[i];
    i+=1;k+=1;
}
while(j<=end){
    temp[k]=a[j];
    j+=1;k+=1;
}
for(int i=end;i>=start;i--){
    a[i]=temp[--k];
}

}

void mergesort(int a[],int start,int end){
if(start<end){
int mid=(start+end)/2;
mergesort(a,start,mid);
mergesort(a,mid+1,end);
merge(a,start,mid,end);

}
}

void display(int a[],int n){
for(int i=0;i<n;i++)
printf("%d ",a[i]);

}

int main()

{
    int a[5]={5,4,6,2,1};
    int n=sizeof(a)/sizeof(a[0]);
    mergesort(a,0,n-1);
    display(a,n);
}

With the worst-case time complexity being Ο(n log n)


问:
Class 'Html' not found in YII2
Finally I try YII2 (can't move on from yii1) in my simple website project.
I've Fatal ERROR Class 'Html' not found in my views.

Case 1.
I put use yii\helpers\Html; in main (layout directory).
When I write Html::img('@web/logo.jpg') in index(view directory)I've got error 'html not found'.

Case 2.
I write Html::img('@web/logo.jpg') in main (layout directory) running well.

case 3.
I delete use yii\helpers\Html in main (layout directory). and I write use yii\helpers\Html in index (view directory) running well, my image can show.

so, what's my mistake. Why I can't Html in index.

答:
un comment short_open_tag and set value ON
after this change reset your web server, also use class element top of file</p>

Title: Class 'Html' not found in YII2


问:
how to set the cdn url using w3total cach plugin using wordpress
In W3total cache plugin:

I'm getting Url

"http://d2vwmkksqncpb8.cloudfront.net/wp-content/themes/twentyten/images/headers/path.jpg" after uploadind cdn...

But i want the url like this

"http://d2vwmkksqncpb8.cloudfront.net/foldername/wp-content/themes/twentyten/images/headers/path.jpg"

答:
Under the CDN configuration, in the "Replace site's hostname with" field you can enter a hostname with a path i.e.

"d2vwmkksqncpb8.cloudfront.net/foldername/"

Which will add the foldername into the path.


问:
Check API response data with interface in Typescript Angular
I have an app that when the user logs in he received some data as a response, but if the response is not what I expect, the app crashes.

Let me show you the following:

I created an interface to tell Typescript the data I expect.

export interface AuthResponseData {
  token: string;
  expires: string;
  role: number;
}
```

<p>Then I created a method to send the login data to the server.</p>

<pre class="lang-js prettyprint-override"><code>login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    catchError(this.handleError),
    tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
  );
}
</code>```

I was expecting that if the response from the server didn't match the interface then the Angular would redirect to catchError. But doesn't happen.

Now my question is: Is there any way to check if an API response is equal to the interface and throw an error if is not. Or what I'm asking isn't possible?

UPDATE:

After searching I discover that the interfaces disappear on run time, so there is no way to compare the api response with the interface (to the best of my knowledge). But I keep searching for a way to check the api response in a dynamic way. I think it is not really secure depending on api response to be always right. So I should check the API response. How can I do that?

Hope you can help me, thanks :)

答:
You can throw an error that would be catched by the catchError()

```<code>login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    map(res => { //  Map should return an observable
      if(!this.isValid()) // isValid() is a hole diffrent story - stucture checking in tyepscript -
          throw new Error('Response structure is not valid.') // Would be catched by catchError
      return res;
    })
    tap(resData => { // tap is for side effects
        this.handleAuthentication(resData.token, resData.expires, resData.role)
    })
    catchError(this.handleError)
  );
}
</code>```

now for response structure you can check Interface type check with Typescript

Body:
I have an app that when the user logs in he received some data as a response, but if the response is not what I expect, the app crashes.

Let me show you the following:

I created an interface to tell Typescript the data I expect.

export interface AuthResponseData {
  token: string;
  expires: string;
  role: number;
}

Then I created a method to send the login data to the server.

login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    catchError(this.handleError),
    tap(resData => { this.handleAuthentication(resData.token, resData.expires, resData.role)})
  );
}

I was expecting that if the response from the server didn't match the interface then the Angular would redirect to catchError. But doesn't happen.

Now my question is: Is there any way to check if an API response is equal to the interface and throw an error if is not. Or what I'm asking isn't possible?

UPDATE:

After searching I discover that the interfaces disappear on run time, so there is no way to compare the api response with the interface (to the best of my knowledge). But I keep searching for a way to check the api response in a dynamic way. I think it is not really secure depending on api response to be always right. So I should check the API response. How can I do that?

Hope you can help me, thanks :)

Body:
You can throw an error that would be catched by the catchError()

login(user: string, password: string){
  return this.http.post<AuthResponseData>(
    'https://localhost:44344/api/auth', { user: user, pwd: password }
  ).pipe(
    map(res => { //  Map should return an observable
      if(!this.isValid()) // isValid() is a hole diffrent story - stucture checking in tyepscript -
          throw new Error('Response structure is not valid.') // Would be catched by catchError
      return res;
    })
    tap(resData => { // tap is for side effects
        this.handleAuthentication(resData.token, resData.expires, resData.role)
    })
    catchError(this.handleError)
  );
}

now for response structure you can check Interface type check with Typescript


问:
C# Testing - compare list of custom type
I'm trying to write test checking if JSON converter corectly deserialize input to my custom list

```<code>    [TestMethod]
    public void JSONInput_Changed()
    {
        List<PointOnChart> _expectedPointsOnChart;
        _expectedPointsOnChart = new List<PointOnChart>();
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:00:00.000Z", Value1 = 10, Value2 = 20, Value3 = 30 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:01:00.000Z", Value1 = 11, Value2 = 21, Value3 = 31 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:02:00.000Z", Value1 = 12, Value2 = 22, Value3 = 32 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:03:00.000Z", Value1 = 13, Value2 = 23, Value3 = 33 });

        MultipleBarChart multipleBarChartTest = new MultipleBarChart();
        multipleBarChartTest.MeInitialize(DateTimeIntervalType.Minutes);
        string JSONstring = System.IO.File.ReadAllText(@"C:\Users\slawomirk\source\repos\VIXCharts\iFixMultipleBarChartTests\TestJson.txt");
        multipleBarChartTest.JSONInput = JSONstring;
        List<PointOnChart> resultPointsOnChart = multipleBarChartTest.PointsOnChart;

        //bool areEqual = _expectedPointsOnChart.SequenceEqual(resultPointsOnChart);
        IEnumerable<PointOnChart> resultList;
        resultList = _expectedPointsOnChart.Except(resultPointsOnChart);
        if (resultList.Any())
        {
            Assert.Fail();
        }
    }
</code>```

List contains object of this class

```<code>public class PointOnChart
{
    public string Timestamp { get; set; }
    public double Value1 { get; set; }
    public double Value2 { get; set; }
    public double Value3 { get; set; }
}
</code>```

And this is file I'm reading to deserialize:

[{"Timestamp":"2020-02-14T09:00:00.000Z","Value1":10,"Value2":20,"Value3":30},
  {"Timestamp":"2020-02-14T09:01:00.000Z","Value1":11,"Value2":21,"Value3":31},
  {"Timestamp":"2020-02-14T09:02:00.000Z","Value1":12,"Value2":22,"Value3":32},
  {"Timestamp":"2020-02-14T09:03:00.000Z","Value1":13,"Value2":23,"Value3":33}]

I tried numerous ways to compare two Lists but all of them fails eg.:
 - Fluent Assertion
 - CollectionAssert

When I inspect both List in debug they are identical.
I know it's probably trivial but I could find any solution online, thanks in advance.

答:
Instead of polluting your production code with Equals overrides, considering using www.fluentassertions.com and write that statement as:

resultPointsOnChart.Should().BeEquivalentTo(expectedPointsOnChart);

Body:
I'm trying to write test checking if JSON converter corectly deserialize input to my custom list

    [TestMethod]
    public void JSONInput_Changed()
    {
        List<PointOnChart> _expectedPointsOnChart;
        _expectedPointsOnChart = new List<PointOnChart>();
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:00:00.000Z", Value1 = 10, Value2 = 20, Value3 = 30 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:01:00.000Z", Value1 = 11, Value2 = 21, Value3 = 31 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:02:00.000Z", Value1 = 12, Value2 = 22, Value3 = 32 });
        _expectedPointsOnChart.Add(new PointOnChart { Timestamp = "2020-02-14T09:03:00.000Z", Value1 = 13, Value2 = 23, Value3 = 33 });

        MultipleBarChart multipleBarChartTest = new MultipleBarChart();
        multipleBarChartTest.MeInitialize(DateTimeIntervalType.Minutes);
        string JSONstring = System.IO.File.ReadAllText(@"C:\Users\slawomirk\source\repos\VIXCharts\iFixMultipleBarChartTests\TestJson.txt");
        multipleBarChartTest.JSONInput = JSONstring;
        List<PointOnChart> resultPointsOnChart = multipleBarChartTest.PointsOnChart;

        //bool areEqual = _expectedPointsOnChart.SequenceEqual(resultPointsOnChart);
        IEnumerable<PointOnChart> resultList;
        resultList = _expectedPointsOnChart.Except(resultPointsOnChart);
        if (resultList.Any())
        {
            Assert.Fail();
        }
    }

List contains object of this class

public class PointOnChart
{
    public string Timestamp { get; set; }
    public double Value1 { get; set; }
    public double Value2 { get; set; }
    public double Value3 { get; set; }
}

And this is file I'm reading to deserialize:

[{"Timestamp":"2020-02-14T09:00:00.000Z","Value1":10,"Value2":20,"Value3":30},
  {"Timestamp":"2020-02-14T09:01:00.000Z","Value1":11,"Value2":21,"Value3":31},
  {"Timestamp":"2020-02-14T09:02:00.000Z","Value1":12,"Value2":22,"Value3":32},
  {"Timestamp":"2020-02-14T09:03:00.000Z","Value1":13,"Value2":23,"Value3":33}]

I tried numerous ways to compare two Lists but all of them fails eg.:
 - Fluent Assertion
 - CollectionAssert

When I inspect both List in debug they are identical.
I know it's probably trivial but I could find any solution online, thanks in advance.


问:
using React Autosuggest with Formik
Did anyone have example / tutorial for implement react-autosuggest in Formik ?
I got issue in passing the inputProps to AutoSuggest component. Below is my sample code. TIA.

```<code>const locationSuggestion = [
  {
    locationName: 'Gambir, Jakarta Pusat, DKI Jakarta',
    districtCode: '31.71.01',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Koja, Jakarta Utara, DKI Jakarta',
    districtCode: '31.72.03',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Tambora, Jakarta Barat, DKI Jakarta',
    districtCode: '31.73.04',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Palmerah, Jakarta Barat, DKI Jakarta',
    districtCode: '31.73.07',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Tebet, Jakarta Selatan, DKI Jakarta',
    districtCode: '31.74.01',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Matraman, Jakarta Timur, DKI Jakarta',
    districtCode: '31.75.01',
    postCode: [11220, 11221, 11222]
  },
];

function escapeRegexCharacters(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function getSuggestions(value) {
  const escapedValue = escapeRegexCharacters(value.trim());

  if (escapedValue === '') {
    return [];
  }
  const regex = new RegExp('^' + escapedValue, 'i');
  return locationSuggestion.filter(loc => regex.test(loc.locationName));
}

function getSuggestionValue(suggestion) {
  return suggestion.locationName;
}

function renderSuggestion(suggestion) {
  return (
    <span>{suggestion.locationName}</span>
  );
}

class SCO extends Component {

onSuggestionsFetchRequested = ({ value }) => {
    console.log("test : ", value);
    this.setState({
      suggestions: getSuggestions(value)
    });
  };

  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

render() {
return (
<Formik
  initialValues={this.state}
  enableReinitialize
  validationSchema={SocioSchema}
  onSubmit={values => {

  }}
>
  {
  props => (
    <Form onSubmit={props.handleSubmit}>
      <CardHeader>

      </CardHeader>
      <CardBody>
    <Row>
      <Col xs="12" sm="8">

        <FormGroup row>
          <Label
        htmlFor="receiverCity"
        className="col-md-3 col-form-label-sm text-right"
          >
        Kecamatan / Kota
          </Label>
          <Col xs="12" md="7">
        <Autosuggest
          suggestions={this.state.suggestions}
          onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
          onSuggestionsClearRequested={this.onSuggestionsClearRequested}
          getSuggestionValue={getSuggestionValue}
          renderSuggestion={renderSuggestion}
          inputProps={props.values.inputProps} />
        <FormFeedback className="help-block">
          {props.errors.receiverCity}
        </FormFeedback>
          </Col>
        </FormGroup>
      </Col>
    </Row>
      </CardBody>
      <CardFooter>
    <Button
      size="sm"
      type="reset"
      className="btn-tumblr btn-brand mr-2"
      onClick={this.handleReset}
    >
      <i className="fa fa-dot-circle-o"></i>
      <span>Reset</span>
    </Button>
    <Button
      type="submit"
      size="sm"
      className="btn-submit btn-brand mr-2"
      // disabled={props.isSubmitting}
    >
      <i className="fa fa-paper-plane"></i>
      <span>Pesen</span>
    </Button>
      </CardFooter>
    </Form>
  )}
</Formik>
)
}
}
</code>```

答:
inputProps have some details like this and it's required so you need to pass this value

```<code>const inputProps = {
  value,
  onChange,
  onBlur,
  type: 'search',
  placeholder: 'Enter city or postcode'
};
</code>```

so can you just add this details to inputProps

Title: using React Autosuggest with Formik

Body:
Did anyone have example / tutorial for implement react-autosuggest in Formik ?
I got issue in passing the inputProps to AutoSuggest component. Below is my sample code. TIA.

const locationSuggestion = [
  {
    locationName: 'Gambir, Jakarta Pusat, DKI Jakarta',
    districtCode: '31.71.01',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Koja, Jakarta Utara, DKI Jakarta',
    districtCode: '31.72.03',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Tambora, Jakarta Barat, DKI Jakarta',
    districtCode: '31.73.04',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Palmerah, Jakarta Barat, DKI Jakarta',
    districtCode: '31.73.07',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Tebet, Jakarta Selatan, DKI Jakarta',
    districtCode: '31.74.01',
    postCode: [11220, 11221, 11222]
  },
  {
    locationName: 'Matraman, Jakarta Timur, DKI Jakarta',
    districtCode: '31.75.01',
    postCode: [11220, 11221, 11222]
  },
];

function escapeRegexCharacters(str) {
  return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
}

function getSuggestions(value) {
  const escapedValue = escapeRegexCharacters(value.trim());

  if (escapedValue === '') {
    return [];
  }
  const regex = new RegExp('^' + escapedValue, 'i');
  return locationSuggestion.filter(loc => regex.test(loc.locationName));
}

function getSuggestionValue(suggestion) {
  return suggestion.locationName;
}

function renderSuggestion(suggestion) {
  return (
    {suggestion.locationName}
  );
}

class SCO extends Component {

onSuggestionsFetchRequested = ({ value }) => {
    console.log("test : ", value);
    this.setState({
      suggestions: getSuggestions(value)
    });
  };

  onSuggestionsClearRequested = () => {
    this.setState({
      suggestions: []
    });
  };

render() {
return (
<Formik
  initialValues={this.state}
  enableReinitialize
  validationSchema={SocioSchema}
  onSubmit={values => {

  }}
>
  {
  props => (
    <Form onSubmit={props.handleSubmit}>
      <CardHeader>

      </CardHeader>
      <CardBody>
    <Row>
      <Col xs="12" sm="8">

        <FormGroup row>

        Kecamatan / Kota

          <Col xs="12" md="7">
        <Autosuggest
          suggestions={this.state.suggestions}
          onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
          onSuggestionsClearRequested={this.onSuggestionsClearRequested}
          getSuggestionValue={getSuggestionValue}
          renderSuggestion={renderSuggestion}
          inputProps={props.values.inputProps} />
        <FormFeedback className="help-block">
          {props.errors.receiverCity}
        </FormFeedback>
          </Col>
        </FormGroup>
      </Col>
    </Row>
      </CardBody>
      <CardFooter>
    <Button
      size="sm"
      type="reset"
      className="btn-tumblr btn-brand mr-2"
      onClick={this.handleReset}
    >

      Reset
    </Button>
    <Button
      type="submit"
      size="sm"
      className="btn-submit btn-brand mr-2"
      // disabled={props.isSubmitting}
    >

      Pesen
    </Button>
      </CardFooter>
    </Form>
  )}
</Formik>
)
}
}

Body:
inputProps have some details like this and it's required so you need to pass this value

const inputProps = {
  value,
  onChange,
  onBlur,
  type: 'search',
  placeholder: 'Enter city or postcode'
};

so can you just add this details to inputProps


问:
SQL Filter by List of ids
I have three tables

```<code>1-rests
2-amenity_rest
3-amenities
</code>```

```<code>rests
id      name
1       rest1
2       rest2
3       rest3

amenities
id     name
1      amenity1
2      amenity2
3      amenity3

amenity_rest
rest_id         amenity_id
1                  1
1                  3
2                  2
3                  1
</code>```

I would like to send a List of amenities like [1,3]

and it should return the rest that its id=1

and if I send array [1,2,3] it should return no result

How would such a query look alike?

答:
You can construct the query as:</p>

```<code>select ar.rest_id
from amenity_rest ar
where ar.amenity_id in (1, 2, 3)
group by ar.rest_id
having count(*) = 3;  -- "3" = size of list
</code>```

Title: SQL Filter by List of ids

Body:
I have three tables

1-rests
2-amenity_rest
3-amenities

rests
id      name
1       rest1
2       rest2
3       rest3

amenities
id     name
1      amenity1
2      amenity2
3      amenity3

amenity_rest
rest_id         amenity_id
1                  1
1                  3
2                  2
3                  1

I would like to send a List of amenities like [1,3]

and it should return the rest that its id=1

and if I send array [1,2,3] it should return no result

How would such a query look alike?

Body:
You can construct the query as:

select ar.rest_id
from amenity_rest ar
where ar.amenity_id in (1, 2, 3)
group by ar.rest_id
having count(*) = 3;  -- "3" = size of list


问:
Fast way of finding the longest substring using only regex
Is it possible to find the longest substring that is at the same time a prefix and a suffix (overlapping is allowed) using only one regular expression? For example:

aab is the longest one in aabaaabaaaaab:

aabaaabaaaaab

aabaaabaaaaab

aabaaabaaaaab

Another example is babab being the longest in babababab:

babababab

babababab

babababab

I was trying to accomplish that using the regular expression suggested by @nhahtdh in Lookahead regex failing to find the same overlapping matches but it fails to find the first example.

I wrote a code that is working properly but it is way too slow because so many uses of text.find. The reason why I have to resort to all that extra logic is because the r'(?=((\w+).*\2.*\2))' regular expression is not tuned to find only suffix and prefixes. I have tried to use ^ and $ but I was not able to make it work properly.

Here is the current correct (but slow) implementation:

```<code>from re import findall
text = "xyzxyzxyzxyzxyz"
matches = findall(r'(?=((\w+).*\2.*\2))', text)
s = ""
result = ""
for (s1, s2) in matches:
  if text.startswith(s1) and text.endswith(s1) and text.startswith(s2) and text.endswith(s2):
    if len(s1) == len(text):
      s = s2
    elif len(s2) == len(text):
      s = s1
    else:
      s = s1 if len(s1) > len(s2) else s2
    mid = text.find(s, 1)
    if not (mid == -1 or mid >= len(text) - len(s)):
      result = s if len(s) > len(result) else result
print(result) # xyzxyzxyz
</code>```

答:
```<code>string = "babababab"
substring = ""
for length in range(1, len(string)):
    prefix = string[:length]
    suffix = string[-length:]
    if prefix == suffix and string.find(prefix, 1) != len(string) - length:
        substring = prefix

print(substring)
</code>```

The extra check string.find(prefix, 1) != len(string) - length ensures that the string also appears strictly in the middle.

Body:
Is it possible to find the longest substring that is at the same time a prefix and a suffix (overlapping is allowed) using only one regular expression? For example:

aab is the longest one in aabaaabaaaaab:

aabaaabaaaaab

aabaaabaaaaab

aabaaabaaaaab

Another example is babab being the longest in babababab:

babababab

babababab

babababab

I was trying to accomplish that using the regular expression suggested by @nhahtdh in Lookahead regex failing to find the same overlapping matches but it fails to find the first example.

I wrote a code that is working properly but it is way too slow because so many uses of text.find. The reason why I have to resort to all that extra logic is because the r'(?=((\w+).*\2.*\2))' regular expression is not tuned to find only suffix and prefixes. I have tried to use ^ and $ but I was not able to make it work properly.

Here is the current correct (but slow) implementation:

from re import findall
text = "xyzxyzxyzxyzxyz"
matches = findall(r'(?=((\w+).*\2.*\2))', text)
s = ""
result = ""
for (s1, s2) in matches:
  if text.startswith(s1) and text.endswith(s1) and text.startswith(s2) and text.endswith(s2):
    if len(s1) == len(text):
      s = s2
    elif len(s2) == len(text):
      s = s1
    else:
      s = s1 if len(s1) > len(s2) else s2
    mid = text.find(s, 1)
    if not (mid == -1 or mid >= len(text) - len(s)):
      result = s if len(s) > len(result) else result
print(result) # xyzxyzxyz

Body:
string = "babababab"
substring = ""
for length in range(1, len(string)):
    prefix = string[:length]
    suffix = string[-length:]
    if prefix == suffix and string.find(prefix, 1) != len(string) - length:
        substring = prefix

print(substring)

The extra check string.find(prefix, 1) != len(string) - length ensures that the string also appears strictly in the middle.


问:
Setting DEADLOCK_PRIORITY in L2S/Entity Framework
Had a little trouble with deadlocks and one of the actions (aside from the "get rid of the deadlock in the first place" action) is to set the deadlock priority of one particular stored procedure so that it should never be chosen as the victim (it is a lot more important).

I can see how to do this in the stored procedure, but I was wondering, as an academic exercise, if this can be achieved using Entity Framework or LINQ2SQL ?

Thanks
Duncan

答: You would almost certainly be better off making sure you have the correct indexes; inappropriate or missing indexes are an often overlooked aspect of excessive locking/ blocking.</p>


答:
You can try Promise.all

async function getRating(item, applicant) {
    let arr = await Applicant.find({ proff: item }).sort({ ball: 'desc' });
    let rating = arr.findIndex(item => item._id.equals(applicant._id));
    let spec = await Spec.findById(item);
    const el = { spec, rating };
    return el;
}

router.get('/test', auth, async (req, res) => {
    let applicant = await Applicant.findOne({ user: req.user.id });

    const ratingsPromise = applicant.proff.map(async item => {
        const rating = await getRating(item, applicant);
        return rating;
    });

    const ratings = await Promise.all(ratingsPromise);
    return res.json(ratings);
});

```

Title: JS: async function


问:
Woocommerce hide product description on load
I need to hide the product description in the product page. But when the user clicks on the description tab I need to show the content. When the user clicks again, I need to hide the description. It needs to work like toogle.

But I can not complete this. Please help. For to hide description on page load I place the following script on single-product.php

```<code>$('.wc-tab').hide();
</code>```

It is working. When page load it is hidden and user clicks it is show (description_tab active)  automatically.

But I need to show hide every click. Please help

This is HTML structure

```<code><ul class="tabs wc-tabs">
                            <li class="description_tab active">
                    <a href="#tab-description">Description</a>
                </li>
</ul>
</code>```

Thank you .

答:
You can hide the tab content on page load using Jquery and then you can show it when you click on tab title using Jquery.

// Remove Empty Tabs
add_filter( 'woocommerce_product_tabs', 'yikes_woo_remove_empty_tabs', 20, 1 );

Here’s a function that will remove any empty tabs:

```<code>add_filter( 'woocommerce_product_tabs', 'rf_woo_remove_empty_tabs', 20, 1 );
    function rf_woo_remove_empty_tabs( $tabs ) {

        if ( ! empty( $tabs ) ) {
            foreach ( $tabs as $title => $tab ) {
                if ( empty( $tab['content'] ) ) {
                    unset( $tabs[ $title ] );
                }
            }
        }
        return $tabs;
    }
</code>```

If you want to remove specific tabs, use the below function.

```<code>add_filter( 'woocommerce_product_tabs', 'rf_remove_product_tabs', 98 );

function rf_remove_product_tabs( $tabs ) {

    unset( $tabs['description'] );          // Remove the description tab
    unset( $tabs['reviews'] );          // Remove the reviews tab
    unset( $tabs['additional_information'] );   // Remove the additional information tab

    return $tabs;

}
</code>```

Body:
I need to hide the product description in the product page. But when the user clicks on the description tab I need to show the content. When the user clicks again, I need to hide the description. It needs to work like toogle.

But I can not complete this. Please help. For to hide description on page load I place the following script on single-product.php

$('.wc-tab').hide();

It is working. When page load it is hidden and user clicks it is show (description_tab active)  automatically.

But I need to show hide every click. Please help

This is HTML structure

                    Description

Thank you .

Body:
You can hide the tab content on page load using Jquery and then you can show it when you click on tab title using Jquery.

// Remove Empty Tabs
add_filter( 'woocommerce_product_tabs', 'yikes_woo_remove_empty_tabs', 20, 1 );

Here’s a function that will remove any empty tabs:

add_filter( 'woocommerce_product_tabs', 'rf_woo_remove_empty_tabs', 20, 1 );
    function rf_woo_remove_empty_tabs( $tabs ) {

        if ( ! empty( $tabs ) ) {
            foreach ( $tabs as $title => $tab ) {
                if ( empty( $tab['content'] ) ) {
                    unset( $tabs[ $title ] );
                }
            }
        }
        return $tabs;
    }

If you want to remove specific tabs, use the below function.

add_filter( 'woocommerce_product_tabs', 'rf_remove_product_tabs', 98 );

function rf_remove_product_tabs( $tabs ) {

    unset( $tabs['description'] );          // Remove the description tab
    unset( $tabs['reviews'] );          // Remove the reviews tab
    unset( $tabs['additional_information'] );   // Remove the additional information tab

    return $tabs;

}


问:
How to solve error Component is not part of any NgModule or not imported correctly in angular 6?
This is error i am getting:-

```<code><b>Error: Component Component is not part of any NgModule or the module has not been imported into your module.
Error: Component Component is not part of any NgModule or the module has not been imported into your module.</b>
</code>```

I want my setup module to be lazily loaded but getting error like component is not part of module or the module has not been imported into your module

```<code>//This is my app.module.ts
import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { LeaveService } from './EW_Leave/leave.service';
import { UtilsModule } from './EW_Utils/utils.module';
import { JobReferenceComponent } from '../app/EW_Utils/job-reference/job-reference.component'
import { CommonModule } from '@angular/common';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { EWDashboardComponent } from './EW_Dashboard/ew-dashboard.component';
import { EWLoginComponent } from './EW_Login/ew-login.component';

@NgModule({
  imports: [
    StorageServiceModule,
    CommonModule,
    BrowserModule,
    FormsModule, ReactiveFormsModule,
    AppRoutingModule,
    UtilsModule, LeaveModule,
  ],
  declarations: [
    AppComponent, JobReferenceComponent, EWDashboardComponent, EWLoginComponent
  ],
  exports: [],
  providers: [LeaveService, Title],
  bootstrap: [AppComponent]
})
export class AppModule {

}
</code>```

//this is my app-routing.module.ts

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EWDashboardComponent } from './EW_Dashboard/ew-dashboard.component';
import { EWLoginComponent } from './EW_Login/ew-login.component';
import { SetupDashboardComponent } from './EW_Setup/setup-dashboard/setup-dashboard.component';
import {CompaniesSetupComponent} from './EW_Setup/companies-setup/companies-setup.component';
const appRoutes: Routes = [
  { path: 'login', component: EWLoginComponent },
  { path: 'dashboard', component: EWDashboardComponent },
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'setup',

   loadChildren: './EW_Setup/setup.module#CustomersModule'

  },

]
@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule],
  declarations: []
})

export class AppRoutingModule {

}
</code>```

THIS BELOW SETUP MODULE THAT I WANT TO BE LAZILY LOADED

```<code>import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CompaniesSetupComponent } from './companies-setup/companies-setup.component';
import { SetupDashboardComponent } from './setup-dashboard/setup-dashboard.component';
import { BusinessUnitSetupComponent } from './business-unit-setup/business-unit-setup.component';

const appRoutes: Routes = [

  { path: '', component: SetupDashboardComponent},
]
@NgModule({
  imports: [RouterModule.forChild(appRoutes)],
  exports: [],
  declarations: []
})

export class SetupRoutingModule {

}
</code>```

//THIS IS MY SETUP.MODULE.TS FILE

```<code>import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UtilsModule } from '../EW_Utils/utils.module';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { SetupDashboardComponent } from './setup-dashboard/setup-dashboard.component';
@NgModule({
  imports: [
    CommonModule,UtilsModule,FormsModule,ReactiveFormsModule,NgxSpinnerModule,SharedModule,SetupRoutingModule,Ng2SearchPipeModule,GrowlerModule,TextareaAutosizeModule
  ],
  declarations: [ SetupDashboardComponent, SidebarMenuComponent, CompaniesSetupComponent, BusinessUnitSetupComponent],
  providers:[CompaniesSetupService,GrowlerService,CommonApiService],
  entryComponents:[]
})
export class SetupModule { }
</code>```

答:
I have a project of the following structure:

gridster module contains @app/modules/gridster/angular-grid/angulargridComponent

analytics module contains @app/modules/analytics/components/analytics-one/AnalyticsOneComponent

Note: Where my gridster module already using analytics module by importing it.

I got the above issue when I tried to access the angulargridComponent inside analytics module due to the varied path and parent-child nestings.

Previously my analytics routing was:

```<code>{ path: 'gross-profit', component: angulargridComponent}
</code>```

Instead of imported using, I changed to this and it worked:

```<code>{ path: 'gross-profit', loadChildren: '@app/modules/gridster/gridster.module#angulargridModule' }
</code>```

Where angulargridModule is the module class name inside gridster module and it contains only one component ie angulargridComponent

Body:
This is error i am getting:-

Error: Component Component is not part of any NgModule or the module has not been imported into your module.
Error: Component Component is not part of any NgModule or the module has not been imported into your module.

I want my setup module to be lazily loaded but getting error like component is not part of module or the module has not been imported into your module

//This is my app.module.ts
import { BrowserModule, Title } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { LeaveService } from './EW_Leave/leave.service';
import { UtilsModule } from './EW_Utils/utils.module';
import { JobReferenceComponent } from '../app/EW_Utils/job-reference/job-reference.component'
import { CommonModule } from '@angular/common';
import { AppComponent } from './app.component';
import { AppRoutingModule } from './app-routing.module';
import { EWDashboardComponent } from './EW_Dashboard/ew-dashboard.component';
import { EWLoginComponent } from './EW_Login/ew-login.component';

@NgModule({
  imports: [
    StorageServiceModule,
    CommonModule,
    BrowserModule,
    FormsModule, ReactiveFormsModule,
    AppRoutingModule,
    UtilsModule, LeaveModule,
  ],
  declarations: [
    AppComponent, JobReferenceComponent, EWDashboardComponent, EWLoginComponent
  ],
  exports: [],
  providers: [LeaveService, Title],
  bootstrap: [AppComponent]
})
export class AppModule {

}

//this is my app-routing.module.ts

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { EWDashboardComponent } from './EW_Dashboard/ew-dashboard.component';
import { EWLoginComponent } from './EW_Login/ew-login.component';
import { SetupDashboardComponent } from './EW_Setup/setup-dashboard/setup-dashboard.component';
import {CompaniesSetupComponent} from './EW_Setup/companies-setup/companies-setup.component';
const appRoutes: Routes = [
  { path: 'login', component: EWLoginComponent },
  { path: 'dashboard', component: EWDashboardComponent },
  { path: '', redirectTo: 'login', pathMatch: 'full' },
  { path: 'setup',

   loadChildren: './EW_Setup/setup.module#CustomersModule'

  },

]
@NgModule({
  imports: [RouterModule.forRoot(appRoutes)],
  exports: [RouterModule],
  declarations: []
})

export class AppRoutingModule {

}

THIS BELOW SETUP MODULE THAT I WANT TO BE LAZILY LOADED

import { NgModule } from '@angular/core';
import { RouterModule, Routes } from '@angular/router';
import { CompaniesSetupComponent } from './companies-setup/companies-setup.component';
import { SetupDashboardComponent } from './setup-dashboard/setup-dashboard.component';
import { BusinessUnitSetupComponent } from './business-unit-setup/business-unit-setup.component';

const appRoutes: Routes = [

  { path: '', component: SetupDashboardComponent},
]
@NgModule({
  imports: [RouterModule.forChild(appRoutes)],
  exports: [],
  declarations: []
})

export class SetupRoutingModule {

}

//THIS IS MY SETUP.MODULE.TS FILE

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { UtilsModule } from '../EW_Utils/utils.module';
import { FormsModule } from '@angular/forms';
import { ReactiveFormsModule } from '@angular/forms';
import { SetupDashboardComponent } from './setup-dashboard/setup-dashboard.component';
@NgModule({
  imports: [
    CommonModule,UtilsModule,FormsModule,ReactiveFormsModule,NgxSpinnerModule,SharedModule,SetupRoutingModule,Ng2SearchPipeModule,GrowlerModule,TextareaAutosizeModule
  ],
  declarations: [ SetupDashboardComponent, SidebarMenuComponent, CompaniesSetupComponent, BusinessUnitSetupComponent],
  providers:[CompaniesSetupService,GrowlerService,CommonApiService],
  entryComponents:[]
})
export class SetupModule { }

Body:
I have a project of the following structure:

gridster module contains @app/modules/gridster/angular-grid/angulargridComponent

analytics module contains @app/modules/analytics/components/analytics-one/AnalyticsOneComponent

Note: Where my gridster module already using analytics module by importing it.

I got the above issue when I tried to access the angulargridComponent inside analytics module due to the varied path and parent-child nestings.

Previously my analytics routing was:

{ path: 'gross-profit', component: angulargridComponent}

Instead of imported using, I changed to this and it worked:

{ path: 'gross-profit', loadChildren: '@app/modules/gridster/gridster.module#angulargridModule' }

Where angulargridModule is the module class name inside gridster module and it contains only one component ie angulargridComponent


问:
In Jenkins-Pipeline how do I use sshPut to copy contents of folder, not folder itself?
On my Jenkins server, I have a simple test pipeline to check into copying build data to a remote server.
I'm using the SSH Pipeline Steps plugin.

My code is:

```<code>            stage('Remote SSH') {
              steps {
                sshRemove remote: remote, path: "/mnt/test"
                sshCommand remote: remote, command: "mkdir /mnt/test"

                writeFile file: './tst/abc.sh', text: 'ls -lrt'
                sshPut remote: remote, from: './tst/', into: '/mnt/test/.'
            }
</code>```

The result is that in /mnt/test I have the created "tst" folder and it's contents.
What I wanted was just the contents of this tst folder to be transfered to the target.

How should I be formatting the sshPut step?

答:
Looking at source-code and reading a bit about copy commands in Java it seems like this is just the way the filecopy operations work in Java.
That one would have to iterate through the directory contents to do it another way.

Since I'm creating the source folder (even in my real build example), it seems that the best option is just to rename the folder before the move:

```<code>  sshRemove remote: remote, path: "/mnt/test"
  writeFile file: './tst/abc.sh', text: 'ls -lrt'
  sh "mv ./tst ./test"
  sshPut remote: remote, from: './test/.', into: '/mnt/'
</code>```

I'd happily listen if someone has another solution.

Body:
On my Jenkins server, I have a simple test pipeline to check into copying build data to a remote server.
I'm using the SSH Pipeline Steps plugin.

My code is:

            stage('Remote SSH') {
              steps {
                sshRemove remote: remote, path: "/mnt/test"
                sshCommand remote: remote, command: "mkdir /mnt/test"

                writeFile file: './tst/abc.sh', text: 'ls -lrt'
                sshPut remote: remote, from: './tst/', into: '/mnt/test/.'
            }

The result is that in /mnt/test I have the created "tst" folder and it's contents.
What I wanted was just the contents of this tst folder to be transfered to the target.

How should I be formatting the sshPut step?

Body:
Looking at source-code and reading a bit about copy commands in Java it seems like this is just the way the filecopy operations work in Java.
That one would have to iterate through the directory contents to do it another way.

Since I'm creating the source folder (even in my real build example), it seems that the best option is just to rename the folder before the move:

  sshRemove remote: remote, path: "/mnt/test"
  writeFile file: './tst/abc.sh', text: 'ls -lrt'
  sh "mv ./tst ./test"
  sshPut remote: remote, from: './test/.', into: '/mnt/'

I'd happily listen if someone has another solution.


问:
I want to get string from list
there is a matrix like below

```<code>[[a1, b, c],
[d2, e, a1],
[c1, dfd, u],
....

]
</code>```

if matched with a specific word, then returns index from matrix.
And find row fixed column.
then I convert Matrix to list.
And I get the result like this ["RESULT DATA"].
I just want to get string RESULT DATA only without [''].

```<code>r, c = np.where(Matrix == SpecificWord)
find_row = np.where(c == 0)
result_data = Matrix[find_row,1].tolist()
print(str(result_data ))
print(result_data[0])
</code>```

答:
Solved</p>

```<code>row, col = np.where(Terms == ElemData)
cList = col .tolist()
rLits = row.tolist()
if 0 not in cList:
    return None
else:
    num_col = cList.index(0)
    num_row = rLits[num_col]
    data = Terms[num_row, 1].tolist()
    return data
</code>```

Title: I want to get string from list

Body:
there is a matrix like below

[[a1, b, c],
[d2, e, a1],
[c1, dfd, u],
....

]

if matched with a specific word, then returns index from matrix.
And find row fixed column.
then I convert Matrix to list.
And I get the result like this ["RESULT DATA"].
I just want to get string RESULT DATA only without [''].

r, c = np.where(Matrix == SpecificWord)
find_row = np.where(c == 0)
result_data = Matrix[find_row,1].tolist()
print(str(result_data ))
print(result_data[0])

Body:
Solved

row, col = np.where(Terms == ElemData)
cList = col .tolist()
rLits = row.tolist()
if 0 not in cList:
    return None
else:
    num_col = cList.index(0)
    num_row = rLits[num_col]
    data = Terms[num_row, 1].tolist()
    return data


问:
how to make chart using data from database?
HI
i am making a window application using visual studio 2010 and vb.net. i want to make charts daynimacilly using data from the database. how this can be done?

thanks
Yatin

答: There is a chart control installed out of the box in Visual Studio 2010 - Have a look in your control toolbox under Data. To start you off, have a look at the System.Windows.Forms.DataVisualization.Charting Namespace</p>


问:
How to enable file sharing for my app?
I have an image editing app where users can apply effects to photos. How could I enable it so that users can see my app in iTunes in the File Sharing tab and then just drag+drop photos to the app?

Some of the eBook readers like Stanza works like this and it would be a cool option. Maybe someone can point out a tutorial or resource that talks about how to enable and use this technique.

答:
You just have to set UIFileSharingEnabled (Application Supports iTunes file sharing) key in the info plist of your app. Here's a link for the documentation. Scroll down to the file sharing support part.

In the past, it was also necessary to define CFBundleDisplayName (Bundle Display Name), if it wasn't already there. More details here.

Title: How to enable file sharing for my app?


问:
Apache CXF 2.7 context passing issues
I wrote a logging filter and pass around certain information from ContainerRequestContext to WriterInterceptorContext using the setProperty() function of ContainerRequestContext.

I am able to retrieve the property I set using getProperty when using with a Jersey implementation.

But the same does not work with the Apache CXF 2.7. Any inputs?

```<code>public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter,WriterInterceptor {

@Override
public void filter(ContainerRequestContext reqContext) throws IOException {
  reqContext.setProperty("sampleProperty", "sampleValue");
}

@Override
public void aroundWriteTo(WriterInterceptorContext context)
    throws IOException, WebApplicationException {
 if (context.getProperty("sampleProperty") != null) { -> passes for jersey, fails for Apache CXF 2.0
 }
}
</code>```

答:
I found the solution to get the context.</p>

```<code>public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter,WriterInterceptor {

@Override
public void filter(ContainerRequestContext reqContext) throws IOException {
  reqContext.setProperty("sampleProperty", "sampleValue");
}

@Override
public void aroundWriteTo(WriterInterceptorContext context)
    throws IOException, WebApplicationException {
    Message message = JAXRSUtils.getCurrentMessage();
    ContainerRequestContext reqContext = new ContainerRequestContextImpl(message.getExchange().getInMessage(),
            false, true);
 if (reqContext.getProperty("sampleProperty") != null) {
 }
}
</code>```

Title: Apache CXF 2.7 context passing issues

Body:
I wrote a logging filter and pass around certain information from ContainerRequestContext to WriterInterceptorContext using the setProperty() function of ContainerRequestContext.

I am able to retrieve the property I set using getProperty when using with a Jersey implementation.

But the same does not work with the Apache CXF 2.7. Any inputs?

public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter,WriterInterceptor {

@Override
public void filter(ContainerRequestContext reqContext) throws IOException {
  reqContext.setProperty("sampleProperty", "sampleValue");
}

@Override
public void aroundWriteTo(WriterInterceptorContext context)
    throws IOException, WebApplicationException {
 if (context.getProperty("sampleProperty") != null) { -> passes for jersey, fails for Apache CXF 2.0
 }
}

Body:
I found the solution to get the context.

public class LoggingFilter implements ContainerRequestFilter, ContainerResponseFilter,WriterInterceptor {

@Override
public void filter(ContainerRequestContext reqContext) throws IOException {
  reqContext.setProperty("sampleProperty", "sampleValue");
}

@Override
public void aroundWriteTo(WriterInterceptorContext context)
    throws IOException, WebApplicationException {
    Message message = JAXRSUtils.getCurrentMessage();
    ContainerRequestContext reqContext = new ContainerRequestContextImpl(message.getExchange().getInMessage(),
            false, true);
 if (reqContext.getProperty("sampleProperty") != null) {
 }
}


问:
ASP.NET Core: validation attributes are ignored on fields defined in children types
My ASP.NET Core 2.1 API exposes the following input DTO in a POST endpoint:

[Route("test")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpPost("endpoint")]
    public async Task<IActionResult> Post([Required]MyDTO dto)
    {
        // Some code
    }
}
```

<pre class="lang-cs prettyprint-override"><code>public class MyDTO
{
  [JsonProperty("foo")]
  [Required]
  public Foo Foo { get; set; }
}
</code>```

The Foo class is defined as follow:

[JsonConverter(typeof(FooConverter))]
public abstract class Foo
{
  [JsonProperty("foo_type")]
  [Required]
  public string FooType { get; set; }
}
```

<p>The <code>FooConverter</code> class is able to instantiate the right implementation based on the <code>foo_type</code> field:</p>

<pre class="lang-cs prettyprint-override"><code>public class FooConverter : JsonConverter<Foo>
{
    public override bool CanRead => true;
    public override bool CanWrite => false;

    public override Foo ReadJson(JsonReader reader, Type objectType, Foo existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var jObject = JObject.Load(reader);
        Foo target = this.CreateFoo(jObject);
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }

    public override void WriteJson(JsonWriter writer, Foo value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    private Foo CreateFoo(JObject jObject)
    {
        string fooType = jObject.Value<string>("foo_type");
        switch (fooType)
        {
            case "foo1":
                return new Foo1();
            case "foo2":
                return new Foo2();
            default:
                throw new JsonSerializationException($"Invalid 'foo_type' '{fooType}'");
        }
    }
}
</code>```

Here is one of the implementations of the Foo abstract class:

public class Foo1 : Foo
{
  [JsonProperty("bar")]
  [Required]
  public string Bar { get; set; }
}
```

My problem is that the [Required] attribute on Foo1.Bar is ignored by ASP.NET validation, even though the [Required] attribute on Foo.FooType works as expected. How can I automatically validate the fields defined in the implementation types so that it works the same as with other fields?

答:
Replace:

```<code>var jObject = JObject.Load(reader);
</code>```

with:

```<code>JToken jObject = JToken.ReadFrom(reader);
</code>```

Body:
My ASP.NET Core 2.1 API exposes the following input DTO in a POST endpoint:

[Route("test")]
[ApiController]
public class TestController : ControllerBase
{
    [HttpPost("endpoint")]
    public async Task<IActionResult> Post([Required]MyDTO dto)
    {
        // Some code
    }
}

public class MyDTO
{
  [JsonProperty("foo")]
  [Required]
  public Foo Foo { get; set; }
}

The Foo class is defined as follow:

[JsonConverter(typeof(FooConverter))]
public abstract class Foo
{
  [JsonProperty("foo_type")]
  [Required]
  public string FooType { get; set; }
}

The FooConverter class is able to instantiate the right implementation based on the foo_type field:

public class FooConverter : JsonConverter<Foo>
{
    public override bool CanRead => true;
    public override bool CanWrite => false;

    public override Foo ReadJson(JsonReader reader, Type objectType, Foo existingValue, bool hasExistingValue, JsonSerializer serializer)
    {
        var jObject = JObject.Load(reader);
        Foo target = this.CreateFoo(jObject);
        serializer.Populate(jObject.CreateReader(), target);

        return target;
    }

    public override void WriteJson(JsonWriter writer, Foo value, JsonSerializer serializer)
    {
        throw new NotImplementedException();
    }

    private Foo CreateFoo(JObject jObject)
    {
        string fooType = jObject.Value<string>("foo_type");
        switch (fooType)
        {
            case "foo1":
                return new Foo1();
            case "foo2":
                return new Foo2();
            default:
                throw new JsonSerializationException($"Invalid 'foo_type' '{fooType}'");
        }
    }
}

Here is one of the implementations of the Foo abstract class:

public class Foo1 : Foo
{
  [JsonProperty("bar")]
  [Required]
  public string Bar { get; set; }
}

My problem is that the [Required] attribute on Foo1.Bar is ignored by ASP.NET validation, even though the [Required] attribute on Foo.FooType works as expected. How can I automatically validate the fields defined in the implementation types so that it works the same as with other fields?

Body:
Replace:

var jObject = JObject.Load(reader);

with:

JToken jObject = JToken.ReadFrom(reader);