问:
AzureDevops API builds list API returns empty json results
I am unable to get a list of builds when using the devops api (I am requesting it without any additional filters)

https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.1

It returns the following

{ "value": [ ], "count": 0 }

It seems that the API is working other wise as if the following URL is working and returning a full details about the build

https://dev.azure.com/{organization}/{project}/_apis/build/builds/{buildId}?api-version=5.1

I am using token authentication and all the other tests seem to work as I would expect. All the {variables} are replaced with my queries, but have left them in as that is somewhat sensitiv(e.

Am I missing something? Is the API broken?

答:
AzureDevops API builds list API returns empty json results

As test, the rest api Builds - List works fine:

```<code>GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.1
</code>```

I test it with postman by using the PAT (only have the build read scope of access):

So, the REST API is fine.

Besides, since you could also get the result with a specify a build Id, please confirm if  there are any errors in your url and if there are too many pipelines in your project, which has not returned the correct value in time. You could test it with a new test project.

Besides, what Eric said is also a possibility, please make sure the token authentication have permission to read all pipeline, you could create a PAT with build read scope of access.

Hope this helps.

Body:
AzureDevops API builds list API returns empty json results

As test, the rest api Builds - List works fine:

GET https://dev.azure.com/{organization}/{project}/_apis/build/builds?api-version=5.1

I test it with postman by using the PAT (only have the build read scope of access):

So, the REST API is fine.

Besides, since you could also get the result with a specify a build Id, please confirm if  there are any errors in your url and if there are too many pipelines in your project, which has not returned the correct value in time. You could test it with a new test project.

Besides, what Eric said is also a possibility, please make sure the token authentication have permission to read all pipeline, you could create a PAT with build read scope of access.

Hope this helps.


来源: stackexchange

问:
How to replace switch-case to OOP
I have methods with which I get data from a database.
Depending on the variable that the user entered through the console, I must execute the desired method

```<code>       while (flag) {
           try {
               sw = new ScannerWrapper();
               menuHeader();
               int choice = sw.readInt();
               switch (choice) {
                   case 1:
                       System.out.println("Input first name: ");
                       String name = sw.readLine().toUpperCase();
                       printResults(DataParser.getFilmByName(name));
                       break;
                     case 0:
                       System.out.println("Bye-bye. Come again");
                       flag = false;
                       break;
                   default:
                       System.out.println("Please enter correct number");
               }
           } catch (Exception e) {
               System.out.println("Enter correct data");
           } finally {
               DBConnector.getInstance().closeConnection();
           }
       }
</code>```

This code is very bad.There are more than 5 cases with methods and the code becomes redundant

答:
You should have a look at the Strategy design pattern. That will allow you to abstract the logic related to an action.

On top of that, you want to replace the switch to find the right strategy according to the input variable. That is the job of the Factory design pattern, which in your case would return one of the different strategies according to the database value.

Basically:

```<code>interface UserAction {
    public void execute();
}

class ListMovies implements UserAction {
    public void execute() {
        // List the movies
    }
}

class ExitProgram implements UserAction {
    public void execute() {
        // Kill kenny
    }
}

class Noop implements UserAction {
    public void execute() {
        // Do nothing
    }
}
</code>```

And a factory:

```<code>class UserActionFactory {
    public UserAction make(int actionId) {
        switch (actionId) {
            0: return new ListMovies();
            1: return new ExitProgram();
            default: return new Noop();
        }
    }
}
</code>```

Which then allows:

```<code>UserActionFactory factory = new UserActionFactory();
ScannerWrapper sw = new ScannerWrapper();

while (true) {
    menuHeader();
    int choice = sw.readInt();
    UserAction action = factory.make(choice);
    action.execute();
</code>```

}

This could also be the Command design pattern, depends on how you name things and instantiate objects for the rest of the classes.

ContentLicense: CC BY-SA 4.0

Title: How to replace switch-case to OOP

Body:
I have methods with which I get data from a database.
Depending on the variable that the user entered through the console, I must execute the desired method

       while (flag) {
           try {
               sw = new ScannerWrapper();
               menuHeader();
               int choice = sw.readInt();
               switch (choice) {
                   case 1:
                       System.out.println("Input first name: ");
                       String name = sw.readLine().toUpperCase();
                       printResults(DataParser.getFilmByName(name));
                       break;
                     case 0:
                       System.out.println("Bye-bye. Come again");
                       flag = false;
                       break;
                   default:
                       System.out.println("Please enter correct number");
               }
           } catch (Exception e) {
               System.out.println("Enter correct data");
           } finally {
               DBConnector.getInstance().closeConnection();
           }
       }

This code is very bad.There are more than 5 cases with methods and the code becomes redundant

Body:
You should have a look at the Strategy design pattern. That will allow you to abstract the logic related to an action.

On top of that, you want to replace the switch to find the right strategy according to the input variable. That is the job of the Factory design pattern, which in your case would return one of the different strategies according to the database value.

Basically:

interface UserAction {
    public void execute();
}

class ListMovies implements UserAction {
    public void execute() {
        // List the movies
    }
}

class ExitProgram implements UserAction {
    public void execute() {
        // Kill kenny
    }
}

class Noop implements UserAction {
    public void execute() {
        // Do nothing
    }
}

And a factory:

class UserActionFactory {
    public UserAction make(int actionId) {
        switch (actionId) {
            0: return new ListMovies();
            1: return new ExitProgram();
            default: return new Noop();
        }
    }
}

Which then allows:

UserActionFactory factory = new UserActionFactory();
ScannerWrapper sw = new ScannerWrapper();

while (true) {
    menuHeader();
    int choice = sw.readInt();
    UserAction action = factory.make(choice);
    action.execute();

}

This could also be the Command design pattern, depends on how you name things and instantiate objects for the rest of the classes.


问:
Creating different admin that everyone has permission to see only the products he enter
I want to allow different sellers to see only their products on their ADMIN site, add products that only they will see (except the general manager)
I attach the model of the products:

```<code>class Item(models.Model):
 ***seller = models.ForeignKey(Seller, on_delete=models.CASCADE)***
    name = models.CharField(max_length=20)
    manufacturer = models.CharField(max_length=20, blank=True)
    category = models.ForeignKey(Categories, on_delete=models.CASCADE)
    subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_DEFAULT, default=types.item_types.GENERAL)
    slug = models.SlugField(max_length=200, db_index=True, blank=True)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to=r'ecommerce/pictures', blank=True)  # adding date to the path?
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
    stock = models.PositiveIntegerField(blank=True)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    sales = models.BooleanField(default=False)
</code>```

Thanks to those who can advise me.

答:
What you need here - the permissions and specifically model admin change permission check. It could be something like this:

```<code>class BankAccountAdmin(admin.ModelAdmin):
    ...

    def has_change_permission(self, request, obj=None):
        return obj is None or obj.seller == request.user

    def get_queryset(self, request):
        return Item.objects.filter(seller=request.user)
</code>```

This will override the queryset and permission check to list/edit only records related with seller.

You may want to extend the logic to allow superuser list/change records or/and add some more specific permission.

Body:
I want to allow different sellers to see only their products on their ADMIN site, add products that only they will see (except the general manager)
I attach the model of the products:

class Item(models.Model):
 ***seller = models.ForeignKey(Seller, on_delete=models.CASCADE)***
    name = models.CharField(max_length=20)
    manufacturer = models.CharField(max_length=20, blank=True)
    category = models.ForeignKey(Categories, on_delete=models.CASCADE)
    subcategory = models.ForeignKey(Subcategory, on_delete=models.SET_DEFAULT, default=types.item_types.GENERAL)
    slug = models.SlugField(max_length=200, db_index=True, blank=True)
    description = models.TextField(blank=True)
    image = models.ImageField(upload_to=r'ecommerce/pictures', blank=True)  # adding date to the path?
    price = models.DecimalField(max_digits=10, decimal_places=2, blank=True)
    stock = models.PositiveIntegerField(blank=True)
    available = models.BooleanField(default=True)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    sales = models.BooleanField(default=False)

Thanks to those who can advise me.

Body:
What you need here - the permissions and specifically model admin change permission check. It could be something like this:

class BankAccountAdmin(admin.ModelAdmin):
    ...

    def has_change_permission(self, request, obj=None):
        return obj is None or obj.seller == request.user

    def get_queryset(self, request):
        return Item.objects.filter(seller=request.user)

This will override the queryset and permission check to list/edit only records related with seller.

You may want to extend the logic to allow superuser list/change records or/and add some more specific permission.


问:
How can I download stock price data with Python?
I have installed pandas-datareader but I'm wondering if there are alternatives.

So far, I'm using this:

```<code>import pandas_datareader.data as web
start_date = '2018-01-01'
end_date = '2018-06-08'
panel_data = web.DataReader('SPY', 'yahoo', start_date, end_date)
</code>```

答:
I found the easiest to be the new SimFin Python API which lets you download stock-prices and fundamental data, save it to disk, and load it into Pandas DataFrames with only a few lines of code. They have also made several tutorials on how to use their data with other libraries such as statsmodels, scikit-learn, TensorFlow, etc. The basic example below is copied from their github page.

You install the SimFin python package by typing this command in a terminal window (preferably in its own environement, see their full instructions):

```<code>pip install simfin
</code>```

Then you copy-paste the following into a Jupyter Notebook or Python source-file:

```<code>import simfin as sf
from simfin.names import *

# Set your API-key for downloading data.
# If the API-key is 'free' then you will get the free data,
# otherwise you will get the data you have paid for.
# See www.simfin.com for what data is free and how to buy more.
sf.set_api_key('free')

# Set the local directory where data-files are stored.
# The dir will be created if it does not already exist.
sf.set_data_dir('~/simfin_data/')

# Load the annual Income Statements for all companies in USA.
# The data is automatically downloaded if you don't have it already.
df = sf.load_income(variant='annual', market='us')

# Print all Revenue and Net Income for Microsoft (ticker MSFT).
print(df.loc['MSFT', [REVENUE, NET_INCOME]])
</code>```

This produces the following output:

```<code>                  Revenue   Net Income
Report Date
2008-06-30   6.042000e+10  17681000000
2009-06-30   5.843700e+10  14569000000
2010-06-30   6.248400e+10  18760000000
2011-06-30   6.994300e+10  23150000000
2012-06-30   7.372300e+10  16978000000
2013-06-30   7.784900e+10  21863000000
2014-06-30   8.683300e+10  22074000000
2015-06-30   9.358000e+10  12193000000
2016-06-30   9.115400e+10  20539000000
2017-06-30   9.657100e+10  25489000000
2018-06-30   1.103600e+11  16571000000
2019-06-30   1.258430e+11  39240000000
</code>```

We can also load the daily share-prices and plot the closing share-price for Microsoft (ticker MSFT):

```<code># Load daily share-prices for all companies in USA.
# The data is automatically downloaded if you don't have it already.
df_prices = sf.load_shareprices(market='us', variant='daily')

# Plot the closing share-prices for ticker MSFT.
df_prices.loc['MSFT', CLOSE].plot(grid=True, figsize=(20,10), title='MSFT Close')
</code>```

This produces the following image:

Body:
I have installed pandas-datareader but I'm wondering if there are alternatives.

