问:
How to use dynamic data in the SCSS file of an Angular 2 app?
I am making a hamburger as follows.

```<code><div class="hamburger">
  <div
    [ngStyle]="{
      backgroundColor: theme.majorTextColor
    }"
    class="hamburger-line"
  ></div>
  <div
    [ngStyle]="{
      backgroundColor: theme.majorTextColor
    }"
    class="hamburger-line"
  ></div>
  <div
    [ngStyle]="{
      backgroundColor: theme.majorTextColor
    }"
    class="hamburger-line"
  ></div>
</div>
</code>```

I want each of the line to have a background color that I decide dynamically. So, I cannot add this directly to the SCSS file. But if I do the above, I am repeating myself. How do I do that in a DRY style without creating a separate component for the hamburger-line?

答:
You can either define the style in your component.ts:

```<code>readonly hamburgerStyle = { backgroundColor: this.theme.majorTextColor };
</code>```

and you can update your component:

```<code><div class="hamburger">
  <div
    [ngStyle]="hamburgerStyle"
    class="hamburger-line"
  ></div>
  <div
    [ngStyle]="hamburgerStyle"
    class="hamburger-line"
  ></div>
  <div
    [ngStyle]="hamburgerStyle"
    class="hamburger-line"
  ></div>
</div>
</code>```

Or you can use a ng-template and use ngTemplateOutlet to insert it (or use both):

```<code><div class="hamburger">
  <ng-container [ngTemplateOutlet]="hamburgerLine"></ng-container>
  <ng-container [ngTemplateOutlet]="hamburgerLine"></ng-container>
  <ng-container [ngTemplateOutlet]="hamburgerLine"></ng-container>
</div>

<ng-template #hamburgerLine>
  <div
    [ngStyle]="{
      backgroundColor: theme.majorTextColor
    }"
    class="hamburger-line"
  ></div>
</ng-template>
</code>```

Body:
I am making a hamburger as follows.

I want each of the line to have a background color that I decide dynamically. So, I cannot add this directly to the SCSS file. But if I do the above, I am repeating myself. How do I do that in a DRY style without creating a separate component for the hamburger-line?

Body:
You can either define the style in your component.ts:

readonly hamburgerStyle = { backgroundColor: this.theme.majorTextColor };

and you can update your component:

<div class="hamburger">
  <div
    [ngStyle]="hamburgerStyle"
    class="hamburger-line"
  ></div>
  <div
    [ngStyle]="hamburgerStyle"
    class="hamburger-line"
  ></div>
  <div
    [ngStyle]="hamburgerStyle"
    class="hamburger-line"
  ></div>
</div>

Or you can use a ng-template and use ngTemplateOutlet to insert it (or use both):

<div class="hamburger">
  <ng-container [ngTemplateOutlet]="hamburgerLine"></ng-container>
  <ng-container [ngTemplateOutlet]="hamburgerLine"></ng-container>
  <ng-container [ngTemplateOutlet]="hamburgerLine"></ng-container>
</div>

<ng-template #hamburgerLine>
  <div
    [ngStyle]="{
      backgroundColor: theme.majorTextColor
    }"
    class="hamburger-line"
  ></div>
</ng-template>


来源: stackexchange

问:
Why is my class not being toggled by this JavaScript function?
I am trying to toggle .active class when clicked on the #datePickerStart div. It only toggles when i click on the div but I want the element to be hidden when clicked outside of datepicker.

```<code>$('#datePickerStart').addEventListener('click', (e) => {
    console.log(e.path);
    if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
        $('#dropDownStart').classList.toggle('active');
    }
});

function checkEventPathForClass(path, selector) {
    for (item of path) {
        if (item.classList && item.classList.contains(selector)) {
            return true;
        }
    }
    return false;
}
</code>```

```<code>.active {
    display: block;
}
</code>```

JSBin for my website.

答:
You need to declare onclick function on entire document and than you can check if clicked Dom is datepicke or just remove active class from datepicker whenever click happens.

```<code>document.addEventListener("click", function(e){
    if( e.target.id == "dropDonStart" ){
        $('#dropDownStart').classList.toggle('active');
    }else{
        $('#dropDownStart').classList.remove('active');
    }
});
</code>```

Not tested but should work.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to toggle .active class when clicked on the #datePickerStart div. It only toggles when i click on the div but I want the element to be hidden when clicked outside of datepicker.

$('#datePickerStart').addEventListener('click', (e) => {
    console.log(e.path);
    if (!checkEventPathForClass(e.path, 'booking-dropdown')) {
        $('#dropDownStart').classList.toggle('active');
    }
});

function checkEventPathForClass(path, selector) {
    for (item of path) {
        if (item.classList && item.classList.contains(selector)) {
            return true;
        }
    }
    return false;
}

.active {
    display: block;
}

JSBin for my website.

Body:
You need to declare onclick function on entire document and than you can check if clicked Dom is datepicke or just remove active class from datepicker whenever click happens.

document.addEventListener("click", function(e){
    if( e.target.id == "dropDonStart" ){
        $('#dropDownStart').classList.toggle('active');
    }else{
        $('#dropDownStart').classList.remove('active');
    }
});

Not tested but should work.


问:
React router 4 url issue
```<code>import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { history } from './history';
import Login from './components/Login';
import Home from './components/Home';
import NotFound from './presentation/NotFound';
import MainContent from './components/MainContent';
import Overview from './components/Overview';

export default () => {
    return(
        <Router history ={history}>
            <Switch>
                <Route path="/" component={Login} exact />
                <Home>
                    <Route path="/main" exact component={MainContent} />
                    <Route path="/admin/:id" exact component={Overview} />
                </Home>
                <Route component={ NotFound } />
            </Switch>
        </Router>
    );
}
</code>```

my webpack config is

```<code>const path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            loader: 'babel-loader',test: /\.js$/,exclude: /node_modules/},
{
            test: /\.s?css$/,
            use: [
                'style-loader',
                'css-loader',
                'sass-loader'
            ]
        }, {
            test: /\.(png|jpg|gif)$/,
            use: [
            'file-loader',
            ],
        },{
            test: /\.svg$/,
            use: ['@svgr/webpack'],
        }, {
            test: /\.ttf$/,
            loader: "file-loader?limit=10000"
        }
        ]
    },
    devtool: 'cheap-module-eval-source-map',
    devServer: {
        contentBase: path.join(__dirname, 'public'),
        historyApiFallback: true
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            __CLIENT__: JSON.stringify(true),
            __DEVELOPMENT__: true,
            __DEVTOOLS__: true
        }),
    ],
    optimization:{}
};
</code>```

So when i land on /main i.e. MainContent component it renders a ViewComponent which renders a list of admins and on click of an individual element of the list it gives the detailed view of the that element on the /admin/:id route which works fine.

but if i refresh or hit the url directly from the address bar, the
  fonts' and the images' network request that were being rendered initially
  from localhost:8080/somerandomid.ttf are now retrieved from
  localhost:8080/admin/somerandomid.ttf throws a 400 bad request error and the styles change.

can anybody suggest how to rectify this error. i am calling a function and passing the id on click of an element from the list.

this.props.history.push('/admin/' + id);

and that ViewComponent is which renders the admin list is connected as export default withRouter(ViewComponent); to get this.props.history.push.

same goes with the image url too. localhost:8080/otherandomid.png is replaced and tried to get > from localhost:8080/admin/otherandomid.png and throws a 400 bad request error with no image
  displaying.

答:
You need to set up a base URL.

It can be done with HtmlWebpackPlugin:

```<code>plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
        __CLIENT__: JSON.stringify(true),
        __DEVELOPMENT__: true,
        __DEVTOOLS__: true
    }),
    new webpack.HtmlWebpackPlugin({
        base: '/'
    }),
],
</code>```

Or directly in the  of your index.html file:

<base href="/">
```

Title: React router 4 url issue

Body:
import React from 'react';
import { Router, Route, Switch } from 'react-router-dom';
import { history } from './history';
import Login from './components/Login';
import Home from './components/Home';
import NotFound from './presentation/NotFound';
import MainContent from './components/MainContent';
import Overview from './components/Overview';

export default () => {
    return(
        <Router history ={history}>
            <Switch>
                <Route path="/" component={Login} exact />
                <Home>
                    <Route path="/main" exact component={MainContent} />
                    <Route path="/admin/:id" exact component={Overview} />
                </Home>
                <Route component={ NotFound } />
            </Switch>
        </Router>
    );
}

my webpack config is

const path = require('path');
var webpack = require('webpack');

module.exports = {
    entry: './src/main.js',
    output: {
        path: path.join(__dirname, 'public'),
        filename: 'bundle.js'
    },
    module: {
        rules: [{
            loader: 'babel-loader',test: /\.js$/,exclude: /node_modules/},
{
            test: /\.s?css$/,
            use: [
                'style-loader',
                'css-loader',
                'sass-loader'
            ]
        }, {
            test: /\.(png|jpg|gif)$/,
            use: [
            'file-loader',
            ],
        },{
            test: /\.svg$/,
            use: ['@svgr/webpack'],
        }, {
            test: /\.ttf$/,
            loader: "file-loader?limit=10000"
        }
        ]
    },
    devtool: 'cheap-module-eval-source-map',
    devServer: {
        contentBase: path.join(__dirname, 'public'),
        historyApiFallback: true
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.DefinePlugin({
            __CLIENT__: JSON.stringify(true),
            __DEVELOPMENT__: true,
            __DEVTOOLS__: true
        }),
    ],
    optimization:{}
};

So when i land on /main i.e. MainContent component it renders a ViewComponent which renders a list of admins and on click of an individual element of the list it gives the detailed view of the that element on the /admin/:id route which works fine.

but if i refresh or hit the url directly from the address bar, the
  fonts' and the images' network request that were being rendered initially
  from localhost:8080/somerandomid.ttf are now retrieved from
  localhost:8080/admin/somerandomid.ttf throws a 400 bad request error and the styles change.

can anybody suggest how to rectify this error. i am calling a function and passing the id on click of an element from the list.

this.props.history.push('/admin/' + id);

and that ViewComponent is which renders the admin list is connected as export default withRouter(ViewComponent); to get this.props.history.push.

same goes with the image url too. localhost:8080/otherandomid.png is replaced and tried to get > from localhost:8080/admin/otherandomid.png and throws a 400 bad request error with no image
  displaying.

Body:
You need to set up a base URL.

It can be done with HtmlWebpackPlugin:

plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new webpack.DefinePlugin({
        __CLIENT__: JSON.stringify(true),
        __DEVELOPMENT__: true,
        __DEVTOOLS__: true
    }),
    new webpack.HtmlWebpackPlugin({
        base: '/'
    }),
],

Or directly in the <head> of your index.html file:

<base href="/">


问:
Hosting asp.net core + ReactJS web app with SSL containing multiple CN or domain names is causing invalid issuer error
I am facing the following problem while hosting a web app built with asp.net core 3.1 and React.

We have used default visual studio template for React. ASP.NET Identity is used for authentication and authorization.

Authentication and Authorization work as expected as long as we host the website with an SSL certificate issued for single domain or CN. (e.g. example.com)

If we host he website with an SSL with multiple CNs (e.g. example.com, sub1.example.com, sub2.example.com), it works fine for any ONE of the domains. For the remaining domains we get the following behavior:

The login works as expected. The /connect/token path issues valid token. Once logged in, when we try to invoke any api (all apis are hosted under /api route), we get 401 unauthorized error. Error description in the header:

WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'https://sub1.example.com' is invalid".

I also tried parsing the issued token on jwt.io. The iss field (issuer) is https://sub1.example.com which exactly matches the error description. I cannot fathom why identity engine refuses to identify the issuer for which it issued token for.

Here is relevant snippet from Startup.cs

```<code>public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
    services.AddAuthentication()
            .AddIdentityServerJwt();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication();
    app.UseIdentityServer();
    app.UseAuthorization();
}
</code>```

Any ideas?

答:
This is probably happening as a result of receiving the token from an instance of IdentityServer4 on one CN, and trying to validate it with a request to IdentityServer4 using another CN. The IdentityServer component that's rejecting the token is TokenValidator's ValidateJwtAsync method. This method passes in the issuer into JwtSecurityTokenHandler's ValidateToken as a property of TokenValidationParameters. The issuer is retrieved from either the issuer configured on the IdentityServerOptions in the 'AddIdentityServer' extension method, or is dynamically generated from the request.

I can think of one way to resolve the validation problems, and that is to set the issuer on the IdentityServerOptions using the delegate passed into AddIdentityServer. This will result in the same issuer being set for all tokens issued, regardless of the CN it was accessed from. This would allow IdentityServer a single source of truth for issuer information, and will allow IdentityServer to know which issuer to verify against when a token comes in for validation.

Other solutions of trying to maintain the issuer are heavily restricted by the TokenValidator being an internal class that can't be inherited and easily replaced with an implementation that will validate against a list of valid issuers. Additionally, the IdentityServerOptions that's configured to have the issuer uri is registered as a singleton and cannot have its values changed. Other contrived implementation could be devised like attempting to dynamically change the host value on the HttpContext with a middleware (which I'm not sure is even possible since I've never tried), but anything that goes against IdentityServer4's design decision is not advised.

Body:
I am facing the following problem while hosting a web app built with asp.net core 3.1 and React.

We have used default visual studio template for React. ASP.NET Identity is used for authentication and authorization.

Authentication and Authorization work as expected as long as we host the website with an SSL certificate issued for single domain or CN. (e.g. example.com)

If we host he website with an SSL with multiple CNs (e.g. example.com, sub1.example.com, sub2.example.com), it works fine for any ONE of the domains. For the remaining domains we get the following behavior:

The login works as expected. The /connect/token path issues valid token. Once logged in, when we try to invoke any api (all apis are hosted under /api route), we get 401 unauthorized error. Error description in the header:

WWW-Authenticate: Bearer error="invalid_token", error_description="The issuer 'https://sub1.example.com' is invalid".

I also tried parsing the issued token on jwt.io. The iss field (issuer) is https://sub1.example.com which exactly matches the error description. I cannot fathom why identity engine refuses to identify the issuer for which it issued token for.

Here is relevant snippet from Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    services.AddIdentityServer()
            .AddApiAuthorization<ApplicationUser, ApplicationDbContext>();
    services.AddAuthentication()
            .AddIdentityServerJwt();
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    app.UseAuthentication();
    app.UseIdentityServer();
    app.UseAuthorization();
}

Any ideas?


问:
DDD: Lazy loading in aggregates
I've been learning DDD for the past few days and struggling to understand some core concepts of aggregate roots. Maybe somebody could give me push in the right direction and elaborate what's best practice in this scenario:

To make this example less complex, let's say we have a domain of two entities: restaurant and opening time. Restaurant is defined as aggregate root.

From what I understood in all the online examples (correct me if I'm mistaken), the aggregate root is eager loading all sub-entities every time I need an instance of it. So whenever I want to call call a method on the restaurant, all opening times are loaded (no matter if they are used or not).

In this example I want to verify that there is no intersection of opening times when a new time get's added to that restaurant. In this case the eager loading of every other opening time makes sense because I need to compare them with the existing ones.

BUT: this is kind of restricting because I know every time I want to add another collection of something (let's say restaurant images), the SQL load get's heavier and heavier even though most of the methods only require one of the collections.

I could think of two possible solutions:

Lazy loading

Lazy loading opening times / sub entities through entity framework property proxies. So the aggregate root can exist without eager loading them but whenever they are needed they can be accessed.
However everywhere I was searching for an answer I've red that lazy loading in aggregate roots is considered bad practice. Maybe somebody could explain why.

Smaller aggregate roots

Of course I could define the opening time itself as an aggregate root but then I need to take the business logic (in this case the verification of intersections) outside of the model.

In all the examples above I'm only talking about the command side (not querying or serializing).

Maybe I'm missing some fundamental ideas. How should the aggregate roots be organized in this example and why is lazy loading considered bad practice?

EDIT
Not sure why this question was closed because of "opinion based". I'm asking for best practice and why lazy loading is not in this case.

答:
This problem classifies as a set validation problem and there's a few potential solutions depending on the domain needs.

Strong Consistency

Create an AR to protect the entire set. In the above example if such set has a reasonable length you may create a dedicated RestaurantSchedule AR. You may even partition such AR further into RestaurantWeekSchedule where you'd have 1 AR for each week. When you want to add/remove opening days it would create/load the AR of the given week. Another option could be to tweak the ORM to load only a subset of the collection e.g. schedule = scheduleRepo.loadForWeek(openingTime.week()); schedule.add(openingTime);. Optimistic locking would still allow to detect conflicts.

Enforce the rule in the DB. If you have a relational DB for instance you may have OpeningTime as an AR and then use unique constraints to prevent violations. The rule would end up living outside the domain, but it may be acceptable. Uniqueness rules aren't that interesting.

Eventual Consistency

A very common way to deal with set validation problems is to avoid trying to avoid the violation and focus on detecting and correcting it after the fact either through manual or automated compensating actions. This can be as simple as an exception report that displays overlapping entries or more complex such as a single-threaded listener to OpeningTimeAdded events that checks for conflicts and marks such entries for correction.

Title: DDD: Lazy loading in aggregates


问:
Http request via one network interface
I would like to call HTTP request for rest webservice only on selected network interface.

Any advice on this would be much appreciated.

答:
I found out that you can define network interface in url like this :

```<code>192.168.1.122%eth0
</code>```

It's working in Ubuntu and I hope that it works in different systems too.

ContentLicense: CC BY-SA 3.0

Title: Http request via one network interface

Body:
I found out that you can define network interface in url like this :

192.168.1.122%eth0

It's working in Ubuntu and I hope that it works in different systems too.


问:
why is this assignment not allowed in Java generic
here is the code example

public static ArrayList<? extends A> get(){
   return null;
}

public static void main(String[] args){
   ArrayList test=get();//not allowed
}
```

since A certainly is the super class of any ? extends A, why is the code snippet not allowed?

答:
You've got it the wrong way round; ArrayList is assignable to ArrayList<? extends A>, but you're trying to assign an ArrayList<? extends A> to ArrayList.

In fact, List<? extends A> is a supertype of List, not a subtype; using the REPL:

> List list = new ArrayList<? extends A>();
Error:
unexpected type
  required: class or interface without bounds
  found:    ? extends A

> List<? extends A> list = new ArrayList();
[]
```

<p>So your code is like <code>String s = new Object();</code>, not like <code>Object s = new String();</code>.</p>

<hr>

<p>OK, so why isn't <code>List<? extends A></code> assignable to <code>List<A></code>? The answer is in the Liskov substitution principle. A <code>List<A></code> can do some things that a <code>List<? extends A></code> can't do, such as <code>.add(new A())</code>:</p>

<pre class="lang-java prettyprint-override"><code>> List<A> listA = new ArrayList<>();
[]

> listA.add(new A());
true

> List<? extends A> listExtendsA = new ArrayList<B>(); // B is a subclass of A
[]

> listExtendsA.add(new A());
Error:
incompatible types: A cannot be converted to capture#2 of ? extends A
</code>```

This makes sense because you shouldn't be allowed to add an instance of A to a List. On the other hand, List is assignable to List<? extends A>, because a List can do everything that a List<? extends A> can do.

Actually, a List<? extends A> can't do very much; you can't even .add(new B()), for example.

Body:
here is the code example

public static ArrayList<? extends A> get(){
   return null;
}

public static void main(String[] args){
   ArrayList test=get();//not allowed
}

since A certainly is the super class of any ? extends A, why is the code snippet not allowed?

Body:
You've got it the wrong way round; ArrayList<A> is assignable to ArrayList<? extends A>, but you're trying to assign an ArrayList<? extends A> to ArrayList<A>.

In fact, List<? extends A> is a supertype of List<A>, not a subtype; using the REPL:

> List<A> list = new ArrayList<? extends A>();
Error:
unexpected type
  required: class or interface without bounds
  found:    ? extends A

> List<? extends A> list = new ArrayList<A>();
[]

So your code is like String s = new Object();, not like Object s = new String();.

OK, so why isn't List<? extends A> assignable to List<A>? The answer is in the Liskov substitution principle. A List<A> can do some things that a List<? extends A> can't do, such as .add(new A()):

> List<A> listA = new ArrayList<>();
[]

> listA.add(new A());
true

> List<? extends A> listExtendsA = new ArrayList<B>(); // B is a subclass of A
[]

> listExtendsA.add(new A());
Error:
incompatible types: A cannot be converted to capture#2 of ? extends A

This makes sense because you shouldn't be allowed to add an instance of A to a List<B>. On the other hand, List<A> is assignable to List<? extends A>, because a List<A> can do everything that a List<? extends A> can do.

Actually, a List<? extends A> can't do very much; you can't even .add(new B()), for example.


问:
How do I check a Pandas Datetime column for missing values?
I have to check some data from an instrument and have to make sure that there are no missing time intervals.
So for example I have a Dataframe like this:

I've tried to generate a new datetime Series with
pd.date_range('2020-02-17 10:29:25', periods=1440, freq='T')
and tried to compare it. But i got stuck.

Body:
You can try to create a daterange and check what values are missing in the DataFrame column. Like this:

df=pd.DataFrame({'Datetime':[*pd.date_range('2020-02-17 10:29:25', periods=3, freq='T'), *pd.date_range('2020-02-17 10:49:25', periods=3, freq='T')]})
df
             Datetime
0 2020-02-17 10:29:25
1 2020-02-17 10:30:25
2 2020-02-17 10:31:25
3 2020-02-17 10:49:25
4 2020-02-17 10:50:25
5 2020-02-17 10:51:25

my_range = pd.date_range(start=df['Datetime'].min(), end=df['Datetime'].max(), freq='T')

my_range[~my_range.isin(df['Datetime'])]
DatetimeIndex(['2020-02-17 10:32:25', '2020-02-17 10:33:25',
               '2020-02-17 10:34:25', '2020-02-17 10:35:25',
               '2020-02-17 10:36:25', '2020-02-17 10:37:25',
               '2020-02-17 10:38:25', '2020-02-17 10:39:25',
               '2020-02-17 10:40:25', '2020-02-17 10:41:25',
               '2020-02-17 10:42:25', '2020-02-17 10:43:25',
               '2020-02-17 10:44:25', '2020-02-17 10:45:25',
               '2020-02-17 10:46:25', '2020-02-17 10:47:25',
               '2020-02-17 10:48:25'],
              dtype='datetime64[ns]', freq='T')

Or you could use this (inspired by @furas):

df_missing = df[df['Datetime'].diff()>pd.Timedelta('60s')]
df_missing['diff'] = df.diff()
df_missing

             Datetime     diff
3 2020-02-17 10:49:25 00:18:00


问:
Android/WearOS Program Structure
I am new to Android development and wanted some guidance. I am building a Mobile + WearOS app. I have a shared project, which I expect to be for the objects each device will manipulate. I have SQLlite utilities, those should be in a directory of the mobile app under the java directory. Does all that sound right from a structure standpoint? I expect I will have cloud utilities as well which will be a different directory under the mobile app java directory.</p>

答:
I assume your problem is: How to share codes between mobile and wear module.

You need to create an AndroidLibrary Module through File - New - New Module. After that
 add it as a dependency to your mobile and wear module. Just in build.gradle (mobile's and wear's) add implementation project(':{your_module_name}') in dependencies section.

Now you can move all your codes that you want to share to the new lib moudule, then both mobile and wear mudule can ues them.

Title: Android/WearOS Program Structure


问:
I am trying to create one randomly selected individual to be positive in a random distribution, but my code is incorrect
I am trying to create one randomly selected individual in a random distribution to be infected with a disease. Firstly I created a random distribution using:

```<code> xcoord<-sample(1:100,60)
 ycoord<-sample(1:100,60)
 infectionstatus<-rep(0,60)
 df2<-data.frame(xcoord,ycoord,infectionstatus)
</code>```

This gives me a plot looking something like this:

In order to randomly choose a point and assign it a value of positive, I have tried creating a for loop like so:

```<code>for(j in 0:60) {
df2[infectionstatus[j]]<-df2[infectionstatus[j]+1]}
</code>```

But this creates an error:

Error in x[[jj]] <- v :
  attempt to select less than one element in integerOneIndex

How can I randomly choose one individual to have an assigned value of 1?

答:
Sample one number from 1 to 60 (call it a):

```<code>a<-sample(1:60, 1)
</code>```

And change

```<code>df2$infectionstatus[a]<-1
</code>```

Body:
I am trying to create one randomly selected individual in a random distribution to be infected with a disease. Firstly I created a random distribution using:

 xcoord<-sample(1:100,60)
 ycoord<-sample(1:100,60)
 infectionstatus<-rep(0,60)
 df2<-data.frame(xcoord,ycoord,infectionstatus)

This gives me a plot looking something like this:

In order to randomly choose a point and assign it a value of positive, I have tried creating a for loop like so:

for(j in 0:60) {
df2[infectionstatus[j]]<-df2[infectionstatus[j]+1]}

But this creates an error:

Error in x[[jj]] <- v :
  attempt to select less than one element in integerOneIndex

How can I randomly choose one individual to have an assigned value of 1?

Body:
Sample one number from 1 to 60 (call it a):

a<-sample(1:60, 1)

And change

df2$infectionstatus[a]<-1


Title: Smooth Transition Linear Gradient on SVG Hover

Body:
i have a transition problem for linear gradient svg hover.
Gradient is ok but i cant apply smooth transition for my path.

ps:i want to use only one path, without mask.

Thank you

path#grad1 { transition: 3s;}

svg {
transition: 3s;
    width: 160px;
    max-height: 80px;
    margin-bottom: 20px;
}

svg .gradient { fill: url("#grad1");  }
svg:hover .gradient { fill: url("#grad2"); }

    <svg viewBox="0 0 30 60">
        <path class="gradient" d="M6.93,59.16A1.36,1.36,0,0,1,6.35,59a1.38,1.38,0,0,1-.74-1.62L12.9,31.65H1.37A1.38,1.38,0,0,1,.29,29.43L22.8.53A1.36,1.36,0,0,1,24.5.15a1.37,1.37,0,0,1,.71,1.59L19.3,23.06H30a1.38,1.38,0,0,1,1.13,2.16L8.06,58.57A1.37,1.37,0,0,1,6.93,59.16ZM4.19,28.9H14.71a1.37,1.37,0,0,1,1.1.55,1.39,1.39,0,0,1,.23,1.2L10.51,50.2,27.37,25.81H17.49a1.37,1.37,0,0,1-1.09-.54,1.35,1.35,0,0,1-.23-1.2L20.71,7.69Z" />
        <defs>
            <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" style="stop-color: #07183d;  " />
                <stop offset="100%" style="stop-color: #07183d; " />
            </linearGradient>
        </defs>
        <defs>
            <linearGradient id="grad2" x1="0%" y1="0%" x2="100%" y2="0%" >
                <stop offset="0%" style="stop-color: #FE8301;  " />
                <stop offset="100%" style="stop-color: #003ec7;  " />
            </linearGradient>
        </defs>
    </svg>

Body:
How's this?

path#grad1 { transition: 3s;}

svg {
    width: 160px;
    max-height: 80px;
    margin-bottom: 20px;
}

svg .gradient1 { fill: url("#grad1");  }
svg .gradient2 { fill: url("#grad2"); }

svg use {
   transition: 3s;
   opacity: 0;
}

svg:hover use {
   opacity: 1;
}

<a href="" target="">
    <svg viewBox="0 0 30 60">
        <defs>
            <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
                <stop offset="0%" style="stop-color: #07183d;  " />
                <stop offset="100%" style="stop-color: #07183d; " />
            </linearGradient>
            <linearGradient id="grad2" x1="0%" y1="0%" x2="100%" y2="0%" >
                <stop offset="0%" style="stop-color: #FE8301;  " />
                <stop offset="100%" style="stop-color: #003ec7;  " />
            </linearGradient>
        </defs>

        <g class="gradient1">
          <path id="shape" d="M6.93,59.16A1.36,1.36,0,0,1,6.35,59a1.38,1.38,0,0,1-.74-1.62L12.9,31.65H1.37A1.38,1.38,0,0,1,.29,29.43L22.8.53A1.36,1.36,0,0,1,24.5.15a1.37,1.37,0,0,1,.71,1.59L19.3,23.06H30a1.38,1.38,0,0,1,1.13,2.16L8.06,58.57A1.37,1.37,0,0,1,6.93,59.16ZM4.19,28.9H14.71a1.37,1.37,0,0,1,1.1.55,1.39,1.39,0,0,1,.23,1.2L10.51,50.2,27.37,25.81H17.49a1.37,1.37,0,0,1-1.09-.54,1.35,1.35,0,0,1-.23-1.2L20.71,7.69Z" />
        </g>
        <use xlink:href="#shape" class="gradient2"/>
    </svg>

</a>


问:
When using .rotate() it leaves 1px Lines behind
I'm currently learning about the html5 canvas, and I was making a program that rotates a square around the center of the page using the .rotate() function, but it was leaving behind 1px lines from where the square used to be even though I was filling the canvas after every turn and nothing in the code was 1px. so can someone please explain why this is happening and how to stop it from happening

thanks!

const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")

canvas.width = 300;
canvas.height = 300;

//debugger;
/*
canvas.addEventListener("mousedown", mouseDown, false)
canvas.addEventListener("mouseup", mouseUp, false)
canvas.addEventListener("mousemove", mouseMove, false)
*/

ctx.fillStyle = "#303030";
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.translate(150, 150)

let turnSquare = setInterval(() =>{
 ctx.fillStyle = "#303030"
 ctx.fillRect(0, 0, canvas.width, canvas.height)

 ctx.rotate(degree(10))

 ctx.beginPath()
 ctx.fillStyle = "lime"
 ctx.fillRect(0, 0, 100, 100)

}, 1000 / 20)

