问:
How can I pass more than one enum to a method that receives only one?
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

```<code>RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline
</code>```

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?

答:
Since it is an Enum with a Flags Attribute, you can use:</p>

```<code>RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhiteSpace | RegexOptions.Multiline
</code>```

Body:
I'm wondering if the following is possible:

The method Regex.Match can receive an enum, so I can specify:

RegexOptions.IgnoreCase
RegexOptions.IgnorePatternWhiteSpace
RegexOptions.Multiline

What if I need to specify more than just one? (eg. I want my regex to be Multiline and I want it to ignore the pattern whitespace).

Could I use | operator like in C/C++?

Body:
Since it is an Enum with a Flags Attribute, you can use:

RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhiteSpace | RegexOptions.Multiline


来源: stackexchange

问:
Spring batch : JobExecution from PreparedStatementSetter
I have a Spring batch with a PreparedStatementSetter for a query reader step. I would like to access to global data from the PreparedStatementSetter that is saved before into the ExecutionContext.

How could I access to the ExecutionContext from this PreparedStatementSetter ?

```<code>@Component
public class CurrentBatchIdPreparedStatementSetter implements PreparedStatementSetter
{
    @Override
    public void setValues(PreparedStatement preparedStatement) throws SQLException
    {
        // how to access to ExecutionContext here ?
    }
}
</code>```

Thanks

YesWeCan

答:
We can get ExecutionContext from step execution if the scope is step.

```<code>    @Component
    public class CurrentBatchIdPreparedStatementSetter implements PreparedStatementSetter
    {
       @Value("#{stepExecution}")
       private StepExecution stepExecution;

        @Override
        public void setValues(PreparedStatement preparedStatement) throws SQLException
        {
            final ExecutionContext executionContext = stepExecution.getExecutionContext();
            //Do your operations here
        }
    }
</code>```

You can also get the same from job executioncontext.

```<code>  @Value("#{jobExecution}")
   private JobExecution jobExecution;
   //inside method
   final ExecutionContext executionContext = jobExecution.getExecutionContext();
</code>```

or you can easily get value from job execution context.

```<code>        @Value ( "# {jobExecutionContext ['param1']}" )
        private String  param1;
        @Value ( "# {jobExecutionContext ['param2']}" )
        private String  param2;
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a Spring batch with a PreparedStatementSetter for a query reader step. I would like to access to global data from the PreparedStatementSetter that is saved before into the ExecutionContext.

How could I access to the ExecutionContext from this PreparedStatementSetter ?

@Component
public class CurrentBatchIdPreparedStatementSetter implements PreparedStatementSetter
{
    @Override
    public void setValues(PreparedStatement preparedStatement) throws SQLException
    {
        // how to access to ExecutionContext here ?
    }
}

Thanks

YesWeCan

Body:
We can get ExecutionContext from step execution if the scope is step.

    @Component
    public class CurrentBatchIdPreparedStatementSetter implements PreparedStatementSetter
    {
       @Value("#{stepExecution}")
       private StepExecution stepExecution;

        @Override
        public void setValues(PreparedStatement preparedStatement) throws SQLException
        {
            final ExecutionContext executionContext = stepExecution.getExecutionContext();
            //Do your operations here
        }
    }

You can also get the same from job executioncontext.

  @Value("#{jobExecution}")
   private JobExecution jobExecution;
   //inside method
   final ExecutionContext executionContext = jobExecution.getExecutionContext();

or you can easily get value from job execution context.

        @Value ( "# {jobExecutionContext ['param1']}" )
        private String  param1;
        @Value ( "# {jobExecutionContext ['param2']}" )
        private String  param2;


问:
getting first answer as undefined in json responce
i dont know why the first value is undefined ,and only getting result without json.parse()  and
the script and html is actually on the same page,
in php i just encode data into json and echo it,
,(dont mind this line)some one help me with stackoverflow is not letting me to post without larger question how to post question with a single line

      well this is what iam actually doing
    iam getting but it seams not the proper one
      <!DOCTYPE html>

         <title></title>

        <button >get data</button>

        r1

    <?php $con=mysqli_connect("localhost","root","","test"); ?>

    <?php
    header("Content-Type: application/json; charset=UTF-8");

    $sql="SELECT * FROM test where id='1'";
    $result=mysqli_query($con,$sql);

    while($row=mysqli_fetch_array($result))
    {

    $data[]=$row;
    //result is [{"0":"1","id":"1","1":"31232","number":"31232","2":"sdasd","text":"sdasd"}]

    }

    $d=json_encode($data);
    echo $d;

    ?>```

答:
First: please get your code in order - its impossible to see anything there.
The actual error is your var res; - you define res as undefined, so this is whats there first. you should use var res = ''!

