问:
Error: Can't resolve 'angular-ui-bootstrap' with webpack-4

Angular-ui-bootstap import issue in angularJS code using ECMA 6 and webpack-4

**Below is my angular.js & angular-ui-bootstrap versions **

"angular": "1.5.3",
    "angular-ui-bootstrap": "^0.12.1",

Below is my webpack config file:

```<code>module.exports = {
  mode: "development",
  entry: {
    app: "./src/app/modules/index.js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: "babel-loader",
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        use: ["style-loader", "css-loader", "less-loader"]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ["file-loader"]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: ["file-loader"]
      },
      {
        test: require.resolve('jquery'),
        use: [{
          loader: 'expose-loader',
          options: 'jQuery'
        },{
          loader: 'expose-loader',
          options: '$'
        }]
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              attributes: true,
              interpolate: true,
            }
          }
        ],
      }
    ]
  },
  devtool: "inline-source-map",
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: "./src/app/index.html",
      inject: true,
      appMountId: "app",
      filename: "index.html"
    }),
  ],
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dist")
  }
};
</code>```

To import angular-ui-bootstrap in app.js:

```<code>import angular from 'angular';
import uirouter from 'angular-ui-router'
import uibootstrap from 'angular-ui-bootstrap'

export default angular.module('App', [uirouter, uibootstrap ]).name;
</code>```

I am getting following error:

ERROR in ./src/app/modules/core/index.js
      Module not found: Error: Can't resolve 'angular-ui-bootstrap'

And webpack build going failed. I have also tried with directly ui-bootstrap import in my html but its not working

答:
I think you need to upgrade your angular-ui-bootstrap version
Refer: https://github.com/angular-ui/bootstrap

Angular Requirements

UI Bootstrap 1.0 and higher requires Angular 1.4.x or higher and it has been tested with Angular 1.4.8.

Body:
Angular-ui-bootstap import issue in angularJS code using ECMA 6 and webpack-4

**Below is my angular.js & angular-ui-bootstrap versions **

"angular": "1.5.3",
    "angular-ui-bootstrap": "^0.12.1",

Below is my webpack config file:

module.exports = {
  mode: "development",
  entry: {
    app: "./src/app/modules/index.js"
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        use: "babel-loader",
        exclude: /node_modules/
      },
      {
        test: /\.less$/,
        use: ["style-loader", "css-loader", "less-loader"]
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use: ["file-loader"]
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/,
        use: ["file-loader"]
      },
      {
        test: require.resolve('jquery'),
        use: [{
          loader: 'expose-loader',
          options: 'jQuery'
        },{
          loader: 'expose-loader',
          options: '$'
        }]
      },
      {
        test: /\.html$/,
        use: [
          {
            loader: "html-loader",
            options: {
              attributes: true,
              interpolate: true,
            }
          }
        ],
      }
    ]
  },
  devtool: "inline-source-map",
  plugins: [
    new CleanWebpackPlugin(),
    new HtmlWebpackPlugin({
      template: "./src/app/index.html",
      inject: true,
      appMountId: "app",
      filename: "index.html"
    }),
  ],
  output: {
    filename: "[name].bundle.js",
    path: path.resolve(__dirname, "dist")
  }
};

To import angular-ui-bootstrap in app.js:

import angular from 'angular';
import uirouter from 'angular-ui-router'
import uibootstrap from 'angular-ui-bootstrap'

export default angular.module('App', [uirouter, uibootstrap ]).name;

I am getting following error:

ERROR in ./src/app/modules/core/index.js
      Module not found: Error: Can't resolve 'angular-ui-bootstrap'

And webpack build going failed. I have also tried with directly ui-bootstrap import in my html but its not working


来源: stackexchange

问:
ValueError: not enough values to unpack (expected 2, got 1) when trying to unpack dict in python for data labeling with pandas
I created a dictionary that label each api endpoint from my backend to a product group.
Currently I'm trying in python 3.7.6 to use this dictionary to further label all data in the csv that I get from NewRelic with data from all transactions (avg latency, request count, etc.).
The code is teh following:

```<code>response = requests.request(
        "GET", self.url,
        auth=(self.user, self.password)
    )
    with open(
            "data.csv",
            "w",
            encoding='utf8'
    ) as jfp:
        jfp.write(response.text)
    doc = pd.DataFrame(pd.read_csv(self.path, sep=";"))
    doc_dic = pd.Series(doc.ProductGroup.values, index=doc.Action).to_dict()
    resp = pd.DataFrame(pd.read_csv("data.csv", sep=","))
    for k, v in doc_dic:
        if k == resp.Action:
            resp.insert(0, "Product Group", v)
</code>```

but I'm getting the following error:

Traceback (most recent call last):

```<code>File "C:/Project/Dev/analytics/app/data.py", line 53, in <module>
    Data().csv_data()
  File "C:/Project/Dev/analytics/app/data.py", line 42, in csv_data
    for k, v in obj:
ValueError: not enough values to unpack (expected 2, got 1)
</code>```

In the dict obj, the keys are the api endpoint and the values are the product groups where each api endpoint belongs to.
The expected behaviour is, after comparing the dictionary with the csv file returned as response from the request, pandas inserting a column with the proper product group for each endpoint (index 0 for product group and index 1 for endpoints).
What can I do to get this output?

答:
Replace your code:

```<code>for k, v in doc_dic:
        if k == resp.Action:
            resp.insert(0, "Product Group", v)
</code>```

with:

```<code>for k, v in doc_dic.items():
        if k == resp.Action:
            resp.insert(0, "Product Group", v)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I created a dictionary that label each api endpoint from my backend to a product group.
Currently I'm trying in python 3.7.6 to use this dictionary to further label all data in the csv that I get from NewRelic with data from all transactions (avg latency, request count, etc.).
The code is teh following:

response = requests.request(
        "GET", self.url,
        auth=(self.user, self.password)
    )
    with open(
            "data.csv",
            "w",
            encoding='utf8'
    ) as jfp:
        jfp.write(response.text)
    doc = pd.DataFrame(pd.read_csv(self.path, sep=";"))
    doc_dic = pd.Series(doc.ProductGroup.values, index=doc.Action).to_dict()
    resp = pd.DataFrame(pd.read_csv("data.csv", sep=","))
    for k, v in doc_dic:
        if k == resp.Action:
            resp.insert(0, "Product Group", v)

but I'm getting the following error:

Traceback (most recent call last):

File "C:/Project/Dev/analytics/app/data.py", line 53, in <module>
    Data().csv_data()
  File "C:/Project/Dev/analytics/app/data.py", line 42, in csv_data
    for k, v in obj:
ValueError: not enough values to unpack (expected 2, got 1)

In the dict obj, the keys are the api endpoint and the values are the product groups where each api endpoint belongs to.
The expected behaviour is, after comparing the dictionary with the csv file returned as response from the request, pandas inserting a column with the proper product group for each endpoint (index 0 for product group and index 1 for endpoints).
What can I do to get this output?

Body:
Replace your code:

for k, v in doc_dic:
        if k == resp.Action:
            resp.insert(0, "Product Group", v)

with:

for k, v in doc_dic.items():
        if k == resp.Action:
            resp.insert(0, "Product Group", v)


问:
I try move one page other page in react native but routes.js getting issue
I can try to add react-native-router-flux in the react-native project but getting an error while run project please blew screenshot.enter link description here

```<code>{
"name": "AsseProject",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"babel-preset-flow": "^6.23.0",
"babel-preset-react-native": "^4.0.1",
"react": "16.9.0",
"react-addons-pure-render-mixin": "^15.6.2",
"react-native": "^0.61.5"
},
"devDependencies": {
"@babel/core": "7.8.4",
"@babel/runtime": "7.8.4",
"@react-native-community/eslint-config": "0.0.5",
"babel-jest": "24.9.0",
"eslint": "6.8.0",
"jest": "24.9.0",
"metro-react-native-babel-preset": "0.56.4",
"react-test-renderer": "16.9.0"
},
"jest": {
"preset": "react-native"
 }
 }
</code>```

答:
In your scenario I think you have not install the native dependencies in order to work with router flux.

SOLUTION

Install native dependencies used by React Native Router - Link

Since the v4.2.0-beta.x is based on React Navigation v4.x you need to install react-navigation v4.x native dependencies before install router flux.

Install navigation using this

```<code>npm install react-navigation
</code>```

After that run this code and install other dependencies

```<code>npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view
</code>```

Finally you can install router flux using this command

```<code>npm install --save react-native-router-flux
</code>```

Clean your project and run the project using react-native run-android / react-native run-ios

NOTE : If you are using react-navigation V5.x you will not be able to use router flux. Therefore make sure you have installed react-navigation v4.x

Body:
I can try to add react-native-router-flux in the react-native project but getting an error while run project please blew screenshot.enter link description here

{
"name": "AsseProject",
"version": "0.0.1",
"private": true,
"scripts": {
"android": "react-native run-android",
"ios": "react-native run-ios",
"start": "react-native start",
"test": "jest",
"lint": "eslint ."
},
"dependencies": {
"babel-preset-flow": "^6.23.0",
"babel-preset-react-native": "^4.0.1",
"react": "16.9.0",
"react-addons-pure-render-mixin": "^15.6.2",
"react-native": "^0.61.5"
},
"devDependencies": {
"@babel/core": "7.8.4",
"@babel/runtime": "7.8.4",
"@react-native-community/eslint-config": "0.0.5",
"babel-jest": "24.9.0",
"eslint": "6.8.0",
"jest": "24.9.0",
"metro-react-native-babel-preset": "0.56.4",
"react-test-renderer": "16.9.0"
},
"jest": {
"preset": "react-native"
 }
 }

Body:
In your scenario I think you have not install the native dependencies in order to work with router flux.

SOLUTION

Install native dependencies used by React Native Router - Link

Since the v4.2.0-beta.x is based on React Navigation v4.x you need to install react-navigation v4.x native dependencies before install router flux.

Install navigation using this

npm install react-navigation

After that run this code and install other dependencies

npm install react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view

Finally you can install router flux using this command

npm install --save react-native-router-flux

Clean your project and run the project using react-native run-android / react-native run-ios

NOTE : If you are using react-navigation V5.x you will not be able to use router flux. Therefore make sure you have installed react-navigation v4.x


问:
Playing with rowspans; how are table cells placed?
I am trying to create brackets using tables and I've done all the calculations for the rowspan heights for all the cell elements, but I'm having trouble with how it keeps placing the cells into the table with rowspans defined in previous rows. See this example:

```<code><table border="1">
<tr>
<td style="min-width: 100px">Begin</td>
<td style="min-width: 10px"></td>
<td style="min-width: 10px"></td>
<td style="min-width: 100px">End</td>
</tr>
<tr>
<td colspan="4" style="height: 20px"></td>
</tr>
<tr>
<td rowspan="2">Seed 1</td>
<td rowspan="2"></td>
<td rowspan="5"></td>
<td rowspan="3"></td>
</tr>
<tr>
<td></td>
</tr>
</table>
</code>```

Here, the current heights for each column (excluding the rows above because they are already even) are at 2, 2, 5, and 3. However when adding another element in the next row just to see where it gets placed in the table, it is rendered to the right of the existing row, creating a fifth column that shouldn't exist. Why is it not placed in the first column making the column heights 3, 2, 5, and 3? I was under the impression that the table would put the element in the next shortest column. Am I completely off with tables? What should I do to make this element actually appear in the first column where it's supposed to be? Does the entire table need to be completed in order for this to render correctly (usually tables will just leave blank space where cells have not been placed)?

I searched on Google for an hour and couldn't find anything pertaining to how the cells are actually supposed to be placed when the HTML is processed by the browser. There's too much other garbage about how tables work and yada yada ya.

答:
Actually, what is happening is that the final cell is trying to go in the next row immediately below the first row.  However, the next row is already full, because every cell is at least two rows high.  The first row contains [Seed 1] [] [] [], and the second row contains the bottom part of the first two cells, and the middle of the third and fourth cell from the row above.

If you make an empty row and move down to the third row below, you see the cells start to appear in the table as you expected:

```<code><tr></tr>
<tr>
    <td>Row 3, Cell 1</td>
    <td>Row 3, Cell 2</td>
    <!-- no room left, now move to row 4 -->