function degree(input){
 return 2 * Math.PI / 360 * input
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></code>```

答:
Anti aliasing edge.

The reason you are getting the ~1px line is because the ctx.fillRect you use to clear the canvas is transformed by the same transform used to draw the box.

When a shape is rendered its edges are anti-aliased, some of the edge pixels are drawn semi-transparent meaning that drawing over that same box will leave some of the original pixels behind.

To fix

Reset the transform to the default before you clear the canvas. ctx.setTransform(1,0,0,1,0,0);

Use a variable to hold the total rotation of the box (see example)

Use setTransform to replace the current transform rather than build the transform in stages using ctx.translate and ctx.rotate.

Transform basics while help understand how setTransform can be used to position, scale, and rotate rendered objects in the 2D canvas API.

Other points

Use requestAnimationFrame rather than setInterval to call the animation loop to ensure the smoothest possible animation.

Use a single object to store related data. Eg the object box in example holds all relevant data needed to animate the box.

Try to express animations in meaningfully ways. In the example the box rotation rate box.rotSpeed is set as rotations per second

Example

requestAnimationFrame(mainLoop);
const ctx = canvas.getContext("2d")
canvas.height = canvas.width = 300;
canvas.style.backgroundColor = "#303030"

const box = {
   color: "lime",
   cx: 0.25,  // x rotation center as fraction of box size
   cy: 0.25,  // y rotation center as fraction of box size
   x: 150,
   y: 150,
   size: (150 * 150 / 2) ** 0.5, // makes diagonal size of box 150
   rot: 0,
   rotSpeed: 0.5,  // in rotations per second
};
function drawBox(box) {
   box.rot += box.rotSpeed * Math.PI / 30; // 2*PI/60 is one rotation per second at 60FPS
   ctx.fillStyle = box.color;
   const xa = Math.cos(box.rot);
   const ya = Math.sin(box.rot);
   ctx.setTransform(xa, ya, -ya, xa, box.x, box.y);
   ctx.fillRect(-box.cx * box.size, -box.cy * box.size, box.size, box.size);
}
function mainLoop() {
   ctx.setTransform(1, 0, 0, 1, 0, 0); // set default transform
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   drawBox(box);
   requestAnimationFrame(mainLoop);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></code>```

Body:
I'm currently learning about the html5 canvas, and I was making a program that rotates a square around the center of the page using the .rotate() function, but it was leaving behind 1px lines from where the square used to be even though I was filling the canvas after every turn and nothing in the code was 1px. so can someone please explain why this is happening and how to stop it from happening

thanks!

const canvas = document.getElementById("canvas")
const ctx = canvas.getContext("2d")

canvas.width = 300;
canvas.height = 300;

//debugger;
/*
canvas.addEventListener("mousedown", mouseDown, false)
canvas.addEventListener("mouseup", mouseUp, false)
canvas.addEventListener("mousemove", mouseMove, false)
*/

ctx.fillStyle = "#303030";
ctx.fillRect(0, 0, canvas.width, canvas.height)
ctx.translate(150, 150)

let turnSquare = setInterval(() =>{
 ctx.fillStyle = "#303030"
 ctx.fillRect(0, 0, canvas.width, canvas.height)

 ctx.rotate(degree(10))

 ctx.beginPath()
 ctx.fillStyle = "lime"
 ctx.fillRect(0, 0, 100, 100)

}, 1000 / 20)

function degree(input){
 return 2 * Math.PI / 360 * input
}

<canvas id="canvas">

Body:
Anti aliasing edge.

The reason you are getting the ~1px line is because the ctx.fillRect you use to clear the canvas is transformed by the same transform used to draw the box.

When a shape is rendered its edges are anti-aliased, some of the edge pixels are drawn semi-transparent meaning that drawing over that same box will leave some of the original pixels behind.

To fix

Reset the transform to the default before you clear the canvas. ctx.setTransform(1,0,0,1,0,0);

Use a variable to hold the total rotation of the box (see example)

Use setTransform to replace the current transform rather than build the transform in stages using ctx.translate and ctx.rotate.

Transform basics while help understand how setTransform can be used to position, scale, and rotate rendered objects in the 2D canvas API.

Other points

Use requestAnimationFrame rather than setInterval to call the animation loop to ensure the smoothest possible animation.

Use a single object to store related data. Eg the object box in example holds all relevant data needed to animate the box.

Try to express animations in meaningfully ways. In the example the box rotation rate box.rotSpeed is set as rotations per second

Example

requestAnimationFrame(mainLoop);
const ctx = canvas.getContext("2d")
canvas.height = canvas.width = 300;
canvas.style.backgroundColor = "#303030"

const box = {
   color: "lime",
   cx: 0.25,  // x rotation center as fraction of box size
   cy: 0.25,  // y rotation center as fraction of box size
   x: 150,
   y: 150,
   size: (150 * 150 / 2) ** 0.5, // makes diagonal size of box 150
   rot: 0,
   rotSpeed: 0.5,  // in rotations per second
};
function drawBox(box) {
   box.rot += box.rotSpeed * Math.PI / 30; // 2*PI/60 is one rotation per second at 60FPS
   ctx.fillStyle = box.color;
   const xa = Math.cos(box.rot);
   const ya = Math.sin(box.rot);
   ctx.setTransform(xa, ya, -ya, xa, box.x, box.y);
   ctx.fillRect(-box.cx * box.size, -box.cy * box.size, box.size, box.size);
}
function mainLoop() {
   ctx.setTransform(1, 0, 0, 1, 0, 0); // set default transform
   ctx.clearRect(0, 0, canvas.width, canvas.height);
   drawBox(box);
   requestAnimationFrame(mainLoop);
}

<canvas id="canvas">


问:
How to show full name instead of merchant id in view "Manage merchant id"
view section

```<code>  <div class="content-header-left col-md-6 col-12 mb-1">
     <h3 class="content-header-title mb-0 font-14">
         <a href="#">
             <i class="close icon-arrow-left font-16 px-50 float-left></i>
        </a> Manage <?php echo $merchantId; ?>
    </h3>

   //we have to replace mechantId with fullname in database
  </div>
</code>```

function in controller

```<code>class SubMerchantController extends AppController {
    public $permission_dashboard=array();
    public $plugin = null;
    public $modelClass = 'SubMerchant';
    public $lang="admin";
    public $merchantId="";
    public $imageFolder="merchants";

    public $module="Multiple Pickup Points";

    public $helpers = array('Html','Form','Time','Text');

    public function initialize()
    {

        parent::initialize();
        $this->loadModel('Merchants.SubMerchant');
        $this->loadModel('Masters.CompanyType');
        $this->loadModel('Masters.Plan');
        $this->loadModel('UserContact');
        $this->loadComponent('Paginator');
        $this->loadComponent('Flash');
        $this->loadComponent('Search.Prg', [ 'actions' => ['index'] ]);
        $this->loadComponent('Common');
        $this->loadComponent('Upload');

    }

    public function beforeRender(Event $event){
        $action=isset($this->request->params['action'])?$this->request->params['action']:"";
        $loginMerchant=$this->request->session()->read('Auth.FrontUser.id');

        if($action=="sortOrder" || $action=="view" || $action=="ajaxPlanData"){
            $this->viewBuilder()->layout('ajax');
        }elseif($loginMerchant!=""){
            $this->viewBuilder()->layout('merchantAfterLogin');

        }else{
            $this->viewBuilder()->layout('adminAfterLogin');

       }
    }

    public function beforeFilter(Event $event){

         $this->CommonAuthCheck();

         $merchantId=$this->request->query('merchant_id');
         //Login Merchant Check
          $loginMerchant=$this->request->session()->read('Auth.FrontUser.id');
         if($merchantId==""){
          $merchantId=$loginMerchant;
         }

         if($merchantId<=0){
          //$this->redirect('/');
          //exit;
         }

         $this->merchantId=$merchantId;
         $this->set('merchantId',$merchantId);

         $this->set('modelName', 'SubMerchant');
         $this->set('lang', 'admin');
         $this->set('module', $this->module);
         $this->set('pluginFolder', 'Merchants');
         $this->set('imageFolder', $this->imageFolder);

    }

    public function index(){
                $sort=isset($this->request->query['sort'])?$this->request->query['sort']:"";
                $direction=isset($this->request->query['direction'])?$this->request->query['direction']:"";

            $query = $this->{$this->modelClass}->find('search', $this->{$this->modelClass}->filterParams(array_map('trim',$this->request->query)));
            $this->paginate = array(
                        'limit' =>  $this->request->query('listing')!=""?$this->request->query('listing'):"10",
                        'fields'=>array('id','parent_id','full_name','email','brand_name','merchant_code','register_pincode','status','last_login','created','updated'),
                        'conditions'=>array('parent_id'=>$this->merchantId),
                        'order'=>array($this->modelClass.'.full_name'=>'asc'),
                    );
            $this->Paginator->settings = $this->paginate;

            $this->set('datas',$this->paginate($query));
            //debug($this->paginate($query));
            //exit;
            $searchArray=array(
            'status'=>(isset($this->request->data['status']) && $this->request->data['status'])?$this->request->data['status']:"",
            'full_name'=>(isset($this->request->data['full_name']) &&
                $this->request->data['full_name'])?$this->request->data['full_name']:"",
            'email'=>(isset($this->request->data['email']) && $this->request->data['email'])?$this->request->data['email']:"",
            'merchant_code'=>(isset($this->request->data['merchant_code']) &&
                $this->request->data['merchant_code'])?$this->request->data['merchant_code']:"",

            );

            $listHeadings=array(
                                'ID'=>array('field'=>'id','icon'=>SORT_ICON),
                                'Name'=>array('field'=>'full_name','icon'=>SORT_ICON),
                                'Email'=>array('field'=>'email','icon'=>SORT_ICON),
                                'Brand',
                                'Date'=>array('field'=>'created','icon'=>SORT_ICON),
                                );
   $this->set(compact('searchArray','listHeadings','sort','direction'));
        }
</code>```

database table

phpmyadmin table

答:
Basic CakePHP:

Interacting with Views

https://book.cakephp.org/3/en/controllers.html#interacting-with-views

Example:

function index() -> set data to -> index.ctp

function view() -> set data to -> view.ctp

Concat strings:

simple: echo $name . ' ' . $surname; // John Doe

complex: ```echo sprintf('%s %s', $name, $surname); // John Doe</li>
</ul>

<p><strong>Set data from controller:</strong> </p>

<ul>
<li>$this->set('full_name', sprintf('%s %s', $name, $surname));</li>
</ul>

<p><strong>Print full_name in view:</strong></p>

<ul>
<li><code>echo $full_name</code></li>
</ul>

<p><strong>CakePHP way:</strong></p>

```$data = $this->Users->find()->first();
$this->set(compact($data));

// view:
echo $data->full_name
```

Body:
view section

         Manage <?php echo $merchantId; ?>

   //we have to replace mechantId with fullname in database

function in controller

class SubMerchantController extends AppController {
    public $permission_dashboard=array();
    public $plugin = null;
    public $modelClass = 'SubMerchant';
    public $lang="admin";
    public $merchantId="";
    public $imageFolder="merchants";

    public $module="Multiple Pickup Points";

    public $helpers = array('Html','Form','Time','Text');

    public function initialize()
    {

        parent::initialize();
        $this->loadModel('Merchants.SubMerchant');
        $this->loadModel('Masters.CompanyType');
        $this->loadModel('Masters.Plan');
        $this->loadModel('UserContact');
        $this->loadComponent('Paginator');
        $this->loadComponent('Flash');
        $this->loadComponent('Search.Prg', [ 'actions' => ['index'] ]);
        $this->loadComponent('Common');
        $this->loadComponent('Upload');

    }

    public function beforeRender(Event $event){
        $action=isset($this->request->params['action'])?$this->request->params['action']:"";
        $loginMerchant=$this->request->session()->read('Auth.FrontUser.id');

        if($action=="sortOrder" || $action=="view" || $action=="ajaxPlanData"){
            $this->viewBuilder()->layout('ajax');
        }elseif($loginMerchant!=""){
            $this->viewBuilder()->layout('merchantAfterLogin');

        }else{
            $this->viewBuilder()->layout('adminAfterLogin');

       }
    }

    public function beforeFilter(Event $event){

         $this->CommonAuthCheck();

         $merchantId=$this->request->query('merchant_id');
         //Login Merchant Check
          $loginMerchant=$this->request->session()->read('Auth.FrontUser.id');
         if($merchantId==""){
          $merchantId=$loginMerchant;
         }

         if($merchantId<=0){
          //$this->redirect('/');
          //exit;
         }

         $this->merchantId=$merchantId;
         $this->set('merchantId',$merchantId);

         $this->set('modelName', 'SubMerchant');
         $this->set('lang', 'admin');
         $this->set('module', $this->module);
         $this->set('pluginFolder', 'Merchants');
         $this->set('imageFolder', $this->imageFolder);

    }

    public function index(){
                $sort=isset($this->request->query['sort'])?$this->request->query['sort']:"";
                $direction=isset($this->request->query['direction'])?$this->request->query['direction']:"";

            $query = $this->{$this->modelClass}->find('search', $this->{$this->modelClass}->filterParams(array_map('trim',$this->request->query)));
            $this->paginate = array(
                        'limit' =>  $this->request->query('listing')!=""?$this->request->query('listing'):"10",
                        'fields'=>array('id','parent_id','full_name','email','brand_name','merchant_code','register_pincode','status','last_login','created','updated'),
                        'conditions'=>array('parent_id'=>$this->merchantId),
                        'order'=>array($this->modelClass.'.full_name'=>'asc'),
                    );
            $this->Paginator->settings = $this->paginate;

            $this->set('datas',$this->paginate($query));
            //debug($this->paginate($query));
            //exit;
            $searchArray=array(
            'status'=>(isset($this->request->data['status']) && $this->request->data['status'])?$this->request->data['status']:"",
            'full_name'=>(isset($this->request->data['full_name']) &&
                $this->request->data['full_name'])?$this->request->data['full_name']:"",
            'email'=>(isset($this->request->data['email']) && $this->request->data['email'])?$this->request->data['email']:"",
            'merchant_code'=>(isset($this->request->data['merchant_code']) &&
                $this->request->data['merchant_code'])?$this->request->data['merchant_code']:"",

            );

            $listHeadings=array(
                                'ID'=>array('field'=>'id','icon'=>SORT_ICON),
                                'Name'=>array('field'=>'full_name','icon'=>SORT_ICON),
                                'Email'=>array('field'=>'email','icon'=>SORT_ICON),
                                'Brand',
                                'Date'=>array('field'=>'created','icon'=>SORT_ICON),
                                );
   $this->set(compact('searchArray','listHeadings','sort','direction'));
        }

database table

phpmyadmin table

Body:
Basic CakePHP:

Interacting with Views

https://book.cakephp.org/3/en/controllers.html#interacting-with-views

Example:

function index() -> set data to -> index.ctp

function view() -> set data to -> view.ctp

Concat strings:

simple: echo $name . ' ' . $surname; // John Doe

complex: ```echo sprintf('%s %s', $name, $surname); // John Doe

Set data from controller:

$this->set('full_name', sprintf('%s %s', $name, $surname));

Print full_name in view:

echo $full_name

CakePHP way:

$data = $this->Users->find()->first();
$this->set(compact($data));

// view:
echo $data->full_name


问:
Why NumberUtils.isNumber() is not working properly?
when i check with condition 08 or 09 or 010  and above leading with 0  in org.apache.commons.lang3.math.NumberUtils.isNumber("08")

答:
Non-hexadecimal strings beginning with a leading zero are treated as octal values.

Thus the string "09" will return false.

This is because 9 is not a valid octal value.

Reference official docs


答:
You can put Datetime in new column but shifted one row down so you will have two values in one row and you can substract them and check if result is bigger then 1 minute.

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

data = {'Datetime': [
    '2020-02-17 10:29:25',
    '2020-02-17 10:30:25',
    '2020-02-17 10:31:25',
    '2020-02-17 10:45:25',
    '2020-02-17 10:46:25',
]}

df = pd.DataFrame(data)
df['Datetime'] = pd.to_datetime(df['Datetime'])

df['DT2'] = df['Datetime'].shift(1)
df['diff'] = df['Datetime'] - df['DT2']

# all values

print(df)

# compare with 1 minut

print(df[df['diff'] > datetime.timedelta(seconds=60)])
</code>```

Result

```<code># all values

             Datetime                 DT2     diff
0 2020-02-17 10:29:25                 NaT      NaT
1 2020-02-17 10:30:25 2020-02-17 10:29:25 00:01:00
2 2020-02-17 10:31:25 2020-02-17 10:30:25 00:01:00
3 2020-02-17 10:45:25 2020-02-17 10:31:25 00:14:00
4 2020-02-17 10:46:25 2020-02-17 10:45:25 00:01:00

# compare with 1 minut

             Datetime                 DT2     diff
3 2020-02-17 10:45:25 2020-02-17 10:31:25 00:14:00
</code>```

EDIT: see @luigigi answer for simpler version which uses

```<code>df[ df['Datetime'].diff() > pd.Timedelta('60s') ]
</code>```

Title: How do I check a Pandas Datetime column for missing values?

Body:
I have to check some data from an instrument and have to make sure that there are no missing time intervals.
So for example I have a Dataframe like this:

I've tried to generate a new datetime Series with
pd.date_range('2020-02-17 10:29:25', periods=1440, freq='T')
and tried to compare it. But i got stuck.

Body:
You can put Datetime in new column but shifted one row down so you will have two values in one row and you can substract them and check if result is bigger then 1 minute.

import pandas as pd
import datetime

data = {'Datetime': [
    '2020-02-17 10:29:25',
    '2020-02-17 10:30:25',
    '2020-02-17 10:31:25',
    '2020-02-17 10:45:25',
    '2020-02-17 10:46:25',
]}

df = pd.DataFrame(data)
df['Datetime'] = pd.to_datetime(df['Datetime'])

df['DT2'] = df['Datetime'].shift(1)
df['diff'] = df['Datetime'] - df['DT2']

# all values

print(df)

# compare with 1 minut

print(df[df['diff'] > datetime.timedelta(seconds=60)])

Result

# all values

             Datetime                 DT2     diff
0 2020-02-17 10:29:25                 NaT      NaT
1 2020-02-17 10:30:25 2020-02-17 10:29:25 00:01:00
2 2020-02-17 10:31:25 2020-02-17 10:30:25 00:01:00
3 2020-02-17 10:45:25 2020-02-17 10:31:25 00:14:00
4 2020-02-17 10:46:25 2020-02-17 10:45:25 00:01:00

# compare with 1 minut

             Datetime                 DT2     diff
3 2020-02-17 10:45:25 2020-02-17 10:31:25 00:14:00

EDIT: see @luigigi answer for simpler version which uses

df[ df['Datetime'].diff() > pd.Timedelta('60s') ]


问:
what does column represent in tfidf matrix?
I am trying to understand the result of TF-IDF matrix. Here is the code I am using.

```<code>sen1 = TextBlob("This is a sample")
d1 = sen1.words
from sklearn.feature_extraction.text import TfidfVectorizer
tfvectorizer = TfidfVectorizer()
tfidf= TfidfVectorizer(tokenizer=identity_tokenizer, stop_words='english', lowercase=False)
tf = tfidf.fit_transform(d1).todense()
</code>```

So, I am trying to understand the tf matrix thus obtained. Following is the attached picture of the tf matrix.

Could someone please help me why do I have 7 columns for a corpus of 4 words? Do the rows represent the number of words.

From what I study in different resources is "The result is a matrix of tf-idf scores with one row per document and as many columns as there are different words in the dataset." But I am not being able to validate it from the result I obtain here.

答:
I can reproduce your result. The d1 variable is ['This', 'is', 'a', 'sample'].
And this means sklearn interprets this as 4 documents and then uses characters as the words.

You can check like this.

tf = tfidf.fit(d1)

tf.get_feature_names()

['T', 'e', 'h', 'l', 'm','p', 's']

Body:
I am trying to understand the result of TF-IDF matrix. Here is the code I am using.

sen1 = TextBlob("This is a sample")
d1 = sen1.words
from sklearn.feature_extraction.text import TfidfVectorizer
tfvectorizer = TfidfVectorizer()
tfidf= TfidfVectorizer(tokenizer=identity_tokenizer, stop_words='english', lowercase=False)
tf = tfidf.fit_transform(d1).todense()

So, I am trying to understand the tf matrix thus obtained. Following is the attached picture of the tf matrix.

Could someone please help me why do I have 7 columns for a corpus of 4 words? Do the rows represent the number of words.

From what I study in different resources is "The result is a matrix of tf-idf scores with one row per document and as many columns as there are different words in the dataset." But I am not being able to validate it from the result I obtain here.


问:
How can I create new recycle views starting from a different recycle view on another activity
can anyone explain to me how can I create a new recycle and add items to that recycle view staring from another recycle view inside another activity?

Basically I want to create a shopping cart, for now, I retrieved the data from Firebase dataset and displayed it inside a recycle view but now I would like to send this data to the shopping cart(the shopping cart is inside another activity), I'm able to send the data but I can't understand how to display the data inside the new recycle view of this new activity. I need this because I want to see the items that I added to the shopping list so then I can pay.

Below I will attach a photo to explain myself better.

My problem is that I can't understand how to add the sent data to a recycle view again in the new activity.

I'm new to android so it's the first time I'm doing this thing.

Thank you in advance for your help.

My code:

SearchItemsActivity :

```<code>package com.example.ipill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

import java.util.ArrayList;
import java.util.List;

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;

String searchText="";

private RecyclerView mResultList;
private DatabaseReference mUserDatabase;

private static ArrayList<Users> arrayList = new ArrayList<>();
public static int cart_count = 0;

RecyclerView productRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_firebasesearch);

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = findViewById(R.id.search_field);
    mSearchBtn   = findViewById(R.id.search_btn);
    mResultList  = findViewById(R.id.result_list_cart);
    AddToCart    = findViewById(R.id.imageButton2);
    Cart         = findViewById(R.id.cartButton);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchText = mSearchField.getText().toString();
            firebaseUserSearch(searchText);
        }
    });

    Cart.setOnClickListener(new View.OnClickListener() {
        private Object Tag="Activity";

        @Override
        public void onClick(View v) {
            if (cart_count < 1) {

            } else {
                startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
            }
        }
    });
 }

   private void firebaseUserSearch(String searchText) {
    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
    Query firebaseSearchQuery =
    mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new
    FirebaseRecyclerAdapter<Users, UsersViewHolder>(
            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery
    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
            viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
            viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
        }
    };
    mResultList.setAdapter(firebaseRecyclerAdapter);
}