So far, I'm using this:

import pandas_datareader.data as web
start_date = '2018-01-01'
end_date = '2018-06-08'
panel_data = web.DataReader('SPY', 'yahoo', start_date, end_date)

Body:
I found the easiest to be the new SimFin Python API which lets you download stock-prices and fundamental data, save it to disk, and load it into Pandas DataFrames with only a few lines of code. They have also made several tutorials on how to use their data with other libraries such as statsmodels, scikit-learn, TensorFlow, etc. The basic example below is copied from their github page.

You install the SimFin python package by typing this command in a terminal window (preferably in its own environement, see their full instructions):

pip install simfin

Then you copy-paste the following into a Jupyter Notebook or Python source-file:

import simfin as sf
from simfin.names import *

# Set your API-key for downloading data.
# If the API-key is 'free' then you will get the free data,
# otherwise you will get the data you have paid for.
# See www.simfin.com for what data is free and how to buy more.
sf.set_api_key('free')

# Set the local directory where data-files are stored.
# The dir will be created if it does not already exist.
sf.set_data_dir('~/simfin_data/')

# Load the annual Income Statements for all companies in USA.
# The data is automatically downloaded if you don't have it already.
df = sf.load_income(variant='annual', market='us')

# Print all Revenue and Net Income for Microsoft (ticker MSFT).
print(df.loc['MSFT', [REVENUE, NET_INCOME]])

This produces the following output:

                  Revenue   Net Income
Report Date
2008-06-30   6.042000e+10  17681000000
2009-06-30   5.843700e+10  14569000000
2010-06-30   6.248400e+10  18760000000
2011-06-30   6.994300e+10  23150000000
2012-06-30   7.372300e+10  16978000000
2013-06-30   7.784900e+10  21863000000
2014-06-30   8.683300e+10  22074000000
2015-06-30   9.358000e+10  12193000000
2016-06-30   9.115400e+10  20539000000
2017-06-30   9.657100e+10  25489000000
2018-06-30   1.103600e+11  16571000000
2019-06-30   1.258430e+11  39240000000

We can also load the daily share-prices and plot the closing share-price for Microsoft (ticker MSFT):

# Load daily share-prices for all companies in USA.
# The data is automatically downloaded if you don't have it already.
df_prices = sf.load_shareprices(market='us', variant='daily')

# Plot the closing share-prices for ticker MSFT.
df_prices.loc['MSFT', CLOSE].plot(grid=True, figsize=(20,10), title='MSFT Close')

This produces the following image:


问:
How can I use C++ class in Python?
I have implemented a class in C++. I want to use it with Python.
Please suggest step by step method and elaborate each step.
Somthing like this...

```<code>class Test{
     private:
        int n;
     public:
        Test(int k){
            n=k;
        }
        void setInt(int k){
            n = k;
        }
        int getInt(){
            return n;
        }
};
</code>```

Now, in Python

```<code>>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32
</code>```

Please suggest.How can I do this ?
NOTE: I would like to know manual way to do that. I don't want any third party library dependency.

答:
Look into Boost.Python. It's a library to write python modules with C++.

Also look into SWIG which can also handle modules for other scripting languages. I've used it in the past to write modules for my class and use them within python. Works great.

You can do it manually by using the Python/C API, writing the interface yourself. It's pretty lowlevel, but you will gain a lot of additional knowledge of how Python works behind the scene (And you will need it when you use SWIG anyway).

OwnerDisplayName: david makcenzie

ContentLicense: CC BY-SA 2.5

Title: How can I use C++ class in Python?

Body:
I have implemented a class in C++. I want to use it with Python.
Please suggest step by step method and elaborate each step.
Somthing like this...

class Test{
     private:
        int n;
     public:
        Test(int k){
            n=k;
        }
        void setInt(int k){
            n = k;
        }
        int getInt(){
            return n;
        }
};

Now, in Python

>>> T1 = Test(12)
>>> T1.getInt()
12
>>> T1.setInt(32)
>>> T1.getInt()
32

Please suggest.How can I do this ?
NOTE: I would like to know manual way to do that. I don't want any third party library dependency.

LastEditorDisplayName: david makcenzie

OwnerDisplayName: litb

LastEditorDisplayName: litb


问:
data binding to grid with unknown number of columns
How do I bind to a WPF grid with an unknown number of columns?

I have a class that can return the number of columns and column names, etc. as well as the items that will get bound to each row. Basically, I want to do what the DataTable can do without using the datatable. There must be an interface I need to implement or something like that.

答:
I ended up solving this problem by using the SyncFusion grid control. I found that the built-in grid, as well as pretty much every grid on the market, is very orientated towards one row being an object returned from the database.

If you deviate from this model then most grids becomes useless or at least very difficult to work with. In my case, each row from the database represented a single cell. The key problem I had with all grid was getting a WPF template to work with the unbound data. The SyncFusion grid was the only one I could find that would work with these two features together (ubound data and data templates).

I also found that the flexgrid will solve this problem although it was a little difficult to work with in this regard.

ContentLicense: CC BY-SA 3.0


问:
Hiding span under div in CSS
Below is the code for my WP post. I'm trying to hide the span for comment. So that it doesn't appear on the blog post.

```<code><div class="blog-stats">
    <span class="clock">
        <i class="fa fa-calendar stats-item"></i>
        <span class="text-center text-light stats-item">February 15, 2020</span>
    </span>
    <span class="comment">
        <i class="fa fa-comment stats-item"></i>
        <span class="text-center text-light stats-item">no comments</span>
    </span>
    <span class="user">
        <i class="fa fa-user stats-item"></i>
        <span class="text-content text-light stats-item">Wayne John</span>
    </span>
</div>
</code>```

I tried a few below and it didn't work.

```<code>.blog-stats.comment {
    display: none;
}

span .comment {
    display: none;
}

span.comment {
    display: none;
}
</code>```

Any idea how to fix it?

答:
please put space between classes like

```<code>.blog-stats .comment {
    display: none;
}
or
.blog-stats .comment {
   display: none !important;
 }
</code>```

this will work please try

Title: Hiding span under div in CSS

Body:
Below is the code for my WP post. I'm trying to hide the span for comment. So that it doesn't appear on the blog post.

        February 15, 2020

        no comments

        Wayne John

I tried a few below and it didn't work.

.blog-stats.comment {
    display: none;
}

span .comment {
    display: none;
}

span.comment {
    display: none;
}

Any idea how to fix it?

Body:
please put space between classes like

.blog-stats .comment {
    display: none;
}
or
.blog-stats .comment {
   display: none !important;
 }

this will work please try


问:
Retrieving string from html on non-unique table
Here is the html I am trying to parse.

```<code><TD>Serial Number</TD><TD>AB12345678</TD>
</code>```

I am attempting to use regex to parse the data. I heard about BeautifulSoup but there are around 50 items like this on the page all using the same table parameters and none of them have ID numbers. The closest they have to unique identifiers is the data in the cell before the data I need.

```<code>serialNumber = re.search("Serial Number</td><td>\n(.*?)</td>", source)
</code>```

Source is simply the source code of the page grabbed using urllib. There is new line in the html between the second  and the serial number but I am unsure if that matters.

答:
Pyparsing can give you a little more robust extractor for your data:

```<code>from pyparsing import makeHTMLTags, Word, alphanums

htmlfrag = """<blah></blah><TD>Serial Number</TD><TD>
            AB12345678
            </TD><stuff></stuff>"""

td,tdEnd = makeHTMLTags("td")

sernoFormat = (td + "Serial Number" + tdEnd +
                td + Word(alphanums)('serialNumber') + tdEnd)

for sernoData in sernoFormat.searchString(htmlfrag):
    print sernoData.serialNumber
</code>```

Prints:

```<code>AB12345678
</code>```

Note that pyparsing doesn't care where the extra whitespace falls, and it also handles unexpected attributes that might crop up in the defined tags, whitespace inside tags, tags in upper/lower case, etc.

Body:
Here is the html I am trying to parse.

Serial Number	AB12345678

I am attempting to use regex to parse the data. I heard about BeautifulSoup but there are around 50 items like this on the page all using the same table parameters and none of them have ID numbers. The closest they have to unique identifiers is the data in the cell before the data I need.

serialNumber = re.search("Serial Number	\n(.*?)	", source)

Source is simply the source code of the page grabbed using urllib. There is new line in the html between the second  and the serial number but I am unsure if that matters.

Body:
Pyparsing can give you a little more robust extractor for your data:

from pyparsing import makeHTMLTags, Word, alphanums

htmlfrag = """<blah></blah><TD>Serial Number</TD><TD>
            AB12345678
            </TD><stuff></stuff>"""

td,tdEnd = makeHTMLTags("td")

sernoFormat = (td + "Serial Number" + tdEnd +
                td + Word(alphanums)('serialNumber') + tdEnd)

for sernoData in sernoFormat.searchString(htmlfrag):
    print sernoData.serialNumber

Prints:

AB12345678

Note that pyparsing doesn't care where the extra whitespace falls, and it also handles unexpected attributes that might crop up in the defined tags, whitespace inside tags, tags in upper/lower case, etc.


问:
Application crashing when clicking on Highcharts data export menu
I am using Highcharts in my mobile application, and it just stops working (crashes) when I click the highcharts export menu button.

Does anyone know how to solve this problem?

note: I am using the demo version.

```<code>  Process: com.ppgcc.mychart, PID: 21923
    java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.ppgcc.mychart.FileProvider
        at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:606)
        at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
        at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
        at com.highsoft.highcharts.Core.d.onDownloadStart(SourceFile:64)
        at ic.a(PG:548)
        at An.handleMessage(PG:25)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
</code>```

答:
I think that the answer to your issue is here:

https://github.com/highcharts/highcharts-android/blob/master/README.md#export-module-requirements

Let me know if creating the provider_paths file resolved the issue.

Body:
I am using Highcharts in my mobile application, and it just stops working (crashes) when I click the highcharts export menu button.

Does anyone know how to solve this problem?

note: I am using the demo version.

  Process: com.ppgcc.mychart, PID: 21923
    java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority com.ppgcc.mychart.FileProvider
        at androidx.core.content.FileProvider.parsePathStrategy(FileProvider.java:606)
        at androidx.core.content.FileProvider.getPathStrategy(FileProvider.java:579)
        at androidx.core.content.FileProvider.getUriForFile(FileProvider.java:417)
        at com.highsoft.highcharts.Core.d.onDownloadStart(SourceFile:64)
        at ic.a(PG:548)
        at An.handleMessage(PG:25)
        at android.os.Handler.dispatchMessage(Handler.java:107)
        at android.os.Looper.loop(Looper.java:214)
        at android.app.ActivityThread.main(ActivityThread.java:7356)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)


问:
Printing fixed width strings that contain multi-byte characters
I have some strings that are stored in multi-byte UTF8 format, and I'd like to print them to the console in a fixed-width space. I am doing this by:

```<code>wprintf(L"////////////// BLOCK 1 ///////////////   ////////////// BLOCK 2 ///////////////   ////////////// BLOCK 3 ///////////////\n");
wprintf(L"// %-32S //   // %-32S //   // %-32S //\n", mymemcard[0].filename, mymemcard[1].filename, mymemcard[2].filename);
wprintf(L"// %-32S //   // %-32S //   // %-32S //\n", mymemcard[0].titleUTF, mymemcard[1].titleUTF, mymemcard[2].titleUTF);
wprintf(L"//////////////////////////////////////   //////////////////////////////////////   //////////////////////////////////////\n\n");
</code>```

The filename variables are in ASCII format and work fine, but the titleUTF variables will print too short if they contain any multi-byte characters. I assume this is because the wprintf function includes each byte of the multi-byte characters when calculating the width. See below for output:

The "dash" character in the THPS2 title is actually a half-width Japanese character, this is what's breaking the wprintf function in this case.

I've tried using "%-32lS" but this prints garbage to the console, and I've tried lower case "s" but this also prints garbage. Any ideas how to get the fixed width print even with multi-byte characters?

EDIT:

Here is a screenshot showing the titleUDF variables in memory, along with the offending "THPS2" string bytes:

As you can see, the "dash" character is represented as 0xef 0xbd 0xb0

It's worth noting that I have to call:

```<code>SetConsoleCP(65001);
SetConsoleOutputCP(65001);
</code>```

To get the multi-byte characters to show up properly. Also, I have to change the font in my console to one that has glyphs for these characters. I use NSimSun.

答:
I think, you will not be able to fix wprintf (or will write your full version of wprintf). So,
there is simple/rough solution :(  :</p>

```<code>void PrintFilenameLine(const wchar_t* line1, const wchar_t* line2, const wchar_t* line3) {
  // Detect sizes of lines
  // Generate output string
}
</code>```

Body:
I have some strings that are stored in multi-byte UTF8 format, and I'd like to print them to the console in a fixed-width space. I am doing this by:

wprintf(L"////////////// BLOCK 1 ///////////////   ////////////// BLOCK 2 ///////////////   ////////////// BLOCK 3 ///////////////\n");
wprintf(L"// %-32S //   // %-32S //   // %-32S //\n", mymemcard[0].filename, mymemcard[1].filename, mymemcard[2].filename);
wprintf(L"// %-32S //   // %-32S //   // %-32S //\n", mymemcard[0].titleUTF, mymemcard[1].titleUTF, mymemcard[2].titleUTF);
wprintf(L"//////////////////////////////////////   //////////////////////////////////////   //////////////////////////////////////\n\n");

The filename variables are in ASCII format and work fine, but the titleUTF variables will print too short if they contain any multi-byte characters. I assume this is because the wprintf function includes each byte of the multi-byte characters when calculating the width. See below for output:

The "dash" character in the THPS2 title is actually a half-width Japanese character, this is what's breaking the wprintf function in this case.

I've tried using "%-32lS" but this prints garbage to the console, and I've tried lower case "s" but this also prints garbage. Any ideas how to get the fixed width print even with multi-byte characters?

EDIT:

Here is a screenshot showing the titleUDF variables in memory, along with the offending "THPS2" string bytes:

As you can see, the "dash" character is represented as 0xef 0xbd 0xb0

It's worth noting that I have to call:

SetConsoleCP(65001);
SetConsoleOutputCP(65001);

To get the multi-byte characters to show up properly. Also, I have to change the font in my console to one that has glyphs for these characters. I use NSimSun.

Body:
I think, you will not be able to fix wprintf (or will write your full version of wprintf). So,
there is simple/rough solution :(  :

void PrintFilenameLine(const wchar_t* line1, const wchar_t* line2, const wchar_t* line3) {
  // Detect sizes of lines
  // Generate output string
}


问:
How can I get albine() to be recognized as a function in Rstudio?

albine(reg=acorn.pl.reg, col="red")
  Error in albine(reg = acorn.pl.reg, col = "red") :
    could not find function "albine"

答: This is a syntax error. I think you want to use the function abline and you wrote albine.


问:
Can't build app in Visual Studio 2017 while using Apache Cordova
I'm trying to get a .apk for my project. I'm using Apache Cordova in Visual Studio 2017. When i tried to build my solution it always give some errors. I installed Gradle, Java Developer Kit. I have latest version of Cordova.
 Project is very simple. I used some scripts and html elements. But always I get errors. I just tried to combine default files with mine to see if I mistakly do something wrong. It doesn't changed. I even tried to build default project.
Here is what I get when i simply combine files without much changes. I always get that 31 errors. Here is my Error List:

```<code>Severity    Code    Description Project File    Line    Suppression State
Error       Picked up _JAVA_OPTIONS: -Xmx512M   Colors      1
Error       Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Server returned HTTP response code: 403 for URL: http://services.gradle.org/distributions/gradle-2.13-all.zip   Colors      1
Error        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:78)    Colors      1
Error        at org.gradle.wrapper.Install.createDist(Install.java:47)  Colors      1
Error        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)    Colors      1
Error        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)    Colors      1
Error       Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: http://services.gradle.org/distributions/gradle-2.13-all.zip   Colors      1
Error        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)  Colors      1
Error        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)   Colors      1
Error        at org.gradle.wrapper.Download.downloadInternal(Download.java:59)  Colors      1
Error        at org.gradle.wrapper.Download.download(Download.java:45)  Colors      1
Error        at org.gradle.wrapper.Install$1.call(Install.java:60)  Colors      1
Error        at org.gradle.wrapper.Install$1.call(Install.java:47)  Colors      1
Error        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)    Colors      1
Error        ... 3 more Colors      1
Error       Error: cmd: Command failed with exit code 1 Error output:   Colors      1
Error       Picked up _JAVA_OPTIONS: -Xmx512M   Colors      1
Error       Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Server returned HTTP response code: 403 for URL: http://services.gradle.org/distributions/gradle-2.13-all.zip   Colors      1
Error        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:78)    Colors      1
Error        at org.gradle.wrapper.Install.createDist(Install.java:47)  Colors      1
Error        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)    Colors      1
Error        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)    Colors      1
Error       Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: http://services.gradle.org/distributions/gradle-2.13-all.zip   Colors      1
Error        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)  Colors      1
Error        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)   Colors      1
Error        at org.gradle.wrapper.Download.downloadInternal(Download.java:59)  Colors      1
Error        at org.gradle.wrapper.Download.download(Download.java:45)  Colors      1
Error        at org.gradle.wrapper.Install$1.call(Install.java:60)  Colors      1
Error        at org.gradle.wrapper.Install$1.call(Install.java:47)  Colors      1
Error        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)    Colors      1
Error        ... 3 more Colors      1
</code>```

I'm just new to all these things. Did i missed something? Should I install some extra plugins or tools?

答:
This issue occurs because Cordova wants to update your gradle package but the url is invalid.

you can try accessing the URL in the error message:
http://services.gradle.org/distributions/gradle-2.13-all.zip
as you can see that link is forbidden by that site.
that is because that site has to use https,
so you can use SSL and try https://services.gradle.org/distributions/gradle-2.13-all.zip
That should work!!!

So how can I resolve this issue?

solution 1 : add a system environment variable

```<code>    CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL
https://services.gradle.org/distributions/gradle-2.13-all.zip
</code>```

here is a tutorial I found: https://www.architectryan.com/2018/08/31/how-to-change-environment-variables-on-windows-10/

solution 2: Update the Gradle package for Cordova manually

here is a useful tutorial I found: https://www.andreszsogon.com/upgrading-gradle-version-for-apache-cordova-mobile-apps/

I hope this helps you !!!

Body:
I'm trying to get a .apk for my project. I'm using Apache Cordova in Visual Studio 2017. When i tried to build my solution it always give some errors. I installed Gradle, Java Developer Kit. I have latest version of Cordova.
 Project is very simple. I used some scripts and html elements. But always I get errors. I just tried to combine default files with mine to see if I mistakly do something wrong. It doesn't changed. I even tried to build default project.
Here is what I get when i simply combine files without much changes. I always get that 31 errors. Here is my Error List:

Severity    Code    Description Project File    Line    Suppression State
Error       Picked up _JAVA_OPTIONS: -Xmx512M   Colors      1
Error       Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Server returned HTTP response code: 403 for URL: http://services.gradle.org/distributions/gradle-2.13-all.zip   Colors      1
Error        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:78)    Colors      1
Error        at org.gradle.wrapper.Install.createDist(Install.java:47)  Colors      1
Error        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)    Colors      1
Error        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)    Colors      1
Error       Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: http://services.gradle.org/distributions/gradle-2.13-all.zip   Colors      1
Error        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)  Colors      1
Error        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)   Colors      1
Error        at org.gradle.wrapper.Download.downloadInternal(Download.java:59)  Colors      1
Error        at org.gradle.wrapper.Download.download(Download.java:45)  Colors      1
Error        at org.gradle.wrapper.Install$1.call(Install.java:60)  Colors      1
Error        at org.gradle.wrapper.Install$1.call(Install.java:47)  Colors      1
Error        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)    Colors      1
Error        ... 3 more Colors      1
Error       Error: cmd: Command failed with exit code 1 Error output:   Colors      1
Error       Picked up _JAVA_OPTIONS: -Xmx512M   Colors      1
Error       Exception in thread "main" java.lang.RuntimeException: java.io.IOException: Server returned HTTP response code: 403 for URL: http://services.gradle.org/distributions/gradle-2.13-all.zip   Colors      1
Error        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:78)    Colors      1
Error        at org.gradle.wrapper.Install.createDist(Install.java:47)  Colors      1
Error        at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:129)    Colors      1
Error        at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)    Colors      1
Error       Caused by: java.io.IOException: Server returned HTTP response code: 403 for URL: http://services.gradle.org/distributions/gradle-2.13-all.zip   Colors      1
Error        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream0(HttpURLConnection.java:1919)  Colors      1
Error        at java.base/sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:1515)   Colors      1
Error        at org.gradle.wrapper.Download.downloadInternal(Download.java:59)  Colors      1
Error        at org.gradle.wrapper.Download.download(Download.java:45)  Colors      1
Error        at org.gradle.wrapper.Install$1.call(Install.java:60)  Colors      1
Error        at org.gradle.wrapper.Install$1.call(Install.java:47)  Colors      1
Error        at org.gradle.wrapper.ExclusiveFileAccessManager.access(ExclusiveFileAccessManager.java:65)    Colors      1
Error        ... 3 more Colors      1

I'm just new to all these things. Did i missed something? Should I install some extra plugins or tools?

Body:
This issue occurs because Cordova wants to update your gradle package but the url is invalid.

you can try accessing the URL in the error message:
http://services.gradle.org/distributions/gradle-2.13-all.zip
as you can see that link is forbidden by that site.
that is because that site has to use https,
so you can use SSL and try https://services.gradle.org/distributions/gradle-2.13-all.zip
That should work!!!

So how can I resolve this issue?

solution 1 : add a system environment variable

    CORDOVA_ANDROID_GRADLE_DISTRIBUTION_URL
https://services.gradle.org/distributions/gradle-2.13-all.zip

here is a tutorial I found: https://www.architectryan.com/2018/08/31/how-to-change-environment-variables-on-windows-10/

solution 2: Update the Gradle package for Cordova manually

here is a useful tutorial I found: https://www.andreszsogon.com/upgrading-gradle-version-for-apache-cordova-mobile-apps/