$(document).ready(function() {
  $("button").click(function() {
    var data = [{"0":"1","id":"1","1":"31232","number":"31232","2":"sdasd","text":"sdasd"}];

    // res is undefined! - should be:
    // var res = "";
    var res;
    for (x in data) {
      res += "
" + data[x].id + "
"
      res += "
" + data[x].number + "
";
    }
    document.getElementById("result").innerHTML = res;
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <body>
    well this is what iam actually doing iam getting but it seems not the proper one
    <button>get data</button><br />
    <span id="result">r1</span>
  </body>
</html></code>```

Body:
First: please get your code in order - its impossible to see anything there.
The actual error is your var res; - you define res as undefined, so this is whats there first. you should use var res = ''!

$(document).ready(function() {
  $("button").click(function() {
    var data = [{"0":"1","id":"1","1":"31232","number":"31232","2":"sdasd","text":"sdasd"}];

    // res is undefined! - should be:
    // var res = "";
    var res;
    for (x in data) {
      res += "<div>" + data[x].id + "</div>"
      res += "<div>" + data[x].number + "</div>";
    }
    document.getElementById("result").innerHTML = res;
  });
});

<!DOCTYPE html>
<html>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <body>
    well this is what iam actually doing iam getting but it seems not the proper one
    <button>get data</button><br />
    <span id="result">r1</span>
  </body>
</html>


问:
OpenCV - Python trackbars not working on macOS, but works fine in Ubuntu
I am running a code which I got from a website, the code runs completely fine on Ubuntu but the trackbars don't move on macOS :

```<code>import cv2
import numpy as np

def nothing(x):
   pass

# Create a black image, a window
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')

# create trackbars for color change
cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)

# create switch for ON/OFF functionality
switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image',0,1,nothing)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

    # get current positions of four trackbars
    r = cv2.getTrackbarPos('R','image')
    g = cv2.getTrackbarPos('G','image')
    b = cv2.getTrackbarPos('B','image')
    s = cv2.getTrackbarPos(switch,'image')

if s == 0:
     img[:] = 0
else:
     img[:] = [b,g,r]

cv2.destroyAllWindows()
</code>```

This is the image from my macbook where the trackbars don't move:

Why does this happen?
Please help. Thanks.

答:
if/else statement should be inside while loop

import cv2
import numpy as np

def nothing(x):
   pass

img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')

cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)

switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image',0,1,nothing)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

    r = cv2.getTrackbarPos('R','image')
    g = cv2.getTrackbarPos('G','image')
    b = cv2.getTrackbarPos('B','image')
    s = cv2.getTrackbarPos(switch,'image')

    if s == 0:
        img[:] = 0
    else:
        img[:] = [b,g,r]

cv2.destroyAllWindows()
```

Body:
I am running a code which I got from a website, the code runs completely fine on Ubuntu but the trackbars don't move on macOS :

import cv2
import numpy as np

def nothing(x):
   pass

# Create a black image, a window
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('image')

# create trackbars for color change
cv2.createTrackbar('R','image',0,255,nothing)
cv2.createTrackbar('G','image',0,255,nothing)
cv2.createTrackbar('B','image',0,255,nothing)

# create switch for ON/OFF functionality
switch = '0 : OFF \n1 : ON'
cv2.createTrackbar(switch, 'image',0,1,nothing)

while(1):
    cv2.imshow('image',img)
    k = cv2.waitKey(1) & 0xFF
    if k == 27:
        break

    # get current positions of four trackbars
    r = cv2.getTrackbarPos('R','image')
    g = cv2.getTrackbarPos('G','image')
    b = cv2.getTrackbarPos('B','image')
    s = cv2.getTrackbarPos(switch,'image')

if s == 0:
     img[:] = 0
else:
     img[:] = [b,g,r]

cv2.destroyAllWindows()

This is the image from my macbook where the trackbars don't move:

Why does this happen?
Please help. Thanks.


问:
replace one column values with another Spark Java
I have a dataframe df1 of the format

```<code>+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
| A    | z    | m    |
| B    | w    | n    |
| C    | x    | o    |
| A    | z    | n    |
| A    | p    | o    |
+------+------+------+
</code>```

and another dataframe df2 of the format

```<code>+------+------+
| Col1 | Col2 |
+------+------+
| 0-A  | 0-z  |
| 1-B  | 3-w  |
| 2-C  | 1-x  |
|      | 2-P  |
+------+------+-
</code>```

I am trying to replace the values in Col1 and Col2 of df1 with values from df2 using Spark Java.

The end dataframe df3 should look like this.

```<code>+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
| 0-A  | 0-z  | m    |
| 1-B  | 3-w  | n    |
| 2-C  | 1-x  | o    |
| 0-A  | 0-z  | n    |
| 0-A  | 2-p  | o    |
+------+------+------+
</code>```

I am trying to replace all the values in the column1 and column2 of df1 with values from col1 and col2 of df2.
Is there anyway that i can achieve this in Spark Java dataframe syntax.?

The initial idea i had was to do the following.

```<code>String pattern1="\\p{L}+(?: \\p{L}+)*$";

df1=df1.join(df2, df1.col("col1").equalTo(regexp_extract(df2.col("col1"),pattern1,1)),"left-semi");
</code>```

答:
Replace your last join operation with below join.

```<code>df1.alias("x").join(df2.alias("y").select(col("y.Col1").alias("newCol1")), col("x.Col1") === regexp_extract(col("newCol1"),"\\p{L}+(?: \\p{L}+)*$",0), "left")
              .withColumn("Col1", col("newCol1"))
              .join(df2.alias("z").select(col("z.Col2").alias("newCol2")), col("x.Col2") === regexp_extract(col("newCol2"),"\\p{L}+(?: \\p{L}+)*$",0), "left")
              .withColumn("Col2", col("newCol2"))
              .drop("newCol1", "newCol2")
              .show(false)

+----+----+----+
|Col1|Col2|Col3|
+----+----+----+
|2-C |1-x |o   |
|0-A |0-z |m   |
|0-A |0-z |n   |
|0-A |2-p |o   |
|1-B |3-w |n   |
+----+----+----+
</code>```

Body:
I have a dataframe df1 of the format

+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
| A    | z    | m    |
| B    | w    | n    |
| C    | x    | o    |
| A    | z    | n    |
| A    | p    | o    |
+------+------+------+

and another dataframe df2 of the format

+------+------+
| Col1 | Col2 |
+------+------+
| 0-A  | 0-z  |
| 1-B  | 3-w  |
| 2-C  | 1-x  |
|      | 2-P  |
+------+------+-

I am trying to replace the values in Col1 and Col2 of df1 with values from df2 using Spark Java.

The end dataframe df3 should look like this.

+------+------+------+
| Col1 | Col2 | Col3 |
+------+------+------+
| 0-A  | 0-z  | m    |
| 1-B  | 3-w  | n    |
| 2-C  | 1-x  | o    |
| 0-A  | 0-z  | n    |
| 0-A  | 2-p  | o    |
+------+------+------+

I am trying to replace all the values in the column1 and column2 of df1 with values from col1 and col2 of df2.
Is there anyway that i can achieve this in Spark Java dataframe syntax.?

The initial idea i had was to do the following.

String pattern1="\\p{L}+(?: \\p{L}+)*$";

df1=df1.join(df2, df1.col("col1").equalTo(regexp_extract(df2.col("col1"),pattern1,1)),"left-semi");

Body:
Replace your last join operation with below join.

df1.alias("x").join(df2.alias("y").select(col("y.Col1").alias("newCol1")), col("x.Col1") === regexp_extract(col("newCol1"),"\\p{L}+(?: \\p{L}+)*$",0), "left")
              .withColumn("Col1", col("newCol1"))
              .join(df2.alias("z").select(col("z.Col2").alias("newCol2")), col("x.Col2") === regexp_extract(col("newCol2"),"\\p{L}+(?: \\p{L}+)*$",0), "left")
              .withColumn("Col2", col("newCol2"))
              .drop("newCol1", "newCol2")
              .show(false)

+----+----+----+
|Col1|Col2|Col3|
+----+----+----+
|2-C |1-x |o   |
|0-A |0-z |m   |
|0-A |0-z |n   |
|0-A |2-p |o   |
|1-B |3-w |n   |
+----+----+----+


问:
How to check if the user is admin?
I am trying to use the latest version of Firebase and Angular. Overall concept I am trying to achieve is admin authentication. I have achieved login logout functions and have saved the googleAuth login user to database with UID.
And I am trying to restrict some pages to Logged in and Admin. I have assigned isAdmin: true as a value in the user object that is stored in the database. I want to see if the user is admin and return true or false for the router params.

Here is what I have:

```<code>import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
import * as firebase from 'firebase';
import { AppUser } from './models/app-user';
@Injectable({
  providedIn: 'root'
})
user.service.ts

export class UserService {

  constructor(private db: AngularFireDatabase) { }

  save(user: firebase.User){
    this.db.object('/users/' + user.uid).update({
      name: user.displayName,
      email: user.email
    });
  }
 get(uid:string): FirebaseObjectObservable<AppUser>{
   return this.db.object('/users/' +uid);
 }
}
</code>```

app.module.ts

```<code>
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {RouterModule} from '@angular/router';
import{NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { BsNavbarComponent } from './bs-navbar/bs-navbar.component';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { CheckOutComponent } from './check-out/check-out.component';
import { OrderSuccessComponent } from './order-success/order-success.component';
import { MyOrdersComponent } from './my-orders/my-orders.component';
import { AdminProductsComponent } from './admin/admin-products/admin-products.component';
import { AdminOrdersComponent } from './admin/admin-orders/admin-orders.component';
import { LoginComponent } from './login/login.component';
import { AppComponent } from './app.component';
import { environment } from 'src/environments/environment';
import { AuthService } from './auth.service';
import { AuthGuard as AuthGuard } from './auth-guard.service';
import { UserService } from './user.service';
import { AdminAuthGuard as AdminAuthGuard } from './admin-auth-guard.service';

@NgModule({
  declarations: [
    AppComponent,
    BsNavbarComponent,
    HomeComponent,
    ProductsComponent,
    ShoppingCartComponent,
    CheckOutComponent,
    OrderSuccessComponent,
    MyOrdersComponent,
    AdminProductsComponent,
    AdminOrdersComponent,
    LoginComponent,
    ShoppingCartComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    NgbModule.forRoot(),
    RouterModule.forRoot([
    {path: '', component: HomeComponent},
    {path: 'products', component: ProductsComponent},
    {path: 'shopping-cart', component: ShoppingCartComponent},
    {path: 'login', component: LoginComponent},
    {path: 'check-out', component: CheckOutComponent,canActivate:[AuthGuard]},
    {path: 'order-success', component: OrderSuccessComponent, canActivate:[AuthGuard]},
    {path: 'my/orders',component: MyOrdersComponent,canActivate:[AuthGuard]},
    {path: 'admin/products', component: AdminProductsComponent,canActivate:[AuthGuard,AdminAuthGuard]},
    {path: 'admin/orders', component: AdminOrdersComponent,canActivate:[AuthGuard,AdminAuthGuard]}
  ])
],
  providers: [
    AuthService,
    AuthGuard,
    AdminAuthGuard,
    UserService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

admin-auth-guard.service.ts

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
import { UserService } from './user.service';
import { Observable } from 'rxjs/Observable';
import { switchMap, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AdminAuthGuard implements CanActivate {

  constructor(private auth: AuthService, private userService: UserService) { }

  canActivate(): Observable<boolean>{
   return this.auth.user$.pipe(
    switchMap(user => this.userService.get(user.uid)),
    map(appUser => appUser.isAdmin)
  );

    }

}
</code>```

答: Did you used displayname property? When doing user or admin registration you can add this property and it will save in authentication db . So in your login function you can check using if displayname property is admin or user. It’s simple and easy method.</p>

Title: How to check if the user is admin?

Body:
I am trying to use the latest version of Firebase and Angular. Overall concept I am trying to achieve is admin authentication. I have achieved login logout functions and have saved the googleAuth login user to database with UID.
And I am trying to restrict some pages to Logged in and Admin. I have assigned isAdmin: true as a value in the user object that is stored in the database. I want to see if the user is admin and return true or false for the router params.

Here is what I have:

import { Injectable } from '@angular/core';
import { AngularFireDatabase, FirebaseObjectObservable } from 'angularfire2/database';
import * as firebase from 'firebase';
import { AppUser } from './models/app-user';
@Injectable({
  providedIn: 'root'
})
user.service.ts

export class UserService {

  constructor(private db: AngularFireDatabase) { }

  save(user: firebase.User){
    this.db.object('/users/' + user.uid).update({
      name: user.displayName,
      email: user.email
    });
  }
 get(uid:string): FirebaseObjectObservable<AppUser>{
   return this.db.object('/users/' +uid);
 }
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import {AngularFireModule} from 'angularfire2';
import {AngularFireDatabaseModule} from 'angularfire2/database';
import {AngularFireAuthModule} from 'angularfire2/auth';
import {RouterModule} from '@angular/router';
import{NgbModule} from '@ng-bootstrap/ng-bootstrap';
import { BsNavbarComponent } from './bs-navbar/bs-navbar.component';
import { HomeComponent } from './home/home.component';
import { ProductsComponent } from './products/products.component';
import { ShoppingCartComponent } from './shopping-cart/shopping-cart.component';
import { CheckOutComponent } from './check-out/check-out.component';
import { OrderSuccessComponent } from './order-success/order-success.component';
import { MyOrdersComponent } from './my-orders/my-orders.component';
import { AdminProductsComponent } from './admin/admin-products/admin-products.component';
import { AdminOrdersComponent } from './admin/admin-orders/admin-orders.component';
import { LoginComponent } from './login/login.component';
import { AppComponent } from './app.component';
import { environment } from 'src/environments/environment';
import { AuthService } from './auth.service';
import { AuthGuard as AuthGuard } from './auth-guard.service';
import { UserService } from './user.service';
import { AdminAuthGuard as AdminAuthGuard } from './admin-auth-guard.service';

@NgModule({
  declarations: [
    AppComponent,
    BsNavbarComponent,
    HomeComponent,
    ProductsComponent,
    ShoppingCartComponent,
    CheckOutComponent,
    OrderSuccessComponent,
    MyOrdersComponent,
    AdminProductsComponent,
    AdminOrdersComponent,
    LoginComponent,
    ShoppingCartComponent
  ],
  imports: [
    BrowserModule,
    AngularFireModule.initializeApp(environment.firebase),
    AngularFireDatabaseModule,
    AngularFireAuthModule,
    NgbModule.forRoot(),
    RouterModule.forRoot([
    {path: '', component: HomeComponent},
    {path: 'products', component: ProductsComponent},
    {path: 'shopping-cart', component: ShoppingCartComponent},
    {path: 'login', component: LoginComponent},
    {path: 'check-out', component: CheckOutComponent,canActivate:[AuthGuard]},
    {path: 'order-success', component: OrderSuccessComponent, canActivate:[AuthGuard]},
    {path: 'my/orders',component: MyOrdersComponent,canActivate:[AuthGuard]},
    {path: 'admin/products', component: AdminProductsComponent,canActivate:[AuthGuard,AdminAuthGuard]},
    {path: 'admin/orders', component: AdminOrdersComponent,canActivate:[AuthGuard,AdminAuthGuard]}
  ])
],
  providers: [
    AuthService,
    AuthGuard,
    AdminAuthGuard,
    UserService
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

admin-auth-guard.service.ts

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { AuthService } from './auth.service';
import { UserService } from './user.service';
import { Observable } from 'rxjs/Observable';
import { switchMap, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class AdminAuthGuard implements CanActivate {

  constructor(private auth: AuthService, private userService: UserService) { }

  canActivate(): Observable<boolean>{
   return this.auth.user$.pipe(
    switchMap(user => this.userService.get(user.uid)),
    map(appUser => appUser.isAdmin)
  );

    }

}


问:
Where is the console API for WebKit/Safari?
WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a console documentation for Firebug, but where can I find the console documentation for Safari/WebKit?</p>

答:
Try this out:</p>

```<code>console.dir(console)
</code>```

OwnerDisplayName: Alessandro Vernet

ContentLicense: CC BY-SA 3.0

Body:
Try this out:

console.dir(console)


问:
ReactJs : What is the proper way of accessing the state data in the root component where the link between React and Redux has been implemented?
DISCLAIMER: This error has been mentioned on stackoverflow before but my case is different.

I have had a problem with the user login which I have explained in this stackOverFlow question. I invite you to go and quickly take a look.

So as I mentioned in that question in my root file I have this:

App.js

```<code>class App extends Component {
  render() {
    const authLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
        <Route
          path="/home"
          name="Home"
          render={props => <DefaultLayout {...props} />}
        />
      </Switch>
    );

    const guestLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/register"
          name="Register Page"
          render={props => <Register {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
      </Switch>
    );

    const currentState = store.getState();
    console.log(
      "currentState.auth.isAuthenticated: ",
      currentState.auth.isAuthenticated
    );
    return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            {console.log(currentState.auth.isAuthenticated)}
            {/* TODO: Not sure if this always works. If after the user logsin he gets a blank page and he has to reload to be redirected to home then
            this way of routing may need to modified */}
            {currentState.auth.isAuthenticated ? authLinks : guestLinks}
          </React.Suspense>
        </HashRouter>
      </Provider>
    );
  }
}
</code>```

I have been told that I am accessing the state isAuthenticated incorrectly:

```<code> {currentState.auth.isAuthenticated ? authLinks : guestLinks}
</code>```

That I should access it by using connect(). That was actually the first thing I have tried. It didn't work. But, I took their advice and tried it again:

```<code>class App extends Component {
  render() {
    const authLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
        <Route
          path="/home"
          name="Home"
          render={props => <DefaultLayout {...props} />}
        />
      </Switch>
    );

    const guestLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/register"
          name="Register Page"
          render={props => <Register {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
      </Switch>
    );

    const currentState = store.getState();
    console.log(
      "currentState.auth.isAuthenticated: ",
      currentState.auth.isAuthenticated
    );
    return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            {console.log(currentState.auth.isAuthenticated)}
            {/* TODO: Not sure if this always works. If after the user logsin he gets a blank page and he has to reload to be redirected to home then
            this way of routing may need to modified */}
            {/* {currentState.auth.isAuthenticated ? authLinks : guestLinks} */}
            {this.props.auth.isAuthenticated ? authLinks : guestLinks}
          </React.Suspense>
        </HashRouter>
      </Provider>
    );
  }
}

App.propTypes = {
  auth: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
  auth: state.auth,
  errors: state.errors
});
export default connect(mapStateToProps, null)(withRouter(App));
</code>```

which gives the error I've mentioned:

```<code>Could not find "store" in the context of "Connect(withRouter(App))". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(withRouter(App)) in connect options.
</code>```

which kind of makes sense, since the store is passed root component App.js through the router. So the state of the app shouldn't be accessed in the same way it is accessed in childComponents through connect.
So I have two questions:

QUESTION 1: Why am I getting this error?

QUESTION 2: What is the right way of accessing the state data inside the root component where the link between the redux and react is implemented?

答:
QUESTION 1:

I believe you have to wrap withRouter first.

Try this:

```<code>import { connect } from "react-redux";
import { withRouter } from "react-router";

export default withRouter(connect(mapStateToProps, null)(App));

</code>```

QUESTION 2:
You are mapping the state to props so the correct way to access auth from your state in your component is this.props.auth

Try to console.log(this.props) in your render and you will see what I mean. Also check the docs on https://react-redux.js.org/api/connect

Hope this helps

Body:
DISCLAIMER: This error has been mentioned on stackoverflow before but my case is different.

I have had a problem with the user login which I have explained in this stackOverFlow question. I invite you to go and quickly take a look.

So as I mentioned in that question in my root file I have this:

App.js

class App extends Component {
  render() {
    const authLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
        <Route
          path="/home"
          name="Home"
          render={props => <DefaultLayout {...props} />}
        />
      </Switch>
    );

    const guestLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/register"
          name="Register Page"
          render={props => <Register {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
      </Switch>
    );

    const currentState = store.getState();
    console.log(
      "currentState.auth.isAuthenticated: ",
      currentState.auth.isAuthenticated
    );
    return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            {console.log(currentState.auth.isAuthenticated)}
            {/* TODO: Not sure if this always works. If after the user logsin he gets a blank page and he has to reload to be redirected to home then
            this way of routing may need to modified */}
            {currentState.auth.isAuthenticated ? authLinks : guestLinks}
          </React.Suspense>
        </HashRouter>
      </Provider>
    );
  }
}

I have been told that I am accessing the state isAuthenticated incorrectly:

 {currentState.auth.isAuthenticated ? authLinks : guestLinks}

That I should access it by using connect(). That was actually the first thing I have tried. It didn't work. But, I took their advice and tried it again:

class App extends Component {
  render() {
    const authLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
        <Route
          path="/home"
          name="Home"
          render={props => <DefaultLayout {...props} />}
        />
      </Switch>
    );

    const guestLinks = (
      <Switch>
        <Route
          exact
          path="/"
          name="Login Page"
          render={props => <Login {...props} />}
        />
        <Route
          exact
          path="/register"
          name="Register Page"
          render={props => <Register {...props} />}
        />
        <Route
          exact
          path="/404"
          name="Page 404"
          render={props => <Page404 {...props} />}
        />
        <Route
          exact
          path="/500"
          name="Page 500"
          render={props => <Page500 {...props} />}
        />
      </Switch>
    );

    const currentState = store.getState();
    console.log(
      "currentState.auth.isAuthenticated: ",
      currentState.auth.isAuthenticated
    );
    return (
      <Provider store={store}>
        <HashRouter>
          <React.Suspense fallback={loading()}>
            {console.log(currentState.auth.isAuthenticated)}
            {/* TODO: Not sure if this always works. If after the user logsin he gets a blank page and he has to reload to be redirected to home then
            this way of routing may need to modified */}
            {/* {currentState.auth.isAuthenticated ? authLinks : guestLinks} */}
            {this.props.auth.isAuthenticated ? authLinks : guestLinks}
          </React.Suspense>
        </HashRouter>
      </Provider>
    );
  }
}

App.propTypes = {
  auth: PropTypes.object.isRequired,
  errors: PropTypes.object.isRequired
};
const mapStateToProps = state => ({
  auth: state.auth,
  errors: state.errors
});
export default connect(mapStateToProps, null)(withRouter(App));

which gives the error I've mentioned:

Could not find "store" in the context of "Connect(withRouter(App))". Either wrap the root component in a <Provider>, or pass a custom React context provider to <Provider> and the corresponding React context consumer to Connect(withRouter(App)) in connect options.

which kind of makes sense, since the store is passed root component App.js through the router. So the state of the app shouldn't be accessed in the same way it is accessed in childComponents through connect.
So I have two questions:

QUESTION 1: Why am I getting this error?

QUESTION 2: What is the right way of accessing the state data inside the root component where the link between the redux and react is implemented?

Body:
QUESTION 1:

I believe you have to wrap withRouter first.

Try this:

import { connect } from "react-redux";
import { withRouter } from "react-router";

export default withRouter(connect(mapStateToProps, null)(App));

QUESTION 2:
You are mapping the state to props so the correct way to access auth from your state in your component is this.props.auth

Try to console.log(this.props) in your render and you will see what I mean. Also check the docs on https://react-redux.js.org/api/connect

Hope this helps


问:
Odoo python, product priceHistory in current order only
I'm a odoo user without development skills.
I have a custom module with a issue.
I explain how module work: I can add in purchase order products lines with custom price and quantity by scanning barcode in a New scanning field. If I scan more time same barcode, in same product line is increase quantity. In new scan barcode field, before scan barcode, I can type new product price and after scan barcode. Will be add line product with new price.
If I scan barcode 1 time, will add product with qty 1, and default supplier price. If I type in new scanning field new price and scan again barcode, will update product line with 1 qty increase and new price. Without priceHistory feature, if I scan again barcode (without type new price), will add 1 qty increase and new price previous updated, it will be substitute with default supplier price. With priceHistory, I can hold (fixed) new price updated, and if I will scan again barcode, new price will not be substitute.
Issue is this:
new price is applied to othes PO of others suppliers also, not only in this current PO.  I need priceHistory fix price history only in current purchase order. Each order own priceHistory data.
Currently code work, If product Shoes I apply new price 1 $ to order PO1 with supplier A, when I will create new orders (PO2,PO3,etc) with others supplier B, supplier C, D, etc.. When I will add product Shoes, priceHistory apply always 1$ (price PO1 of supplier A). This is the Issue, I need to apply 1$ only in PO1 of supplier A, and not in all order (PO2,PO3, of others suppliers)
I'm not a developer, please anyone can be help to correct code? And write me modify to do.
Thanks very much

BELOW ALL COMPLETE CODE

```<code># -*- coding: utf-8 -*-

from odoo import api, fields, models
from odoo.exceptions import Warning
import math
import dateutil.relativedelta
import datetime
import locale

# added the price history map
priceHistory = {}

class PurchaseOrder(models.Model):
    """Inherit Purchase Order."""

    _inherit = "purchase.order"
    barcode = fields.Char(string='Barcode', size=50)

    def _add_product(self, product, qty, price):
        corresponding_line = self.order_line.filtered(lambda r: r.product_id.id == product.id)
        supplierinfo = product.mapped('seller_ids')[:1]
        if corresponding_line:
            corresponding_line[0].product_qty += float(qty)
            corresponding_line[0].price_unit = float(price) or supplierinfo.price
        else:
            self.order_line += self.order_line.new({
                'product_id': product.id,
                'product_qty': qty,
                'date_planned': fields.Datetime.to_string(datetime.datetime.now() - dateutil.relativedelta.relativedelta(months=1)),
                'name': product.name,
                'product_uom': product.uom_id.id,
                'price_unit': float(price) or supplierinfo.price,
                'taxes_id': product.supplier_taxes_id,
            })
        return True

    @api.onchange('barcode')
    def barcode_scanning(self):
        """Barcode decode."""
        if self.barcode:
            scan_barcode = self.barcode
            barcode = scan_barcode
            qty_position = scan_barcode.find('*')
            price_position = scan_barcode.find('/')

            if price_position > 0:
                price = scan_barcode[:price_position].replace(',','.')
                barcode = scan_barcode[price_position + 1:]
            else:
                price = 0

            if qty_position > 0:
                qty = scan_barcode[price_position + 1:qty_position].replace(',','.')
                barcode = scan_barcode[qty_position + 1:]
            else:
                if float(price) > 0:
                    qty = 0
                else:
                    qty = 1

            #added, to search internal reference
            product_id = self.env['product.product'].search([('default_code', '=ilike', barcode)], limit=1)
            # product_id = self.env['product.product'].search([('default_code', '=', barcode)])
            if barcode and not product_id:
                product_id = self.env['product.product'].search([('barcode', '=', barcode)])
                if barcode and not product_id:
                    self.barcode = barcode = None
                    raise Warning('Barcode sconosciuto')

              if product_id:
                # get the history price
                if price_position == -1:
                    #if priceHistory.has_key(product_id.id):
                    if product_id.id in priceHistory.keys():
                        price = priceHistory[product_id.id]
                self._add_product(product_id, qty, price)
                self.barcode = barcode = None
                #save the product price
                priceHistory[product_id.id] = price
                return
</code>```

答:
```<code>def _add_product(self, product, qty, price):
    corresponding_line = self.order_line.filtered(lambda r: r.product_id.id == product.id)
    # Get all Vendor List
    supplierinfo = product.mapped('seller_ids')
    for supp_info in supplierinfo:
        # Match with current PO Vendor with assign product Vendor
        if self.partner_id.id == supp_info.id:
            # Update the Pice
            price = supp_info.price
    if corresponding_line:
        corresponding_line[0].product_qty += float(qty)
        corresponding_line[0].price_unit = float(price)
    else:
        self.order_line += self.order_line.new({
            'product_id': product.id,
            'product_qty': qty,
            'date_planned': fields.Datetime.to_string(datetime.datetime.now() - dateutil.relativedelta.relativedelta(months=1)),
            'name': product.name,
            'product_uom': product.uom_id.id,
            'price_unit': float(price),
            'taxes_id': product.supplier_taxes_id,
        })
    return True
</code>```

Body:
I'm a odoo user without development skills.
I have a custom module with a issue.
I explain how module work: I can add in purchase order products lines with custom price and quantity by scanning barcode in a New scanning field. If I scan more time same barcode, in same product line is increase quantity. In new scan barcode field, before scan barcode, I can type new product price and after scan barcode. Will be add line product with new price.
If I scan barcode 1 time, will add product with qty 1, and default supplier price. If I type in new scanning field new price and scan again barcode, will update product line with 1 qty increase and new price. Without priceHistory feature, if I scan again barcode (without type new price), will add 1 qty increase and new price previous updated, it will be substitute with default supplier price. With priceHistory, I can hold (fixed) new price updated, and if I will scan again barcode, new price will not be substitute.
Issue is this:
new price is applied to othes PO of others suppliers also, not only in this current PO.  I need priceHistory fix price history only in current purchase order. Each order own priceHistory data.
Currently code work, If product Shoes I apply new price 1 $ to order PO1 with supplier A, when I will create new orders (PO2,PO3,etc) with others supplier B, supplier C, D, etc.. When I will add product Shoes, priceHistory apply always 1$ (price PO1 of supplier A). This is the Issue, I need to apply 1$ only in PO1 of supplier A, and not in all order (PO2,PO3, of others suppliers)
I'm not a developer, please anyone can be help to correct code? And write me modify to do.
Thanks very much

BELOW ALL COMPLETE CODE

# -*- coding: utf-8 -*-

from odoo import api, fields, models
from odoo.exceptions import Warning
import math
import dateutil.relativedelta
import datetime
import locale

# added the price history map
priceHistory = {}

class PurchaseOrder(models.Model):
    """Inherit Purchase Order."""

    _inherit = "purchase.order"
    barcode = fields.Char(string='Barcode', size=50)

    def _add_product(self, product, qty, price):
        corresponding_line = self.order_line.filtered(lambda r: r.product_id.id == product.id)
        supplierinfo = product.mapped('seller_ids')[:1]
        if corresponding_line:
            corresponding_line[0].product_qty += float(qty)
            corresponding_line[0].price_unit = float(price) or supplierinfo.price
        else:
            self.order_line += self.order_line.new({
                'product_id': product.id,
                'product_qty': qty,
                'date_planned': fields.Datetime.to_string(datetime.datetime.now() - dateutil.relativedelta.relativedelta(months=1)),
                'name': product.name,
                'product_uom': product.uom_id.id,
                'price_unit': float(price) or supplierinfo.price,
                'taxes_id': product.supplier_taxes_id,
            })
        return True

    @api.onchange('barcode')
    def barcode_scanning(self):
        """Barcode decode."""
        if self.barcode:
            scan_barcode = self.barcode
            barcode = scan_barcode
            qty_position = scan_barcode.find('*')
            price_position = scan_barcode.find('/')

            if price_position > 0:
                price = scan_barcode[:price_position].replace(',','.')
                barcode = scan_barcode[price_position + 1:]
            else:
                price = 0

            if qty_position > 0:
                qty = scan_barcode[price_position + 1:qty_position].replace(',','.')
                barcode = scan_barcode[qty_position + 1:]
            else:
                if float(price) > 0:
                    qty = 0
                else:
                    qty = 1

            #added, to search internal reference
            product_id = self.env['product.product'].search([('default_code', '=ilike', barcode)], limit=1)
            # product_id = self.env['product.product'].search([('default_code', '=', barcode)])
            if barcode and not product_id:
                product_id = self.env['product.product'].search([('barcode', '=', barcode)])
                if barcode and not product_id:
                    self.barcode = barcode = None
                    raise Warning('Barcode sconosciuto')

              if product_id:
                # get the history price
                if price_position == -1:
                    #if priceHistory.has_key(product_id.id):
                    if product_id.id in priceHistory.keys():
                        price = priceHistory[product_id.id]
                self._add_product(product_id, qty, price)
                self.barcode = barcode = None
                #save the product price
                priceHistory[product_id.id] = price
                return


问:
Is it possible to simulate connection timeout using wiremock tools?
I know that it can simulate SocketTimeoutException by using withFixedDelay, but what about ConnectionTimeoutException?

答:
When using WireMock.Net, adding a delay is also possible.

Example:

var server = WireMockServer.Start();

// add a delay of 30 seconds for all requests
server.AddRequestProcessingDelay(TimeSpan.FromSeconds(30));
```

<p>or</p>

<pre class="lang-cs prettyprint-override"><code>var server = WireMockServer.Start();
server
  .Given(Request.Create().WithPath("/slow"))
  .RespondWith(
    Responses.Create()
      .WithStatusCode(200)
      .WithBody(@"{ ""msg"": ""Hello I'm a little bit slow!"" }")
      .WithDelay(TimeSpan.FromSeconds(10)
  )
);
</code>```

Body:
When using WireMock.Net, adding a delay is also possible.

Example:

var server = WireMockServer.Start();

// add a delay of 30 seconds for all requests
server.AddRequestProcessingDelay(TimeSpan.FromSeconds(30));

or

var server = WireMockServer.Start();
server
  .Given(Request.Create().WithPath("/slow"))
  .RespondWith(
    Responses.Create()
      .WithStatusCode(200)
      .WithBody(@"{ ""msg"": ""Hello I'm a little bit slow!"" }")
      .WithDelay(TimeSpan.FromSeconds(10)
  )
);


问:
Making Model class from JSON
Here I am trying to make the model class of this JSON

```<code>{
  "debit": 1,
  "train": {
    "number": "14207",
    "name": "PADMAVAT EXP",
    "days": [
      {
        "code": "MON",
        "runs": "Y"
      },
      {
        "code": "TUE",
        "runs": "Y"
      },
      {
        "code": "WED",
        "runs": "Y"
      },
      {
        "code": "THU",
        "runs": "Y"
      },
      {
        "code": "FRI",
        "runs": "Y"
      },
      {
        "code": "SAT",
        "runs": "Y"
      },
      {
        "code": "SUN",
        "runs": "Y"
      }
    ],
    "classes": [
      {
        "code": "2A",
        "available": "Y",
        "name": "SECOND AC"
      },
      {
        "code": "3E",
        "available": "N",
        "name": "3rd AC ECONOMY"
      },
      {
        "code": "3A",
        "available": "Y",
        "name": "THIRD AC"
      },
      {
        "code": "2S",
        "available": "N",
        "name": "SECOND SEATING"
      },
      {
        "code": "CC",
        "available": "N",
        "name": "AC CHAIR CAR"
      },
      {
        "code": "SL",
        "available": "Y",
        "name": "SLEEPER CLASS"
      },
      {
        "code": "FC",
        "available": "N",
        "name": "FIRST CLASS"
      },
      {
        "code": "1A",
        "available": "Y",
        "name": "FIRST AC"
      }
    ]
  },
  "response_code": 200
}
</code>```

And I try this
First I create two Integer variable name response_code and debit(because inside "{" and "}" are key and value pairs)
Then I create on array List and one List named as train and classes which represents train list and classes array in json. Still Not Working

```<code>public class NewTrain {
    @SerializedName("response_code")
    private int response_code;
    @SerializedName("debit")
    private int debit;
    @SerializedName("train")
    private List<TrainClass> train= null;
   @SerializedName("classes")
    private ArrayList<classes> arrayList = null;

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public int getDebit() {
        return debit;
    }

    public void setDebit(int debit) {
        this.debit = debit;
    }

    public List<TrainClass> getTrain() {
        return train;
    }

    public void setTrain(List<TrainClass> train) {
        this.train = train;
    }

    public ArrayList<classes> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<classes> arrayList) {
        this.arrayList = arrayList;
    }
}

public class TrainClass
 @SerializedName("number")
    private int number;
    @SerializedName("name")
    private String name;
    @SerializedName("days")
    private List<Day> dayList = null;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Day> getDayList() {
        return dayList;
    }

    public void setDayList(List<Day> dayList) {
        this.dayList = dayList;
    }
}
public class Day {
    @SerializedName("code")
    private String code;
    @SerializedName("runs")
    private String runs;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getRuns() {
        return runs;
    }

    public void setRuns(String runs) {
        this.runs = runs;
    }

}
public class classes {
    @SerializedName("code")
    private String code;

    @SerializedName("available")
    private String available;

    @SerializedName("name")
    private String name;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAvailable() {
        return available;
    }

    public void setAvailable(String available) {
        this.available = available;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}
</code>```

But instead it is giving Begin Array but was Begin Object at line 1 column 2!!!
Calling API data from server method

```<code> public void Show(View view) {

        MyWebService myWebService = MyWebService.retrofitfortrain.create(MyWebService.class);
        Call<List<NewTrain>>  call = myWebService.getTrainList();
      call.enqueue(new Callback<List<NewTrain>>() {
          @Override
          public void onResponse(Call<List<NewTrain>> call, Response<List<NewTrain>> response) {
              if(response.isSuccessful())
              {
                  for(NewTrain newTrain: response.body()) {
                      t.append(String.valueOf(newTrain.getResponse_code()));
                  }
              }
          }

          @Override
          public void onFailure(Call<List<NewTrain>> call, Throwable t) {
              Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

          }
      });

    }
</code>```

答:
According to the json mentioned train is not a list, but in the class you made it a list. May be that is the issue. So , instead of:

```<code>@SerializedName("train")
private List<TrainClass> train= null;
</code>```

make it

```<code>@SerializedName("train")
private TrainClass train= null;
</code>```

and update the getter, setter methods accordingly

Title: Making Model class from JSON

Body:
Here I am trying to make the model class of this JSON

{
  "debit": 1,
  "train": {
    "number": "14207",
    "name": "PADMAVAT EXP",
    "days": [
      {
        "code": "MON",
        "runs": "Y"
      },
      {
        "code": "TUE",
        "runs": "Y"
      },
      {
        "code": "WED",
        "runs": "Y"
      },
      {
        "code": "THU",
        "runs": "Y"
      },
      {
        "code": "FRI",
        "runs": "Y"
      },
      {
        "code": "SAT",
        "runs": "Y"
      },
      {
        "code": "SUN",
        "runs": "Y"
      }
    ],
    "classes": [
      {
        "code": "2A",
        "available": "Y",
        "name": "SECOND AC"
      },
      {
        "code": "3E",
        "available": "N",
        "name": "3rd AC ECONOMY"
      },
      {
        "code": "3A",
        "available": "Y",
        "name": "THIRD AC"
      },
      {
        "code": "2S",
        "available": "N",
        "name": "SECOND SEATING"
      },
      {
        "code": "CC",
        "available": "N",
        "name": "AC CHAIR CAR"
      },
      {
        "code": "SL",
        "available": "Y",
        "name": "SLEEPER CLASS"
      },
      {
        "code": "FC",
        "available": "N",
        "name": "FIRST CLASS"
      },
      {
        "code": "1A",
        "available": "Y",
        "name": "FIRST AC"
      }
    ]
  },
  "response_code": 200
}

And I try this
First I create two Integer variable name response_code and debit(because inside "{" and "}" are key and value pairs)
Then I create on array List and one List named as train and classes which represents train list and classes array in json. Still Not Working

public class NewTrain {
    @SerializedName("response_code")
    private int response_code;
    @SerializedName("debit")
    private int debit;
    @SerializedName("train")
    private List<TrainClass> train= null;
   @SerializedName("classes")
    private ArrayList<classes> arrayList = null;

    public int getResponse_code() {
        return response_code;
    }

    public void setResponse_code(int response_code) {
        this.response_code = response_code;
    }

    public int getDebit() {
        return debit;
    }

    public void setDebit(int debit) {
        this.debit = debit;
    }

    public List<TrainClass> getTrain() {
        return train;
    }

    public void setTrain(List<TrainClass> train) {
        this.train = train;
    }

    public ArrayList<classes> getArrayList() {
        return arrayList;
    }

    public void setArrayList(ArrayList<classes> arrayList) {
        this.arrayList = arrayList;
    }
}

public class TrainClass
 @SerializedName("number")
    private int number;
    @SerializedName("name")
    private String name;
    @SerializedName("days")
    private List<Day> dayList = null;

    public int getNumber() {
        return number;
    }

    public void setNumber(int number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<Day> getDayList() {
        return dayList;
    }

    public void setDayList(List<Day> dayList) {
        this.dayList = dayList;
    }
}
public class Day {
    @SerializedName("code")
    private String code;
    @SerializedName("runs")
    private String runs;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getRuns() {
        return runs;
    }

    public void setRuns(String runs) {
        this.runs = runs;
    }

}
public class classes {
    @SerializedName("code")
    private String code;

    @SerializedName("available")
    private String available;

    @SerializedName("name")
    private String name;

    public String getCode() {
        return code;
    }

    public void setCode(String code) {
        this.code = code;
    }

    public String getAvailable() {
        return available;
    }

    public void setAvailable(String available) {
        this.available = available;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

But instead it is giving Begin Array but was Begin Object at line 1 column 2!!!
Calling API data from server method

 public void Show(View view) {

        MyWebService myWebService = MyWebService.retrofitfortrain.create(MyWebService.class);
        Call<List<NewTrain>>  call = myWebService.getTrainList();
      call.enqueue(new Callback<List<NewTrain>>() {
          @Override
          public void onResponse(Call<List<NewTrain>> call, Response<List<NewTrain>> response) {
              if(response.isSuccessful())
              {
                  for(NewTrain newTrain: response.body()) {
                      t.append(String.valueOf(newTrain.getResponse_code()));
                  }
              }
          }

          @Override
          public void onFailure(Call<List<NewTrain>> call, Throwable t) {
              Toast.makeText(getApplicationContext(),t.getMessage(),Toast.LENGTH_LONG).show();

          }
      });

    }

Body:
According to the json mentioned train is not a list, but in the class you made it a list. May be that is the issue. So , instead of:

@SerializedName("train")
private List<TrainClass> train= null;

make it

@SerializedName("train")
private TrainClass train= null;

and update the getter, setter methods accordingly


问:
grep regex multiple replacements
I will probably have done it "manually" by the time I get an answer for this.

I have two variables (varA, varB) I want to replace with (a, b) respectively, this currently requires two separate find and replaces.

with regex grep I know how to do two separate searches using
    varA | varB

but there is no replace function that will similarly do a respective replacement

unless you know better? thanks for any insight

答:
grep is used for searching pattern in a given input. You should use sed for text replacements. For multiple replacements in single sed command just use it like this:</p>

```<code>sed -e 's/varA/foo/g' -e 's/varB/bar/g' file.txt
</code>```

Title: grep regex multiple replacements

Body:
grep is used for searching pattern in a given input. You should use sed for text replacements. For multiple replacements in single sed command just use it like this:

sed -e 's/varA/foo/g' -e 's/varB/bar/g' file.txt


问:
Create table using iterative statements in "react" rendering
I try to create a table with two arrays in a state(week_today, week_count) and a repeating sentence when rendering.
I don't know how to use map() function . Please advise.

my code

```<code>    render() {
        const {week_today, week_count} = this.state; // this.state in my array put

        return (
            <div>

                <table class="table">
                    <thead class="thead-dark">
                        <tr>
                            <th scope="col">today</th>
                            <th scope="col">count</th>
                        </tr>
                    </thead>
                    <tbody>
                     //<== here my array table

                    </tbody>

                </table>
            </div>

        )
    }
</code>```

use my arrays

```<code>week_today = [ 01,02,03,04,05]
week_count = [ 1,2,3,4,5]
</code>```

答:
Slightly changed the data structure (add this to your state):

```<code>week: [
 { today: '01', count: 1 },
 { today: '02', count: 2 },
 { today: '03', count: 3 },
 { today: '04', count: 4 },
 { today: '05', count: 5 }
]
</code>```

And add this to your render:

```<code><tbody>
  {this.state.week.map( element => {
      return (
        <tr>
          <td>
            {element.today}
          </td>
          <td>
            {element.count}
          </td>
        </tr>
      )
    })
  }
</tbody>
</code>```

Body:
I try to create a table with two arrays in a state(week_today, week_count) and a repeating sentence when rendering.
I don't know how to use map() function . Please advise.

my code

    render() {
        const {week_today, week_count} = this.state; // this.state in my array put

        return (

                            today
                            count

                     //<== here my array table

        )
    }

use my arrays

week_today = [ 01,02,03,04,05]
week_count = [ 1,2,3,4,5]

Body:
Slightly changed the data structure (add this to your state):

week: [
 { today: '01', count: 1 },
 { today: '02', count: 2 },
 { today: '03', count: 3 },
 { today: '04', count: 4 },
 { today: '05', count: 5 }
]

And add this to your render:

<tbody>
  {this.state.week.map( element => {
      return (
        <tr>
          <td>
            {element.today}
          </td>
          <td>
            {element.count}
          </td>
        </tr>
      )
    })
  }
</tbody>


问:
FullCalendar - inline scrollable calendar
I'm hardly editing Easy!Appoinments to adapt it to our needs.
I'm developing a page that lists a biweekly providers' calendar.

FullCalendar allows to create a biweekly calendar with this option:

```<code>views: {
   agendaBiWeek: {
       type: 'basic',
       duration: { weeks: 2 },
       buttonText: '14 giorni'
   }
},
</code>```

but the 2 weeks are split into 2 rows.

I, instead, would like to show 14 days in only one scrollable row.

This is my actual situation:

But I'd like to have this result:

I'm obtain this result by manipute DOM objects through JS, but when refreshed, it all mess up. Fullcalendar adds new events expecting to find 2 rows.

The only easy way to make it work is to alter CSS in order to show the 2 DIV inline, but I don't know how to do it because there are too many elements.

Can you help me?

I create the calendar with this options:

```<code>$('#custom-calendar-' + provider.id).fullCalendar({
                defaultView: 'agendaBiWeek',
                height: BackendCalendarDefaultView._getCalendarHeight,
                contentHeight: 100,
                editable: true,
                firstDay: 1,
                snapDuration: '00:30:00',
                timeFormat: timeFormat,
                slotLabelFormat: slotTimeFormat,
                columnHeader: false,
                header: {
                    left: null,
                    center: null,
                    right: null
                },
                // visibleRange: {
                //     start: '2020-03-22',
                //     end: '2020-03-25'
                // },
                views: {
                    agendaBiWeek: {
                        type: 'basic',
                        duration: { weeks: 2 },
                        buttonText: '14 giorni'
                    }
                },
                // Selectable
                selectable: true,
                selectHelper: true,
                select:

                                           .

                                           .

                                           .

                                           .
</code>```

This is an example of generated calendar:

```<code><div id="custom-calendar-105" class="custom-calendar fc fc-unthemed fc-ltr" style="">
    <div class="fc-view-container" style="">
        <div class="fc-view fc-agendaBiWeek-view fc-basic-view" style="">
            <table class="">
                <tbody class="fc-body">
                    <tr>
                        <th class="fc-widget-header-custom">Provider14</th>
                        <td class="fc-widget-content">
                            <div class="fc-scroller fc-day-grid-container" style="overflow: hidden; height: 98.4px;">
                                <div class="fc-day-grid fc-unselectable">
                                    <div class="fc-row fc-week fc-widget-content" style="">
                                        <div class="fc-bg">
                                            <table class="">
                                                <tbody>
                                                    <tr class="giorno">
                                                        <td class="fc-day fc-widget-content fc-mon fc-past" data-date="2020-01-20"></td>
                                                        <td class="fc-day fc-widget-content fc-tue fc-past" data-date="2020-01-21"></td>
                                                        <td class="fc-day fc-widget-content fc-wed fc-past" data-date="2020-01-22"></td>
                                                        <td class="fc-day fc-widget-content fc-thu fc-today " data-date="2020-01-23"></td>
                                                        <td class="fc-day fc-widget-content fc-fri fc-future" data-date="2020-01-24"></td>
                                                        <td class="fc-day fc-widget-content fc-sat fc-future" data-date="2020-01-25"></td>
                                                        <td class="fc-day fc-widget-content fc-sun fc-future" data-date="2020-01-26"></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                        <div class="fc-content-skeleton">
                                            <table class="eventiGiorno">
                                                <thead>
                                                    <tr>
                                                        <td class="fc-day-top fc-mon fc-past" data-date="2020-01-20"><span class="fc-day-number">20</span></td>
                                                        <td class="fc-day-top fc-tue fc-past" data-date="2020-01-21"><span class="fc-day-number">21</span></td>
                                                        <td class="fc-day-top fc-wed fc-past" data-date="2020-01-22"><span class="fc-day-number">22</span></td>
                                                        <td class="fc-day-top fc-thu fc-today " data-date="2020-01-23"><span class="fc-day-number">23</span></td>
                                                        <td class="fc-day-top fc-fri fc-future" data-date="2020-01-24"><span class="fc-day-number">24</span></td>
                                                        <td class="fc-day-top fc-sat fc-future" data-date="2020-01-25"><span class="fc-day-number">25</span></td>
                                                        <td class="fc-day-top fc-sun fc-future" data-date="2020-01-26"><span class="fc-day-number">26</span></td>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td></td>
                                                        <td class="fc-event-container"><a class="fc-day-grid-event fc-h-event fc-event fc-start fc-end fc-draggable">
                                                                <div class="fc-content"><span class="fc-time">14:30</span> <span class="fc-title">MONTES</span></div>
                                                            </a></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    <div class="fc-row fc-week fc-widget-content" style="">
                                        <div class="fc-bg">
                                            <table class="">
                                                <tbody>
                                                    <tr>
                                                        <td class="fc-day fc-widget-content fc-mon fc-future" data-date="2020-01-27"></td>
                                                        <td class="fc-day fc-widget-content fc-tue fc-future" data-date="2020-01-28"></td>
                                                        <td class="fc-day fc-widget-content fc-wed fc-future" data-date="2020-01-29"></td>
                                                        <td class="fc-day fc-widget-content fc-thu fc-future" data-date="2020-01-30"></td>
                                                        <td class="fc-day fc-widget-content fc-fri fc-future" data-date="2020-01-31"></td>
                                                        <td class="fc-day fc-widget-content fc-sat fc-future" data-date="2020-02-01"></td>
                                                        <td class="fc-day fc-widget-content fc-sun fc-future" data-date="2020-02-02"></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                        <div class="fc-content-skeleton">
                                            <table>
                                                <thead>
                                                    <tr>
                                                        <td class="fc-day-top fc-mon fc-future" data-date="2020-01-27"><span class="fc-day-number">27</span></td>
                                                        <td class="fc-day-top fc-tue fc-future" data-date="2020-01-28"><span class="fc-day-number">28</span></td>
                                                        <td class="fc-day-top fc-wed fc-future" data-date="2020-01-29"><span class="fc-day-number">29</span></td>
                                                        <td class="fc-day-top fc-thu fc-future" data-date="2020-01-30"><span class="fc-day-number">30</span></td>
                                                        <td class="fc-day-top fc-fri fc-future" data-date="2020-01-31"><span class="fc-day-number">31</span></td>
                                                        <td class="fc-day-top fc-sat fc-future" data-date="2020-02-01"><span class="fc-day-number">1</span></td>
                                                        <td class="fc-day-top fc-sun fc-future" data-date="2020-02-02"><span class="fc-day-number">2</span></td>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <tr>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                        <td></td>
                                                    </tr>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</div>

</code>```

答:
MY SOLUTION:

I simply modified the css like this:

```<code>#calendar-page .custom-calendar .fc-scroller{
    overflow-x: scroll !important;
    overflow-y: hidden !important;
    height: auto !important
}

#calendar-page .custom-calendar .fc-scroller > .fc-day-grid {
    width: 200%
}

#calendar-page .custom-calendar .fc-basic-view .fc-body .fc-row {
    display: table-cell;
    width: 50%
}

#calendar-page .custom-calendar .fc-row td {
    width: 90px;
}

#calendar-page .fc th.fc-widget-header-custom {
    width: 100px;
    vertical-align: middle
}

@media (max-width: 767px) {
    #calendar-page .fc th.fc-widget-header-custom {
        display: block;
        width: 100%;
        padding-top: 10px;
        padding-bottom: 10px;
    }

    #calendar-page .fc th.fc-widget-header-custom + td {
        display: block;
        width: 100%;
        border: none
    }

    #calendar-page .custom-calendar .fc-row:first-of-type {
        border-left: 1px solid #ddd
    }
}
</code>```

Body:
I'm hardly editing Easy!Appoinments to adapt it to our needs.
I'm developing a page that lists a biweekly providers' calendar.

FullCalendar allows to create a biweekly calendar with this option:

views: {
   agendaBiWeek: {
       type: 'basic',
       duration: { weeks: 2 },
       buttonText: '14 giorni'
   }
},

but the 2 weeks are split into 2 rows.

I, instead, would like to show 14 days in only one scrollable row.

This is my actual situation:

But I'd like to have this result:

I'm obtain this result by manipute DOM objects through JS, but when refreshed, it all mess up. Fullcalendar adds new events expecting to find 2 rows.

The only easy way to make it work is to alter CSS in order to show the 2 DIV inline, but I don't know how to do it because there are too many elements.

Can you help me?

I create the calendar with this options:

$('#custom-calendar-' + provider.id).fullCalendar({
                defaultView: 'agendaBiWeek',
                height: BackendCalendarDefaultView._getCalendarHeight,
                contentHeight: 100,
                editable: true,
                firstDay: 1,
                snapDuration: '00:30:00',
                timeFormat: timeFormat,
                slotLabelFormat: slotTimeFormat,
                columnHeader: false,
                header: {
                    left: null,
                    center: null,
                    right: null
                },
                // visibleRange: {
                //     start: '2020-03-22',
                //     end: '2020-03-25'
                // },
                views: {
                    agendaBiWeek: {
                        type: 'basic',
                        duration: { weeks: 2 },
                        buttonText: '14 giorni'
                    }
                },
                // Selectable
                selectable: true,
                selectHelper: true,
                select:

                                           .

                                           .

                                           .

                                           .

This is an example of generated calendar:

                        Provider14

                                                        20
                                                        21
                                                        22
                                                        23
                                                        24
                                                        25
                                                        26

14:30 MONTES

                                                        27
                                                        28
                                                        29
                                                        30
                                                        31
                                                        1
                                                        2

Body:
MY SOLUTION:

I simply modified the css like this:

#calendar-page .custom-calendar .fc-scroller{
    overflow-x: scroll !important;
    overflow-y: hidden !important;
    height: auto !important
}

#calendar-page .custom-calendar .fc-scroller > .fc-day-grid {
    width: 200%
}

#calendar-page .custom-calendar .fc-basic-view .fc-body .fc-row {
    display: table-cell;
    width: 50%
}

#calendar-page .custom-calendar .fc-row td {
    width: 90px;
}

#calendar-page .fc th.fc-widget-header-custom {
    width: 100px;
    vertical-align: middle
}

@media (max-width: 767px) {
    #calendar-page .fc th.fc-widget-header-custom {
        display: block;
        width: 100%;
        padding-top: 10px;
        padding-bottom: 10px;
    }

    #calendar-page .fc th.fc-widget-header-custom + td {
        display: block;
        width: 100%;
        border: none
    }

    #calendar-page .custom-calendar .fc-row:first-of-type {
        border-left: 1px solid #ddd
    }
}


问:
Split SQL Server Column value
I have a SQL Server table which name is AbundanceImpact.

```<code>Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95
</code>```

So I want the all integer values only with SUM.

答:
Demo on db<>fiddle

```<code>SELECT SUM(
           CAST(
                RIGHT(Value,
                            LEN(Value) - (CHARINDEX('~', Value)))
                AS  Decimal(18, 2)
               )
      ) Total
FROM
(
    VALUES
    ('Monetary~50'),
    ('Monetary~120'),
    ('Monetary~200'),
    ('Monetary~269.90'),
    ('Monetary~125'),
    ('Magnanimous~50'),
    ('Monetary~22.05'),
    ('Unlimited~500'),
    ('Monetary~150'),
    ('Monetary~300'),
    ('Monetary~21.89'),
    ('Monetary~10.95')
)v(Value)
</code>```

Output

Title: Split SQL Server Column value

Body:
I have a SQL Server table which name is AbundanceImpact.

Monetary~50
Monetary~120
Monetary~200
Monetary~269.90
Monetary~125
Magnanimous~50
Monetary~22.05
Unlimited~500
Monetary~150
Monetary~300
Monetary~21.89
Monetary~10.95

So I want the all integer values only with SUM.

Body:
Demo on db<>fiddle

SELECT SUM(
           CAST(
                RIGHT(Value,
                            LEN(Value) - (CHARINDEX('~', Value)))
                AS  Decimal(18, 2)
               )
      ) Total
FROM
(
    VALUES
    ('Monetary~50'),
    ('Monetary~120'),
    ('Monetary~200'),
    ('Monetary~269.90'),
    ('Monetary~125'),
    ('Magnanimous~50'),
    ('Monetary~22.05'),
    ('Unlimited~500'),
    ('Monetary~150'),
    ('Monetary~300'),
    ('Monetary~21.89'),
    ('Monetary~10.95')
)v(Value)

Output


问:
push view after 2 seconds in swiftui
how to push a view after x seconds in swiftUI without any interaction?</p>

```<code> NavigationView{
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
                    NavigationLink(destination: pageViewUi()) {
                        EmptyView()
                    }
                }
            }
}
</code>```

答:
You need to manage it using a state variable:</p>

```<code>import SwiftUI

struct Home : View {
    @State var isActive = false

    var body: some View {
        NavigationView {
            VStack {
                Text("Home")
                NavigationLink(destination: Details(), isActive: self.$isActive) {
                    EmptyView()
                }
            }
        }.onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                self.isActive.toggle()
            }
        }
    }
}

struct Details : View {
    var body: some View {
        VStack {
            Text("sample code")
        }.navigationBarBackButtonHidden(true) // To hide back button
    }
}
</code>```

Title: push view after 2 seconds in swiftui

Body:
how to push a view after x seconds in swiftUI without any interaction?

 NavigationView{
            .onAppear {
                DispatchQueue.main.asyncAfter(deadline: .now()+1.0) {
                    NavigationLink(destination: pageViewUi()) {
                        EmptyView()
                    }
                }
            }
}

Body:
You need to manage it using a state variable:

import SwiftUI

struct Home : View {
    @State var isActive = false

    var body: some View {
        NavigationView {
            VStack {
                Text("Home")
                NavigationLink(destination: Details(), isActive: self.$isActive) {
                    EmptyView()
                }
            }
        }.onAppear {
            DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
                self.isActive.toggle()
            }
        }
    }
}

struct Details : View {
    var body: some View {
        VStack {
            Text("sample code")
        }.navigationBarBackButtonHidden(true) // To hide back button
    }
}


问:
How to read netstat ports?
I did the netstat -tulpn | grep listen and had the next results:

```<code>tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      14901/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1011/exim4
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      826/ang
tcp6       0      0 :::80                   :::*                    LISTEN      655/apache2
tcp6       0      0 :::22                   :::*                    LISTEN      14901/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1011/exim4
tcp6       0      0 :::443                  :::*                    LISTEN      655/apache2
</code>```

How can you close a port?
Does this configuration have any security issue?

答:
The 1st part of the question - How to close the port ?

You can stop the service listed in the last column, or kill it. Stopping the service makes sure it wont start again on its own. Killing the service means some other process like upstart might start it up again.

The 2nd part of the question - Does this have a security issue ?

I would say yes, unless you have some firewall and access control mechanism in place. The reason is that the ssh service is listening for connections from any source. Ideally, you would restrict this on the firewall (or in the ssh config) and only allow known sources to connect. If you want to go one step further, make ssh listen on another port than the default port (22) so that you can avoid being seen by the most basic/common scanners. I only mention ssh as an example. You will need to review this periodically for any more software/services you deploy on that machine.

Title: How to read netstat ports?

Body:
I did the netstat -tulpn | grep listen and had the next results:

tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      14901/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1011/exim4
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      826/ang
tcp6       0      0 :::80                   :::*                    LISTEN      655/apache2
tcp6       0      0 :::22                   :::*                    LISTEN      14901/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1011/exim4
tcp6       0      0 :::443                  :::*                    LISTEN      655/apache2

How can you close a port?
Does this configuration have any security issue?


问:
Regular Expression for Code
I am having a hard time finding a regular expression that can match these Strings:

```<code>@OSMHO:6:75
@4F0SO:5:56
@40KIR:5:15
@VDXBC:4:13
@WYRRA:6:59
@A4AUN:1118:803
</code>```

As you guys can see these strings start with an '@' followed by 5 alphanumeric characters, then a ':', then a number, then another ':', then another number.
Thanks so much for your help.

答:
Tried this in python:

```<code>>>> str = 'this is a test @WYRRA:6:59tyusd'
>>> match = re.search('\@[A-Z0-9]{5}\:[0-9]+\:[0-9]+',str)
>>> print match.group(0)
@WYRRA:6:59
</code>```

So, the regex is:

\@ == the @ sign escaped (not really needed to be escaped though)

[A-Z0-9]{5} == exactly 5 occurences of any capital letter or numeric digit

\: == the : sign escaped

[0-9]+ == any numeric digit one or more times

The other answers seem correct. You might notice little differences in the regular expressions in each answer like the starting and ending '/' used in javascript.

Title: Regular Expression for Code

Body:
I am having a hard time finding a regular expression that can match these Strings:

@OSMHO:6:75
@4F0SO:5:56
@40KIR:5:15
@VDXBC:4:13
@WYRRA:6:59
@A4AUN:1118:803

As you guys can see these strings start with an '@' followed by 5 alphanumeric characters, then a ':', then a number, then another ':', then another number.
Thanks so much for your help.

Body:
Tried this in python:

>>> str = 'this is a test @WYRRA:6:59tyusd'
>>> match = re.search('\@[A-Z0-9]{5}\:[0-9]+\:[0-9]+',str)
>>> print match.group(0)
@WYRRA:6:59

So, the regex is:

\@ == the @ sign escaped (not really needed to be escaped though)

[A-Z0-9]{5} == exactly 5 occurences of any capital letter or numeric digit

\: == the : sign escaped

[0-9]+ == any numeric digit one or more times

The other answers seem correct. You might notice little differences in the regular expressions in each answer like the starting and ending '/' used in javascript.


问:
Counter in double loop with counting in both internal and external for
I would like to know if there is a well-known formula for the following way of counting:

```<code>count = 0
for i in range(n):
   for j in range(m):
      count = count + 1
   count = count + 10
</code>```

Many thanks in advance,

Cayo

EDIT 1:

Thanks Ernest, you are right, but that is not really the problem. Sorry, I was not clear enough, let me explain better my problem. I don't just want to count, I need use this counter inside the inner loop. I have a 2D flatten array and I want to access just a sub-2D-region of this array. So, actually, what I am doing is:

```<code>count = 0
for i in range(n):
   for j in range(m):
      big_flatten_array(count) = value
      count = count + 1
   count = count + 10
</code>```

EDIT 2:
It doesn't work just using

```<code>count = i * 10 + j
</code>```

Try checking the values:

```<code>count = 0
for i in range(3):
   for j in range():
      k = i * 2 + j
      vec[k] = count
      vec2[k] = i * 10 + j
      count = count + 1
   count = count + 10
</code>```

And you will see the vec and vec2 are not the same...

答:
There is really simple solution

count = n*(10+m)
```

Body:
I would like to know if there is a well-known formula for the following way of counting:

count = 0
for i in range(n):
   for j in range(m):
      count = count + 1
   count = count + 10

Many thanks in advance,

Cayo

EDIT 1:

Thanks Ernest, you are right, but that is not really the problem. Sorry, I was not clear enough, let me explain better my problem. I don't just want to count, I need use this counter inside the inner loop. I have a 2D flatten array and I want to access just a sub-2D-region of this array. So, actually, what I am doing is:

count = 0
for i in range(n):
   for j in range(m):
      big_flatten_array(count) = value
      count = count + 1
   count = count + 10

EDIT 2:
It doesn't work just using

count = i * 10 + j

Try checking the values:

count = 0
for i in range(3):
   for j in range():
      k = i * 2 + j
      vec[k] = count
      vec2[k] = i * 10 + j
      count = count + 1
   count = count + 10

And you will see the vec and vec2 are not the same...


问:
NativeQuery mapping with @SqlResultSetMapping with multiple @Entity classes, is it possible?
I have a situation where I have a single native query which contains data of 2 entity classes, how can I map that data to the entity classes by @SqlResultSetMapping?
For Example

```<code>Native query:- select customer.name, address.area from customer, address where customer.id=address.custid;
</code>```

2 Entity Classes like customer and address with name as a variable in customer and area as a variable in the address entity class.

```<code>Customer class:
@Entity
public class Customer {
    @Id
    private String name;
    getters and setters
.....
.....
.....
}

Address Class entity:
@Entity
public class Address{
    @Id
    private String area;
    getters and setters
.....
.....
.....
}
</code>```

To map the native query with the entity class it can be done by giving @SqlResultSetMapping in entity and give the name of the mapping in the nativeQuery

```<code>Query query = entityManager.createNativeQuery(sbQuery, "checkInfoMapping");
</code>```

it will check the mapping name and map to the respective entity class, this can be done for a single entity class.

Can it be done if I have data from the native query of 2 entity classes, if yes how can I map it to the entity class with native query?

答:
The easiest way is to just use JOIN in your native query as shown below .

Native query :- select c.name,a.area from customer c JOIN address a ON  c.id = a.custid

And hence you have to just provide result set mapping on customer entity.

Body:
I have a situation where I have a single native query which contains data of 2 entity classes, how can I map that data to the entity classes by @SqlResultSetMapping?
For Example

Native query:- select customer.name, address.area from customer, address where customer.id=address.custid;

2 Entity Classes like customer and address with name as a variable in customer and area as a variable in the address entity class.

Customer class:
@Entity
public class Customer {
    @Id
    private String name;
    getters and setters
.....
.....
.....
}

Address Class entity:
@Entity
public class Address{
    @Id
    private String area;
    getters and setters
.....
.....
.....
}

To map the native query with the entity class it can be done by giving @SqlResultSetMapping in entity and give the name of the mapping in the nativeQuery

Query query = entityManager.createNativeQuery(sbQuery, "checkInfoMapping");

it will check the mapping name and map to the respective entity class, this can be done for a single entity class.

Can it be done if I have data from the native query of 2 entity classes, if yes how can I map it to the entity class with native query?


问:
Disable the "Weekend" on SSRS Date Type Parameter
I have a report and the report has parameter (@date) for user to pick a date.

Currently, my parameter (@date) use Parameter Properties > Default Values >  =Today() (For set today date as default paramter).

But I also want the parameter can disable the weekend days.
So the user only can select the weekday.

How can i do it ? Please help.

答:
If you don't mind losing the functionality of the date picker you could set up the @date parameter to use the following query, currently set to +/- 60 days from current date, which you could amend to suit your requirements:</p>

```<code>;with dates ([startDate]) as (
Select convert(date,DateAdd("d",-60,(getdate()))) as [startDate]
union all
Select dateadd(day, 1, [startDate])
from dates
where [startDate] <= DateAdd("d",60,(getdate())))
select [startDate]
from dates
where datepart(dw,[startDate]) in (2,3,4,5,6)
option (maxrecursion 32767)
</code>```

Body:
If you don't mind losing the functionality of the date picker you could set up the @date parameter to use the following query, currently set to +/- 60 days from current date, which you could amend to suit your requirements:

;with dates ([startDate]) as (
Select convert(date,DateAdd("d",-60,(getdate()))) as [startDate]
union all
Select dateadd(day, 1, [startDate])
from dates
where [startDate] <= DateAdd("d",60,(getdate())))
select [startDate]
from dates
where datepart(dw,[startDate]) in (2,3,4,5,6)
option (maxrecursion 32767)