@Override
protected void onStart() {
    super.onStart();
    invalidateOptionsMenu();
}

// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
    View mView;
    String nome;
    String surname;
    Long prezzo;
    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);
        addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cart_count++;
                Context context = v.getContext();
                Intent intent = new Intent(context, CartActivity.class);
                intent.putExtra("Name",nome);
                intent.putExtra("Surname",surname);
                intent.putExtra("Prezzo",Long.toString(prezzo));
                context.startActivity(intent);
            }
        });
    }

    public void getDetails(String name,String cognome,Long price){
        nome=name;
        surname=cognome;
        prezzo=price;
    }

    public void setDetails(String name, String surname, Long price) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
        TextView user_price = (TextView)mView.findViewById(R.id.price);

        user_name.setText(name);
        user_surname.setText(surname);
        user_price.setText(Long.toString(price));

        }
    }
}
</code>```

enter code here

The second activity where I receive the data and where I want to create the recycle view

```<code>     package com.example.ipill;

   import android.content.Context;
   import android.os.Build;
   import android.os.Bundle;
   import android.util.Log;
   import android.view.View;
   import android.widget.Button;
   import android.widget.LinearLayout;
   import android.widget.TextView;
   import android.widget.Toast;
   import android.widget.Toolbar;

   import androidx.annotation.RequiresApi;
   import androidx.appcompat.app.AppCompatActivity;
   import androidx.recyclerview.widget.LinearLayoutManager;
   import androidx.recyclerview.widget.RecyclerView;

   import java.util.ArrayList;
   import java.util.Collection;

  public class CartActivity extends AppCompatActivity {

   public static TextView grandTotal;
   public static int grandTotalplus;
   // create a temp list and add cartitem list
   public static ArrayList<Users> temparraylist;
   RecyclerView cartRecyclerView;

   Button proceedToBook;
Context context;
String name,surname,price;
private static ArrayList<Users> arrayList2 = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    context = this;
    temparraylist = new ArrayList<>();
    proceedToBook = findViewById(R.id.buyNow);
    grandTotal = findViewById(R.id.TotalPrice);

    cartRecyclerView=findViewById(R.id.cartList);

    String passedArg = getIntent().getExtras().getString("Name");
    name=passedArg;

    String passedArg2 = getIntent().getExtras().getString("Surname");
    surname=passedArg2;

    String passedArg3 = getIntent().getExtras().getString("Price");
    price=passedArg3;

    System.out.println("DATA"+name+surname+price);

    cartRecyclerView.setHasFixedSize(true);
    cartRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}

}
</code>```

答: you can re use the cart adapter just implement a recylerView into new Activity and make the cart adater object and set it into the new reyclerView and it done </p>

Body:
can anyone explain to me how can I create a new recycle and add items to that recycle view staring from another recycle view inside another activity?

Basically I want to create a shopping cart, for now, I retrieved the data from Firebase dataset and displayed it inside a recycle view but now I would like to send this data to the shopping cart(the shopping cart is inside another activity), I'm able to send the data but I can't understand how to display the data inside the new recycle view of this new activity. I need this because I want to see the items that I added to the shopping list so then I can pay.

Below I will attach a photo to explain myself better.

My problem is that I can't understand how to add the sent data to a recycle view again in the new activity.

I'm new to android so it's the first time I'm doing this thing.

Thank you in advance for your help.

My code:

SearchItemsActivity :

package com.example.ipill;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Context;
import android.content.Intent;
import android.nfc.Tag;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;

import java.util.ArrayList;
import java.util.List;

public class FirebaseSearch extends AppCompatActivity {

private EditText mSearchField;
private ImageButton mSearchBtn;
private ImageButton AddToCart;
private ImageButton Cart;

String searchText="";

private RecyclerView mResultList;
private DatabaseReference mUserDatabase;

private static ArrayList<Users> arrayList = new ArrayList<>();
public static int cart_count = 0;

RecyclerView productRecyclerView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_firebasesearch);

    mUserDatabase = FirebaseDatabase.getInstance().getReference("Users");

    mSearchField = findViewById(R.id.search_field);
    mSearchBtn   = findViewById(R.id.search_btn);
    mResultList  = findViewById(R.id.result_list_cart);
    AddToCart    = findViewById(R.id.imageButton2);
    Cart         = findViewById(R.id.cartButton);

    mResultList.setHasFixedSize(true);
    mResultList.setLayoutManager(new LinearLayoutManager(this));

    mSearchBtn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            searchText = mSearchField.getText().toString();
            firebaseUserSearch(searchText);
        }
    });

    Cart.setOnClickListener(new View.OnClickListener() {
        private Object Tag="Activity";

        @Override
        public void onClick(View v) {
            if (cart_count < 1) {

            } else {
                startActivity(new Intent(FirebaseSearch.this, CartActivity.class));
            }
        }
    });
 }

   private void firebaseUserSearch(String searchText) {
    Toast.makeText(FirebaseSearch.this, "Started Search", Toast.LENGTH_LONG).show();
    Query firebaseSearchQuery =
    mUserDatabase.orderByChild("Name").startAt(searchText).endAt(searchText + "\uf8ff");
    FirebaseRecyclerAdapter<Users, UsersViewHolder> firebaseRecyclerAdapter = new
    FirebaseRecyclerAdapter<Users, UsersViewHolder>(
            Users.class,
            R.layout.list_layout,
            UsersViewHolder.class,
            firebaseSearchQuery
    ) {
        @Override
        protected void populateViewHolder(UsersViewHolder viewHolder, Users model, int position) {
            viewHolder.getDetails(model.getName(), model.getSurname(),model.getPrice());
            viewHolder.setDetails(model.getName(), model.getSurname(),model.getPrice());
        }
    };
    mResultList.setAdapter(firebaseRecyclerAdapter);
}

@Override
protected void onStart() {
    super.onStart();
    invalidateOptionsMenu();
}

// View Holder Class
public static class UsersViewHolder extends RecyclerView.ViewHolder {
    View mView;
    String nome;
    String surname;
    Long prezzo;
    public UsersViewHolder(View itemView) {
        super(itemView);
        mView = itemView;
        ImageButton addToCart = (ImageButton)mView.findViewById(R.id.imageButton2);
        addToCart.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cart_count++;
                Context context = v.getContext();
                Intent intent = new Intent(context, CartActivity.class);
                intent.putExtra("Name",nome);
                intent.putExtra("Surname",surname);
                intent.putExtra("Prezzo",Long.toString(prezzo));
                context.startActivity(intent);
            }
        });
    }

    public void getDetails(String name,String cognome,Long price){
        nome=name;
        surname=cognome;
        prezzo=price;
    }

    public void setDetails(String name, String surname, Long price) {

        TextView user_name = (TextView) mView.findViewById(R.id.name_text);
        TextView user_surname = (TextView)mView.findViewById(R.id.status_text);
        TextView user_price = (TextView)mView.findViewById(R.id.price);

        user_name.setText(name);
        user_surname.setText(surname);
        user_price.setText(Long.toString(price));

        }
    }
}

enter code here

The second activity where I receive the data and where I want to create the recycle view

     package com.example.ipill;

   import android.content.Context;
   import android.os.Build;
   import android.os.Bundle;
   import android.util.Log;
   import android.view.View;
   import android.widget.Button;
   import android.widget.LinearLayout;
   import android.widget.TextView;
   import android.widget.Toast;
   import android.widget.Toolbar;

   import androidx.annotation.RequiresApi;
   import androidx.appcompat.app.AppCompatActivity;
   import androidx.recyclerview.widget.LinearLayoutManager;
   import androidx.recyclerview.widget.RecyclerView;

   import java.util.ArrayList;
   import java.util.Collection;

  public class CartActivity extends AppCompatActivity {

   public static TextView grandTotal;
   public static int grandTotalplus;
   // create a temp list and add cartitem list
   public static ArrayList<Users> temparraylist;
   RecyclerView cartRecyclerView;

   Button proceedToBook;
Context context;
String name,surname,price;
private static ArrayList<Users> arrayList2 = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cart);
    context = this;
    temparraylist = new ArrayList<>();
    proceedToBook = findViewById(R.id.buyNow);
    grandTotal = findViewById(R.id.TotalPrice);

    cartRecyclerView=findViewById(R.id.cartList);

    String passedArg = getIntent().getExtras().getString("Name");
    name=passedArg;

    String passedArg2 = getIntent().getExtras().getString("Surname");
    surname=passedArg2;

    String passedArg3 = getIntent().getExtras().getString("Price");
    price=passedArg3;

    System.out.println("DATA"+name+surname+price);

    cartRecyclerView.setHasFixedSize(true);
    cartRecyclerView.setLayoutManager(new LinearLayoutManager(this));
}

}


问:
ActionScript 3 - objects?
I'm new to Flash AS3. I started making a game and I am a bit confused. Let's assume that I want to create a game that has multiple levels/modes, how can I do this in an object orientated way?

When i create games in other languages e.g. XNA C#, i create a separate class then create an object of that class within the main class and run the game based on a simple statement.

```<code>if(player picks second option)
object2.start_level
else
object1.start_level
</code>```

How can this be done is AS3? Are there any Tutorials I could read on, please? Thanks.

答:
You may create your levels and attach them onto the main scene dynamically

```<code>if(player picks second option)
  addChild(object2);