</tr>
</code>```

Cells don't automatically flow from one row to the next.  You have to explicitly close the row and start the next row when each row is full.  In your case, you entirely filled two full rows at once, so you have to skip a row to get to the next row with available cells.

Here is a sample that shows the cells working as you expect: http://jsfiddle.net/UmLqw/1/

ContentLicense: CC BY-SA 3.0

Body:
I am trying to create brackets using tables and I've done all the calculations for the rowspan heights for all the cell elements, but I'm having trouble with how it keeps placing the cells into the table with rowspans defined in previous rows. See this example:

Begin

End

Seed 1

Here, the current heights for each column (excluding the rows above because they are already even) are at 2, 2, 5, and 3. However when adding another element in the next row just to see where it gets placed in the table, it is rendered to the right of the existing row, creating a fifth column that shouldn't exist. Why is it not placed in the first column making the column heights 3, 2, 5, and 3? I was under the impression that the table would put the element in the next shortest column. Am I completely off with tables? What should I do to make this element actually appear in the first column where it's supposed to be? Does the entire table need to be completed in order for this to render correctly (usually tables will just leave blank space where cells have not been placed)?

I searched on Google for an hour and couldn't find anything pertaining to how the cells are actually supposed to be placed when the HTML is processed by the browser. There's too much other garbage about how tables work and yada yada ya.

Body:
Actually, what is happening is that the final cell is trying to go in the next row immediately below the first row.  However, the next row is already full, because every cell is at least two rows high.  The first row contains [Seed 1] [] [] [], and the second row contains the bottom part of the first two cells, and the middle of the third and fourth cell from the row above.

If you make an empty row and move down to the third row below, you see the cells start to appear in the table as you expected:

<tr></tr>
<tr>
    <td>Row 3, Cell 1</td>
    <td>Row 3, Cell 2</td>
    <!-- no room left, now move to row 4 -->
</tr>

Cells don't automatically flow from one row to the next.  You have to explicitly close the row and start the next row when each row is full.  In your case, you entirely filled two full rows at once, so you have to skip a row to get to the next row with available cells.

Here is a sample that shows the cells working as you expect: http://jsfiddle.net/UmLqw/1/


问:
How to waitFor when page refreshes in Puppeteer?
I have an app I'm working with that is behaving like this... You visit a url /refresh, and it loads the page with a loader/spinner/bar showing for like 5 seconds, then it refreshes the page after it's done. It does this so it can load the latest data that was computed during /refresh.

Right now I am just setting a timeout longer than the loader will most likely stay around, but this is brittle because a bad network connection could put it over the line.

How can I instead "watch" for when the refresh happens? What technique would you recommend. It seems to start to get hairy pretty fast.

Into the nitty gritty, when the loader is showing, when it finishes it is gone for like a half a second before the page reload. So I can't just wait til the loader is gone. It seems like I need to keep some sort of state variable around in the DOM like in localStorage, but can't pinpoint it. Would love some help.

答:
well you could "watch" for the element that display the data using page.$(selector), or if no such element you could also wait for the specific request 's response:

```<code>const waitForResponse = (page, url) => {
    return new Promise(resolve => {
        page.on("response", function callback(response){
            if (response.url() === url) {
                resolve(response);
                page.removeListener("response",callback)
            }
        })
    })
};

const res = await waitForResponse(page,"url of the request you want to wait for");
</code>```

Wait for Network request before continuing process

Body:
well you could "watch" for the element that display the data using page.$(selector), or if no such element you could also wait for the specific request 's response:

const waitForResponse = (page, url) => {
    return new Promise(resolve => {
        page.on("response", function callback(response){
            if (response.url() === url) {
                resolve(response);
                page.removeListener("response",callback)
            }
        })
    })
};

const res = await waitForResponse(page,"url of the request you want to wait for");

Wait for Network request before continuing process


问:
Is it good practice to create SQL view by joining tables?
I have this question, is there any performance issue with creating SQL view by joining two or more tables?
Is it good practice or one should create another table with joins and create view on top of it?</p>

答:
Yes, you can create view by joining two or more tables. For more performance efficient views check on creating indexed views.
Basically, views are used to hide the internal column and table details from user by providing only required interface(renamed columns and data).</p>


问:
React, typescript and prop-types: how to use own type?
I have a string type literal, something in the form of type MyType = 'str1' | 'str2' | 'str3' and I want one of my props to accept only this type, but I have no idea how to tell PropTypes.

I've tried to use propTypes.oneOf(['str1', 'str2', 'str3']) but then typescript infer it as a normal string, which I don't want.

答:
Since this is type checking with TypeScript, you don't try to do it at the React runtime level (propTypes), you do it at the TypeScript level.

Your component should use your string literal type in its props type:

```<code>type MyComponentProps = {
    propName: MyType;
}
</code>```

Then if its a class component:

```<code>class MyComponent extends React.Component<MyComponentProps, /*...your state type here...*/> {
    // ...
}
</code>```

Or if you're using a functional component:

```<code>const MyComponent: React.FC<MyComponentProps> = ({propName}) => {
    // ...
};
</code>```

Body:
Since this is type checking with TypeScript, you don't try to do it at the React runtime level (propTypes), you do it at the TypeScript level.

Your component should use your string literal type in its props type:

type MyComponentProps = {
    propName: MyType;
}

Then if its a class component:

class MyComponent extends React.Component<MyComponentProps, /*...your state type here...*/> {
    // ...
}

Or if you're using a functional component:

const MyComponent: React.FC<MyComponentProps> = ({propName}) => {
    // ...
};


问:
Flutter - Handler != null is not true
Can anyone explain me this error log

```<code>Another exception was thrown: 'package:flutter/src/semantics/semantics.dart': Failed assertion: line 2847 pos 12: 'handler != null': is not true
</code>```

It does not affect in any screen but this does keep coming when I change child of a certain controller through setState((){}).

Thanks for your help,

答:
If parent widget is WidgetApp, change it to Material as most of the widget results in the same exception because of their must needed parent: MaterialApp.

If MaterialApp is already there and still resulting with the exception, wrap it with "ExcludeSemantics" widget.

Check out this link for more...

Title: Flutter - Handler != null is not true

Body:
Can anyone explain me this error log

Another exception was thrown: 'package:flutter/src/semantics/semantics.dart': Failed assertion: line 2847 pos 12: 'handler != null': is not true

It does not affect in any screen but this does keep coming when I change child of a certain controller through setState((){}).

Thanks for your help,


问:
File to import not found or unreadable: node_modules/bootstrap/scss/functions
I am using core UI version 2.1.1 with react.

When I try to run npm start I got this error.

```<code>(/Users/umairsaleem/Desktop/abc/abc/node_modules/css-loader??ref--6-oneOf-5-1!/Users/umairsaleem/Desktop/abc/abc/node_modules/postcss-loader/src??postcss!/Users/umairsaleem/Desktop/abc/abc/node_modules/sass-loader/lib/loader.js??ref--6-oneOf-5-3!./src/App.scss)
@import "node_modules/bootstrap/scss/functions"; // from bootstrap node_modules
^

File to import not found or unreadable: node_modules/bootstrap/scss/functions.
      in ......
</code>```

答: run npm i -S bootstrap, you're missing it in your project and it's a dependency. if you have a package.json file there you can try just running npm install or if you have a yarn.lock file there install yarn and run yarn

Body:
I am using core UI version 2.1.1 with react.

When I try to run npm start I got this error.

(/Users/umairsaleem/Desktop/abc/abc/node_modules/css-loader??ref--6-oneOf-5-1!/Users/umairsaleem/Desktop/abc/abc/node_modules/postcss-loader/src??postcss!/Users/umairsaleem/Desktop/abc/abc/node_modules/sass-loader/lib/loader.js??ref--6-oneOf-5-3!./src/App.scss)
@import "node_modules/bootstrap/scss/functions"; // from bootstrap node_modules
^

File to import not found or unreadable: node_modules/bootstrap/scss/functions.
      in ......


问:
My angular 2 app takes a long time to load for first time users, I need help to speed it up
Below I have pasted in my app.ts file.

I'm using angular2, with firebase and typescript.

Is the reason its slow because I have a lot of routes and I'm injecting a lot of files?

Also, my app works fine its just for first time users visiting the homepage I have this issue for.

I'm not sure if the bootstrap can be improved at the bottom or if I'm doing anything wrong.

This is my app.ts file:

```<code>import {Component, bind, provide, Injectable} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser'
import {NgIf} from 'angular2/common';
import {Router, Location, ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF, CanActivate, OnActivate,
    ComponentInstruction} from 'angular2/router';
import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';
import {ANGULAR2_GOOGLE_MAPS_PROVIDERS} from 'angular2-google-maps/core';
import {enableProdMode} from 'angular2/core';
enableProdMode();

import {LoggedInRouterOutlet} from './interceptor';

import {AuthService} from './services/authService/authService';
import {SocialService} from './services/socialService/socialService';
import {UserService} from './services/userService/userService';
import {OrganisationService} from './services/organisationService/organisationService';
import {NotificationService} from './services/notificationService/notificationService';
import {EmailService} from './services/emailService/emailService';

import {UserProfile} from './models/profile/profile';
import {Organisation} from './models/organisation/organisation';

import {HeaderNavigation} from './components/header/header';
import {HeaderNavigationLoggedIn} from './components/header/headerNavigationLoggedIn';
import {HeaderNavigationLoggedInCompany} from './components/header/headerNavigationLoggedInCompany';
import {Footer} from './components/footer/footer';
import {SideMenuCompany} from './components/header/sideMenuCompany';
import {SideMenuUser} from './components/header/sideMenuUser';
import {Splash} from './components/splash/splash';