I hope this helps you !!!


问:
How to scroll the webpages based on the hand gesture.hand motion
How to scroll the page up / down or left/right side by using the hand gesture using pyhton/javascript.
I tried lot to find the solution but not able figure out.</p>

答:
Javascript Hand Gesture Plugin (JSHG) is a wonderful plugin that allows you to support the hand gesture recognition of users through web camera in your existing websites or web applications. You do not need to have any background in computer vision to use this plugin. It currently offers the basic set of hand gestures which include the position of the hand (left, right, up, down) and counts the number of fingers. We provide a well-designed API for you to integrate JSHG to your application easily. If you have a strong background in computer vision, it is very simple for you to customize JSHG according to your preference.
https://nhudinhtuan.github.io/jshg/ refer too this link </p>


问:
Is there anyway to catch javascript 'hover' event with chrome console?
So, I have many lines of Javascript codes which is quite unorganized right now.
One function among many function is doing some action on 'hover' event, however I cannot find it by just looking through the codes.

I am wondering if it is possible to catch which function cause on hover event with google chrome browser's 'Console.log'

答: There is no native "hover" event on the dom api. There are on the other hand the next best things : mouseenter, mouseleave and mouseover, mouseout. Internally you will find that the jQuery library treats "hover" events as a combination of events where when you mouseenter it fires the first function, when you leave it fires the second method. You can find jQuery documentation on hover here.</p>


问:
While Loop Function after a button is pressed and stop looping when another button is pressed C#
In my Windorm Form application, I have two buttons which a loop function will begin to do the work when button1 is pressed and stop executing after button2 is pressed. How could i do this to prevent my GUI from non-responsive.
How could i insert command while(button2.clicked != true)

My code for button 1:

```<code>private async void EmoStart_Click_1(object sender, EventArgs e)
    {
        //var repeat = "true";
        string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
       while (VoiceStart_Click_2 != "true")
       {
        var image = pictureBox1.Image;
        image = resizeImage(image, new Size(1209, 770));
        image.Save(imageFilePath);
        if (File.Exists(imageFilePath))
        {
            var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
            if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
            {
                EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Contempt >= 0.5)
            {
                EmoBox.Text = "Contempt, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Disgust >= 0.5)
            {
                EmoBox.Text = "Disgust, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Fear >= 0.5)
            {
                EmoBox.Text = "Fear, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Happiness >= 0.5)
            {
                EmoBox.Text = "Happiness, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Neutral >= 0.5)
            {
                EmoBox.Text = "Neutral, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Sadness >= 0.5)
            {
                EmoBox.Text = "Sadness, Bad Driving Condition, Rock Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Surprise >= 0.5)
            {
                EmoBox.Text = "Happiness, Bad Driving Condition, Soft Music will be played";
            }
            else
            {
                EmoBox.Text = "Stable Condition, Good Driving Condition";
            }
        }
    }
</code>```

While for my button2 code:

```<code>private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    string command = await Voice.RecognizeSpeechAsync();
    VoiceBox.Text = command;
}
</code>```

Thank you!

答:
You have to run your loop in a separate thread. For example, you can run it asynchroniously. Something like this:

```<code>// start the loop
private async void button1_Click(object sender, EventArgs e)
{
    LoopStopped = false;
    await StartLoopAsync();
}

// put yor while loop here
private Task StartLoopAsync()
{
    return Task.Run(() =>
    {
        while (LoopStopped == false)
        {
            var date = DateTime.Now;
            System.Diagnostics.Debug.WriteLine(date);

        }
        System.Diagnostics.Debug.WriteLine("Thread stopped.");
    });
}

// stop the loop
private void button2_Click(object sender, EventArgs e)
{
    LoopStopped = true;
}
</code>```

Where LoopStopped is global boolean variable.

Body:
In my Windorm Form application, I have two buttons which a loop function will begin to do the work when button1 is pressed and stop executing after button2 is pressed. How could i do this to prevent my GUI from non-responsive.
How could i insert command while(button2.clicked != true)

My code for button 1:

private async void EmoStart_Click_1(object sender, EventArgs e)
    {
        //var repeat = "true";
        string imageFilePath = "C:\\Users\\Administrator\\source\\repos\\FaceDetection\\FaceDetection\\test3.jpg";
       while (VoiceStart_Click_2 != "true")
       {
        var image = pictureBox1.Image;
        image = resizeImage(image, new Size(1209, 770));
        image.Save(imageFilePath);
        if (File.Exists(imageFilePath))
        {
            var Emo = await FaceEmotion.MakeAnalysisRequest(imageFilePath);
            if (Emo[0].FaceAttributes.Emotion.Anger >= 0.5)
            {
                EmoBox.Text = "Anger, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Contempt >= 0.5)
            {
                EmoBox.Text = "Contempt, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Disgust >= 0.5)
            {
                EmoBox.Text = "Disgust, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Fear >= 0.5)
            {
                EmoBox.Text = "Fear, Bad Driving Condition, Soft Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Happiness >= 0.5)
            {
                EmoBox.Text = "Happiness, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Neutral >= 0.5)
            {
                EmoBox.Text = "Neutral, Good Driving Condition";
            }
            else if (Emo[0].FaceAttributes.Emotion.Sadness >= 0.5)
            {
                EmoBox.Text = "Sadness, Bad Driving Condition, Rock Music will be played";
            }
            else if (Emo[0].FaceAttributes.Emotion.Surprise >= 0.5)
            {
                EmoBox.Text = "Happiness, Bad Driving Condition, Soft Music will be played";
            }
            else
            {
                EmoBox.Text = "Stable Condition, Good Driving Condition";
            }
        }
    }

While for my button2 code:

private async void VoiceStart_Click_2(object sender, EventArgs e)
{
    string command = await Voice.RecognizeSpeechAsync();
    VoiceBox.Text = command;
}

Thank you!

Body:
You have to run your loop in a separate thread. For example, you can run it asynchroniously. Something like this:

// start the loop
private async void button1_Click(object sender, EventArgs e)
{
    LoopStopped = false;
    await StartLoopAsync();
}

// put yor while loop here
private Task StartLoopAsync()
{
    return Task.Run(() =>
    {
        while (LoopStopped == false)
        {
            var date = DateTime.Now;
            System.Diagnostics.Debug.WriteLine(date);

        }
        System.Diagnostics.Debug.WriteLine("Thread stopped.");
    });
}

// stop the loop
private void button2_Click(object sender, EventArgs e)
{
    LoopStopped = true;
}

Where LoopStopped is global boolean variable.


问:
How to change nav "active" class on different pages with base.html
I have my navbar on my base.html, so I extend it on all other pages.
But I have a class "active" on the home page, so it also stays active in all other pages.

```<code><ul class="navbar-nav">
    <li class="nav-item">
        <a class="nav-link active" href="http://127.0.0.1:8000/backend/">
            <i class="ni ni-shop text-primary"></i>
            <span class="nav-link-text">Dashboard</span>
        </a>
    </li>
    <li class="nav-item">
        <a class="nav-link" href="http://127.0.0.1:8000/backend/clientes">
            <i class="ni ni-ungroup text-orange"></i>
            <span class="nav-link-text">Clients</span>
        </a>
    </li>
</ul>
</code>```

How can I change the active class to a different menu item based on the page I am?

答:
OPTION 1
You can use django contex_processors.
add your settings.py

```<code>TEMPLATES = [
{
     #other settings
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
     #other settings
    'OPTIONS': {
        'context_processors': [
             #other options
            'context_file_path.defaults',

        ],
    },
},
</code>```

]

in your context_file.py

```<code>def defaults(request):
    active_bar = "" # your active bar logic
    return {
        'active_bar': active_bar,
    }
</code>```

with this method, each request decide which bar active. And active_bar variable is being passed to your template. In your template you can add active class if active_bar variable equals your bar name. Like that:

```<code><ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link {% if active_bar == 'dashboard' %}active{% endif %}" href="http://127.0.0.1:8000/backend/">
            <i class="ni ni-shop text-primary"></i>
            <span class="nav-link-text">Dashboard</span>
          </a>
        </li>
        <li class="nav-item  {% if active_bar == 'clients' %}active{% endif %}">
          <a class="nav-link" href="http://127.0.0.1:8000/backend/clientes">
            <i class="ni ni-ungroup text-orange"></i>
            <span class="nav-link-text">Clients</span>
          </a>
        </li>
      </ul>
</code>```

OPTION 2

You can write a custom js file and add your base html. In this js file you can detect url and decide active pane. After that you can add active class to list pane.

Body:
I have my navbar on my base.html, so I extend it on all other pages.
But I have a class "active" on the home page, so it also stays active in all other pages.

            Dashboard

            Clients

How can I change the active class to a different menu item based on the page I am?

Body:
OPTION 1
You can use django contex_processors.
add your settings.py

TEMPLATES = [
{
     #other settings
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
     #other settings
    'OPTIONS': {
        'context_processors': [
             #other options
            'context_file_path.defaults',

        ],
    },
},

]

in your context_file.py

def defaults(request):
    active_bar = "" # your active bar logic
    return {
        'active_bar': active_bar,
    }

with this method, each request decide which bar active. And active_bar variable is being passed to your template. In your template you can add active class if active_bar variable equals your bar name. Like that:

<ul class="navbar-nav">
        <li class="nav-item">
          <a class="nav-link {% if active_bar == 'dashboard' %}active{% endif %}" href="http://127.0.0.1:8000/backend/">
            <i class="ni ni-shop text-primary"></i>
            <span class="nav-link-text">Dashboard</span>
          </a>
        </li>
        <li class="nav-item  {% if active_bar == 'clients' %}active{% endif %}">
          <a class="nav-link" href="http://127.0.0.1:8000/backend/clientes">
            <i class="ni ni-ungroup text-orange"></i>
            <span class="nav-link-text">Clients</span>
          </a>
        </li>
      </ul>

OPTION 2

You can write a custom js file and add your base html. In this js file you can detect url and decide active pane. After that you can add active class to list pane.


问:
solving ode with time-array input - PYTHON
I am trying to solve this problem, searched stack overflow and couldn't find an answer.

I want to integrate a set of state equations, where my inputs that I want to pass as arguments, are arrays as the same length of t.

Example of time-invariant arguments:

```<code># state function
def state(x, t, u_in):
    u     = x[0]
    v     = x[1]
    w     = x[2]
    phi   = x[3]
    theta = x[4]
    psi   = x[5]
    h     = x[6]

    ax   = u_in[0]
    ay   = u_in[1]
    az   = u_in[2]
    p    = u_in[3]
    q    = u_in[4]
    r    = u_in[5]
    pdot = u_in[6]
    qdot = u_in[7]
    rdot = u_in[8]

    xdot = np.zeros(len(x))
    xdot[0] = ax - g * np.sin(theta) + r * v - q * w
    xdot[1] = ay + g * np.sin(phi) * np.cos(theta) + p * w - r * u
    xdot[2] = az + g * np.cos(phi) * np.cos(theta) + q * u - p * v
    xdot[3] = p + (q * np.sin(phi) + r * np.cos(phi)) * np.tan(theta)
    xdot[4] = q * np.cos(phi) - r * np.sin(phi)
    xdot[5] = (q * np.sin(phi) + r * np.cos(phi)) / np.cos(theta)
    xdot[6] = u * np.sin(theta) - v * np.sin(phi) * np.cos(theta) - w * np.cos(phi) * np.cos(theta)
    return xdot

# initial condition
x0 = np.zeros(7)

# set problem
n = 101
t = np.linspace(0, 10, num=n)
uinp = np.zeros(9)
uinp[0] = 0
uinp[1] = 0
uinp[2] = -g
uinp[3] = 0
uinp[4] = 0
uinp[5] = 0
uinp[6] = 0
uinp[7] = 0
uinp[8] = 0

# solve ODE
x = odeint(state, x0, t, args=(uinp,))
</code>```

This works fine because my inputs are time invariant.

What I want to do and it doesn't work is to set my uinp as np.zeros_like(t) and solve the same ODE.

i.e.

```<code>uinp = np.zeros((n, 9))
uinp[:, 0] = 0
uinp[:, 1] = 0
uinp[:, 2] = -g
uinp[:, 3] = 0
uinp[:, 4] = 0
uinp[:, 5] = 0
uinp[:, 6] = 0
uinp[:, 7] = 0
uinp[:, 8] = 0
</code>```

and I get this error:

```<code>ValueError: setting an array element with a sequence.
enter code here
</code>```

Using a loop for each timepiece input is not an option, as it creates too much overhead and it takes forever to run this simulation.

Thanks for the help and insights

答:
Couldn't you make your state function time dependent? If I understood correctly, then this part:

```<code>ax   = u_in[0]
ay   = u_in[1]
az   = u_in[2]
p    = u_in[3]
q    = u_in[4]
r    = u_in[5]
pdot = u_in[6]
qdot = u_in[7]
rdot = u_in[8]
</code>```

should depend on time t:

```<code>ax   = u_in[t, 0]
ay   = u_in[t, 1]
az   = u_in[t, 2]
p    = u_in[t, 3]
q    = u_in[t, 4]
r    = u_in[t, 5]
pdot = u_in[t, 6]
qdot = u_in[t, 7]
rdot = u_in[t, 8]
</code>```

You might need to find a way of mapping the input t, which may be a float to the corresponding column in u_in

Body:
I am trying to solve this problem, searched stack overflow and couldn't find an answer.

I want to integrate a set of state equations, where my inputs that I want to pass as arguments, are arrays as the same length of t.

Example of time-invariant arguments:

# state function
def state(x, t, u_in):
    u     = x[0]
    v     = x[1]
    w     = x[2]
    phi   = x[3]
    theta = x[4]
    psi   = x[5]
    h     = x[6]

    ax   = u_in[0]
    ay   = u_in[1]
    az   = u_in[2]
    p    = u_in[3]
    q    = u_in[4]
    r    = u_in[5]
    pdot = u_in[6]
    qdot = u_in[7]
    rdot = u_in[8]

    xdot = np.zeros(len(x))
    xdot[0] = ax - g * np.sin(theta) + r * v - q * w
    xdot[1] = ay + g * np.sin(phi) * np.cos(theta) + p * w - r * u
    xdot[2] = az + g * np.cos(phi) * np.cos(theta) + q * u - p * v
    xdot[3] = p + (q * np.sin(phi) + r * np.cos(phi)) * np.tan(theta)
    xdot[4] = q * np.cos(phi) - r * np.sin(phi)
    xdot[5] = (q * np.sin(phi) + r * np.cos(phi)) / np.cos(theta)
    xdot[6] = u * np.sin(theta) - v * np.sin(phi) * np.cos(theta) - w * np.cos(phi) * np.cos(theta)
    return xdot

# initial condition
x0 = np.zeros(7)

# set problem
n = 101
t = np.linspace(0, 10, num=n)
uinp = np.zeros(9)
uinp[0] = 0
uinp[1] = 0
uinp[2] = -g
uinp[3] = 0
uinp[4] = 0
uinp[5] = 0
uinp[6] = 0
uinp[7] = 0
uinp[8] = 0

# solve ODE
x = odeint(state, x0, t, args=(uinp,))

This works fine because my inputs are time invariant.

What I want to do and it doesn't work is to set my uinp as np.zeros_like(t) and solve the same ODE.

i.e.

uinp = np.zeros((n, 9))
uinp[:, 0] = 0
uinp[:, 1] = 0
uinp[:, 2] = -g
uinp[:, 3] = 0
uinp[:, 4] = 0
uinp[:, 5] = 0
uinp[:, 6] = 0
uinp[:, 7] = 0
uinp[:, 8] = 0

and I get this error:

ValueError: setting an array element with a sequence.
enter code here

Using a loop for each timepiece input is not an option, as it creates too much overhead and it takes forever to run this simulation.

Thanks for the help and insights

Body:
Couldn't you make your state function time dependent? If I understood correctly, then this part:

ax   = u_in[0]
ay   = u_in[1]
az   = u_in[2]
p    = u_in[3]
q    = u_in[4]
r    = u_in[5]
pdot = u_in[6]
qdot = u_in[7]
rdot = u_in[8]

should depend on time t:

ax   = u_in[t, 0]
ay   = u_in[t, 1]
az   = u_in[t, 2]
p    = u_in[t, 3]
q    = u_in[t, 4]
r    = u_in[t, 5]
pdot = u_in[t, 6]
qdot = u_in[t, 7]
rdot = u_in[t, 8]

You might need to find a way of mapping the input t, which may be a float to the corresponding column in u_in


问:
C# (winforms) text file in DataGridView (substring )
How can I pass substring or a single character within the datagridview.

this is my text file

```<code>qwqwqw
a000v00   5000x222w000
BB00fFF   444422555550
qwqwqw
</code>```

i want to show this content in DataGridView in below format

```<code>1      2     3       4
a000   v00   5000x   222w000
BB00   fFF   44442   2555550
</code>```

This is my error code
How should I do ?

```<code>            DataTable table = new DataTable();
            table.Columns.Add("1", typeof(string));
            table.Columns.Add("2", typeof(string));
            table.Columns.Add("3", typeof(string));
            table.Columns.Add("4", typeof(string));
            string path;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            ofd.Title = "txt";
            if (ofd.ShowDialog(this) == DialogResult.Cancel) return;
            path = ofd.FileName;

            string[] lines = File.ReadAllLines(path);
            string[] values;
            for (int i = 1; i < lines.Length-1; i++)
            {

                values = lines[i].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                string[] row = new string[values.Length];

                for (int j = 0; j < values.Length; j++)
                {
                    row[j] = values[j].Trim();
                }
                table.Rows.Add(row);
            }

</code>```

```<code> private void Form1_Load(object sender, EventArgs e)
        {
            DataView.DataSource = table;
        }
</code>```

Thank you very much

答:
Your split appears to only split into two items as only one space.  Also you seem to be ignoring lines without a space separator.

If so, try chaning the code that parses the text line and creates the datatable to something like this:

```<code>        for (int i = 1; i < lines.Length - 1; i++)
        {

            values = lines[i].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (values.Length == 2)
            {
                DataRow row = table.NewRow();
                row[0] = values[0].Substring(0, 4);
                row[1] = values[0].Substring(4).Trim();
                row[2] = values[1].Substring(0, 5);
                row[3] = values[1].Substring(5).Trim();
                table.Rows.Add(row);
            }
        }
</code>```

and make sure the table datasource of the datagridview.

Body:
How can I pass substring or a single character within the datagridview.

this is my text file

qwqwqw
a000v00   5000x222w000
BB00fFF   444422555550
qwqwqw

i want to show this content in DataGridView in below format

1      2     3       4
a000   v00   5000x   222w000
BB00   fFF   44442   2555550

This is my error code
How should I do ?

            DataTable table = new DataTable();
            table.Columns.Add("1", typeof(string));
            table.Columns.Add("2", typeof(string));
            table.Columns.Add("3", typeof(string));
            table.Columns.Add("4", typeof(string));
            string path;
            OpenFileDialog ofd = new OpenFileDialog();
            ofd.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
            ofd.Title = "txt";
            if (ofd.ShowDialog(this) == DialogResult.Cancel) return;
            path = ofd.FileName;

            string[] lines = File.ReadAllLines(path);
            string[] values;
            for (int i = 1; i < lines.Length-1; i++)
            {

                values = lines[i].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                string[] row = new string[values.Length];

                for (int j = 0; j < values.Length; j++)
                {
                    row[j] = values[j].Trim();
                }
                table.Rows.Add(row);
            }

 private void Form1_Load(object sender, EventArgs e)
        {
            DataView.DataSource = table;
        }

Thank you very much

Body:
Your split appears to only split into two items as only one space.  Also you seem to be ignoring lines without a space separator.

If so, try chaning the code that parses the text line and creates the datatable to something like this:

        for (int i = 1; i < lines.Length - 1; i++)
        {

            values = lines[i].Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
            if (values.Length == 2)
            {
                DataRow row = table.NewRow();
                row[0] = values[0].Substring(0, 4);
                row[1] = values[0].Substring(4).Trim();
                row[2] = values[1].Substring(0, 5);
                row[3] = values[1].Substring(5).Trim();
                table.Rows.Add(row);
            }
        }

and make sure the table datasource of the datagridview.


问:
Django - templatedoesnotexist
I'm creating a project named "crepes_bretonnes". In this project, I have an application blog. I created a template date.html. Here is the structure of my folders :

```<code>crepes_bretonnes/
    blog/
        __init__.py
        admin.py
        migrations/
            __init__.py
        models.py
        templates/
            blog/
                addition.html
                date.html
        tests.py
        views.py
    crepes_bretonnes/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    templates/
    db.sqlite3
    manage.py
</code>```

When I try to see the page, I have a message templateDoesNotExist. I have read a lot about it on the web but I have not succeed in resolving my problem. In fact, I don't understand why Django does not search in my template folder of the app blog although I wrote "blog" in INSTALLED_APP in setting.py. Obviously, I have put TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) in setting.py. I also tried to change the dictionary TEMPLATES. However, if I have understood well, it has no link as here Django should find my template even without this.
I don't have any solution.

Thank you for your help.

PS: If I put date.html in the general template folder and I arrange some lines, it works. However that is not a solution, I would like to respect a good structure.

UPDATE:

Thank you for your answer. Yes it really says INSTALLED_APPS in my setting and APP_DIRS is already True.

Here is my TEMPLATES in setting.py:

```<code>TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
</code>```

UPDATE:
The debug message shows that Django search in django.template.loaders.app_directories.Loader: /Users/benjamin/anaconda/lib/python2.7/site-packages/django/contrib/admin/templates/blog/date.html.
However I have not written anything in these folder ... I'm working in Documents. Why does Django search here and not in Documents ?

答:
Go to your setting.py and try something like:

```<code>os.path.join(BASE_DIR, "templates")
</code>```

For example:

```<code>TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, "templates")],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},
</code>```

]

Title: Django - templatedoesnotexist

Body:
I'm creating a project named "crepes_bretonnes". In this project, I have an application blog. I created a template date.html. Here is the structure of my folders :

crepes_bretonnes/
    blog/
        __init__.py
        admin.py
        migrations/
            __init__.py
        models.py
        templates/
            blog/
                addition.html
                date.html
        tests.py
        views.py
    crepes_bretonnes/
        __init__.py
        settings.py
        urls.py
        wsgi.py
    templates/
    db.sqlite3
    manage.py

When I try to see the page, I have a message templateDoesNotExist. I have read a lot about it on the web but I have not succeed in resolving my problem. In fact, I don't understand why Django does not search in my template folder of the app blog although I wrote "blog" in INSTALLED_APP in setting.py. Obviously, I have put TEMPLATE_DIRS = (os.path.join(BASE_DIR, 'templates'),) in setting.py. I also tried to change the dictionary TEMPLATES. However, if I have understood well, it has no link as here Django should find my template even without this.
I don't have any solution.

Thank you for your help.

PS: If I put date.html in the general template folder and I arrange some lines, it works. However that is not a solution, I would like to respect a good structure.

UPDATE:

Thank you for your answer. Yes it really says INSTALLED_APPS in my setting and APP_DIRS is already True.

Here is my TEMPLATES in setting.py:

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates")],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

UPDATE:
The debug message shows that Django search in django.template.loaders.app_directories.Loader: /Users/benjamin/anaconda/lib/python2.7/site-packages/django/contrib/admin/templates/blog/date.html.
However I have not written anything in these folder ... I'm working in Documents. Why does Django search here and not in Documents ?

Body:
Go to your setting.py and try something like:

os.path.join(BASE_DIR, "templates")

For example:

TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [os.path.join(BASE_DIR, "templates")],
    'APP_DIRS': True,
    'OPTIONS': {
        'context_processors': [
            'django.template.context_processors.debug',
            'django.template.context_processors.request',
            'django.contrib.auth.context_processors.auth',
            'django.contrib.messages.context_processors.messages',
        ],
    },
},

]


问:
React native graph using event drops
I working with Event drops in react js. This is working fine in web app. But I am trying to implement same into React-native mobile app. Unfortunately no success yet.

Any help would be appreciated?

Thanks in advance!

答:
use this Library, It is working fine for me I implemented charts to my react native app through this library couples days back.

if it doesn't help check this link

Title: React native graph using event drops


问:
How can I pass an array to a function that cannot modify it?
I'm programming in C and I want to pass an array to a function; this function cannot modify the elements of the array. What is the correct syntax for the arguments of the function?

```<code>void func(const Foo array_in[])
</code>```

or

```<code>void func(Foo const array_in[])
</code>```

or maybe they are the same?
Thank you.

答:
You should use pointer to constant in order to handle that:

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

void fun(const int *ptr)//pointer to constant - array boils down to pointer when passed to function
{
    ptr[0]=9;        //ERROR: Read-Only
}

int main(void)
{
    int arr[]={1,2,3,4};

    fun(arr);
    return 0;
}
</code>```

NOTE: Do not confuse it with constant pointer

Body:
I'm programming in C and I want to pass an array to a function; this function cannot modify the elements of the array. What is the correct syntax for the arguments of the function?

void func(const Foo array_in[])

or

void func(Foo const array_in[])

or maybe they are the same?
Thank you.

Body:
You should use pointer to constant in order to handle that:

#include<stdio.h>

void fun(const int *ptr)//pointer to constant - array boils down to pointer when passed to function
{
    ptr[0]=9;        //ERROR: Read-Only
}

int main(void)
{
    int arr[]={1,2,3,4};

    fun(arr);
    return 0;
}

NOTE: Do not confuse it with constant pointer


问:
Data-frame to show selected results only from columns divisions
A data-frame to divide the month columns by the Total column. At the end, I want to only show the results greater than 35% (0.35).

```<code>import pandas as pd

data = {'Name' : ["John","Peter","Kate","Liz"],
'Jan-2016': [408,88,277,32],
'Feb-2016': [313,348,73,302],
'Mar-2016': [497,197,196,164],
'Apr-2016': [88,87,447,118],
'May-2016': [79,20,235,273],
'Total': [1385,740,1228,889]}

df = pd.DataFrame(data)

df_1 = df[["Jan-2016","Feb-2016","Mar-2016","Apr-2016","May-2016"]].div(df["Total"], axis=0)
</code>```

I can only work out the calculation.

What's the way to output the results greater and equal to 0.3 only?
(please note 1 person may have 0-3 columns fit)

Thank you.

Body:
A data-frame to divide the month columns by the Total column. At the end, I want to only show the results greater than 35% (0.35).

import pandas as pd

data = {'Name' : ["John","Peter","Kate","Liz"],
'Jan-2016': [408,88,277,32],
'Feb-2016': [313,348,73,302],
'Mar-2016': [497,197,196,164],
'Apr-2016': [88,87,447,118],
'May-2016': [79,20,235,273],
'Total': [1385,740,1228,889]}

df = pd.DataFrame(data)

df_1 = df[["Jan-2016","Feb-2016","Mar-2016","Apr-2016","May-2016"]].div(df["Total"], axis=0)

I can only work out the calculation.

What's the way to output the results greater and equal to 0.3 only?
(please note 1 person may have 0-3 columns fit)

Thank you.

Body:
import pandas as pd

data = {'Name' : ["John","Peter","Kate","Liz"],
'Jan-2016': [408,88,277,32],
'Feb-2016': [313,348,73,302],
'Mar-2016': [497,197,196,164],
'Apr-2016': [88,87,447,118],
'May-2016': [79,20,235,273],
'Total': [1385,740,1228,889]}

df = pd.DataFrame(data)

cols = ["Jan-2016","Feb-2016","Mar-2016","Apr-2016","May-2016"]

df[cols] = df[cols].div(df["Total"], axis=0)

# reshape to use months as a single column
reshaped = pd.melt(df, id_vars="Name", value_vars=cols)

result = reshaped[reshaped['value'] >= 0.3]

print(result)

Output:

     Name  variable     value
5   Peter  Feb-2016  0.470270
7     Liz  Feb-2016  0.339708
8    John  Mar-2016  0.358845
14   Kate  Apr-2016  0.364007
19    Liz  May-2016  0.307087


问:
shell - Yes no prompt not working using case
I am using bash 4.2 to create a prompt

```<code>        read -p "Want to print the output to $newname ? (y/n)" $yesno
        case "$yesno" in
           [Yy])
                   outname=$newname;;
           [Nn])
                   echo "Quitting ...";
                   exit 4;;
           *)
                   echo "Quitting !!";
                   exit 5;;
        esac