else
  addChild(object1);
</code>```

In your objects you can link the initialization of the level when the event Event.ADDED_TO_STAGE is distpached.

Cheers

Title: ActionScript 3 - objects?

Body:
I'm new to Flash AS3. I started making a game and I am a bit confused. Let's assume that I want to create a game that has multiple levels/modes, how can I do this in an object orientated way?

When i create games in other languages e.g. XNA C#, i create a separate class then create an object of that class within the main class and run the game based on a simple statement.

if(player picks second option)
object2.start_level
else
object1.start_level

How can this be done is AS3? Are there any Tutorials I could read on, please? Thanks.

Body:
You may create your levels and attach them onto the main scene dynamically

if(player picks second option)
  addChild(object2);
else
  addChild(object1);

In your objects you can link the initialization of the level when the event Event.ADDED_TO_STAGE is distpached.

Cheers


问:
Sort Data By the 2nd Last Letter in a cell then the first- Google Apps Script / Google Sheets
In the image shown (highlighted Bright Green G:H), I would have liked to sort the data according to the 2nd last letter - not the first. This would have meant F01A1 should have been appeared higher in list than E09C1, and then would have been selected in the A column.

How could I have the data Sorted by 2nd Last Letter in Cell, in Column G:H ?

答:
Since you mentioned Google Apps Script, you could use the following custom function to sort the data:

function CUSTOMSORT(input) {
  input.sort(function(a, b) {
    if (a[0].slice(-2)  b[0].slice(-2)) {
      return 1;
    }
    return 0;
  })
  return input;
}
```