import {CreateJob} from './components/createJob/createJob';
import {SearchJobs} from './components/searchJobs/searchJobs';
import {Login} from './components/login/login';
import {Applications} from './components/applications/applications';
import {Register} from './components/register/register';
import {ForgotPassword} from './components/forgotpassword/forgotpassword';
import {ChangePassword} from './components/changepassword/changepassword';
import {ChangeEmail} from './components/changeemail/changeemail';
import {SocialRegister} from './components/socialregister/socialregister';
import {Admin} from './components/admin/admin';
import {Contact} from './components/contact/contact';
import {SearchUsers} from './components/searchusers/searchusers';

import {Jobs} from './components/job/jobs';
import {CompanyProfile} from './components/company/company';
import {Home} from './components/home/home';
import {Dashboard} from './components/dashboard/dashboard';
import {Profile} from './components/profile/profile';
import {UserApplications} from './components/userApplications/userApplications';

@Component({
    selector: 'app',
    providers: [UserService, UserProfile, OrganisationService, Organisation],
    template: `

        <Splash *ngIf="isLoggedIn"></Splash>

        <HeaderNavigation *ngIf="!isLoggedIn"></HeaderNavigation>

        <HeaderNavigationLoggedIn *ngIf="isLoggedIn && isUserLogin"></HeaderNavigationLoggedIn>
        <HeaderNavigationLoggedInCompany *ngIf="isLoggedIn && isCompanyLogin"></HeaderNavigationLoggedInCompany>

        <SideMenuCompany *ngIf="isLoggedIn && isCompanyLogin"></SideMenuCompany>
        <SideMenuUser *ngIf="isLoggedIn && isUserLogin"></SideMenuUser>

        <div class="content">
            <router-outlet></router-outlet>
        </div>
    `,
    directives: [RouterOutlet, RouterLink, Splash, HeaderNavigation, HeaderNavigationLoggedIn, NgIf, HeaderNavigationLoggedInCompany, SideMenuCompany, SideMenuUser, Footer, LoggedInRouterOutlet]
})

@RouteConfig([
    { path: '/', component: Home, as: 'Home', data:{title: 'Welcome Home'}},
    { path: '/home', component: Home, as: 'Home', useAsDefault: true},
    { path: '/login', component: Login, as: 'Login' },
    { path: '/register/:id', component: Register, as: 'Register' },
    { path: '/forgotpassword', component: ForgotPassword, as: 'ForgotPassword' },
    { path: '/dashboard', component: Dashboard, as: 'Dashboard' },
    { path: '/search', component: SearchJobs, as: 'Search' },
    { path: '/profile', component: Profile, as: 'Profile' },
    { path: '/settings', component: CompanyProfile, as: 'Settings' },
    { path: '/jobs', component: Jobs, as: 'Jobs' },
    { path: '/password', component: ChangePassword, as: 'Password' },
    { path: '/email', component: ChangeEmail, as: 'Email' },
    { path: '/applications', component: Applications, as: 'Applications' },
    { path: '/socialRegister/:id', component: SocialRegister, as: 'SocialRegister' },
    { path: '/socialRegister', component: SocialRegister, as: 'SocialRegister' },
    { path: '/applys', component: UserApplications, as: 'Applys' },
    { path: '/contact', component: Contact, as: 'Contact' },
    { path: '/searchTeachers', component: SearchUsers, as: 'SearchUsers' },
    { path: '/createJob', component: CreateJob, as: 'CreateJob' },
    { path: '/adminmarkchris2016', component: Admin, as: 'AdminMarkChris2016' },

    { path:'/**', redirectTo: ['Home']}
])

@Injectable()

export class AppComponent {
    router: Router;
    location: Location;
    authService: AuthService;
    userService: UserService
    isLoggedIn: boolean = false;
    isCompanyLogin: boolean = false;
    isUserLogin: boolean = false;
    userProfile: UserProfile;

    constructor(_router: Router, _location: Location, _authService: AuthService, _userService: UserService, _userProfile: UserProfile){
        this.router = _router;
        this.location = _location;
        this.authService = _authService;
        this.userService = _userService;
        this.userProfile = _userProfile;

        this.isUserLoggedIn(this.location.path());

        //On refresh
        this.router.subscribe((currentRoute) => {
            this.isUserLoggedIn(currentRoute);
        })
    }

    isUserLoggedIn(currentRoute): void{
        this.authService.checkIfLoggedIn().then((response) => {
            this.isLoggedIn = response

            if(this.isLoggedIn){
                this.isUserOrganisationOrTeacher();
            }

            if(currentRoute.substring(0, 14) == "socialRegister" || currentRoute == "socialRegister" || currentRoute == "home" || currentRoute == "contact" || currentRoute == "" || currentRoute == "forgotpassword" || currentRoute == "login" || currentRoute.substring(0, 8) == "register"){
                this.isCompanyLogin = false;
                this.isUserLogin = false;
                this.isLoggedIn = false;
            }
        });
    }

    isUserOrganisationOrTeacher(): void{
        this.userService.checkIfProfileExists().then((response) => {
            this.isCompanyLogin = false;
            this.isUserLogin = false;

            if(response){
                this.isUserLogin = true;
                this.isCompanyLogin = false;
            }else{
                this.isCompanyLogin = true;
                this.isUserLogin = false;
            }
        });
    }
}

bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'}), HTTP_PROVIDERS, AuthService, SocialService, UserService, EmailService, OrganisationService, NotificationService, ANGULAR2_GOOGLE_MAPS_PROVIDERS]);
</code>```

答: The main issue is zone.js on polyfills, Zone.js slowdown the app considerable</p>

Body:
Below I have pasted in my app.ts file.

I'm using angular2, with firebase and typescript.

Is the reason its slow because I have a lot of routes and I'm injecting a lot of files?

Also, my app works fine its just for first time users visiting the homepage I have this issue for.

I'm not sure if the bootstrap can be improved at the bottom or if I'm doing anything wrong.

This is my app.ts file:

import {Component, bind, provide, Injectable} from 'angular2/core';
import {bootstrap} from 'angular2/platform/browser'
import {NgIf} from 'angular2/common';
import {Router, Location, ROUTER_BINDINGS, RouterOutlet, RouteConfig, RouterLink, ROUTER_PROVIDERS, APP_BASE_HREF, CanActivate, OnActivate,
    ComponentInstruction} from 'angular2/router';
import {HTTP_PROVIDERS, Http, Headers} from 'angular2/http';
import {ANGULAR2_GOOGLE_MAPS_PROVIDERS} from 'angular2-google-maps/core';
import {enableProdMode} from 'angular2/core';
enableProdMode();

import {LoggedInRouterOutlet} from './interceptor';

import {AuthService} from './services/authService/authService';
import {SocialService} from './services/socialService/socialService';
import {UserService} from './services/userService/userService';
import {OrganisationService} from './services/organisationService/organisationService';
import {NotificationService} from './services/notificationService/notificationService';
import {EmailService} from './services/emailService/emailService';

import {UserProfile} from './models/profile/profile';
import {Organisation} from './models/organisation/organisation';

import {HeaderNavigation} from './components/header/header';
import {HeaderNavigationLoggedIn} from './components/header/headerNavigationLoggedIn';
import {HeaderNavigationLoggedInCompany} from './components/header/headerNavigationLoggedInCompany';
import {Footer} from './components/footer/footer';
import {SideMenuCompany} from './components/header/sideMenuCompany';
import {SideMenuUser} from './components/header/sideMenuUser';
import {Splash} from './components/splash/splash';

import {CreateJob} from './components/createJob/createJob';
import {SearchJobs} from './components/searchJobs/searchJobs';
import {Login} from './components/login/login';
import {Applications} from './components/applications/applications';
import {Register} from './components/register/register';
import {ForgotPassword} from './components/forgotpassword/forgotpassword';
import {ChangePassword} from './components/changepassword/changepassword';
import {ChangeEmail} from './components/changeemail/changeemail';
import {SocialRegister} from './components/socialregister/socialregister';
import {Admin} from './components/admin/admin';
import {Contact} from './components/contact/contact';
import {SearchUsers} from './components/searchusers/searchusers';

import {Jobs} from './components/job/jobs';
import {CompanyProfile} from './components/company/company';
import {Home} from './components/home/home';
import {Dashboard} from './components/dashboard/dashboard';
import {Profile} from './components/profile/profile';
import {UserApplications} from './components/userApplications/userApplications';

@Component({
    selector: 'app',
    providers: [UserService, UserProfile, OrganisationService, Organisation],
    template: `

        <Splash *ngIf="isLoggedIn"></Splash>

        <HeaderNavigation *ngIf="!isLoggedIn"></HeaderNavigation>

        <HeaderNavigationLoggedIn *ngIf="isLoggedIn && isUserLogin"></HeaderNavigationLoggedIn>
        <HeaderNavigationLoggedInCompany *ngIf="isLoggedIn && isCompanyLogin"></HeaderNavigationLoggedInCompany>

        <SideMenuCompany *ngIf="isLoggedIn && isCompanyLogin"></SideMenuCompany>
        <SideMenuUser *ngIf="isLoggedIn && isUserLogin"></SideMenuUser>

            <router-outlet></router-outlet>

    `,
    directives: [RouterOutlet, RouterLink, Splash, HeaderNavigation, HeaderNavigationLoggedIn, NgIf, HeaderNavigationLoggedInCompany, SideMenuCompany, SideMenuUser, Footer, LoggedInRouterOutlet]
})

@RouteConfig([
    { path: '/', component: Home, as: 'Home', data:{title: 'Welcome Home'}},
    { path: '/home', component: Home, as: 'Home', useAsDefault: true},
    { path: '/login', component: Login, as: 'Login' },
    { path: '/register/:id', component: Register, as: 'Register' },
    { path: '/forgotpassword', component: ForgotPassword, as: 'ForgotPassword' },
    { path: '/dashboard', component: Dashboard, as: 'Dashboard' },
    { path: '/search', component: SearchJobs, as: 'Search' },
    { path: '/profile', component: Profile, as: 'Profile' },
    { path: '/settings', component: CompanyProfile, as: 'Settings' },
    { path: '/jobs', component: Jobs, as: 'Jobs' },
    { path: '/password', component: ChangePassword, as: 'Password' },
    { path: '/email', component: ChangeEmail, as: 'Email' },
    { path: '/applications', component: Applications, as: 'Applications' },
    { path: '/socialRegister/:id', component: SocialRegister, as: 'SocialRegister' },
    { path: '/socialRegister', component: SocialRegister, as: 'SocialRegister' },
    { path: '/applys', component: UserApplications, as: 'Applys' },
    { path: '/contact', component: Contact, as: 'Contact' },
    { path: '/searchTeachers', component: SearchUsers, as: 'SearchUsers' },
    { path: '/createJob', component: CreateJob, as: 'CreateJob' },
    { path: '/adminmarkchris2016', component: Admin, as: 'AdminMarkChris2016' },

    { path:'/**', redirectTo: ['Home']}
])

@Injectable()

export class AppComponent {
    router: Router;
    location: Location;
    authService: AuthService;
    userService: UserService
    isLoggedIn: boolean = false;
    isCompanyLogin: boolean = false;
    isUserLogin: boolean = false;
    userProfile: UserProfile;

    constructor(_router: Router, _location: Location, _authService: AuthService, _userService: UserService, _userProfile: UserProfile){
        this.router = _router;
        this.location = _location;
        this.authService = _authService;
        this.userService = _userService;
        this.userProfile = _userProfile;

        this.isUserLoggedIn(this.location.path());

        //On refresh
        this.router.subscribe((currentRoute) => {
            this.isUserLoggedIn(currentRoute);
        })
    }

    isUserLoggedIn(currentRoute): void{
        this.authService.checkIfLoggedIn().then((response) => {
            this.isLoggedIn = response

            if(this.isLoggedIn){
                this.isUserOrganisationOrTeacher();
            }

            if(currentRoute.substring(0, 14) == "socialRegister" || currentRoute == "socialRegister" || currentRoute == "home" || currentRoute == "contact" || currentRoute == "" || currentRoute == "forgotpassword" || currentRoute == "login" || currentRoute.substring(0, 8) == "register"){
                this.isCompanyLogin = false;
                this.isUserLogin = false;
                this.isLoggedIn = false;
            }
        });
    }

    isUserOrganisationOrTeacher(): void{
        this.userService.checkIfProfileExists().then((response) => {
            this.isCompanyLogin = false;
            this.isUserLogin = false;

            if(response){
                this.isUserLogin = true;
                this.isCompanyLogin = false;
            }else{
                this.isCompanyLogin = true;
                this.isUserLogin = false;
            }
        });
    }
}

bootstrap(AppComponent, [ROUTER_PROVIDERS, provide(APP_BASE_HREF, {useValue: '/'}), HTTP_PROVIDERS, AuthService, SocialService, UserService, EmailService, OrganisationService, NotificationService, ANGULAR2_GOOGLE_MAPS_PROVIDERS]);


问:
How to directly initialize a HashMap (in a literal way)?
Is there some way of initializing a Java HashMap like this?:

```<code>Map<String,String> test =
    new HashMap<String, String>{"test":"test","test":"test"};