</code>```

The problem is that whether I give y or n, the output is "Quitting !!"

But if I comment the case *), the result equates outname to newname

What am I doing wrong?

答:
Variable name in read have to be without $

```<code>read -p "Want to print the output to $newname ? (y/n)" yesno
</code>```

Body:
I am using bash 4.2 to create a prompt

        read -p "Want to print the output to $newname ? (y/n)" $yesno
        case "$yesno" in
           [Yy])
                   outname=$newname;;
           [Nn])
                   echo "Quitting ...";
                   exit 4;;
           *)
                   echo "Quitting !!";
                   exit 5;;
        esac

The problem is that whether I give y or n, the output is "Quitting !!"

But if I comment the case *), the result equates outname to newname

What am I doing wrong?

Body:
Variable name in read have to be without $

read -p "Want to print the output to $newname ? (y/n)" yesno


问:
Prevent class .cke_show_borders to be added to table element in ckeditor
When I load the table element in CKeditor 4.11.4 Eg.
Hello
 then it adds className cke_show_borders by default like
Hello
.
The config contains allowedContents as true.
Also, I think that cke_show_borders class has been added so that the table element always has a border which is not required in my case. So how can I prevent cke_show_borders class from getting added?

when I do allowedContent as false it removes all the HTML element which was not desired.

答:
This issue due to the Ck-editor plugin 'showborders'.
To remove this border remove plugin from Ck-editor config.</p>

```<code>config.removePlugins = 'showborders';
</code>```

Body:
This issue due to the Ck-editor plugin 'showborders'.
To remove this border remove plugin from Ck-editor config.

config.removePlugins = 'showborders';


问:
Hashmap. Find key(s) which have same values between two hashmaps
Lets consider we have two hashmaps as below:

```<code> HashMap<String, Integer> map1  = new HashMap<>();
 map1.put("vishal", 10);
 map1.put("sachin", 30);
 map1.put("vaibhav", 20);

 HashMap<String, Integer> map2  = new HashMap<>();
 map2.put("Raja", 10);
 map2.put("John", 30);
 map2.put("Krishna", 20);
</code>```

The "vaibhav" from map1 and "krishna" from map2 have the same values.

I need to find the keys from both the maps, which have the same values. In this case, "vaibhav" and "Krishna".

Thanks.

答:
Group by values and store keys in list:

Stream.of(map1.entrySet(), map2.entrySet())
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(
        Map.Entry::getValue,
        Collectors.mapping(
                Map.Entry::getKey,
                Collectors.toList()
        )
));
```
<p>It will create:</p>
```{20=[vaibhav, Krishna], 10=[vishal, Raja], 30=[sachin, John]}
```
<h3>UPDATE</h3>
<p>Other approach</p>
<pre class="lang-java prettyprint-override"><code>Map<Integer, List<String>> collect = new HashMap<>();
map1.entrySet().forEach(e -> collect
        .computeIfAbsent(e.getValue(), k -> new ArrayList<>())
        .add(e.getKey()));
map2.entrySet().forEach(e -> collect
        .computeIfAbsent(e.getValue(), k -> new ArrayList<>())
        .add(e.getKey()));