Once it is defined, you can use this function the same you would any sheets built-in function. For example, if you want to sort data from A1:A10, just call the function like this:

=CUSTOMSORT(A1:A10)

Reference:

Custom Functions in Google Sheets

Array.prototype.sort()

Array.prototype.slice()

Body:
Since you mentioned Google Apps Script, you could use the following custom function to sort the data:

function CUSTOMSORT(input) {
  input.sort(function(a, b) {
    if (a[0].slice(-2) < b[0].slice(-2)) {
      return -1;
    } else if (a[0].slice(-2) > b[0].slice(-2)) {
      return 1;
    }
    return 0;
  })
  return input;
}

Once it is defined, you can use this function the same you would any sheets built-in function. For example, if you want to sort data from A1:A10, just call the function like this:

=CUSTOMSORT(A1:A10)

Reference:

Custom Functions in Google Sheets

Array.prototype.sort()

Array.prototype.slice()


问:
Open a Workbook with XLWINGS without making it visible
I am starting to use XLWings (not that I like Excel, at all, but it is something I HAVE TO do). The thing is that I cannot find the way to make Python open a Workbook without showing it.

It seems the constructor for Workbooks in the old XLWings 0.6.4 was xlwings.Workbook, and one of the arguments was a flag 'app_visible' (see http://docs.xlwings.org/en/v0.6.4/api.html).

However, in the new v0.9.2 Workbook has been replaced by Book, and Book does not have any such flag (http://docs.xlwings.org/en/stable/api.html). The App object does have it, and I thought that was the way to go. So I coded:

```<code>import xlwings as xw

app = xw.App(visible=False)
filename = os.path.join(PATH_EXCEL_SAMPLES, r"rangosConDatos_sample01.xls")
book = xw.Book(filename)
# Do stuff with the info in the book
book.close()  # Ya puedo cerrar el libro.
app.kill()
</code>```

But, regretably, when

```<code>book = xw.Book(filename)
</code>```

is executed the 'visible' attribute of app suddenly becomes True, and the book is shown. I do not know if this is a desired feature or an unexpected behaviour. Anyway, any ideas how should I do it?

答:
Here is my working code fragment:</p>

```<code>    import xlwings

    excel_app = xlwings.App(visible=False)
    excel_book = excel_app.books.open('PATH_TO_YOUR_XLSX_FILE')
    excel_book.save()
    excel_book.close()
    excel_app.quit()
</code>```

Body:
I am starting to use XLWings (not that I like Excel, at all, but it is something I HAVE TO do). The thing is that I cannot find the way to make Python open a Workbook without showing it.

It seems the constructor for Workbooks in the old XLWings 0.6.4 was xlwings.Workbook, and one of the arguments was a flag 'app_visible' (see http://docs.xlwings.org/en/v0.6.4/api.html).

However, in the new v0.9.2 Workbook has been replaced by Book, and Book does not have any such flag (http://docs.xlwings.org/en/stable/api.html). The App object does have it, and I thought that was the way to go. So I coded:

import xlwings as xw

app = xw.App(visible=False)
filename = os.path.join(PATH_EXCEL_SAMPLES, r"rangosConDatos_sample01.xls")
book = xw.Book(filename)
# Do stuff with the info in the book
book.close()  # Ya puedo cerrar el libro.
app.kill()

But, regretably, when

book = xw.Book(filename)

is executed the 'visible' attribute of app suddenly becomes True, and the book is shown. I do not know if this is a desired feature or an unexpected behaviour. Anyway, any ideas how should I do it?

Body:
Here is my working code fragment:

    import xlwings

    excel_app = xlwings.App(visible=False)
    excel_book = excel_app.books.open('PATH_TO_YOUR_XLSX_FILE')
    excel_book.save()
    excel_book.close()
    excel_app.quit()


答:
Check that every row is -1min compared to the next one and then do something if it isn't.</p>

```<code>for i in range(len(df.index)-1):
   if datetime.datetime.strptime(df.loc[i, 'DateTime'], '%Y-%m-%d %H:%M:%S) != datetime.datetime.strptime(df.loc[i+1, 'DateTime'], '%Y-%m-%d %H:%M:%S) + datetime.timedelta(minutes=1):
      print('Data missing')
</code>```

Body:
Check that every row is -1min compared to the next one and then do something if it isn't.

for i in range(len(df.index)-1):
   if datetime.datetime.strptime(df.loc[i, 'DateTime'], '%Y-%m-%d %H:%M:%S) != datetime.datetime.strptime(df.loc[i+1, 'DateTime'], '%Y-%m-%d %H:%M:%S) + datetime.timedelta(minutes=1):
      print('Data missing')


问:
INSERT INTO based on SELECT and versioned record
I have a table that contains the current state of employees like below :

```<code> SELECT EmployeeId ,OfficeId from EmpCurrent
</code>```

The output is like below :

```<code>EmployeeId OfficeId
54          67
64          57
89          23
</code>```

And I have another table containing the full history for an employee except for OfficeId which isn't historised (I added the column OfficeId which is NULL to insert from EmpCurrent) :

```<code>SELECT EmployeeId ,Func AS [Function],OfficeId,Version from EmpHistory
</code>```

The output is like below for EmployeeId=54:

```<code>EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   NULL     3
</code>```

I want to get the OfficeId from EmpCurrent and insert it in EmpHistory in the last Version(max version) of the each Employee, my output will be like below :

```<code>EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   67       3
</code>```

答:
If you want the most recent value for the join, then:

```<code>select eh.*, ec.officeid
from (select eh.*,
             row_number() over (partition by employeeid order by version desc) as seqnum
      from emphistory eh
     ) eh left join
     empcurrent ec
     on ec.employeeid = eh.employeeid and eh.seqnum = 1;
</code>```

This is one of the unusual instances where you filter on the first table  in a left join.  You can also do this as:

```<code>select eh.*,
       (case when eh.seqnum = 1 then ec.officeid end) as officeid
from (select eh.*,
             row_number() over (partition by employeeid order by version desc) as seqnum
      from emphistory eh
     ) eh left join
     empcurrent ec
     on ec.employeeid = eh.employeeid ;
</code>```

Body:
I have a table that contains the current state of employees like below :

 SELECT EmployeeId ,OfficeId from EmpCurrent

The output is like below :

EmployeeId OfficeId
54          67
64          57
89          23

And I have another table containing the full history for an employee except for OfficeId which isn't historised (I added the column OfficeId which is NULL to insert from EmpCurrent) :

SELECT EmployeeId ,Func AS [Function],OfficeId,Version from EmpHistory

The output is like below for EmployeeId=54:

EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   NULL     3

I want to get the OfficeId from EmpCurrent and insert it in EmpHistory in the last Version(max version) of the each Employee, my output will be like below :

EmployeeId Function OfficeId Version
54         Manager  NULL     1
54         Director NULL     2
54         HeadOf   67       3

Body:
If you want the most recent value for the join, then:

select eh.*, ec.officeid
from (select eh.*,
             row_number() over (partition by employeeid order by version desc) as seqnum
      from emphistory eh
     ) eh left join
     empcurrent ec
     on ec.employeeid = eh.employeeid and eh.seqnum = 1;

This is one of the unusual instances where you filter on the first table  in a left join.  You can also do this as:

select eh.*,
       (case when eh.seqnum = 1 then ec.officeid end) as officeid
from (select eh.*,
             row_number() over (partition by employeeid order by version desc) as seqnum
      from emphistory eh
     ) eh left join
     empcurrent ec
     on ec.employeeid = eh.employeeid ;


问:
How do I truncate a file in Visual C++?
I have the following case. I have a big file say 1 KB. I want to read the first 100 bytes and then delete the 100 bytes read data from the file and then read next 100 bytes. To read 100 bytes is ok, but how do I delete 100 bytes from the file?</p>

答: That wouldn't be called truncating; that term refers to removing data from the end, not the beginning. I'm not aware of any operating system where this is possible, other than by copying the contents of the file to a new file, starting at the 100th byte.

Title: How do I truncate a file in Visual C++?


问:
Process cobol flat feed file (with different format) using spring batch
I am trying to use spring batch to consume data generated by a cobol program. Lets assume the below is the data.

```<code>CBMWM3    COU**********EA40176
CBMWM5    CON**********G114738
SMERGLS4507BLU**********F231353
TFORF150  5*******G539501
</code>```

There are three different formats in the file based on the first character.

```<code>C - MAKE, MODEL, CLASSIFICATION, VIN
S - MAKE, MODEL, PASS CAPACITY, COLOR, VIN
T - MAKE, MODEL, PASS CAPACITY, VIN
</code>```

I would like to use a FlatFileItemReader and it works best for a single format. How can I update the code to process different formats on the same file ?
I am using Spring boot for this batch job.

Edit 1:

```<code>@Bean
    public FlatFileItemReader<CarDetails> reader() {
        return new FlatFileItemReaderBuilder<CarDetails>()
                .name("carDetailsReader")
                .resource(new FileSystemResource("/path/to/inputFile"))
                .fixedLength()
                    .addColumns(new Range(1))

                    /* Format for lines starting with C
                    .addColumns(new Range(2,4))
                    .addColumns(new Range(5,9))
                    .addColumns(new Range(10,12))
                    .addColumns(new Range(13,29)) */

                    /* Format for lines starting with S
                    .addColumns(new Range(2,4))
                    .addColumns(new Range(5,9))
                    .addColumns(new Range(9,10))
                    .addColumns(new Range(11,13))
                    .addColumns(new Range(14,30)) */

                    /* Format for lines starting with T
                    .addColumns(new Range(2,4))
                    .addColumns(new Range(5,9))
                    .addColumns(new Range(9,10))
                    .addColumns(new Range(11,26)) * /

                 // Looks like I cant have all three formats here.

                .names(new String[]{"Char", "make", "model", "Clasification", "VIN"})
                // Need some facility to accept multiple formats in names too.

                .fieldSetMapper(new BeanWrapperFieldSetMapper<>() {{
                    setTargetType(CarDetails.class);
                }})
                .build();
    }
</code>```

答:
PatternMatchingCompositeLineMapper is what you are looking for. It allows you to match lines based on a pattern and tokenize/map each line type to the corresponding domain type.

You can find an example of how to use it here.

Body:
I am trying to use spring batch to consume data generated by a cobol program. Lets assume the below is the data.

CBMWM3    COU**********EA40176
CBMWM5    CON**********G114738
SMERGLS4507BLU**********F231353
TFORF150  5*******G539501

There are three different formats in the file based on the first character.

C - MAKE, MODEL, CLASSIFICATION, VIN
S - MAKE, MODEL, PASS CAPACITY, COLOR, VIN
T - MAKE, MODEL, PASS CAPACITY, VIN

I would like to use a FlatFileItemReader and it works best for a single format. How can I update the code to process different formats on the same file ?
I am using Spring boot for this batch job.

Edit 1:

@Bean
    public FlatFileItemReader<CarDetails> reader() {
        return new FlatFileItemReaderBuilder<CarDetails>()
                .name("carDetailsReader")
                .resource(new FileSystemResource("/path/to/inputFile"))
                .fixedLength()
                    .addColumns(new Range(1))

                    /* Format for lines starting with C
                    .addColumns(new Range(2,4))
                    .addColumns(new Range(5,9))
                    .addColumns(new Range(10,12))
                    .addColumns(new Range(13,29)) */

                    /* Format for lines starting with S
                    .addColumns(new Range(2,4))
                    .addColumns(new Range(5,9))
                    .addColumns(new Range(9,10))
                    .addColumns(new Range(11,13))
                    .addColumns(new Range(14,30)) */

                    /* Format for lines starting with T
                    .addColumns(new Range(2,4))
                    .addColumns(new Range(5,9))
                    .addColumns(new Range(9,10))
                    .addColumns(new Range(11,26)) * /

                 // Looks like I cant have all three formats here.

                .names(new String[]{"Char", "make", "model", "Clasification", "VIN"})
                // Need some facility to accept multiple formats in names too.

                .fieldSetMapper(new BeanWrapperFieldSetMapper<>() {{
                    setTargetType(CarDetails.class);
                }})
                .build();
    }


问:
Why my angular stepper doesn't have style?
Recently I started working with Angular, and I needed to create a multi-step form, first of all it was a mess to install it, but at the end there it is, but when I use it on my component it doesn,t have style at all, I searched in a lot of sites and videos, but everyone does the same I do. Any idea what is the problem?

This are my app.module.ts:

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { DrawingsComponent } from './drawings/drawings.component';
import {HttpClientModule} from '@angular/common/http';
import {FormsModule} from '@angular/forms';
import { MatStepperModule } from '@angular/material/stepper';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatPseudoCheckboxModule } from '@angular/material/core';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    DrawingsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    MatStepperModule,
    MatIconModule,
    MatButtonModule,
    MatPseudoCheckboxModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
</code>```

This is my example:

```<code><mat-horizontal-stepper>
  <mat-step label="Step 1">
    Content 1
  </mat-step>
  <mat-step label="Step 1">
    Content 2
  </mat-step>
</mat-horizontal-stepper>
</code>```

Here is how it should look like

This is how it looks

答: Did you choose a theme when you have installed angular material? Please take a look here</p>

Body:
Recently I started working with Angular, and I needed to create a multi-step form, first of all it was a mess to install it, but at the end there it is, but when I use it on my component it doesn,t have style at all, I searched in a lot of sites and videos, but everyone does the same I do. Any idea what is the problem?

This are my app.module.ts:

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { HomeComponent } from './home/home.component';
import { DrawingsComponent } from './drawings/drawings.component';
import {HttpClientModule} from '@angular/common/http';
import {FormsModule} from '@angular/forms';
import { MatStepperModule } from '@angular/material/stepper';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatIconModule } from '@angular/material/icon';
import { MatButtonModule } from '@angular/material/button';
import { MatPseudoCheckboxModule } from '@angular/material/core';

@NgModule({
  declarations: [
    AppComponent,
    HomeComponent,
    DrawingsComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    HttpClientModule,
    FormsModule,
    MatStepperModule,
    MatIconModule,
    MatButtonModule,
    MatPseudoCheckboxModule,
    BrowserAnimationsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

This is my example:

<mat-horizontal-stepper>
  <mat-step label="Step 1">
    Content 1
  </mat-step>
  <mat-step label="Step 1">
    Content 2
  </mat-step>
</mat-horizontal-stepper>

Here is how it should look like

This is how it looks


问:
java 8 stream - how to get original object reference after map
Is at all possible to simply the below code using Java 8 stream?

Code:-

```<code>private double calculateBCMMatrixCostForAnalyte(Long startingMaterialId) {

    double bcmMatrixCost = 0;

    StartingMaterialMatrix smm = startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId);

    if (smm.getBlending1MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId()) * smm.getBlending1MatrixConcentration()) / 1000000f;
    }

    if (smm.getBlending2MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending2Matrix().getId() * smm.getBlending2MatrixConcentration())) / 1000000f;
    }

    return Precision.round(bcmMatrixCost, 4);
}
</code>```

I tried something like below

```<code>    Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
            .filter(smm -> smm.getBlending1MatrixConcentration() != null)
            .mapToDouble(smm ->  priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f);
</code>```

But after this, I won't have any reference to the original 'smm' object to do further checks.

答:
I honestly would not be hell-bent on turning this into a stream, it doesn't really need to be.

If it's overly complex to turn something into a stream, it may not be worth it, is there a specific reason?

that being said, you could make two streams, filter one, one way, then filter the other way, then use Stream.concat to combine the two streams, and call .sum but I do not think it'd be worth it.

edit:

You may need DoubleStream.concat, since you are mapping to double.

https://docs.oracle.com/javase/8/docs/api/java/util/stream/DoubleStream.html#concat-java.util.stream.DoubleStream-java.util.stream.DoubleStream-

Body:
Is at all possible to simply the below code using Java 8 stream?

Code:-

private double calculateBCMMatrixCostForAnalyte(Long startingMaterialId) {

    double bcmMatrixCost = 0;

    StartingMaterialMatrix smm = startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId);

    if (smm.getBlending1MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending1Matrix().getId()) * smm.getBlending1MatrixConcentration()) / 1000000f;
    }

    if (smm.getBlending2MatrixConcentration() != null) {
        bcmMatrixCost += (priceService.findNeatMaterialCostByStartingMaterialId(smm.getBlending2Matrix().getId() * smm.getBlending2MatrixConcentration())) / 1000000f;
    }

    return Precision.round(bcmMatrixCost, 4);
}

I tried something like below

    Stream.of(startingMaterialMatrixRepository.findByStartingMaterialId(startingMaterialId))
            .filter(smm -> smm.getBlending1MatrixConcentration() != null)
            .mapToDouble(smm ->  priceService.findNeatMaterialCostByStartingMaterialId(smm.getStartingMaterial().getId()) * smm.getBlending1MatrixConcentration() / 1000000f);

But after this, I won't have any reference to the original 'smm' object to do further checks.


问:
SQL Server 2012 ForceEncryption without SSL certificate?
Using information from some consultants about 2 years ago we set up a SQL Server 2012 box to always have an encrypted connection (at least we thought so). A week ago the SSL certificate expired and everything continues to work fine which is puzzling.

We forced encryption by doing the following:

Obtain an SSL certificate and install it on the SQL Server via MMC. Explicit instructions for this step are here.

Open SQL Server Configuration Manger and expand the SQL Server Network Configuration node in the left pane.

Right click Protocols for MSSQLServer and choose properties.

Go to Certificate tab and choose the installed SSL cert from the drop down.

Go to the Flags tab and set force encryption to Yes.

Now, since the SSL cert expired, there is no longer any cert selected in the drop down when I visit step 3 above. However, I put WireShark on the DB server and use SSMS to request some data. The TDS (Tabular Data Stream) packets are still encrypted? When I put WireShark on a different DB Server I set ForceEncryption to NO, those TDS packets are not encrypted as expected.

So my questions are:

How are the TDS packets still encrypted if the cert is expired?

Even when the cert was valid, why didn't I have to select Options > Encrypt Connection to connect to my encrypted DB server? I thought setting ForceEncryption=Yes required ALL client connections to specify Encrypt in their connection string (or the SSMS checkbox)?

If Web APIs are the only method of accessing my DB, and they do so over SSL, is it even necessary to encrypt the SQL Protocol?

答:
1)How are the TDS packets still encrypted if the cert is expired?

you don't need a valid certificate in order to encrypt, you can still encrypt using an expired certificate.

2)Even when the cert was valid, why didn't I have to select Options > Encrypt Connection to connect to my encrypted DB server? I thought setting ForceEncryption=Yes required ALL client connections to specify Encrypt in their connection string (or the SSMS checkbox)?

Do not enable the Force Protocol Encryption option on both the client and the server,
if you enabled force encryption on SQL server you don't need to do it on any client-side

3)If Web APIs are the only method of accessing my DB, and they do so over SSL, is it even necessary to encrypt the SQL Protocol?

To enable SSL you need the certificate to be installed on SQL server so in order to access the DBusing SSL you are doing the same job.

Thank you


问:
Git - How do I just switch to and pull the changes from another branch? All locally
So I’m having problems with git since it’s needlessly complicated, literally the only thing I want to do, is, let’s say, switch from master to a newer or older branch and pull the changes to my local machine, that’s it. I’ve tried doing

```<code>git checkout <branchname>

git fetch

git pull
</code>```

but it doesn’t download any changes from the branch I switched to.

How do I do it properly? I don’t want to upload anything to the actual repository, no commits or merges to master etc., I just need to switch branches for testing purposes, being able to run it locally.

答:
```<code>git fetch
git checkout <branchname>
</code>```

It's important you FIRST fetch and then checkout the branch. If you want to see the available branches:

```<code>git branch -r
</code>```

And this post is actually a duplicate, so try to find the proper article in stackoverflow next time:

How do I check out a remote Git branch?

Body:
So I’m having problems with git since it’s needlessly complicated, literally the only thing I want to do, is, let’s say, switch from master to a newer or older branch and pull the changes to my local machine, that’s it. I’ve tried doing

git checkout <branchname>

git fetch

git pull

but it doesn’t download any changes from the branch I switched to.

How do I do it properly? I don’t want to upload anything to the actual repository, no commits or merges to master etc., I just need to switch branches for testing purposes, being able to run it locally.

Body:
git fetch
git checkout <branchname>

It's important you FIRST fetch and then checkout the branch. If you want to see the available branches:

git branch -r

And this post is actually a duplicate, so try to find the proper article in stackoverflow next time:

How do I check out a remote Git branch?