</code>```

What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastest way to put some "final/static" values in a map that never change and are known in advance when creating the Map.

答:
Unfortunately, using varargs if the type of the keys and values are not the same is not very reasonable as you'd have to use Object... and lose type safety completely. If you always want to create e.g. a Map<String, String>, of course a toMap(String... args) would be possible though, but not very pretty as it would be easy to mix up keys and values, and an odd number of arguments would be invalid.

You could create a sub-class of HashMap that has a chainable method like

```<code>public class ChainableMap<K, V> extends HashMap<K, V> {
  public ChainableMap<K, V> set(K k, V v) {
    put(k, v);
    return this;
  }
}
</code>```

and use it like new ChainableMap<String, Object>().set("a", 1).set("b", "foo")

Another approach is to use the common builder pattern:

```<code>public class MapBuilder<K, V> {
  private Map<K, V> mMap = new HashMap<>();

  public MapBuilder<K, V> put(K k, V v) {
    mMap.put(k, v);
    return this;
  }

  public Map<K, V> build() {
    return mMap;
  }
}
</code>```

and use it like new MapBuilder<String, Object>().put("a", 1).put("b", "foo").build();

However, the solution I've used now and then utilizes varargs and the Pair class:

```<code>public class Maps {
  public static <K, V> Map<K, V> of(Pair<K, V>... pairs) {
    Map<K, V> = new HashMap<>();

    for (Pair<K, V> pair : pairs) {
      map.put(pair.first, pair.second);
    }

    return map;
  }
}
</code>```

Map<String, Object> map = Maps.of(Pair.create("a", 1), Pair.create("b", "foo");

The verbosity of Pair.create() bothers me a bit, but this works quite fine. If you don't mind static imports you could of course create a helper:

```<code>public <K, V> Pair<K, V> p(K k, V v) {
  return Pair.create(k, v);
}
</code>```

Map<String, Object> map = Maps.of(p("a", 1), p("b", "foo");

(Instead of Pair one could imagine using Map.Entry, but since it's an interface it requires an implementing class and/or a helper factory method. It's also not immutable, and contains other logic not useful for this task.)

Body:
Is there some way of initializing a Java HashMap like this?:

Map<String,String> test =
    new HashMap<String, String>{"test":"test","test":"test"};

What would be the correct syntax? I have not found anything regarding this. Is this possible? I am looking for the shortest/fastest way to put some "final/static" values in a map that never change and are known in advance when creating the Map.

Body:
Unfortunately, using varargs if the type of the keys and values are not the same is not very reasonable as you'd have to use Object... and lose type safety completely. If you always want to create e.g. a Map<String, String>, of course a toMap(String... args) would be possible though, but not very pretty as it would be easy to mix up keys and values, and an odd number of arguments would be invalid.

You could create a sub-class of HashMap that has a chainable method like

public class ChainableMap<K, V> extends HashMap<K, V> {
  public ChainableMap<K, V> set(K k, V v) {
    put(k, v);
    return this;
  }
}

and use it like new ChainableMap<String, Object>().set("a", 1).set("b", "foo")

Another approach is to use the common builder pattern:

public class MapBuilder<K, V> {
  private Map<K, V> mMap = new HashMap<>();

  public MapBuilder<K, V> put(K k, V v) {
    mMap.put(k, v);
    return this;
  }

  public Map<K, V> build() {
    return mMap;
  }
}

and use it like new MapBuilder<String, Object>().put("a", 1).put("b", "foo").build();

However, the solution I've used now and then utilizes varargs and the Pair class:

public class Maps {
  public static <K, V> Map<K, V> of(Pair<K, V>... pairs) {
    Map<K, V> = new HashMap<>();

    for (Pair<K, V> pair : pairs) {
      map.put(pair.first, pair.second);
    }

    return map;
  }
}

Map<String, Object> map = Maps.of(Pair.create("a", 1), Pair.create("b", "foo");

The verbosity of Pair.create() bothers me a bit, but this works quite fine. If you don't mind static imports you could of course create a helper:

public <K, V> Pair<K, V> p(K k, V v) {
  return Pair.create(k, v);
}

Map<String, Object> map = Maps.of(p("a", 1), p("b", "foo");

(Instead of Pair one could imagine using Map.Entry, but since it's an interface it requires an implementing class and/or a helper factory method. It's also not immutable, and contains other logic not useful for this task.)


问:
Getting 400 from samltest.id when attempting SP-initiated worflow
I have used itfoxtec's SAML2 library to implement an SP in my ASP.NET MVC app. I am testing using samltest.id as the IdP. The IdP-initiated workflow works perfectly, but the SP-initiated workflow always gets a 400 error back from samltest.id. I have attempted to look through samltest.id's log to see if an error is being recorded there for my request, but I cannot seem to find anything there.

This is the Action that handles the URL that he user would go to when initiating SSO:

```<code>public ActionResult SSOLogin() {
    LogManager logger = new LogManager("SSOLogin");

    string hostname = this.GetHostname();
    SchoolSettings settings = this.GetClientSettings();

    if (settings.UseSAMLSSO) {
        Saml2Configuration samlConfig = null;
        try {
            samlConfig = SamlConfigLoader.GetSaml2Config(HttpContext, settings, this.IsSandbox());
        } catch (Exception e) {
            logger.exception($"loading Saml2Configuration for {hostname}", e);
        }

        if (samlConfig != null) {
            try {
                var binding = new Saml2RedirectBinding();

                binding.SetRelayStateQuery(new Dictionary<string, string> { { "Home/Index", Url.Content("~/") } });

                return binding.Bind(new Saml2AuthnRequest(samlConfig) {

                }).ToActionResult();
            } catch (Exception e) {
                logger.error($"Exception redirecting to IdP. {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
                ViewBag.ssoerror = $"Error redirecting to IdP for {hostname}";
            }
        } else {
            logger.critical($"Could not load SAML2 configuration for {hostname}");
            ViewBag.ssoerror = $"Could not load SAML2 configuration for {hostname}";
        }
    } else {
        ViewBag.ssoerror = "SSO is not configured for this client. Please contact Support";
    }

    return Redirect("/Home/SSOError");
}
</code>```

The method that loads a client-specific metadata looks like this:

```<code>public static Saml2Configuration GetSaml2Config(HttpContextBase context, SchoolSettings forSchool, bool forSandbox) {
    LogManager log = new LogManager("getSaml2Config");

    Saml2Configuration config = new Saml2Configuration();
    if (!forSandbox) {
        config.Issuer = _saml2Issuer;
    } else {
        config.Issuer = _saml2IssuerSandbox;
    }

    config.SignatureAlgorithm = _saml2SignatureAlgo;
    config.CertificateValidationMode = X509CertificateValidationMode.None;
    config.RevocationMode = (X509RevocationMode)Enum.Parse(typeof(X509RevocationMode), ConfigurationManager.AppSettings["Saml2:RevocationMode"]);
    config.AllowedAudienceUris.Add(config.Issuer);

    var entityDescriptor = new EntityDescriptor();
    if (forSchool.SAMLMetadataLocationIsUrl) {
        try {
            entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(forSchool.SAMLMetadataLocation));
        } catch (Exception e) {
            log.error($"Exception caught loading metadata from school {forSchool.Hostname} at URL {forSchool.SAMLMetadataLocation}\n Exception {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
            entityDescriptor.IdPSsoDescriptor = null;
        }
    } else {
        var schoolMetadataPath = context.Server.MapPath("~/App_Data/SAMLMetadata/" + forSchool.SAMLMetadataLocation);
        log.info($"Loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}");
        try {
            entityDescriptor.ReadIdPSsoDescriptorFromFile(schoolMetadataPath);
        } catch (IOException ioe) {
            log.error($"IOException caught loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}: {ioe.Message}\n{ioe.StackTrace}");
            entityDescriptor.IdPSsoDescriptor = null;
        } catch (Exception e) {
            log.error($"Exception caught loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}\n Exception {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
            entityDescriptor.IdPSsoDescriptor = null;
        }
    }

    if (entityDescriptor.IdPSsoDescriptor != null) {
        if (entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.Count() > 0) {
            config.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
        } else {
            log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SingleSignOnServices that could be parsed.");
        }

        if (entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.Count() > 0) {
            config.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
        } else {
            log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SingleLogoutServices that could be parsed.");
        }

        if (entityDescriptor.IdPSsoDescriptor.SigningCertificates.Count() > 0) {
            config.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
        } else {
            log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SigningCertificates that could be parsed.");
        }
    } else {
        throw new Exception("IdPSsoDescriptor not loaded from metadata.");
    }

    return config;
}
</code>```

If it would help to clarify the situation, I can add the code for the AssertionConsumerService Action which works perfectly in an IdP-initiated scenario.

答:
Your code looks correct.

It is probably an integration issue but very hard to find if the IdP do not log an error message.

What error status message do you get back instead of success, maybe that tells you something.

Maybe the IdP do not accept the SAML 2.0 Authn Response, here is something to look for:

The config.SingleSignOnDestination probably is required

Meybe the IdP requere the request to be signed

It is also possible to add other attributes in the request, do the IdP documentation describe any requirements?

Body:
I have used itfoxtec's SAML2 library to implement an SP in my ASP.NET MVC app. I am testing using samltest.id as the IdP. The IdP-initiated workflow works perfectly, but the SP-initiated workflow always gets a 400 error back from samltest.id. I have attempted to look through samltest.id's log to see if an error is being recorded there for my request, but I cannot seem to find anything there.

This is the Action that handles the URL that he user would go to when initiating SSO:

public ActionResult SSOLogin() {
    LogManager logger = new LogManager("SSOLogin");

    string hostname = this.GetHostname();
    SchoolSettings settings = this.GetClientSettings();

    if (settings.UseSAMLSSO) {
        Saml2Configuration samlConfig = null;
        try {
            samlConfig = SamlConfigLoader.GetSaml2Config(HttpContext, settings, this.IsSandbox());
        } catch (Exception e) {
            logger.exception($"loading Saml2Configuration for {hostname}", e);
        }

        if (samlConfig != null) {
            try {
                var binding = new Saml2RedirectBinding();

                binding.SetRelayStateQuery(new Dictionary<string, string> { { "Home/Index", Url.Content("~/") } });

                return binding.Bind(new Saml2AuthnRequest(samlConfig) {

                }).ToActionResult();
            } catch (Exception e) {
                logger.error($"Exception redirecting to IdP. {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
                ViewBag.ssoerror = $"Error redirecting to IdP for {hostname}";
            }
        } else {
            logger.critical($"Could not load SAML2 configuration for {hostname}");
            ViewBag.ssoerror = $"Could not load SAML2 configuration for {hostname}";
        }
    } else {
        ViewBag.ssoerror = "SSO is not configured for this client. Please contact Support";
    }

    return Redirect("/Home/SSOError");
}

The method that loads a client-specific metadata looks like this:

public static Saml2Configuration GetSaml2Config(HttpContextBase context, SchoolSettings forSchool, bool forSandbox) {
    LogManager log = new LogManager("getSaml2Config");

    Saml2Configuration config = new Saml2Configuration();
    if (!forSandbox) {
        config.Issuer = _saml2Issuer;
    } else {
        config.Issuer = _saml2IssuerSandbox;
    }

    config.SignatureAlgorithm = _saml2SignatureAlgo;
    config.CertificateValidationMode = X509CertificateValidationMode.None;
    config.RevocationMode = (X509RevocationMode)Enum.Parse(typeof(X509RevocationMode), ConfigurationManager.AppSettings["Saml2:RevocationMode"]);
    config.AllowedAudienceUris.Add(config.Issuer);

    var entityDescriptor = new EntityDescriptor();
    if (forSchool.SAMLMetadataLocationIsUrl) {
        try {
            entityDescriptor.ReadIdPSsoDescriptorFromUrl(new Uri(forSchool.SAMLMetadataLocation));
        } catch (Exception e) {
            log.error($"Exception caught loading metadata from school {forSchool.Hostname} at URL {forSchool.SAMLMetadataLocation}\n Exception {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
            entityDescriptor.IdPSsoDescriptor = null;
        }
    } else {
        var schoolMetadataPath = context.Server.MapPath("~/App_Data/SAMLMetadata/" + forSchool.SAMLMetadataLocation);
        log.info($"Loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}");
        try {
            entityDescriptor.ReadIdPSsoDescriptorFromFile(schoolMetadataPath);
        } catch (IOException ioe) {
            log.error($"IOException caught loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}: {ioe.Message}\n{ioe.StackTrace}");
            entityDescriptor.IdPSsoDescriptor = null;
        } catch (Exception e) {
            log.error($"Exception caught loading metadata for school {forSchool.Hostname} from file {schoolMetadataPath}\n Exception {e.GetType().ToString()}: {e.Message}\n{e.StackTrace}");
            entityDescriptor.IdPSsoDescriptor = null;
        }
    }

    if (entityDescriptor.IdPSsoDescriptor != null) {
        if (entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.Count() > 0) {
            config.SingleSignOnDestination = entityDescriptor.IdPSsoDescriptor.SingleSignOnServices.First().Location;
        } else {
            log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SingleSignOnServices that could be parsed.");
        }

        if (entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.Count() > 0) {
            config.SingleLogoutDestination = entityDescriptor.IdPSsoDescriptor.SingleLogoutServices.First().Location;
        } else {
            log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SingleLogoutServices that could be parsed.");
        }

        if (entityDescriptor.IdPSsoDescriptor.SigningCertificates.Count() > 0) {
            config.SignatureValidationCertificates.AddRange(entityDescriptor.IdPSsoDescriptor.SigningCertificates);
        } else {
            log.error($"WARNING: metadata for {forSchool.Hostname} does not have any SigningCertificates that could be parsed.");
        }
    } else {
        throw new Exception("IdPSsoDescriptor not loaded from metadata.");
    }

    return config;
}

If it would help to clarify the situation, I can add the code for the AssertionConsumerService Action which works perfectly in an IdP-initiated scenario.


问:
How do I execute cron service in linux?
I am trying to run a Python code every minute in Linux but at loss to configure cron service.  Following is what I added after running 'crontab -e' but nothing is happening.

```<code>* * * * * cd /home/kali && /usr/bin/python3.8 /home/kali/time.py
</code>```

time.py contains simple code to show current time.

```<code>from datetime import datetime
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
</code>```

Any suggestions?

答:
you should run your code with python3. i dont understand why you use cd command, so i omit that.

This is the way you can run your python code in cron:

```<code>* * * * * python3  /home/kali/time.py
</code>```

Note: Check if you have permission to execute .py file.

Title: How do I execute cron service in linux?

Body:
I am trying to run a Python code every minute in Linux but at loss to configure cron service.  Following is what I added after running 'crontab -e' but nothing is happening.

* * * * * cd /home/kali && /usr/bin/python3.8 /home/kali/time.py

time.py contains simple code to show current time.

from datetime import datetime
print(datetime.now().strftime('%Y-%m-%d %H:%M:%S'))

Any suggestions?

Body:
you should run your code with python3. i dont understand why you use cd command, so i omit that.

This is the way you can run your python code in cron:

* * * * * python3  /home/kali/time.py

Note: Check if you have permission to execute .py file.


问:
Why graphics::plot call on hexbin object throws an error?
In short: I'm trying to run this hexbin example which works fine unless I replace plot with graphics::plot. The latter throws following error:

```<code>> graphics::plot(bin, main="" , colramp=my_colors , legend=F )
Error in as.double(y) :
  cannot coerce type 'S4' to vector of type 'double'
</code>```

How to make this work?

Wider context why I need this work this way. I contribute to the clojisr project which brings R to Clojure using RServe. There is an option to require R packages and create corresponding Clojure functions. This works well (see this or this). The underlying calls to R are in the form of {package::symbol} for everything.

答:
Class hexbin is an S4 class and the package defines an S4 generic and a method for plot. (The source code is here). There is no S4 generic for plot in the graphics package namespace, only an S3 generic.

The solution is therefore very simple:

```<code>hexbin::plot(bin, main="" , colramp=my_colors , legend=F )
</code>```

Here's a reprex to prove it:

library(hexbin)
library(RColorBrewer)

# Create data
x <- rnorm(mean=1.5, 5000)
y <- rnorm(mean=1.6, 5000)

# Make the plot
bin<-hexbin(x, y, xbins=40)
my_colors=colorRampPalette(rev(brewer.pal(11,'Spectral')))
hexbin::plot(bin, main="" , colramp=my_colors , legend=F )
```

Created on 2020-02-17 by the reprex package (v0.3.0)

Body:
In short: I'm trying to run this hexbin example which works fine unless I replace plot with graphics::plot. The latter throws following error:

> graphics::plot(bin, main="" , colramp=my_colors , legend=F )
Error in as.double(y) :
  cannot coerce type 'S4' to vector of type 'double'

How to make this work?

Wider context why I need this work this way. I contribute to the clojisr project which brings R to Clojure using RServe. There is an option to require R packages and create corresponding Clojure functions. This works well (see this or this). The underlying calls to R are in the form of {package::symbol} for everything.

Body:
Class hexbin is an S4 class and the package defines an S4 generic and a method for plot. (The source code is here). There is no S4 generic for plot in the graphics package namespace, only an S3 generic.

The solution is therefore very simple:

hexbin::plot(bin, main="" , colramp=my_colors , legend=F )

Here's a reprex to prove it:

library(hexbin)
library(RColorBrewer)

# Create data
x <- rnorm(mean=1.5, 5000)
y <- rnorm(mean=1.6, 5000)

# Make the plot
bin<-hexbin(x, y, xbins=40)
my_colors=colorRampPalette(rev(brewer.pal(11,'Spectral')))
hexbin::plot(bin, main="" , colramp=my_colors , legend=F )

Created on 2020-02-17 by the reprex package (v0.3.0)


问:
Error on Conversion from NVARCHAR TO ASCII
I am having some issues with a table (view?) in SAS Enterprise Guide.

When running below code I get the following error:

```<code>DATA Dataset;
SET SAPFolder.TableOrView (KEEP=ColA ColB);
RUN;
</code>```

Error message:

ERROR: CLI cursor extended fetch error: [SAP AG][LIBODBCHDB
  DLL][HDBODBC] General error;-10427 Conversion of parameter/column (2)
         from data type NVARCHAR to ASCII failed

Seemingly I get the error at arbitrary points, i.e. for several tries it might return 302,400 observations, then suddenly that number increases to 1,320,000 observations before it terminates with the error. It always terminates with the error however.

Is there some way to ignore and skip the rows that returns the error and just keep all the rest?

I have no control of neither SAP nor the underlying data, so my only solution is somehow handle the errors directly in the script and ignore the rows that have the error. It is not important to my project if I lose the rows that give the error.

Thanks!

答:
Out of curiosity, what happens if you try this?

```<code>DATA Dataset;
SET SAPFolder.TableOrView (KEEP=ColA ColB);
if _ERROR_ = 1 then do;
 putlog _all_;
 _ERROR_ = 0;
end;
RUN;
</code>```

A similar pattern is sometimes used for index joins. I have no idea whether this will have any positive effect in your situation, but even if the data step still stops, it might at least show you which row it got to.

Body:
I am having some issues with a table (view?) in SAS Enterprise Guide.

When running below code I get the following error:

DATA Dataset;
SET SAPFolder.TableOrView (KEEP=ColA ColB);
RUN;

Error message:

ERROR: CLI cursor extended fetch error: [SAP AG][LIBODBCHDB
  DLL][HDBODBC] General error;-10427 Conversion of parameter/column (2)
         from data type NVARCHAR to ASCII failed

Seemingly I get the error at arbitrary points, i.e. for several tries it might return 302,400 observations, then suddenly that number increases to 1,320,000 observations before it terminates with the error. It always terminates with the error however.

Is there some way to ignore and skip the rows that returns the error and just keep all the rest?

I have no control of neither SAP nor the underlying data, so my only solution is somehow handle the errors directly in the script and ignore the rows that have the error. It is not important to my project if I lose the rows that give the error.

Thanks!

Body:
Out of curiosity, what happens if you try this?

DATA Dataset;
SET SAPFolder.TableOrView (KEEP=ColA ColB);
if _ERROR_ = 1 then do;
 putlog _all_;
 _ERROR_ = 0;
end;
RUN;

A similar pattern is sometimes used for index joins. I have no idea whether this will have any positive effect in your situation, but even if the data step still stops, it might at least show you which row it got to.


问:
Get an input's "checked" state
I have this basic HTML structure:

```<code><fieldset>
    <input/>
    <label></label>
    <div class="toggle_box">
        <div class="switch"></div>
    </div>
</fieldset>
</code>```

I would like this to happen when my input is checked:

```<code><fieldset>
    <input checked="checked" />
    <label></label>
    <div class="toggle_box">
        <div class="switch" state="on"></div>
    </div>
</fieldset>
</code>```

Add state="on" to the switch div. Is there any selector in jquery I can use to get the checked state of that particular input? (there are multiple on a page).

Thanks for your brainstorming!

答:
This will accomplish it for you.

```<code>$('input:checkbox').change(function () {
    if ($(this).is(':checked')) {
        $(this).parent().children('div.toggle_box').children('div.switch').attr('state', 'on');
    } else {
        $(this).parent().children('div.toggle_box').children('div.switch').removeAttr('state');
    }
});
</code>```

You'll also have to modify your <input /> to <input type="checkbox" />

Title: Get an input's "checked" state

Body:
I have this basic HTML structure:

<fieldset>
    <input/>

</fieldset>

I would like this to happen when my input is checked:

<fieldset>
    <input checked="checked" />

</fieldset>

Add state="on" to the switch div. Is there any selector in jquery I can use to get the checked state of that particular input? (there are multiple on a page).

Thanks for your brainstorming!

Body:
This will accomplish it for you.

$('input:checkbox').change(function () {
    if ($(this).is(':checked')) {
        $(this).parent().children('div.toggle_box').children('div.switch').attr('state', 'on');
    } else {
        $(this).parent().children('div.toggle_box').children('div.switch').removeAttr('state');
    }
});

You'll also have to modify your <input /> to <input type="checkbox" />


问:
GraphQL Asynchronous query results
I'm trying to implement a batch query interface with GraphQL. I can get a request to work synchronously without issue, but I'm not sure how to approach making the result asynchronous. Basically, I want to be able to kick off the query and return a pointer of sorts to where the results will eventually be when the query is done. I'd like to do this because the queries can sometimes take quite a while.

In REST, this is trivial. You return a 202 and return a Location header pointing to where the client can go to fetch the result. GraphQL as a specification does not seem to have this notion; it appears to always want requests to be handled synchronously.

Is there any convention for doing things like this in GraphQL? I very much like the query specification but I'd prefer to not leave the client HTTP connection open for up to a few minutes while a large query is executed on the backend. If anything happens to kill that connection the entire query would need to be retried, even if the results themselves are durable.

答:
I was working on a similar issue recently. My use case was to submit a job to create a report and provide the result back to the user. Creating a report takes couple of minutes which makes it an asynchronous operation. I created a mutation which submitted the job to the backend processing system and returned a job ID. Then I periodically poll the jobs field using a query to find out about the state of the job and eventually the results. As the result is a file, I return a link to a different endpoint where it can be downloaded (similar approach Github uses).

Polling for actual results is working as expected but I guess this might be better solved by subscriptions.

Title: GraphQL Asynchronous query results


问:
Replacing whole XML tree in Python
How to replace a whole XML tree?
Let's say I have a file that looks like:

```<code><root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <elem3>
       <sub1>'something else here'</sub1>
       <sub2>'blablabla'</sub2>
    </elem3>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>
</code>```

And I also have another xml file that would be an alternative for elem3 that looks like:

```<code>    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
</code>```

What I need is to replace elem3 with NewElem, that results in:

```<code><root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>
</code>```

I am using xml.etree.ElementTree and tried to append it but I end up getting the NewElem in the end, after </folder>. I could not remove the elem3 of the updated xml file.

I tried to append it using this:

```<code>import xml.etree.ElementTree as ET

tree = ET.parse('base.xml')
baseroot = tree.getroot()
tree2 = ET.parse('new.xml')
newroot = tree2.getroot()

old_element = baseroot.findall('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)
</code>```

With that the NewElem gets appended after folder, and I need in the same place where elem3 was, or at least inside <folder>
Also, when removing I get an error:
TypeError: remove() argument must be xml.etree.ElementTree.Element, not list
If I change to

```<code>old_element = baseroot.find('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)
</code>```

I get very similar error: ValueError: list.remove(x): x not in list

答:
if you insist on using 'ElementTree', first you should realize that erase only works on the node that directly contain the node you want to remove.

so while searching for it like this

```<code>old_element = baseroot.find('.//elem3')
</code>```

is fine, you cannot remove it from the baseroot, you need to get the  it resides in, and remove it from there. The easiest must be to get it's parent

```<code>old_element_parent = xml.find('.//elem3/..')
old_element_parent.remove(old_element )
</code>```

adding a new element can be done with SubElement

```<code>a = ET.SubElement(old_element_parent, 'NewElement')
</code>```

Title: Replacing whole XML tree in Python

Body:
How to replace a whole XML tree?
Let's say I have a file that looks like:

<root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <elem3>
       <sub1>'something else here'</sub1>
       <sub2>'blablabla'</sub2>
    </elem3>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>

And I also have another xml file that would be an alternative for elem3 that looks like:

    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>

What I need is to replace elem3 with NewElem, that results in:

<root>
  <folder>
    <elem1>'something here'</elem1>
    <elem2>'more stuff here'</elem2>
    <NewElem>
       <Difsub1>'something else here, but different'</Difsub1>
       <Difsub2>'all sorts of different blablabla'</Difsub2>
    </NewElem>
    <elem4>'even more stuff here with subelements too'</elem4>
  </folder>
</root>

I am using xml.etree.ElementTree and tried to append it but I end up getting the NewElem in the end, after </folder>. I could not remove the elem3 of the updated xml file.

I tried to append it using this:

import xml.etree.ElementTree as ET

tree = ET.parse('base.xml')
baseroot = tree.getroot()
tree2 = ET.parse('new.xml')
newroot = tree2.getroot()

old_element = baseroot.findall('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)

With that the NewElem gets appended after folder, and I need in the same place where elem3 was, or at least inside <folder>
Also, when removing I get an error:
TypeError: remove() argument must be xml.etree.ElementTree.Element, not list
If I change to

old_element = baseroot.find('.//elem3')
baseroot.append(newroot)
baseroot.remove(old_element)

I get very similar error: ValueError: list.remove(x): x not in list

Body:
if you insist on using 'ElementTree', first you should realize that erase only works on the node that directly contain the node you want to remove.

so while searching for it like this

old_element = baseroot.find('.//elem3')

is fine, you cannot remove it from the baseroot, you need to get the  it resides in, and remove it from there. The easiest must be to get it's parent

old_element_parent = xml.find('.//elem3/..')
old_element_parent.remove(old_element )

adding a new element can be done with SubElement

a = ET.SubElement(old_element_parent, 'NewElement')


问:
Problems using git diff to create file list for deploy
I want to use something like the following command to create a tarball to deploy:

```<code>tar cjvf ~/deploy.tar.bz2 `git diff --name-only 0abc 1def`
</code>```

The inner git diff command produces a list of files with relative including the relative path when i run it separately.

I'm running into two problems though, I need to be able to auto escape spaces in the output, so tar doesn't complain about files containing spaces and when the tar does get created, all the files have a duplicate 'hidden file' preceded by a '.' that don't show up with ls -al. These are OSX specific metafiles as noted by kch.

Anyway, does anyone know of the solution to these problems, or is there just a plain easier way to script this?

答:
Why do not use --files-from=FILE or -T FILE option of tar, where FILE can be '-' to signify standard input?

```<code> git diff --name-only 0abc 1def | tar -T - cjf ~/deploy.tar.bz2
</code>```

You shouldn't have problem with spaces or tabs in filenames, or with single quotes, or backquotes, or backslashes (I think your solution would have problems with single quote "'" in filename). You might have problem with newlines in filenames, just like in IFS solution.

OwnerDisplayName: Dana the Sane

ContentLicense: CC BY-SA 2.5

Body:
I want to use something like the following command to create a tarball to deploy:

tar cjvf ~/deploy.tar.bz2 `git diff --name-only 0abc 1def`

The inner git diff command produces a list of files with relative including the relative path when i run it separately.

I'm running into two problems though, I need to be able to auto escape spaces in the output, so tar doesn't complain about files containing spaces and when the tar does get created, all the files have a duplicate 'hidden file' preceded by a '.' that don't show up with ls -al. These are OSX specific metafiles as noted by kch.

Anyway, does anyone know of the solution to these problems, or is there just a plain easier way to script this?

LastEditorDisplayName: Dana the Sane

Body:
Why do not use --files-from=FILE or -T FILE option of tar, where FILE can be '-' to signify standard input?

 git diff --name-only 0abc 1def | tar -T - cjf ~/deploy.tar.bz2

You shouldn't have problem with spaces or tabs in filenames, or with single quotes, or backquotes, or backslashes (I think your solution would have problems with single quote "'" in filename). You might have problem with newlines in filenames, just like in IFS solution.

OwnerDisplayName: Jakub Narębski


问:
Is this good approach to create new branch without merging current one using git?
kindly guide me about it please, for example, I have master branch. My team lead assigned a task to me for terms and conditions content. So I pulled from master and then created branch feature/terms-and-conditions through git checkout -b and then commit, pushed. Just guess for one minute that my team lead does not merged with master.

Now feature/terms-and-conditions is 1 commit ahead from master. So here I am confused that if I created again one new branch for another feature suppose feature/user-list and when I will commit and push for it then there would be two branches. Both would be 1 commit ahead from master. In such a case there would be any conflict?

答:
To add to the excellent answer provided by @Mureinik

In git branch is just a pointer to the commit, so there is no problem whatsoever to maintain as many branches as you want, they're "cheap".

Now as long as the branch is not merged, its only yours so you can push to it as many times as you want, so once the feature/terms-and-conditions gets merged into master (and assuming you haven't merged the feature/user-list branch yet, you can rebase your changes on top of master. I usually do (probably there are more "precise" commands, but it does the job for me):

```<code>// while being on feature/user-list branch
>> git fetch --all // to fetch the changes about the origin/master update into your local git repo
>> git status // just to make sure that you don't have any work in progress
>> git rebase origin/master
</code>```

Now the last command will put all your local commits "on top of" the last master commit. At this point you might have conflicts if you worked on the same files, but in general it should not really happen (as was already explained project-wise you'll probably won't do two changes that modify the same files at the same time). Even if there will be a confict you can resolve it.

After that, if you've already pushed to remote branch origin/feature/user-list you might want to forcefully push new sha1-s of your commits (git push -f), if you haven't pushed anything yet, you just can keep working.

Body:
To add to the excellent answer provided by @Mureinik

In git branch is just a pointer to the commit, so there is no problem whatsoever to maintain as many branches as you want, they're "cheap".

Now as long as the branch is not merged, its only yours so you can push to it as many times as you want, so once the feature/terms-and-conditions gets merged into master (and assuming you haven't merged the feature/user-list branch yet, you can rebase your changes on top of master. I usually do (probably there are more "precise" commands, but it does the job for me):

// while being on feature/user-list branch
>> git fetch --all // to fetch the changes about the origin/master update into your local git repo
>> git status // just to make sure that you don't have any work in progress
>> git rebase origin/master

Now the last command will put all your local commits "on top of" the last master commit. At this point you might have conflicts if you worked on the same files, but in general it should not really happen (as was already explained project-wise you'll probably won't do two changes that modify the same files at the same time). Even if there will be a confict you can resolve it.

After that, if you've already pushed to remote branch origin/feature/user-list you might want to forcefully push new sha1-s of your commits (git push -f), if you haven't pushed anything yet, you just can keep working.


答:
A view creates a logical table and that table can be the result of any SQL statement.

When you create a view, you remember these things:-

Limiting the visibility of columns (via select) or rows (via where)
to just those pertinent to a task

Combining rows (via union) and or columns (via join) from multiple
tables into one logical table.

Aggregating rows (via Group BY and Having) into a more distinct
presentation pulled from a table with finer detail.

Views have the following benefits: (Refer by - What is a good reason to use SQL views?)

Security - Views can be made accessible to users while the underlying
tables are not directly accessible. This allows the DBA to give users only the data
they need while protecting other data in the same table.

Simplicity - Views can be used to hide and reuse complex queries.

Column Name Simplication or Clarification - Views can be used to
provide aliases on column names to make them more memorable or
meaningful.

Thanks!!!

Title: Is it good practice to create SQL view by joining tables?

Body:
I have this question, is there any performance issue with creating SQL view by joining two or more tables?
Is it good practice or one should create another table with joins and create view on top of it?


问:
Why each time after creating component I have reference to previous data?
I have component that gets data from service by event message:

```<code>this.objectDetailsSubscription = this.eventService.subscribe(
      EventsChannels.OBJECT_DETAILS,
      semantic => {
        this.layer = this.layerSemanticService.getObjectSemantic(semantic);
      }
    );
</code>```

Where service is:

```<code>@Injectable({
  providedIn: "root"
})
export class LayersSemanticService {
  getObjectSemantic(semantic: LayerItemGeneric): ObjectInformationCustom {
    this.semantic = semantic;
    this.configuration = this.getConfigurationSemantic(semantic.layerIdCommon);

    return {
      buttons: this.getButtons(this.configuration),
    }

  }

    getButtons(configuration: LayerSemanticConfig) {
    configuration.tools = configuration.tools || [];
    configuration.tools.push(EButtonTypes.Pin);
    return configuration.tools;
  }
}
</code>```

In child component I pass buttons as Input():

```<code>  *ngFor="let btn of buttons"
</code>```

I have tried to reset variable:

```<code> ngOnInit() {
    this.layer = <ObjectInformationCustom>{};
}
</code>```

No effect

答:
Services are singletons by default (when decorated with @Injectable({ providedIn: 'root' }), as yours is).

This means that there is one instance that lives in memory for the lifetime of the application. So the state that exists within the service will be the same for all components that are injected with the service, until that state changes.

If the state shouldn't exist beyond the lifetime of a component, then store that state in the component. If it needs to be stored and updated in the service, then update it in the service.

It is possible to configure component-level services by setting them as providers in the @Component() decorator. This approach needs to be used with caution, though, as it could get confusing.

Body:
I have component that gets data from service by event message:

this.objectDetailsSubscription = this.eventService.subscribe(
      EventsChannels.OBJECT_DETAILS,
      semantic => {
        this.layer = this.layerSemanticService.getObjectSemantic(semantic);
      }
    );

Where service is:

@Injectable({
  providedIn: "root"
})
export class LayersSemanticService {
  getObjectSemantic(semantic: LayerItemGeneric): ObjectInformationCustom {
    this.semantic = semantic;
    this.configuration = this.getConfigurationSemantic(semantic.layerIdCommon);

    return {
      buttons: this.getButtons(this.configuration),
    }

  }

    getButtons(configuration: LayerSemanticConfig) {
    configuration.tools = configuration.tools || [];
    configuration.tools.push(EButtonTypes.Pin);
    return configuration.tools;
  }
}

In child component I pass buttons as Input():

  *ngFor="let btn of buttons"

I have tried to reset variable:

 ngOnInit() {
    this.layer = <ObjectInformationCustom>{};
}

No effect


问:
"Conversion to non-scalar type is requested" error on linux terminal using cmake
I faced an issue when i try to generate CodeLite using CMake. I encountered it during 'make -j4' step. it shows "Conversion to non-scalar type is requested".

```<code>'''
[ 68%] Built target codelitephp
[ 68%] Built target codelite-make
[ 69%] Built target codelite-terminal
[ 83%] Built target wxCrafter
[ 83%] [ 83%] [ 83%] Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilerMainPage.cpp.o
Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilersFoundDlgBase.cpp.o
Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilersFoundDlg.cpp.o
[ 83%] Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilersFoundDlg_liteeditor_bitmaps.cpp.o
[ 83%] Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilersModifiedDlg.cpp.o
/home/osboxes/Desktop/codelite-13.0/LiteEditor/CompilerMainPage.cpp: In member function ‘void CompilerMainPage::InitializeTools()’:
/home/osboxes/Desktop/codelite-13.0/LiteEditor/CompilerMainPage.cpp:543:76: error: conversion from ‘wxPGIterator<wxPGProperty,wxPropertyGridPageState>’ to non-scalar type ‘wxPGIterator<const wxPGProperty,const wxPropertyGridPageState>’ requested
     wxPropertyGridConstIterator iter = m_pgMgrTools->GetGrid()->GetIterator();
                                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
[ 83%] Building CXX object LiteEditor/CMakeFiles/codelite.dir/ConfigManagerBaseDlg.cpp.o
make[2]: *** [LiteEditor/CMakeFiles/codelite.dir/CompilerMainPage.cpp.o] Error 1
make[2]: *** Waiting for unfinished jobs....
make[1]: *** [LiteEditor/CMakeFiles/codelite.dir/all] Error 2
make: *** [all] Error 2
</code>```

'''

Anyone can help me resolve the issue? I followed this GitHub link. It seems like there might be something wrong with the 'cmake' step. Greatly appreciate it if anyone can help me solve it!

答:
This problem doesn't seem to be related to CMAKE rather than to the actual compilation.

I don't know the library personally but as far as I can tell from the wiki page you shared, it seems maybe those instructions might be outdated because it's dated from 2018 but there's recent changes in the library.

I would check the dependencies versions to see if they match with the one that the maintainer specifies in the README.md

Body:
I faced an issue when i try to generate CodeLite using CMake. I encountered it during 'make -j4' step. it shows "Conversion to non-scalar type is requested".

'''
[ 68%] Built target codelitephp
[ 68%] Built target codelite-make
[ 69%] Built target codelite-terminal
[ 83%] Built target wxCrafter
[ 83%] [ 83%] [ 83%] Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilerMainPage.cpp.o
Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilersFoundDlgBase.cpp.o
Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilersFoundDlg.cpp.o
[ 83%] Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilersFoundDlg_liteeditor_bitmaps.cpp.o
[ 83%] Building CXX object LiteEditor/CMakeFiles/codelite.dir/CompilersModifiedDlg.cpp.o
/home/osboxes/Desktop/codelite-13.0/LiteEditor/CompilerMainPage.cpp: In member function ‘void CompilerMainPage::InitializeTools()’:
/home/osboxes/Desktop/codelite-13.0/LiteEditor/CompilerMainPage.cpp:543:76: error: conversion from ‘wxPGIterator<wxPGProperty,wxPropertyGridPageState>’ to non-scalar type ‘wxPGIterator<const wxPGProperty,const wxPropertyGridPageState>’ requested
     wxPropertyGridConstIterator iter = m_pgMgrTools->GetGrid()->GetIterator();
                                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^~
[ 83%] Building CXX object LiteEditor/CMakeFiles/codelite.dir/ConfigManagerBaseDlg.cpp.o
make[2]: *** [LiteEditor/CMakeFiles/codelite.dir/CompilerMainPage.cpp.o] Error 1
make[2]: *** Waiting for unfinished jobs....
make[1]: *** [LiteEditor/CMakeFiles/codelite.dir/all] Error 2
make: *** [all] Error 2

'''

Anyone can help me resolve the issue? I followed this GitHub link. It seems like there might be something wrong with the 'cmake' step. Greatly appreciate it if anyone can help me solve it!


问:
Get rid of "Show Quoted Text" in Gmail
Is there a way to code HTML emails in a way that will NOT show the "show quoted text" and will NOT turn text to purple?
The web app I'm developing sends out a notification each time a user gets a reply on the web app and if the user gets 2 or more replies from the same person everything excpet the date a photo in the email turns to "show quoted text". Even the call-to-action button that's supposed to take the user to the actual conversation.

I know that this question has been answered before but I just can't find it..

Thanks!

答: You could change the body of the email, possibly by including a section of the reply, so that gmail won't hide the identical content.</p>

Title: Get rid of "Show Quoted Text" in Gmail


问:
Form Recognizer
I generated the Model Id using From Recognizer Labeling too (The docker image).
I am trying to use this same model id in From Recognizer API.

https://{endpoint}/formrecognizer/v1.0-preview/custom/models/{id}

but it say 404 .

https://centralus.dev.cognitive.microsoft.com/docs/services/form-recognizer-api/operations/GetCustomModel

The below URL says we can use the generated model Id:
https://learn.microsoft.com/en-us/azure/cognitive-services/form-recognizer/quickstarts/label-tool

Model ID - The ID of the model that was created and trained. Each training call creates a new model with its own ID. Copy this string to a secure location; you'll need it if you want to do prediction calls through the REST API.

答:
I have recently tried the form-recognizer API. Please use the below URL and test it in the Postman first.

https://{{endpoint}}/formrecognizer/v2.0-preview/custom/models/{{modelId}}

Replace endpoint  and modelId with  {{name of your form-recognizer-service}}.cognitiveservices.azure.com and your modelId  respectively. Let me know if it works.

Title: Form Recognizer


问:
How to find indices of matching elements in arrays?
I have two vectors, vector A is (1298,1), Vector B varies in a for loop but is always just a column vector, I am trying to use numpy.where to find the A-indices of the elements in B. Currently I have a for loop combing through Vector B element-wise and using numpy.isclose but I was wondering if anyone knows a quicker function and/or how to do this without a nested for loop? It works but very slowly.
The for loops looks like this</p>

```<code>sphere_indices=[]
for k in range(len(A)):
    for j in range(len(B)):
         if np.isclose(B[j,0],A[k,0]):
              sphere_indices.append(k) ```
</code>```

答:
There was never any reason to iterate through the all 1298 elements of vector A, in order to use numpy.where and numpy.isclose I just needed to use the elements in B one at a time so numpy can broadcast properly. The following code runs much faster. Any further improvements are always welcome. </p>

```<code>                    for j in range(len(index)):
                        sphere_indices1=np.where(np.isclose(sphere_index[:,0],index[j,0]))
                        sphere_indices.append(sphere_indices1[0])```
</code>```

Body:
I have two vectors, vector A is (1298,1), Vector B varies in a for loop but is always just a column vector, I am trying to use numpy.where to find the A-indices of the elements in B. Currently I have a for loop combing through Vector B element-wise and using numpy.isclose but I was wondering if anyone knows a quicker function and/or how to do this without a nested for loop? It works but very slowly.
The for loops looks like this

sphere_indices=[]
for k in range(len(A)):
    for j in range(len(B)):
         if np.isclose(B[j,0],A[k,0]):
              sphere_indices.append(k) ```

Body:
There was never any reason to iterate through the all 1298 elements of vector A, in order to use numpy.where and numpy.isclose I just needed to use the elements in B one at a time so numpy can broadcast properly. The following code runs much faster. Any further improvements are always welcome.

                    for j in range(len(index)):
                        sphere_indices1=np.where(np.isclose(sphere_index[:,0],index[j,0]))
                        sphere_indices.append(sphere_indices1[0])```


问:
Recursively filter array of objects
Hitting a wall with this one, thought I would post it here in case some kind soul has come across a similar one. I have some data that looks something like this:

```<code>const input = [
  {
    value: 'Miss1',
    children: [
      { value: 'Miss2' },
      { value: 'Hit1', children: [ { value: 'Miss3' } ] }
    ]
  },
  {
    value: 'Miss4',
    children: [
      { value: 'Miss5' },
      { value: 'Miss6', children: [ { value: 'Hit2' } ] }
    ]
  },
  {
    value: 'Miss7',
    children: [
      { value: 'Miss8' },
      { value: 'Miss9', children: [ { value: 'Miss10' } ] }
    ]
  },
  {
    value: 'Hit3',
    children: [
      { value: 'Miss11' },
      { value: 'Miss12', children: [ { value: 'Miss13' } ] }
    ]
  },
  {
    value: 'Miss14',
    children: [
      { value: 'Hit4' },
      { value: 'Miss15', children: [ { value: 'Miss16' } ] }
    ]
  },
];
</code>```

I don't know at run time how deep the hierarchy will be, i.e. how many levels of objects will have a children array. I have simplified the example somewhat, I will actually need to match the value properties against an array of search terms. Let's for the moment assume that I am matching where value.includes('Hit').

I need a function that returns a new array, such that:

Every non-matching object with no children, or no matches in children hierarchy, should not exist in output object

Every object with a descendant that contains a matching object, should remain

All descendants of matching objects should remain

I am considering a 'matching object' to be one with a value property that contains the string Hit in this case, and vice versa.

The output should look something like the following:

```<code>const expected = [
  {
    value: 'Miss1',
    children: [
      { value: 'Hit1', children: [ { value: 'Miss3' } ] }
    ]
  },
  {
    value: 'Miss4',
    children: [
      { value: 'Miss6', children: [ { value: 'Hit2' } ] }
    ]
  },
  {
    value: 'Hit3',
    children: [
      { value: 'Miss11' },
      { value: 'Miss12', children: [ { value: 'Miss13' } ] }
    ]
  },
  {
    value: 'Miss14',
    children: [
      { value: 'Hit4' },
    ]
  }
];
</code>```

Many thanks to anyone who took the time to read this far, will post my solution if I get there first.

答:
const input = [
  {
    value: 'Miss1',
    children: [
      { value: 'Miss1' },
      { value: 'Hit1', children: [ { value: 'Miss3' } ] }
    ]
  },
  {
    value: 'Miss4',
    children: [
      { value: 'Miss5' },
      { value: 'Miss6', children: [ { value: 'Hit2' } ] }
    ]
  },
  {
    value: 'Miss7',
    children: [
      { value: 'Miss8' },
      { value: 'Miss9', children: [ { value: 'Miss10' } ] }
    ]
  },
  {
    value: 'Hit3',
    children: [
      { value: 'Miss11' },
      { value: 'Miss12', children: [ { value: 'Miss13' } ] }
    ]
  },
  {
    value: 'Miss14asds',
    children: [
      { value: 'Hit4sdas' },
      { value: 'Miss15', children: [ { value: 'Miss16' } ] }
    ]
  },
];

function filter(arr, term) {
    var matches = [];

    if (!Array.isArray(arr)) return matches;

    arr.forEach(function(i) {

        if (i.value === term) {

         const filterData =  (i.children && Array.isArray(i.children))? i.children.filter(values => values.value ===term):[];
         console.log(filterData)
         i.children =filterData;
            matches.push(i);

        } else {
       // console.log(i.children)
            let childResults = filter(i.children, term);
            if (childResults.length)
     matches.push(Object.assign({}, i, { children: childResults }));
        }
    })

    return matches;
}

const filterData= filter(input,'Miss1');
console.log(filterData)```
</div>
</div>
</p>

<p>Below code for filter the parent and child array data using recursive function</p>

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>const input = [
  {
    value: 'Miss1',
    children: [
      { value: 'Miss2' },
      { value: 'Hit1', children: [ { value: 'Miss3' } ] }
    ]
  },
  {
    value: 'Miss4',
    children: [
      { value: 'Miss5' },
      { value: 'Miss6', children: [ { value: 'Hit2' } ] }
    ]
  },
  {
    value: 'Miss7',
    children: [
      { value: 'Miss8' },
      { value: 'Miss9', children: [ { value: 'Miss10' } ] }
    ]
  },
  {
    value: 'Hit3',
    children: [
      { value: 'Miss11' },
      { value: 'Miss12', children: [ { value: 'Miss13' } ] }
    ]
  },
  {
    value: 'Miss14',
    children: [
      { value: 'Hit4' },
      { value: 'Miss15', children: [ { value: 'Miss16' } ] }
    ]
  },
];

var res = input.filter(function f(o) {
  if (o.value.includes("Hit")) return true

  if (o.children) {
    return (o.children = o.children.filter(f)).length
  }
})
console.log(JSON.stringify(res, null, 2))</code>```

Title: Recursively filter array of objects

Body:
Hitting a wall with this one, thought I would post it here in case some kind soul has come across a similar one. I have some data that looks something like this:

const input = [
  {
    value: 'Miss1',
    children: [
      { value: 'Miss2' },
      { value: 'Hit1', children: [ { value: 'Miss3' } ] }
    ]
  },
  {
    value: 'Miss4',
    children: [
      { value: 'Miss5' },
      { value: 'Miss6', children: [ { value: 'Hit2' } ] }
    ]
  },
  {
    value: 'Miss7',
    children: [
      { value: 'Miss8' },
      { value: 'Miss9', children: [ { value: 'Miss10' } ] }
    ]
  },
  {
    value: 'Hit3',
    children: [
      { value: 'Miss11' },
      { value: 'Miss12', children: [ { value: 'Miss13' } ] }
    ]
  },
  {
    value: 'Miss14',
    children: [
      { value: 'Hit4' },
      { value: 'Miss15', children: [ { value: 'Miss16' } ] }
    ]
  },
];

I don't know at run time how deep the hierarchy will be, i.e. how many levels of objects will have a children array. I have simplified the example somewhat, I will actually need to match the value properties against an array of search terms. Let's for the moment assume that I am matching where value.includes('Hit').

I need a function that returns a new array, such that:

Every non-matching object with no children, or no matches in children hierarchy, should not exist in output object

Every object with a descendant that contains a matching object, should remain

All descendants of matching objects should remain

I am considering a 'matching object' to be one with a value property that contains the string Hit in this case, and vice versa.

The output should look something like the following:

const expected = [
  {
    value: 'Miss1',
    children: [
      { value: 'Hit1', children: [ { value: 'Miss3' } ] }
    ]
  },
  {
    value: 'Miss4',
    children: [
      { value: 'Miss6', children: [ { value: 'Hit2' } ] }
    ]
  },
  {
    value: 'Hit3',
    children: [
      { value: 'Miss11' },
      { value: 'Miss12', children: [ { value: 'Miss13' } ] }
    ]
  },
  {
    value: 'Miss14',
    children: [
      { value: 'Hit4' },
    ]
  }
];

Many thanks to anyone who took the time to read this far, will post my solution if I get there first.

Body:
const input = [
  {
    value: 'Miss1',
    children: [
      { value: 'Miss1' },
      { value: 'Hit1', children: [ { value: 'Miss3' } ] }
    ]
  },
  {
    value: 'Miss4',
    children: [
      { value: 'Miss5' },
      { value: 'Miss6', children: [ { value: 'Hit2' } ] }
    ]
  },
  {
    value: 'Miss7',
    children: [
      { value: 'Miss8' },
      { value: 'Miss9', children: [ { value: 'Miss10' } ] }
    ]
  },
  {
    value: 'Hit3',
    children: [
      { value: 'Miss11' },
      { value: 'Miss12', children: [ { value: 'Miss13' } ] }
    ]
  },
  {
    value: 'Miss14asds',
    children: [
      { value: 'Hit4sdas' },
      { value: 'Miss15', children: [ { value: 'Miss16' } ] }
    ]
  },
];

function filter(arr, term) {
    var matches = [];

    if (!Array.isArray(arr)) return matches;

    arr.forEach(function(i) {

        if (i.value === term) {

         const filterData =  (i.children && Array.isArray(i.children))? i.children.filter(values => values.value ===term):[];
         console.log(filterData)
         i.children =filterData;
            matches.push(i);

        } else {
       // console.log(i.children)
            let childResults = filter(i.children, term);
            if (childResults.length)
     matches.push(Object.assign({}, i, { children: childResults }));
        }
    })

    return matches;
}

const filterData= filter(input,'Miss1');
console.log(filterData)

Below code for filter the parent and child array data using recursive function

const input = [
  {
    value: 'Miss1',
    children: [
      { value: 'Miss2' },
      { value: 'Hit1', children: [ { value: 'Miss3' } ] }
    ]
  },
  {
    value: 'Miss4',
    children: [
      { value: 'Miss5' },
      { value: 'Miss6', children: [ { value: 'Hit2' } ] }
    ]
  },
  {
    value: 'Miss7',
    children: [
      { value: 'Miss8' },
      { value: 'Miss9', children: [ { value: 'Miss10' } ] }
    ]
  },
  {
    value: 'Hit3',
    children: [
      { value: 'Miss11' },
      { value: 'Miss12', children: [ { value: 'Miss13' } ] }
    ]
  },
  {
    value: 'Miss14',
    children: [
      { value: 'Hit4' },
      { value: 'Miss15', children: [ { value: 'Miss16' } ] }
    ]
  },
];

var res = input.filter(function f(o) {
  if (o.value.includes("Hit")) return true

  if (o.children) {
    return (o.children = o.children.filter(f)).length
  }
})
console.log(JSON.stringify(res, null, 2))