</code>```

Body:
Lets consider we have two hashmaps as below:

 HashMap<String, Integer> map1  = new HashMap<>();
 map1.put("vishal", 10);
 map1.put("sachin", 30);
 map1.put("vaibhav", 20);

 HashMap<String, Integer> map2  = new HashMap<>();
 map2.put("Raja", 10);
 map2.put("John", 30);
 map2.put("Krishna", 20);

The "vaibhav" from map1 and "krishna" from map2 have the same values.

I need to find the keys from both the maps, which have the same values. In this case, "vaibhav" and "Krishna".

Thanks.

Body:
Group by values and store keys in list:

Stream.of(map1.entrySet(), map2.entrySet())
.flatMap(Collection::stream)
.collect(Collectors.groupingBy(
        Map.Entry::getValue,
        Collectors.mapping(
                Map.Entry::getKey,
                Collectors.toList()
        )
));

It will create:

{20=[vaibhav, Krishna], 10=[vishal, Raja], 30=[sachin, John]}

UPDATE

Other approach

Map<Integer, List<String>> collect = new HashMap<>();
map1.entrySet().forEach(e -> collect
        .computeIfAbsent(e.getValue(), k -> new ArrayList<>())
        .add(e.getKey()));
map2.entrySet().forEach(e -> collect
        .computeIfAbsent(e.getValue(), k -> new ArrayList<>())
        .add(e.getKey()));


问:
EF6 generated SQL is not valid SQL server side
This one sounds crazy - but fact is following is what I observe:
I have a apsx mvc application connected to a SQL server using EF6.
From time to time I I get exception on the underlaying generated SQL. Like:

Incorrect syntax near the keyword 'AS'" and "Incorrect syntax near
  '[Extend1]'

(And variations of this)

In my best opinion that should not happen from a framework like EF.

Luckily I have introduced a SQL interceptor (like https://learn.microsoft.com/en-us/ef/ef6/fundamentals/logging-and-interception) given me that chance to see the SQL prior to execution.
My first step was to examine the generated SQL - and that looks sane. In an other step I attached a profiler on the SQL server!
And guess what - the SQL that the intercepted logs does not match the SQL recorded in the profiler. (sound fubar, but it is what is observer)
Conclusion is so far: from time to time single characters in the SQL changes (In the observed cases it is commas that becomes formfeed.)

Does anyone on the internet have a clue what could be the background for this?

UPDATE 1: (Requested information)

=== EF Code ===

```<code>public Customer GetById(string id)
{
    return DbContext.Customers.Include("Address").FirstOrDefault(a => a.Id == id);
}
</code>```

=== From the Interceptor ===

```<code>2019-11-06 09:07:14.471 +01:00 [Interceptors.SqlLogInterceptor] [44] [<<username>>] [Debug] SELECT
     [Limit1].[AddressTypeId] AS [AddressTypeId],
    [Limit1].[Id] AS [Id],
    [Limit1].[AddressId] AS [AddressId],
    [Limit1].[ShowPrebooking] AS [ShowPrebooking],
    [Limit1].[Id1] AS [Id1],
    [Limit1].[Name1] AS [Name1],
    [Limit1].[Name2] AS [Name2],
    [Limit1].[Address1] AS [Address1],
    [Limit1].[Address2] AS [Address2],
    [Limit1].[HouseNumber] AS [HouseNumber],
    [Limit1].[PostCode] AS [PostCode],
    [Limit1].[City] AS [City],
    [Limit1].[State] AS [State],
    [Limit1].[CountryCode] AS [CountryCode],
    [Limit1].[ContactName] AS [ContactName],
    [Limit1].[Email] AS [Email],
    [Limit1].[Phone] AS [Phone],
    [Limit1].[Mobile] AS [Mobile],
    [Limit1].[CreatedByUserId] AS [CreatedByUserId],
    [Limit1].[CreatedDateTime] AS [CreatedDateTime],
    [Limit1].[UpdatedByUserId] AS [UpdatedByUserId],
    [Limit1].[UpdatedDateTime] AS [UpdatedDateTime],
    [Limit1].[DeliveryDescription] AS [DeliveryDescription],
    [Limit1].[OpeningHoursTo] AS [OpeningHoursTo],
    [Limit1].[OpeningHoursFrom] AS [OpeningHoursFrom]
    FROM ( SELECT TOP (1)
        [Extent1].[Id] AS [Id],
        [Extent1].[AddressId] AS [AddressId],
        [Extent1].[ShowPrebooking] AS [ShowPrebooking],
        [Extent2].[Id] AS [Id1],
        [Extent2].[Name1] AS [Name1],
        [Extent2].[Name2] AS [Name2],
        [Extent2].[Address1] AS [Address1],
        [Extent2].[Address2] AS [Address2],
        [Extent2].[HouseNumber] AS [HouseNumber],
        [Extent2].[PostCode] AS [PostCode],
        [Extent2].[City] AS [City],
        [Extent2].[State] AS [State],
        [Extent2].[CountryCode] AS [CountryCode],
        [Extent2].[ContactName] AS [ContactName],
        [Extent2].[Email] AS [Email],
        [Extent2].[Phone] AS [Phone],
        [Extent2].[Mobile] AS [Mobile],
        [Extent2].[AddressTypeId] AS [AddressTypeId],
        [Extent2].[CreatedByUserId] AS [CreatedByUserId],
        [Extent2].[CreatedDateTime] AS [CreatedDateTime],
        [Extent2].[UpdatedByUserId] AS [UpdatedByUserId],
        [Extent2].[UpdatedDateTime] AS [UpdatedDateTime],
        [Extent2].[DeliveryDescription] AS [DeliveryDescription],
        [Extent2].[OpeningHoursTo] AS [OpeningHoursTo],
        [Extent2].[OpeningHoursFrom] AS [OpeningHoursFrom]
        FROM  [dbo].[Customers] AS [Extent1]
        INNER JOIN [dbo].[Addresses] AS [Extent2] ON [Extent1].[AddressId] = [Extent2].[Id]
        WHERE [Extent1].[Id] = @p__linq__0
    )  AS [Limit1]
2019-11-06 09:07:14.471 +01:00 [Yourleman.Ef.Interceptors.SqlLogInterceptor] [44] [<<username>>] [Debug] -- Failed in 1 ms with error: Incorrect syntax near 'Limit1'.
Incorrect syntax near the keyword 'AS'.
</code>```

=== Trace from profiler ===

```<code>exec sp_executesql N'SELECT
    [Limit1].[AddressTypeId] AS [AddressTypeId],
    [Limit1].[Id] AS [Id],
    [Limit1].[AddressId] AS [AddressId],
    [Limit1].[ShowPrebooking] AS [ShowPrebooking],
    [Limit1].[Id1] AS [Id1],
    [Limit1].[Name1] AS [Name1],
    [Limit1].[Name2] AS [Name2],
    [Limit1].[Address1] AS [Address1],
    [Limit1].[Address2] AS [Address2],
    [Limit1].[HouseNumber] AS [HouseNumber],
    [Limit1].[PostCode] AS [PostCode],
    [Limit1].[City] AS [City],
    [Limit1].[State] AS [State],
    [Limit1].[CountryCode] AS [CountryCode],
    [Limit1].[ContactName] AS [ContactName],
    [Limit1].[Email] AS [Email],
    [Limit1].[Phone] AS [Phone],
    [Limit1].[Mobile] AS [Mobile],
    [Limit1].[CreatedByUserId] AS [CreatedByUserId],
    [Limit1].[CreatedDateTime] AS [CreatedDateTime],
    [Limit1].[UpdatedByUserId] AS [UpdatedByUserId],
    [Limit1].[UpdatedDateTime] AS [UpdatedDateTime],
    [Limit1].[DeliveryDescription] AS [DeliveryDescription],
    [Limit1].[OpeningHoursTo] AS [OpeningHoursTo]
    [Limit1].[OpeningHoursFrom] AS [OpeningHoursFrom]
    FROM ( SELECT TOP (1)
        [Extent1].[Id] AS [Id],
        [Extent1].[AddressId] AS [AddressId],
        [Extent1].[ShowPrebooking] AS [ShowPrebooking],
        [Extent2].[Id] AS [Id1],
        [Extent2].[Name1] AS [Name1],
        [Extent2].[Name2] AS [Name2],
        [Extent2].[Address1] AS [Address1],
        [Extent2].[Address2] AS [Address2],
        [Extent2].[HouseNumber] AS [HouseNumber],
        [Extent2].[PostCode] AS [PostCode],
        [Extent2].[City] AS [City],
        [Extent2].[State] AS [State],
        [Extent2].[CountryCode] AS [CountryCode],
        [Extent2].[ContactName] AS [ContactName],
        [Extent2].[Email] AS [Email],
        [Extent2].[Phone] AS [Phone],
        [Extent2].[Mobile] AS [Mobile],
        [Extent2].[AddressTypeId] AS [AddressTypeId],
        [Extent2].[CreatedByUserId] AS [CreatedByUserId],
        [Extent2].[CreatedDateTime] AS [CreatedDateTime],
        [Extent2].[UpdatedByUserId] AS [UpdatedByUserId],
        [Extent2].[UpdatedDateTime] AS [UpdatedDateTime],
        [Extent2].[DeliveryDescription] AS [DeliveryDescription],
        [Extent2].[OpeningHoursTo] AS [OpeningHoursTo],
        [Extent2].[OpeningHoursFrom] AS [OpeningHoursFrom]
        FROM  [dbo].[Customers] AS [Extent1]
        INNER JOIN [dbo].[Addresses] AS [Extent2] ON [Extent1].[AddressId] = [Extent2].[Id]
        WHERE [Extent1].[Id] = @p__linq__0
    )  AS [Limit1]',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'2341234'
</code>```

Examine the bytes showed that after the  [OpeningHoursTo] there is a Form Feed character (\u000C)

答:
Lo and behold, on the 3rd of February, the error returned out of nowhere. All traffic out of our production server seemed to be affected and our customers would experience random errors.

Using log files and Wireshark on the server hosting the website we could rule out that particular server, since the data in the TCP packages was correct. We could also rule out the database server and another application server, since requests to both servers would fail in the same way.

In the end, Infrastructure was able to isolate the issue to a defective port on a switch in the network. After disabling this port, the issues was resolved instantly.

Body:
This one sounds crazy - but fact is following is what I observe:
I have a apsx mvc application connected to a SQL server using EF6.
From time to time I I get exception on the underlaying generated SQL. Like:

Incorrect syntax near the keyword 'AS'" and "Incorrect syntax near
  '[Extend1]'

(And variations of this)

In my best opinion that should not happen from a framework like EF.

Luckily I have introduced a SQL interceptor (like https://learn.microsoft.com/en-us/ef/ef6/fundamentals/logging-and-interception) given me that chance to see the SQL prior to execution.
My first step was to examine the generated SQL - and that looks sane. In an other step I attached a profiler on the SQL server!
And guess what - the SQL that the intercepted logs does not match the SQL recorded in the profiler. (sound fubar, but it is what is observer)
Conclusion is so far: from time to time single characters in the SQL changes (In the observed cases it is commas that becomes formfeed.)

Does anyone on the internet have a clue what could be the background for this?

UPDATE 1: (Requested information)

=== EF Code ===

public Customer GetById(string id)
{
    return DbContext.Customers.Include("Address").FirstOrDefault(a => a.Id == id);
}

=== From the Interceptor ===

2019-11-06 09:07:14.471 +01:00 [Interceptors.SqlLogInterceptor] [44] [<<username>>] [Debug] SELECT
     [Limit1].[AddressTypeId] AS [AddressTypeId],
    [Limit1].[Id] AS [Id],
    [Limit1].[AddressId] AS [AddressId],
    [Limit1].[ShowPrebooking] AS [ShowPrebooking],
    [Limit1].[Id1] AS [Id1],
    [Limit1].[Name1] AS [Name1],
    [Limit1].[Name2] AS [Name2],
    [Limit1].[Address1] AS [Address1],
    [Limit1].[Address2] AS [Address2],
    [Limit1].[HouseNumber] AS [HouseNumber],
    [Limit1].[PostCode] AS [PostCode],
    [Limit1].[City] AS [City],
    [Limit1].[State] AS [State],
    [Limit1].[CountryCode] AS [CountryCode],
    [Limit1].[ContactName] AS [ContactName],
    [Limit1].[Email] AS [Email],
    [Limit1].[Phone] AS [Phone],
    [Limit1].[Mobile] AS [Mobile],
    [Limit1].[CreatedByUserId] AS [CreatedByUserId],
    [Limit1].[CreatedDateTime] AS [CreatedDateTime],
    [Limit1].[UpdatedByUserId] AS [UpdatedByUserId],
    [Limit1].[UpdatedDateTime] AS [UpdatedDateTime],
    [Limit1].[DeliveryDescription] AS [DeliveryDescription],
    [Limit1].[OpeningHoursTo] AS [OpeningHoursTo],
    [Limit1].[OpeningHoursFrom] AS [OpeningHoursFrom]
    FROM ( SELECT TOP (1)
        [Extent1].[Id] AS [Id],
        [Extent1].[AddressId] AS [AddressId],
        [Extent1].[ShowPrebooking] AS [ShowPrebooking],
        [Extent2].[Id] AS [Id1],
        [Extent2].[Name1] AS [Name1],
        [Extent2].[Name2] AS [Name2],
        [Extent2].[Address1] AS [Address1],
        [Extent2].[Address2] AS [Address2],
        [Extent2].[HouseNumber] AS [HouseNumber],
        [Extent2].[PostCode] AS [PostCode],
        [Extent2].[City] AS [City],
        [Extent2].[State] AS [State],
        [Extent2].[CountryCode] AS [CountryCode],
        [Extent2].[ContactName] AS [ContactName],
        [Extent2].[Email] AS [Email],
        [Extent2].[Phone] AS [Phone],
        [Extent2].[Mobile] AS [Mobile],
        [Extent2].[AddressTypeId] AS [AddressTypeId],
        [Extent2].[CreatedByUserId] AS [CreatedByUserId],
        [Extent2].[CreatedDateTime] AS [CreatedDateTime],
        [Extent2].[UpdatedByUserId] AS [UpdatedByUserId],
        [Extent2].[UpdatedDateTime] AS [UpdatedDateTime],
        [Extent2].[DeliveryDescription] AS [DeliveryDescription],
        [Extent2].[OpeningHoursTo] AS [OpeningHoursTo],
        [Extent2].[OpeningHoursFrom] AS [OpeningHoursFrom]
        FROM  [dbo].[Customers] AS [Extent1]
        INNER JOIN [dbo].[Addresses] AS [Extent2] ON [Extent1].[AddressId] = [Extent2].[Id]
        WHERE [Extent1].[Id] = @p__linq__0
    )  AS [Limit1]
2019-11-06 09:07:14.471 +01:00 [Yourleman.Ef.Interceptors.SqlLogInterceptor] [44] [<<username>>] [Debug] -- Failed in 1 ms with error: Incorrect syntax near 'Limit1'.
Incorrect syntax near the keyword 'AS'.

=== Trace from profiler ===

exec sp_executesql N'SELECT
    [Limit1].[AddressTypeId] AS [AddressTypeId],
    [Limit1].[Id] AS [Id],
    [Limit1].[AddressId] AS [AddressId],
    [Limit1].[ShowPrebooking] AS [ShowPrebooking],
    [Limit1].[Id1] AS [Id1],
    [Limit1].[Name1] AS [Name1],
    [Limit1].[Name2] AS [Name2],
    [Limit1].[Address1] AS [Address1],
    [Limit1].[Address2] AS [Address2],
    [Limit1].[HouseNumber] AS [HouseNumber],
    [Limit1].[PostCode] AS [PostCode],
    [Limit1].[City] AS [City],
    [Limit1].[State] AS [State],
    [Limit1].[CountryCode] AS [CountryCode],
    [Limit1].[ContactName] AS [ContactName],
    [Limit1].[Email] AS [Email],
    [Limit1].[Phone] AS [Phone],
    [Limit1].[Mobile] AS [Mobile],
    [Limit1].[CreatedByUserId] AS [CreatedByUserId],
    [Limit1].[CreatedDateTime] AS [CreatedDateTime],
    [Limit1].[UpdatedByUserId] AS [UpdatedByUserId],
    [Limit1].[UpdatedDateTime] AS [UpdatedDateTime],
    [Limit1].[DeliveryDescription] AS [DeliveryDescription],
    [Limit1].[OpeningHoursTo] AS [OpeningHoursTo]
    [Limit1].[OpeningHoursFrom] AS [OpeningHoursFrom]
    FROM ( SELECT TOP (1)
        [Extent1].[Id] AS [Id],
        [Extent1].[AddressId] AS [AddressId],
        [Extent1].[ShowPrebooking] AS [ShowPrebooking],
        [Extent2].[Id] AS [Id1],
        [Extent2].[Name1] AS [Name1],
        [Extent2].[Name2] AS [Name2],
        [Extent2].[Address1] AS [Address1],
        [Extent2].[Address2] AS [Address2],
        [Extent2].[HouseNumber] AS [HouseNumber],
        [Extent2].[PostCode] AS [PostCode],
        [Extent2].[City] AS [City],
        [Extent2].[State] AS [State],
        [Extent2].[CountryCode] AS [CountryCode],
        [Extent2].[ContactName] AS [ContactName],
        [Extent2].[Email] AS [Email],
        [Extent2].[Phone] AS [Phone],
        [Extent2].[Mobile] AS [Mobile],
        [Extent2].[AddressTypeId] AS [AddressTypeId],
        [Extent2].[CreatedByUserId] AS [CreatedByUserId],
        [Extent2].[CreatedDateTime] AS [CreatedDateTime],
        [Extent2].[UpdatedByUserId] AS [UpdatedByUserId],
        [Extent2].[UpdatedDateTime] AS [UpdatedDateTime],
        [Extent2].[DeliveryDescription] AS [DeliveryDescription],
        [Extent2].[OpeningHoursTo] AS [OpeningHoursTo],
        [Extent2].[OpeningHoursFrom] AS [OpeningHoursFrom]
        FROM  [dbo].[Customers] AS [Extent1]
        INNER JOIN [dbo].[Addresses] AS [Extent2] ON [Extent1].[AddressId] = [Extent2].[Id]
        WHERE [Extent1].[Id] = @p__linq__0
    )  AS [Limit1]',N'@p__linq__0 nvarchar(4000)',@p__linq__0=N'2341234'

Examine the bytes showed that after the  [OpeningHoursTo] there is a Form Feed character (\u000C)


问:
Extract rows with duplicates entries in one column satisfying a given condition in another column
I have a sample dataframe with duplicate entries in the first column given below:

```<code>df <- data.frame(ID=c(rep(101,3),rep(102,2),103,rep(104,3)),Type=c(2,1,1,1,2,1,3,1,2),sex=c(0,0,0,1,1,1,0,0,0))
df
  ID Type sex
1 101    2   0
2 101    1   0
3 101    1   0
4 102    1   1
5 102    2   1
6 103    1   1
7 104    3   0
8 104    1   0
9 104    2   0
</code>```

Question: For each variable 'ID', I want the rows to start from where the first occurrence of the variable 'Type' is 1 (i.e. Type=1).

I know for each ID, the position satisfying the condition Type=1 using the code below:

```<code>aggregate(df$Type,list(ID=df$ID),function(x) match(1,x))
 ID x
1 101 2
2 102 1
3 103 1
4 104 2
</code>```

but I have not been able to solve the problem.

Desired Output: The output should look like this:

```<code>df.result <- data.frame(ID=c(101,101,102,102,103,104,104),Type=c(1,1,1,2,1,1,2),sex=c(0,0,1,1,1,0,0))
df.result
 ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0
</code>```

Thanks!

答:
Another option is using cumsum():

```<code>library(dplyr)
df %>%
  group_by(ID) %>%
  filter(cumsum(Type==1) > 0)
</code>```

Body:
I have a sample dataframe with duplicate entries in the first column given below:

df <- data.frame(ID=c(rep(101,3),rep(102,2),103,rep(104,3)),Type=c(2,1,1,1,2,1,3,1,2),sex=c(0,0,0,1,1,1,0,0,0))
df
  ID Type sex
1 101    2   0
2 101    1   0
3 101    1   0
4 102    1   1
5 102    2   1
6 103    1   1
7 104    3   0
8 104    1   0
9 104    2   0

Question: For each variable 'ID', I want the rows to start from where the first occurrence of the variable 'Type' is 1 (i.e. Type=1).

I know for each ID, the position satisfying the condition Type=1 using the code below:

aggregate(df$Type,list(ID=df$ID),function(x) match(1,x))
 ID x
1 101 2
2 102 1
3 103 1
4 104 2

but I have not been able to solve the problem.

Desired Output: The output should look like this:

df.result <- data.frame(ID=c(101,101,102,102,103,104,104),Type=c(1,1,1,2,1,1,2),sex=c(0,0,1,1,1,0,0))
df.result
 ID Type sex
1 101    1   0
2 101    1   0
3 102    1   1
4 102    2   1
5 103    1   1
6 104    1   0
7 104    2   0

Thanks!

Body:
Another option is using cumsum():

library(dplyr)
df %>%
  group_by(ID) %>%
  filter(cumsum(Type==1) > 0)


问:
How to test custom WebApplicationInitializer in Spring
I moved web.xml to Java annotation configuration

My custom code is

```<code>public class WebInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext container) {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.setDisplayName("app-name");
    context.register(Config.class);
    container.addListener(new RequestContextListener());
    container.addListener(new ContextLoaderListener(context));

    Dynamic dispatcher = container.addServlet("app-name", new DispatcherServlet(context));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/app-name-rest/*");
}
</code>```

I tried the solution https://stackoverflow.com/a/25210356/6700081 but the line coverage is still 0%

答:
I had the same problem and solved in this way:

```<code>public class WebInitializerTest {

@Mock
private MockServletContext mockServletContext;

@Mock
private ServletRegistration.Dynamic mockServletRegistration;

@BeforeEach
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testOnStartup() {
    WebInitializer webInitializer = new WebInitializer();
    when(mockServletContext.addServlet(ArgumentMatchers.eq("app-name"), any(Servlet.class))).thenReturn(mockServletRegistration);

    webInitializer.onStartup(mockServletContext);

    verify(mockServletContext, times(1)).addListener(any(RequestContextListener.class));
    // other asserts..
}}
</code>```

Note: I use Junit5 (@BeforeEach)

Body:
I moved web.xml to Java annotation configuration

My custom code is

public class WebInitializer implements WebApplicationInitializer {

@Override
public void onStartup(ServletContext container) {
    AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
    context.setDisplayName("app-name");
    context.register(Config.class);
    container.addListener(new RequestContextListener());
    container.addListener(new ContextLoaderListener(context));

    Dynamic dispatcher = container.addServlet("app-name", new DispatcherServlet(context));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/app-name-rest/*");
}

I tried the solution https://stackoverflow.com/a/25210356/6700081 but the line coverage is still 0%

Body:
I had the same problem and solved in this way:

public class WebInitializerTest {

@Mock
private MockServletContext mockServletContext;

@Mock
private ServletRegistration.Dynamic mockServletRegistration;

@BeforeEach
public void setUp() {
    MockitoAnnotations.initMocks(this);
}

@Test
public void testOnStartup() {
    WebInitializer webInitializer = new WebInitializer();
    when(mockServletContext.addServlet(ArgumentMatchers.eq("app-name"), any(Servlet.class))).thenReturn(mockServletRegistration);

    webInitializer.onStartup(mockServletContext);

    verify(mockServletContext, times(1)).addListener(any(RequestContextListener.class));
    // other asserts..
}}

Note: I use Junit5 (@BeforeEach)