问:
getting CORS error while using passport-facebook for facebook login in MEAN app
I am trying to add facebook login feature for my web app. Which is being developed in express js, mongodb and angular 2.

Client part of the app is generated through angular-cli (which is running on port 4200). To connect it to the express app (which is running on port 4300) I am using proxy config provided by angular-cli itself.

I have searched web and nothing is working for me. Please help me out.

This is the Error I am getting while clicking on facebook login button

```<code> XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…alhost%3A4200%2Fapi%2Fuser%2Ffacebook%2Fcallback&client_id=404659989876073. Redirect from 'https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…alhost%3A4200%2Fapi%2Fuser%2Ffacebook%2Fcallback&client_id=404659989876073' to 'https://www.facebook.com/login.php?skip_api_login=1&api_key=404659989876073…_&display=page&locale=en_GB&logger_id=9f59d18b-00cb-48a9-a544-7e49a66acfe4' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.
</code>```

I can understand that this is CORS issue, I have searched a lot of place but all the solutions which are available online are not working for me. Like allowing cross origin in express, using third party library for it etc.

Here is my app.ts

import * as express from 'express';
import { json, urlencoded } from 'body-parser';
import * as path from 'path';
import * as cors from 'cors';
import * as compression from 'compression';
import * as mongoose from 'mongoose';
import * as ejs from 'ejs';
import * as passport from 'passport';
import * as session from 'express-session';

import { MONGODB_URI } from './config';
import { AuthConfig } from './api/auth/passport';

import { thingRouter } from './api/thing/';
import { userRouter } from './api/user';

const app: express.Application = express();

app.disable('x-powered-by');

app.use(json());
app.use(compression());
app.use(urlencoded({ extended: true }));
app.use(session({ secret: 'my-secret-key', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

mongoose.connect(process.env.MONGODB_URI || MONGODB_URI);

// allow cors only for local dev

app.use(cors({
  origin: 'http://localhost:4200'
}));

AuthConfig(passport);
// app.set('env', 'production');

// api routes

app.use('/api/thing', thingRouter);
app.use('/api/user', userRouter);

if (app.get('env') === 'production') {

  // in production mode run application from dist folder
  app.use(express.static(path.join(__dirname, '/../client')));
  app.engine('html', ejs.renderFile);
  app.set('view engin', 'html');
}

// catch 404 and forward to error handler
app.use(function (req: express.Request, res: express.Response, next) {
  res.render(path.join(__dirname, '/../client/index.html'));
});

// production error handler
// no stacktrace leaked to user
app.use(function (err: any, req: express.Request, res: express.Response, next: express.NextFunction) {

  res.status(err.status || 500);
  res.json({
    error: {},
    message: err.message
  });
});

export { app }```
</div>
</div>
</p>

<p><strong>passport.ts</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>let LocalStrategy = require('passport-local').Strategy;
let FacebookStrategy = require('passport-facebook').Strategy;

import { FacebookAuth } from '../../config';

import { User } from '../user/user.model'

import * as uuid from 'uuid';

 let passportConfig = function (passport) {
  passport.serializeUser((user, done) => {
    console.log('serializeing user');
    done(null, user.id);
  });

  passport.deserializeUser((id, done) => {
    console.log('deserializing user');
    User.findOne({ id: id }, (err, user) => {
      done(err, user);
    })
  });

  // Facebook Strategy
  passport.use(new FacebookStrategy({
    clientID: FacebookAuth.clientId,
    clientSecret: FacebookAuth.clientSecret,
    callbackURL: FacebookAuth.callbackURL // for my app - 'http://localhost:4200/api/user/facebook/callback'
  },
  (token, refreshToken, profile, done) => {
    console.log('in passport.js'); //never printed
    console.log('token', token); //never printed
    console.log('refreshToken', refreshToken); //never printed
    console.log('profile', profile); // never printed
    User.findOne({ 'facebook.id': profile.id}, (err, user) => {
      if (err) { return done(err) }
      if (user) { return done(null, user) }
      let newUser = new User();
      newUser.id = uuid.v4();
      newUser.facebook.id = profile.id;
      newUser.facebook.token = token;
      newUser.name = profile.name.givenName + ' ' + profile.name.familyName;
      newUser.email = profile.emails[0].value;
      newUser.save(err => {
        if (err) { return done(err) }
        return done(null, newUser);
      })
    })
  }));
}

export let AuthConfig = passportConfig;</code>```

route file

import { Router } from 'express';

import { UserController } from './user.controller';

const userRouter: Router = Router();
const controller: UserController = new UserController();

userRouter.get('/facebook', controller.facebook);
userRouter.get('/facebook/callback', controller.facebookCallback);

export { userRouter };```
</div>
</div>
</p>

<p><strong>User controller file</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Router, Response, Request, NextFunction } from 'express';
import * as passport from 'passport';
import * as uuid from 'uuid';

import { User } from './user.model';

export class UserController {
  constructor() { }

  facebook(req: Request, res: Response, next: NextFunction) {
    console.log('got the request in facebook()'); //this get printed
    passport.authenticate('facebook')(req, res, next);

  }

  facebookCallback(req: Request, res: Response, next: NextFunction) {
    console.log('got the call in facebookCallback()');
    passport.authenticate('facebook', (err, user) => {
      console.log('passport callback\'s callback');
      if (err) {
        return res.status(200)
        .json({
          title: 'error',
          data: err
        })
      }
      return res.status(200)
        .json({
          title: 'logged in',
          data: user
        })
    })
  }
}</code>```

**HTML for facebook icon with click event **

```
</div>
</div>
</p>

<p><strong>Angular 2 component (function) which is working fine</strong></p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastyService, ToastyConfig, ToastOptions, ToastData } from 'ng2-toasty';

import { AuthService } from './../../services/auth/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {

  constructor(private toastyService: ToastyService,
    private router: Router,
    private toastyConfig: ToastyConfig,
    private authService: AuthService) {

    this.toastyConfig.theme = 'bootstrap';

  }

  ngOnInit() {
      }

  facebookLogin() {
    this.authService.facebookLogin()
    .subscribe(
      data => {
        console.log('login.component data', data);
      },
      err => {
        console.log('login.component err', err);
      }
    )
  }

}</code>```

Auth Service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/Rx';

@Injectable()
export class AuthService {

  constructor(private http: Http) {
  }

  facebookLogin() {
    return this.http.get('/api/user/facebook')
    .map(response => response.json())
    .catch(err => Observable.throw(err.json));
  }

}```

答:
This is what I have done to avoid Angular to call facebook auth dialogue API as AJAX request.

Use 'window.location="http://localhost:3000/auth/facebook"'; in your Angular Controller Function from where you send the request to your Express Server which contains passport.authenticate stuff.

It works for me!

Body:
I am trying to add facebook login feature for my web app. Which is being developed in express js, mongodb and angular 2.

Client part of the app is generated through angular-cli (which is running on port 4200). To connect it to the express app (which is running on port 4300) I am using proxy config provided by angular-cli itself.

I have searched web and nothing is working for me. Please help me out.

This is the Error I am getting while clicking on facebook login button

 XMLHttpRequest cannot load https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…alhost%3A4200%2Fapi%2Fuser%2Ffacebook%2Fcallback&client_id=404659989876073. Redirect from 'https://www.facebook.com/dialog/oauth?response_type=code&redirect_uri=http%…alhost%3A4200%2Fapi%2Fuser%2Ffacebook%2Fcallback&client_id=404659989876073' to 'https://www.facebook.com/login.php?skip_api_login=1&api_key=404659989876073…_&display=page&locale=en_GB&logger_id=9f59d18b-00cb-48a9-a544-7e49a66acfe4' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access.

I can understand that this is CORS issue, I have searched a lot of place but all the solutions which are available online are not working for me. Like allowing cross origin in express, using third party library for it etc.

Here is my app.ts

import * as express from 'express';
import { json, urlencoded } from 'body-parser';
import * as path from 'path';
import * as cors from 'cors';
import * as compression from 'compression';
import * as mongoose from 'mongoose';
import * as ejs from 'ejs';
import * as passport from 'passport';
import * as session from 'express-session';

import { MONGODB_URI } from './config';
import { AuthConfig } from './api/auth/passport';

import { thingRouter } from './api/thing/';
import { userRouter } from './api/user';

const app: express.Application = express();

app.disable('x-powered-by');

app.use(json());
app.use(compression());
app.use(urlencoded({ extended: true }));
app.use(session({ secret: 'my-secret-key', resave: true, saveUninitialized: true }));
app.use(passport.initialize());
app.use(passport.session());

mongoose.connect(process.env.MONGODB_URI || MONGODB_URI);

// allow cors only for local dev

app.use(cors({
  origin: 'http://localhost:4200'
}));

AuthConfig(passport);
// app.set('env', 'production');

// api routes

app.use('/api/thing', thingRouter);
app.use('/api/user', userRouter);

if (app.get('env') === 'production') {

  // in production mode run application from dist folder
  app.use(express.static(path.join(__dirname, '/../client')));
  app.engine('html', ejs.renderFile);
  app.set('view engin', 'html');
}

// catch 404 and forward to error handler
app.use(function (req: express.Request, res: express.Response, next) {
  res.render(path.join(__dirname, '/../client/index.html'));
});

// production error handler
// no stacktrace leaked to user
app.use(function (err: any, req: express.Request, res: express.Response, next: express.NextFunction) {

  res.status(err.status || 500);
  res.json({
    error: {},
    message: err.message
  });
});

export { app }

passport.ts

let LocalStrategy = require('passport-local').Strategy;
let FacebookStrategy = require('passport-facebook').Strategy;

import { FacebookAuth } from '../../config';

import { User } from '../user/user.model'

import * as uuid from 'uuid';

 let passportConfig = function (passport) {
  passport.serializeUser((user, done) => {
    console.log('serializeing user');
    done(null, user.id);
  });

  passport.deserializeUser((id, done) => {
    console.log('deserializing user');
    User.findOne({ id: id }, (err, user) => {
      done(err, user);
    })
  });

  // Facebook Strategy
  passport.use(new FacebookStrategy({
    clientID: FacebookAuth.clientId,
    clientSecret: FacebookAuth.clientSecret,
    callbackURL: FacebookAuth.callbackURL // for my app - 'http://localhost:4200/api/user/facebook/callback'
  },
  (token, refreshToken, profile, done) => {
    console.log('in passport.js'); //never printed
    console.log('token', token); //never printed
    console.log('refreshToken', refreshToken); //never printed
    console.log('profile', profile); // never printed
    User.findOne({ 'facebook.id': profile.id}, (err, user) => {
      if (err) { return done(err) }
      if (user) { return done(null, user) }
      let newUser = new User();
      newUser.id = uuid.v4();
      newUser.facebook.id = profile.id;
      newUser.facebook.token = token;
      newUser.name = profile.name.givenName + ' ' + profile.name.familyName;
      newUser.email = profile.emails[0].value;
      newUser.save(err => {
        if (err) { return done(err) }
        return done(null, newUser);
      })
    })
  }));
}

export let AuthConfig = passportConfig;

route file

import { Router } from 'express';

import { UserController } from './user.controller';

const userRouter: Router = Router();
const controller: UserController = new UserController();

userRouter.get('/facebook', controller.facebook);
userRouter.get('/facebook/callback', controller.facebookCallback);

export { userRouter };

User controller file

import { Router, Response, Request, NextFunction } from 'express';
import * as passport from 'passport';
import * as uuid from 'uuid';

import { User } from './user.model';

export class UserController {
  constructor() { }

  facebook(req: Request, res: Response, next: NextFunction) {
    console.log('got the request in facebook()'); //this get printed
    passport.authenticate('facebook')(req, res, next);

  }

  facebookCallback(req: Request, res: Response, next: NextFunction) {
    console.log('got the call in facebookCallback()');
    passport.authenticate('facebook', (err, user) => {
      console.log('passport callback\'s callback');
      if (err) {
        return res.status(200)
        .json({
          title: 'error',
          data: err
        })
      }
      return res.status(200)
        .json({
          title: 'logged in',
          data: user
        })
    })
  }
}

**HTML for facebook icon with click event **

Angular 2 component (function) which is working fine

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormControl, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { ToastyService, ToastyConfig, ToastOptions, ToastData } from 'ng2-toasty';

import { AuthService } from './../../services/auth/auth.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.less']
})
export class LoginComponent implements OnInit {

  constructor(private toastyService: ToastyService,
    private router: Router,
    private toastyConfig: ToastyConfig,
    private authService: AuthService) {

    this.toastyConfig.theme = 'bootstrap';

  }

  ngOnInit() {
      }

  facebookLogin() {
    this.authService.facebookLogin()
    .subscribe(
      data => {
        console.log('login.component data', data);
      },
      err => {
        console.log('login.component err', err);
      }
    )
  }

}

Auth Service

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import 'rxjs/Rx';

@Injectable()
export class AuthService {

  constructor(private http: Http) {
  }

  facebookLogin() {
    return this.http.get('/api/user/facebook')
    .map(response => response.json())
    .catch(err => Observable.throw(err.json));
  }

}


来源: stackexchange

问:
using matb33:collection-hooks in typescript
I am creating an Angular2-Meteor app, starting with the Socially tutorial. I am trying to implement user Roles using alanning:roles and matb33:collection-hooks. The solution would be similar to that proposed here. The only difference would be that Angular 2 requires typescript definitions for Roles and Collection-Hooks.
I have found meteor-typescript-libs, which has a definition for Roles that seems to work. However, the only resource for collection-hooks I found was typed-meteor-collection-hooks. I tried referencing index.d.ts by copy/pasting the file into my project, but I still get the following error:

server/imports/accounts.ts (30, 14): Property 'after' does not exist on type 'Collection < User >'.

At the following line:

```<code>Meteor.users.after.insert(function (userId, doc) {
if (doc.profile.type === "basic") {
    Roles.addUsersToRoles(doc._id, [ROLES.Basic])
} else if (doc.profile.type === "admin") {
    Roles.addUsersToRoles(doc._id, [ROLES.Admin])
} else if (doc.profile.type === "manager") {
    Roles.addUsersToRoles(doc._id, [ROLES.Manager])
}});
</code>```

I am new to typescript, and it's not clear to me how I should implement type definitions for Meteor Packages. Clearly, my approach is wrong. Does anyone have any experience with roles and collection-hooks in Meteor-Angular2?

UPDATE: It seems like the Meteor.users.after.insert() code is executing after inserting a user, despite the error. I am continuing development, but would appreciate a solution for removing the error.

答:
Have you tried installing the typings from npm?

https://www.npmjs.com/package/@types/meteor-collection-hooks

Don't forget to also add to your tsconfig "types" array like:

```<code>"types": [
  "@types/meteor-collection-hooks"
]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am creating an Angular2-Meteor app, starting with the Socially tutorial. I am trying to implement user Roles using alanning:roles and matb33:collection-hooks. The solution would be similar to that proposed here. The only difference would be that Angular 2 requires typescript definitions for Roles and Collection-Hooks.
I have found meteor-typescript-libs, which has a definition for Roles that seems to work. However, the only resource for collection-hooks I found was typed-meteor-collection-hooks. I tried referencing index.d.ts by copy/pasting the file into my project, but I still get the following error:

server/imports/accounts.ts (30, 14): Property 'after' does not exist on type 'Collection < User >'.

At the following line:

Meteor.users.after.insert(function (userId, doc) {
if (doc.profile.type === "basic") {
    Roles.addUsersToRoles(doc._id, [ROLES.Basic])
} else if (doc.profile.type === "admin") {
    Roles.addUsersToRoles(doc._id, [ROLES.Admin])
} else if (doc.profile.type === "manager") {
    Roles.addUsersToRoles(doc._id, [ROLES.Manager])
}});

I am new to typescript, and it's not clear to me how I should implement type definitions for Meteor Packages. Clearly, my approach is wrong. Does anyone have any experience with roles and collection-hooks in Meteor-Angular2?

UPDATE: It seems like the Meteor.users.after.insert() code is executing after inserting a user, despite the error. I am continuing development, but would appreciate a solution for removing the error.

Body:
Have you tried installing the typings from npm?

https://www.npmjs.com/package/@types/meteor-collection-hooks

Don't forget to also add to your tsconfig "types" array like:

"types": [
  "@types/meteor-collection-hooks"
]


问:
Sublime Text: disable all packages
I'm using Sublime Text 3083.

When I load a file with several thousand lines and try to edit it, it gets amazingly un-responsive to the point that adding/removing even one character takes it seconds.

I have > 20 packages installed and I need a way to disable all of them at once, to check if this issue is package related or o not.

I've searched around and I know that you can disable packages one by one but that's not good when lots of packages are installed. According to this post in the sublime forum, there is no way to do this but the post is rather old (and also not an official statement)

So, is there a way to do this? Perhaps with a package or a --no-packages flag or some other trick?

BTW: for the sake of completeness, after applying the solution I found that there were two packages responsible for the lag: GitGutter and WordHighlight.

答:
Packages can be simply disabled as follows

Press Ctrl+Shift+P to open Command Palette

Type disable, select Package Control: Disable Package

This will give the list of all the Installed Packages, click on the one which you want to disable.

That's it. And you can enable disabled package anytime, just type enable in step:2.

Title: Sublime Text: disable all packages


问:
Global push notification service
I am building a hybrid which needs to be released across globe including china. I have started development with GCM and later came to know that GCM won't work in china. I have two questions

Like china is there any other country that GCM won't work ?

If not GCM, which is best push notification services which will work in china as well as outside china ?

Please suggest.

答:
For your first question, I don't think any other country except China has banned it completely although some Arab countries have their own reason for blocking or banning some of Google's products.

Google restricts access to some of its business services (like YouTube, Gmail, Blogger, Maps) in certain countries or regions, such as Crimea, Cuba, Iran, North Korea, Sudan, Syria, Pakistan and almost all Arab countries.

 Screenshot from here

For your second question, from AWS SNS ( Simple Notification Service),

SNS Mobile Push lets you use Simple Notification Service (SNS) to
  deliver push notifications to Apple, Google, Fire OS, and Windows
  devices, as well as Android devices in China with Baidu Cloud Push.

Title: Global push notification service


问:
How to read selected mock location app in Android M - API 23
I am trying to find a way of reading the new settings for mock locations in Android M.

Before Android M, the mock location setting was a toggle option called "use mock locations", and it was readable with this setting: Settings.Secure.ALLOW_MOCK_LOCATION

With Android M, the mock location setting is an app to select for mock locations, so it is a multi-elements list, which selected element can be "none".

That thread has a solution for determining the source of the location update when listening for locations, but unfortunately I would like to read the setting itself:
How to check for Mock Location in Android Marshmallow?

I would like to read whether there is a selected app for mock locations or not, and ideally the selected app as well. Any idea about how to do that are welcome!

答:
```<code>  PackageManager pm = context.getPackageManager();
    List<ApplicationInfo> packages =
            pm.getInstalledApplications(PackageManager.GET_META_DATA);

    for (ApplicationInfo applicationInfo : packages) {
        try {
            PackageInfo packageInfo = pm.getPackageInfo(applicationInfo.packageName,
                    PackageManager.GET_PERMISSIONS);

            // Get Permissions
            String[] requestedPermissions = packageInfo.requestedPermissions;

            if (requestedPermissions != null) {
                for (int i = 0; i < requestedPermissions.length; i++) {
                    if (requestedPermissions[i].equals("android.permission.ACCESS_MOCK_LOCATION")
                            && !applicationInfo.packageName.equals(context.getPackageName())) {
                        //we get Package name here
                    }
                }
            }
        } catch (PackageManager.NameNotFoundException e) {

        }
    }
</code>```


问:
Securing connection strings and app settings in an Azure App - how to use them locally
In my web app which is hosted as an Azure App Service, I have the following in my web.config for testing:

```<code><connectionStrings>
    <add name="ProductionConnection" providerName="System.Data.SqlClient" connectionString="Data Source=tcp:something.database.windows.net,1433;Initial Catalog=DatabaseName;User Id=admin@sssdddr;Password=Pass@word1;Trusted_Connection=False;Encrypt=True;Connection Timeout=30; MultipleActiveResultSets=True" />
</connectionStrings>
</code>```

I'm trying to follow some basic security best practices here, so I've moved my connection string up to the Application Settings section of my web app:

This particular setting is a bad example because ideally I'd only ever have ProductionConnection stored in Azure and never used locally - but for other connection strings and appSettings used both locally and in production that should should be protected, how should I handle the values when developing locally?

答:
if you're looking for securing secrets/connection strings from developer, go for Azure Key Vault which is designed to secure all your secrets from everyone. Each secret will be exposed as a URI to end developer to consume via REST.

for this, you need to register your application with Azure AD as KeyVault would request for AD Token to provide secrets.

Body:
In my web app which is hosted as an Azure App Service, I have the following in my web.config for testing:

<connectionStrings>
    <add name="ProductionConnection" providerName="System.Data.SqlClient" connectionString="Data Source=tcp:something.database.windows.net,1433;Initial Catalog=DatabaseName;User Id=admin@sssdddr;Password=Pass@word1;Trusted_Connection=False;Encrypt=True;Connection Timeout=30; MultipleActiveResultSets=True" />
</connectionStrings>

I'm trying to follow some basic security best practices here, so I've moved my connection string up to the Application Settings section of my web app:

This particular setting is a bad example because ideally I'd only ever have ProductionConnection stored in Azure and never used locally - but for other connection strings and appSettings used both locally and in production that should should be protected, how should I handle the values when developing locally?


问:
Cannot read functions from external javascript file used by html file
I have an index.html file:

```<code><head>
    <title>Jiggle Into JavaScript</title>
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>

    <p>Press the buttons to change the box!</p>

    <div id="box" style="height:150px; width:150px; background-color:darkorange; margin:25px"></div>

    <button type="button1" onclick="growFunc()">Grow</button>
    <button type="button2" onclick="blueFunc()">Blue</button>
    <button type="button3" onclick="fadeFunc()">Fade</button>
    <button type="button4" onclick="resetFunc()">Reset</button>
    <script type="text/javascript" src="javascript.js"></script>
</body>
</code>```

My javascript.js file looks like this:

```<code>function growFunc() {
    document.getElementById("button1").addEventListener("click",
        function(){document.getElementById("box").style.height = "250px";
    });
}

function blueFunc() {
    document.getElementById("button2").addEventListener("click",
      function(){document.getElementById("box").style.backgroundColor = "blue";
    });
}

function fadeFunc() {

    document.getElementById("button3").addEventListener("click", function(){

        document.getElementById("box").style.backgroundColor = "orange";

    });

}

function resetFunc() {
    document.getElementById("button4").addEventListener("click",
       function(){
        document.getElementById("box").style.height = "150px";
        document.getElementById("box").style.backgroundColor = "darkorange";
       });
}
</code>```

Both files are in the same directory. When I try to run index.html in Firefox, for example, nothing happens when I click on the buttons. But if I have the functions all in the index.html file(see below), it works. I can't seem to find what's wrong with my code(I'm new at this). Thank you for your help.

```<code><head>
<title>Jiggle Into JavaScript</title>
</code>```

```<code><p>Press the buttons to move the box!</p>

<div id="box" style="height:150px; width:150px; background-color:darkorange; margin:25px"></div>

<button id="growBtn">Grow</button>
<button id="blueBtn">Blue</button>
<button id="fadeBtn">Fade</button>
<button id="resetBtn">Reset</button>

<script type="text/javascript">

    document.getElementById("growBtn").addEventListener("click", function(){
        document.getElementById("box").style.height = "250px";
    });

    document.getElementById("blueBtn").addEventListener("click", function(){
         document.getElementById("box").style.backgroundColor = "blue";
    });

    document.getElementById("fadeBtn").addEventListener("click", function(){
        document.getElementById("box").style.backgroundColor = "orange";
    });

    document.getElementById("resetBtn").addEventListener("click", function()
        document.getElementById("box").style.height = "150px";
        document.getElementById("box").style.backgroundColor = "darkorange";
    });
</script>

</body>
</code>```

答:
In your functions you're adding some event listeners, that is not useful because when the function is triggered the click has already been performed.

Just apply CSS changes in the functions.

Plus: your buttons do not have an id, but a type. So you can't select them with getElementById.

Body:
I have an index.html file:

    <title>Jiggle Into JavaScript</title>

Press the buttons to change the box!

    <button type="button1" onclick="growFunc()">Grow</button>
    <button type="button2" onclick="blueFunc()">Blue</button>
    <button type="button3" onclick="fadeFunc()">Fade</button>
    <button type="button4" onclick="resetFunc()">Reset</button>

My javascript.js file looks like this:

function growFunc() {
    document.getElementById("button1").addEventListener("click",
        function(){document.getElementById("box").style.height = "250px";
    });
}

function blueFunc() {
    document.getElementById("button2").addEventListener("click",
      function(){document.getElementById("box").style.backgroundColor = "blue";
    });
}

function fadeFunc() {

    document.getElementById("button3").addEventListener("click", function(){

        document.getElementById("box").style.backgroundColor = "orange";

    });

}

function resetFunc() {
    document.getElementById("button4").addEventListener("click",
       function(){
        document.getElementById("box").style.height = "150px";
        document.getElementById("box").style.backgroundColor = "darkorange";
       });
}

Both files are in the same directory. When I try to run index.html in Firefox, for example, nothing happens when I click on the buttons. But if I have the functions all in the index.html file(see below), it works. I can't seem to find what's wrong with my code(I'm new at this). Thank you for your help.

<title>Jiggle Into JavaScript</title>

Press the buttons to move the box!

<button id="growBtn">Grow</button>
<button id="blueBtn">Blue</button>
<button id="fadeBtn">Fade</button>
<button id="resetBtn">Reset</button>


问:
Trasform cUrl PHP in cUrl C# .Net
I have this cUrl command for PHP:

```<code>curl --user AUTH_KEY:AUTH_SECRET -XPOST https://api.smshosting.it/rest/api/sms/send \
-d "from=mrossi" \
-d "to=393480000000" \
-d "text=Test Sms"
</code>```

POST type = "application/x-www-form-urlencoded"

Info at: https://www.smshosting.it/it/docs/sms-rest-api/invio

but now i need use it in C# .Net 4.5.

I have no idea where to start though, I do not think it's complicated but I have never used the curl in C #

答:
```<code>string url = "https://api.smshosting.it/rest/api/sms/send";
            WebRequest request = WebRequest.Create(url);
            request.ContentType = "application/x-www-form-urlencoded";
            request.Method = "POST";
            string authInfo = "XXXXXXXXXXXX:XXXXXXXXXXXX";
            request.Headers["Authorization"] = "Basic " + Convert.ToBase64String(Encoding.ASCII.GetBytes(authInfo));
            byte[] buffer = Encoding.GetEncoding("UTF-8").GetBytes("from=XXXX&to=XXXXXX&text=XXXXX");
            Stream reqstr = request.GetRequestStream();
            reqstr.Write(buffer, 0, buffer.Length);
            reqstr.Close();
</code>```

Title: Trasform cUrl PHP in cUrl C# .Net

Body:
I have this cUrl command for PHP:

curl --user AUTH_KEY:AUTH_SECRET -XPOST https://api.smshosting.it/rest/api/sms/send \
-d "from=mrossi" \
-d "to=393480000000" \
-d "text=Test Sms"

POST type = "application/x-www-form-urlencoded"

Info at: https://www.smshosting.it/it/docs/sms-rest-api/invio

but now i need use it in C# .Net 4.5.

I have no idea where to start though, I do not think it's complicated but I have never used the curl in C #


问:
git pull on server using hook after I push locally
I'm working with html & css files locally. After I git push the files to my server (into a bare directory which I created with mkdir bare_repos/mysite && cd bare_repos/mysite && git init --bare), I don't want to have to ssh into the server, go into my ~/public_html/mysite directory and type git pull. I think a hook should do this but I'm not sure how?

The files in my bare_repos/mysite/hooks/ directory are: applypatch-msg.sample, post-update.sample, pre-commit.sample, pre-rebase.sample, prepare-commit-msg.sample, commit-msg.sample, pre-applypatch.sample, pre-push.sample, pre-receive.sample, update.sample

Which file should I edit and what should be added to it? I want to be able to push from my local machine and then simply see the changes on website from my browser (no ssh'ing needed)

答:
You need update or post-receive hook enabled in your bare repository. Search for some examples: post-receive, update.

The hooks must be named exactly update or post-receive (not update.sample or post-receive.sh, for example). They also must be executable.


问:
About casting and objects
it's simple, i just want a explanation about this:

```<code>internal class B { // Base class
}
internal class D : B { // Derived class
}
</code>```

in other class I wrote:

```<code>B b3 = new Object(); //compilation time error!
</code>```

why??? We suposse that all  classes inherit from "object"

答:
All classes are objects, but not all objects are {someclass}.

In a similar way, all buses are vehicles, but not all vehicles are buses.

ContentLicense: CC BY-SA 2.5

Title: About casting and objects

Body:
it's simple, i just want a explanation about this:

internal class B { // Base class
}
internal class D : B { // Derived class
}

in other class I wrote:

B b3 = new Object(); //compilation time error!

why??? We suposse that all  classes inherit from "object"


问:
Update Query is being skipped in if statement vb.net
I don't now why the method is being skipped in the if statement Can anybody help me with this problem?

here's the update sql query

```<code>    Public Sub Edituser()
   conn()
   dbconn.Open()
    sql = "UPDATE player SET First Name=@1 Last Name=@2, Gender=@3, Date of Birth=@4, Civil Status=@5, Nationality=@6, Address=@7, Status=@8 WHERE ID = " + TextBox8.Text + ""
    Try
        dbcomm = New MySqlCommand(sql, dbconn)
        dbcomm.Parameters.Add(New MySqlParameter("@1", TextBox1.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@2", TextBox2.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@3", TextBox9.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@4", TextBox3.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@5", TextBox4.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@6", TextBox5.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@7", TextBox6.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@8", TextBox7.Text))
        dbread = dbcomm.ExecuteReader()
        dbread.Close()
        MsgBox("Successfully updated!")
    Catch ex As Exception
    Finally
        dbconn.Close()
    End Try
End Sub
</code>```

and here's the if statement

```<code>Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Or TextBox7.Text = "" Or TextBox9.Text = "" Then
        MsgBox("Please complete all the fields")
    Else
        Dim result As Integer = MessageBox.Show("Are you sure you want to Edit the information?", "Update", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
        If result = DialogResult.OK Then

            Edituser()

            MsgBox(" Player information Updated!")
            Me.Close()
            Player.Show()
        End If

    End If
End Sub
</code>```

Thanks in advance.

答:
sub is called edituser, you are calling editplayer?

ok. you are squashing the error in the empty catch block. most likely you are hitting a sql error passing the date parameter as a string.

you would need to remove the try catch to get a look at the error message, or output it to console/msgbox.

also what @Rahul says also is correct. possibly combination of both.

Body:
I don't now why the method is being skipped in the if statement Can anybody help me with this problem?

here's the update sql query

    Public Sub Edituser()
   conn()
   dbconn.Open()
    sql = "UPDATE player SET First Name=@1 Last Name=@2, Gender=@3, Date of Birth=@4, Civil Status=@5, Nationality=@6, Address=@7, Status=@8 WHERE ID = " + TextBox8.Text + ""
    Try
        dbcomm = New MySqlCommand(sql, dbconn)
        dbcomm.Parameters.Add(New MySqlParameter("@1", TextBox1.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@2", TextBox2.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@3", TextBox9.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@4", TextBox3.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@5", TextBox4.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@6", TextBox5.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@7", TextBox6.Text))
        dbcomm.Parameters.Add(New MySqlParameter("@8", TextBox7.Text))
        dbread = dbcomm.ExecuteReader()
        dbread.Close()
        MsgBox("Successfully updated!")
    Catch ex As Exception
    Finally
        dbconn.Close()
    End Try
End Sub

and here's the if statement

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    If TextBox1.Text = "" Or TextBox2.Text = "" Or TextBox3.Text = "" Or TextBox4.Text = "" Or TextBox5.Text = "" Or TextBox6.Text = "" Or TextBox7.Text = "" Or TextBox9.Text = "" Then
        MsgBox("Please complete all the fields")
    Else
        Dim result As Integer = MessageBox.Show("Are you sure you want to Edit the information?", "Update", MessageBoxButtons.OKCancel, MessageBoxIcon.Question)
        If result = DialogResult.OK Then

            Edituser()

            MsgBox(" Player information Updated!")
            Me.Close()
            Player.Show()
        End If

    End If
End Sub

Thanks in advance.


问:
Angular cli assets photo issue - giving 404 not found
I'm trying to import the image file from assets folder like this
background: url('../../assets/img/drag-icon.png')

it gives this error and doesn't load the image
http://localhost:4200/assets/img/drag-icon.png

I couldn't find those images in dist as well

This is my angularcli.json

{   "$schema": "./node_modules/@angular/cli/lib/config/schema.json",
  "project": {
      "name": "app-name"   },   "apps": [
      {
        "root": "src",
        "outDir": "dist",
        "assets": [
          "[assets]",
          "favicon.ico"
        ],
        "index": "index.html",
        "main": "main.ts",
        "polyfills": "polyfills.ts",
        "test": "test.ts",
        "tsconfig": "tsconfig.app.json",
        "testTsconfig": "tsconfig.spec.json",
        "prefix": "wf",
        "styles": [
          "styles.scss"
        ],
        "scripts": [],
        "environmentSource": "environments/environment.ts",
        "environments": {
          "dev": "environments/environment.ts",
          "prod": "environments/environment.prod.ts"
        }
      }   ],   "e2e": {
      "protractor": {
        "config": "./protractor.conf.js"
      }   },   "lint": [
      {
        "project": "src/tsconfig.app.json"
      },
      {
        "project": "src/tsconfig.spec.json"
      },
      {
        "project": "e2e/tsconfig.e2e.json"
      }   ],   "test": {
      "karma": {
        "config": "./karma.conf.js"
      }   },   "defaults": {
      "styleExt": "scss",
      "component": {}   } }

答:
in your angular cli you need to set you asset dir.    angular-cli.json

```<code> "apps": [
        {
          "root": "src",
          "outDir": "dist",
          "assets": [
            "assets", // set here your whatever dir  where you store images
            "favicon.ico"
</code>```

Make Sure your dir in angular cli.

Body:
in your angular cli you need to set you asset dir.    angular-cli.json

 "apps": [
        {
          "root": "src",
          "outDir": "dist",
          "assets": [
            "assets", // set here your whatever dir  where you store images
            "favicon.ico"

Make Sure your dir in angular cli.


问:
Java: Variable requires Class and Interface
I have the following classes and interfaces

```<code>interface R
class A extends Component implements R
class B extends JButton implements R
class C extends JPanel implements R
class D extends xyz (that extends Component) implements R
</code>```

So I have several classes that all extend some kind of Component (more or less directly) and that all implement R.

Then I have a different class F that has variables AND methods that needs to work like this:

```<code>public class F {

  public TYPE myVariable;

  public myMethod void (TYPE argument) {
    //...code...
    myVariable = argument;
    actionThatRequiresComponent(argument);
    argument.actionDefinedInR();
    //...code...
  }

  public anotherMethod void () {
    //...code...
    myMethod(myVariable);
    //...code...
  }
}
</code>```

The problem is, that TYPE has to meet two requirments: It has to be any kind of Component and has to implement the interface R. The variable has therefore the same requirements.

I'm not sure at all which approach to take? Shall I make some kind of abstract classes extending Component, implementing R? Shall I skip the requirement of interface R and just do it with try catch? Shall I work with generic classes and how do I do that when it comes to variables?
Any suggestions?

答:
If you want to write a method that accepts a parameter that must extend Component and implement R, you can do it like this:

```<code>public <T extends Component & R> void myMethod(T item) {
    ...
}
</code>```

Then you should be able to pass into your method any argument whose type extends/implements the types you specified.

See https://docs.oracle.com/javase/tutorial/java/generics/bounded.html

Body:
I have the following classes and interfaces

interface R
class A extends Component implements R
class B extends JButton implements R
class C extends JPanel implements R
class D extends xyz (that extends Component) implements R

So I have several classes that all extend some kind of Component (more or less directly) and that all implement R.

Then I have a different class F that has variables AND methods that needs to work like this:

public class F {

  public TYPE myVariable;

  public myMethod void (TYPE argument) {
    //...code...
    myVariable = argument;
    actionThatRequiresComponent(argument);
    argument.actionDefinedInR();
    //...code...
  }

  public anotherMethod void () {
    //...code...
    myMethod(myVariable);
    //...code...
  }
}

The problem is, that TYPE has to meet two requirments: It has to be any kind of Component and has to implement the interface R. The variable has therefore the same requirements.

I'm not sure at all which approach to take? Shall I make some kind of abstract classes extending Component, implementing R? Shall I skip the requirement of interface R and just do it with try catch? Shall I work with generic classes and how do I do that when it comes to variables?
Any suggestions?

Body:
If you want to write a method that accepts a parameter that must extend Component and implement R, you can do it like this:

public <T extends Component & R> void myMethod(T item) {
    ...
}

Then you should be able to pass into your method any argument whose type extends/implements the types you specified.

See https://docs.oracle.com/javase/tutorial/java/generics/bounded.html


问:
array group by iteration in scala
I have a array with data like this.

```<code>tagid,timestamp,listner,orgid,suborgid,rssi
[4,1496745915,718,4,3,0.30]
[2,1496745915,3878,4,3,0.20]
[4,1496745918,362,4,3,0.60]
[4,1496745913,362,4,3,0.60]
</code>```

I want to iterate this array and find the latest 10 seconds timestamp data for each tag & listner.This is my code.

```<code> override def inputSchema: StructType =
 StructType(StructField("time", StringType) :: StructField("tagid", StringType) :: StructField("listener", StringType) :: StructField("rssi", StringType) :: Nil)

   override def initialize(buffer: org.apache.spark.sql.expressions.MutableAggregationBuffer): Unit = {
buffer(0) = Array[String]();
}

override def update(buffer: MutableAggregationBuffer, input: Row): Unit =      {
buffer(0) = buffer.getAs[WrappedArray[String]](0) :+ (input.getAs[String](0)+";"+
  input.getAs[String](1)+";"+input.getAs[String](2));
}

override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit     =  {
buffer1(0) = buffer1.getAs[WrappedArray[String]](0) ++ buffer2.getAs[WrappedArray[String]](0)
}

override def evaluate(buffer: Row): Any = {
val in_array = buffer.getAs[WrappedArray[String]](0);
}
</code>```

The in_array contains all the data.I dont know how to proceed further .Any help will be appreciated.

答:
First you are not iterating over an array. Your "array" is actually a schema and you should define your dataframe to be this way (i.e. each element should be a column). If your dataframe has arrays of string you can create the columns by using a udf (see here

Next you should convert your timestamp to a timestamp type so it would be orderable.

Lastly you could do argmax (see here) for each of the two column

Title: array group by iteration in scala

Body:
I have a array with data like this.

tagid,timestamp,listner,orgid,suborgid,rssi
[4,1496745915,718,4,3,0.30]
[2,1496745915,3878,4,3,0.20]
[4,1496745918,362,4,3,0.60]
[4,1496745913,362,4,3,0.60]

I want to iterate this array and find the latest 10 seconds timestamp data for each tag & listner.This is my code.

 override def inputSchema: StructType =
 StructType(StructField("time", StringType) :: StructField("tagid", StringType) :: StructField("listener", StringType) :: StructField("rssi", StringType) :: Nil)

   override def initialize(buffer: org.apache.spark.sql.expressions.MutableAggregationBuffer): Unit = {
buffer(0) = Array[String]();
}

override def update(buffer: MutableAggregationBuffer, input: Row): Unit =      {
buffer(0) = buffer.getAs[WrappedArray[String]](0) :+ (input.getAs[String](0)+";"+
  input.getAs[String](1)+";"+input.getAs[String](2));
}

override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit     =  {
buffer1(0) = buffer1.getAs[WrappedArray[String]](0) ++ buffer2.getAs[WrappedArray[String]](0)
}

override def evaluate(buffer: Row): Any = {
val in_array = buffer.getAs[WrappedArray[String]](0);
}

The in_array contains all the data.I dont know how to proceed further .Any help will be appreciated.


问:
What's the point of Perl's map?
Not really getting the point of the map function. Can anyone explain with examples its use?

Are there any performance benefits to using this instead of a loop or is it just sugar?

答:
"Just sugar" is harsh.  Remember, a loop is just sugar -- if's and goto can do everything loop constructs do and more.

Map is a high enough level function that it helps you hold much more complex operations in your head, so you can code and debug bigger problems.

OwnerDisplayName: Brian

Title: What's the point of Perl's map?

LastEditorDisplayName: brian d foy

OwnerDisplayName: Darron


问:
php - How do I weed out similar items from an associative array?
UPDATE: someone edited my question incorrectly, but it's fixed now

Let's say I have the following associative array:

```<code>Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)
</code>```

You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:

```<code>Array ( [Postponement no issue for Man Utd] => 18 )
</code>```

Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".

In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.

Is this possible and how? Thanks in advance.

答:
Ok... the only way to do this is to iterate through the array twice, and have a function compare them:

```<code>foreach ($my_array as $key1 => $value1) {
    foreach ($my_array as $key2 => $value2) {
        if ($key1 != $key2) { // don't compare them if they're the same
            if (compareKeys($key1,$key2)) {
                $my_array[$key1] += $value2;
                unset($my_array[$key2]);
            }
        }
    }
}
</code>```

Then your compareKeys function could look something like this:

```<code>function compareKeys($val1,$val2) {
    return (strpos($val1,$val2)!==false);
}
</code>```

Body:
UPDATE: someone edited my question incorrectly, but it's fixed now

Let's say I have the following associative array:

Array (
[Postponement no issue for Man Utd (BBC) ] => 8
[Postponement no issue for Man Utd ] => 7
[Postponement no issue for Man Utd: Manchester United say they have no issue over Sunday's game at Chelsea being ... ] => 3
)

You'll notice that the term "Postponement no issue for Man Utd" appears in all three keys. I want to turn this array into a new array like this:

Array ( [Postponement no issue for Man Utd] => 18 )

Where 18 is the sum of all values where the key contains "Postponement no issue for Man Utd".

In other words: if one key appears inside another key, the latter is dropped fom the new array and it's value is added on to the former key's value.

Is this possible and how? Thanks in advance.

Body:
Ok... the only way to do this is to iterate through the array twice, and have a function compare them:

foreach ($my_array as $key1 => $value1) {
    foreach ($my_array as $key2 => $value2) {
        if ($key1 != $key2) { // don't compare them if they're the same
            if (compareKeys($key1,$key2)) {
                $my_array[$key1] += $value2;
                unset($my_array[$key2]);
            }
        }
    }
}

Then your compareKeys function could look something like this:

function compareKeys($val1,$val2) {
    return (strpos($val1,$val2)!==false);
}


问:
How to break string by separator into multidimensional array in PHP
I have a string 'value1/value2'. The required output is $_SESSION['value1']['value2']. i tried using explode and then array_reduce over explode values but with no success.

My code looks like

```<code>function set($key, $value){
/* code */
}

set('key1/key2', 'some_text');
</code>```

required output like $_SESSION['key1']['key2'] = 'some_text';

key1/key2 is not fixed it may be 'key1' or 'key1/key2/key3' and so on.
Anyone be make fiddle of it is Highly appreciable.
Thanks

答:
Try this</p>

```<code><?php
  session_start();
  $string  = 'value1/value2';
  $array = explode("/",$string);
  $_SESSION[$array[0]][$array[1]] = "ccccccc";//$_SESSION['value1']['value2']
</code>```

Body:
I have a string 'value1/value2'. The required output is $_SESSION['value1']['value2']. i tried using explode and then array_reduce over explode values but with no success.

My code looks like

function set($key, $value){
/* code */
}

set('key1/key2', 'some_text');

required output like $_SESSION['key1']['key2'] = 'some_text';

key1/key2 is not fixed it may be 'key1' or 'key1/key2/key3' and so on.
Anyone be make fiddle of it is Highly appreciable.
Thanks

Body:
Try this

<?php
  session_start();
  $string  = 'value1/value2';
  $array = explode("/",$string);
  $_SESSION[$array[0]][$array[1]] = "ccccccc";//$_SESSION['value1']['value2']


问:
keywords calling in robot framework for our own java library
i want to write my own keywords java library and call them in my testcases.
i tried in many ways but not found any correct solution.
Even the robot framework documentation is not clear for java based libraries.
Any help would be appreciated.

Thanks,
Venkat.

答:
Have you tried through command line?
The following steps might help you:
1) Create java file, compile it to java class
2) In Test Suite, Import Library as fully qualified name, e.g. if java file which you have made reside under package (not default)
Library  packganame/javafilenamewithoutextension
3) add java class into classpath
4 ) run jybot command
You need to run jybot (robot installed in jython) command to extend robot framework using java.</p>


问:
How to insert item into list in order?
I have a List of DateTimeOffset objects, and I want to insert new ones into the list in order.

```<code>List<DateTimeOffset> TimeList = ...
// determine the order before insert or add the new item
</code>```

Sorry, need to update my question.

```<code>List<customizedClass> ItemList = ...
//customizedClass contains DateTimeOffset object and other strings, int, etc.

ItemList.Sort();    // this won't work until set data comparison with DateTimeOffset
ItemList.OrderBy(); // this won't work until set data comparison with DateTimeOffset
</code>```

Also, how to put DateTimeOffset as the parameter of .OrderBy()?

I have also tried:

```<code>ItemList = from s in ItemList
           orderby s.PublishDate descending    // .PublishDate is type DateTime
           select s;
</code>```

However, it returns this error message,

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Gerneric.List'. An explicit conversion exist (are  you missing a cast?)

答:
I took @Noseratio's answer and reworked and combined it with @Jeppe's answer from here
to get a function that works for Collections that implement IList (I needed it for an ObservableCollection of Paths) and type that does not implement IComparable.</p>

```<code>    /// <summary>
    /// Inserts a new value into a sorted collection.
    /// </summary>
    /// <typeparam name="T">The type of collection values, where the type implements IComparable of itself</typeparam>
    /// <param name="collection">The source collection</param>
    /// <param name="item">The item being inserted</param>
    public static void InsertSorted<T>(this IList<T> collection, T item)
        where T : IComparable<T>
    {
        InsertSorted(collection, item, Comparer<T>.Create((x, y) => x.CompareTo(y)));
    }

    /// <summary>
    /// Inserts a new value into a sorted collection.
    /// </summary>
    /// <typeparam name="T">The type of collection values</typeparam>
    /// <param name="collection">The source collection</param>
    /// <param name="item">The item being inserted</param>
    /// <param name="comparerFunction">An IComparer to comparer T values, e.g. Comparer<T>.Create((x, y) => (x.Property < y.Property) ? -1 : (x.Property > y.Property) ? 1 : 0)</param>
    public static void InsertSorted<T>(this IList<T> collection, T item, IComparer<T> comparerFunction)
    {
        if (collection.Count == 0)
        {
            // Simple add
            collection.Add(item);
        }
        else if (comparerFunction.Compare(item, collection[collection.Count - 1]) >= 0)
        {
            // Add to the end as the item being added is greater than the last item by comparison.
            collection.Add(item);
        }
        else if (comparerFunction.Compare(item, collection[0]) <= 0)
        {
            // Add to the front as the item being added is less than the first item by comparison.
            collection.Insert(0, item);
        }
        else
        {
            // Otherwise, search for the place to insert.
            int index = 0;
            if (collection is List<T> list)
            {
                index = list.BinarySearch(item, comparerFunction);
            }
            else if (collection is T[] arr)
            {
                index = Array.BinarySearch(arr, item, comparerFunction);
            }
            else
            {
                for (int i = 0; i < collection.Count; i++)
                {
                    if (comparerFunction.Compare(collection[i], item) <= 0)
                    {
                        // If the item is the same or before, then the insertion point is here.
                        index = i;
                        break;
                    }

                    // Otherwise loop. We're already tested the last element for greater than count.
                }
            }

            if (index < 0)
            {
                // The zero-based index of item if item is found,
                // otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.
                index = ~index;
            }

            collection.Insert(index, item);
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Title: How to insert item into list in order?

Body:
I have a List of DateTimeOffset objects, and I want to insert new ones into the list in order.

List<DateTimeOffset> TimeList = ...
// determine the order before insert or add the new item

Sorry, need to update my question.

List<customizedClass> ItemList = ...
//customizedClass contains DateTimeOffset object and other strings, int, etc.

ItemList.Sort();    // this won't work until set data comparison with DateTimeOffset
ItemList.OrderBy(); // this won't work until set data comparison with DateTimeOffset

Also, how to put DateTimeOffset as the parameter of .OrderBy()?

I have also tried:

ItemList = from s in ItemList
           orderby s.PublishDate descending    // .PublishDate is type DateTime
           select s;

However, it returns this error message,

Cannot implicitly convert type 'System.Linq.IOrderedEnumerable' to 'System.Collections.Gerneric.List'. An explicit conversion exist (are  you missing a cast?)

Body:
I took @Noseratio's answer and reworked and combined it with @Jeppe's answer from here
to get a function that works for Collections that implement IList (I needed it for an ObservableCollection of Paths) and type that does not implement IComparable.

    /// <summary>
    /// Inserts a new value into a sorted collection.
    /// </summary>
    /// <typeparam name="T">The type of collection values, where the type implements IComparable of itself</typeparam>
    /// <param name="collection">The source collection</param>
    /// <param name="item">The item being inserted</param>
    public static void InsertSorted<T>(this IList<T> collection, T item)
        where T : IComparable<T>
    {
        InsertSorted(collection, item, Comparer<T>.Create((x, y) => x.CompareTo(y)));
    }

    /// <summary>
    /// Inserts a new value into a sorted collection.
    /// </summary>
    /// <typeparam name="T">The type of collection values</typeparam>
    /// <param name="collection">The source collection</param>
    /// <param name="item">The item being inserted</param>
    /// <param name="comparerFunction">An IComparer to comparer T values, e.g. Comparer&lt;T&gt;.Create((x, y) =&gt; (x.Property &lt; y.Property) ? -1 : (x.Property &gt; y.Property) ? 1 : 0)</param>
    public static void InsertSorted<T>(this IList<T> collection, T item, IComparer<T> comparerFunction)
    {
        if (collection.Count == 0)
        {
            // Simple add
            collection.Add(item);
        }
        else if (comparerFunction.Compare(item, collection[collection.Count - 1]) >= 0)
        {
            // Add to the end as the item being added is greater than the last item by comparison.
            collection.Add(item);
        }
        else if (comparerFunction.Compare(item, collection[0]) <= 0)
        {
            // Add to the front as the item being added is less than the first item by comparison.
            collection.Insert(0, item);
        }
        else
        {
            // Otherwise, search for the place to insert.
            int index = 0;
            if (collection is List<T> list)
            {
                index = list.BinarySearch(item, comparerFunction);
            }
            else if (collection is T[] arr)
            {
                index = Array.BinarySearch(arr, item, comparerFunction);
            }
            else
            {
                for (int i = 0; i < collection.Count; i++)
                {
                    if (comparerFunction.Compare(collection[i], item) <= 0)
                    {
                        // If the item is the same or before, then the insertion point is here.
                        index = i;
                        break;
                    }

                    // Otherwise loop. We're already tested the last element for greater than count.
                }
            }

            if (index < 0)
            {
                // The zero-based index of item if item is found,
                // otherwise, a negative number that is the bitwise complement of the index of the next element that is larger than item or, if there is no larger element, the bitwise complement of Count.
                index = ~index;
            }

            collection.Insert(index, item);
        }
    }


问:
How to Formatting XML data using C#, JQuery or HTML
How i can get following XML data to easy understand format.

Input XML Data

```<code><?xml version="1.0"?>
<user>
<details><name>xyz</name><class>mno</class><city>pqr</city></details>
<info><id>321</id><code>654</code></info>
</user>
</code>```

Expected Output

```<code><?xml version="1.0"?>
<user>
    <details>
        <name>xyz</name>
        <class>mno</class>
        <city>pqr</city>
    </details>
    <info>
        <id>321</id>
        <code>654</code>
    </info>
</user>
</code>```

Anyone idea how to do this using HTML,JQuery and C#.

Thank you

答:
I got snippet solution for that XElement.Parse(); using  linq. Example as follow

```<code>string rawStringXML = "<user><details><name><firstname>pradip</firstname><lastname>Talaviya</lastname></name><class>mno</class><city>pqr</city></details><info><id>321</id><code>654</code></info></user>";
XElement message = XElement.Parse(rawStringXML);
Console.WriteLine(message.ToString());
Console.Read();
</code>```

Body:
How i can get following XML data to easy understand format.

Input XML Data

<?xml version="1.0"?>
<user>
<name>xyz</name><class>mno</class><city>pqr</city>
<info><id>321</id>654</info>
</user>

Expected Output

<?xml version="1.0"?>
<user>

        <name>xyz</name>
        <class>mno</class>
        <city>pqr</city>

    <info>
        <id>321</id>
        654
    </info>
</user>

Anyone idea how to do this using HTML,JQuery and C#.

Thank you

Body:
I got snippet solution for that XElement.Parse(); using  linq. Example as follow

string rawStringXML = "<user><details><name><firstname>pradip</firstname><lastname>Talaviya</lastname></name><class>mno</class><city>pqr</city></details><info><id>321</id><code>654</code></info></user>";
XElement message = XElement.Parse(rawStringXML);
Console.WriteLine(message.ToString());
Console.Read();


问:
PSNR values differ in matlab implementation and python
I have implemented a python code for calculating PSNR values of Y channel in YCrCb channel.
I get the PSNR values to be around 35.7dB(for a pair of images)

```<code>import cv2, main
import sys

i1 = cv2.imread(sys.argv[1])
i2 = cv2.imread(sys.argv[2])

i1= cv2.cvtColor(i1, cv2.COLOR_BGR2YCrCb)
i2= cv2.cvtColor(i2, cv2.COLOR_BGR2YCrCb)

print(main.psnr(i1[:,:,0], i2[:,:,0]))
</code>```

In main psnr is defined as:

```<code>def psnr(target, ref):
    import cv2
    target_data = numpy.array(target, dtype=numpy.float64)
    ref_data = numpy.array(ref,dtype=numpy.float64)

    diff = ref_data - target_data
    print(diff.shape)
    diff = diff.flatten('C')

    rmse = math.sqrt(numpy.mean(diff ** 2.))

    return 20 * math.log10(255 / rmse)
</code>```

I got an online implementation(from the paper I am referring to) in matlab
I get PSNR values to be around 37.06dB (for the same pair of images)

```<code>function psnr=compute_psnr(im1,im2)
if size(im1, 3) == 3,
    im1 = rgb2ycbcr(im1);
    im1 = im1(:, :, 1);
end

if size(im2, 3) == 3,
    im2 = rgb2ycbcr(im2);
    im2 = im2(:, :, 1);
end

imdff = double(im1) - double(im2);
imdff = imdff(:);

rmse = sqrt(mean(imdff.^2));
psnr = 20*log10(255/rmse)
</code>```

Can this error be due to errors introduced by numpy or accuracy numpy seems to achieve?

答:
Your two conversion functions seem to produce wildly different results:

Python output:

Octave output:

which explains the discrepancy.

Octave does mention there are several YCbCr standards:

```<code> The formula used for the conversion is dependent on two constants,
 KB and KR which can be specified individually, or according to
 existing standards:

 "601" (default)
      According to the ITU-R BT.601 (formerly CCIR 601) standard.
      Its values of KB and KR are 0.114 and 0.299 respectively.
 "709" (default)
      According to the ITU-R BT.709 standard.  Its values of KB and
      KR are 0.0722 and 0.2116 respectively.
</code>```

Maybe the python version is using a different standard? (or maybe it's a BGR vs RGB issue?). In any case, that's where the discrepancy lies, it doesn't seem to be a matter of numpy precision (when those functions are tested separately with identical inputs, they produce the same results).

EDIT:

According to these:

Why is the Y, converted by rgb2ycbcr in the Matlab, in the range [16, 235]?

http://docs.opencv.org/3.1.0/de/d25/imgproc_color_conversions.html#color_convert_rgb_ycrcb

https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion

python (or rather, the opencv library) seems to be outputting the 'analog' (unscaled) version, whereas matlab / octave is outputting the 'digital' (scaled) version.

This is confirmed:

```<code># Python
RGB = numpy.concatenate(
  ( numpy.array([[[0], [255], [255], [0],   [0],   [0],   [255]]], dtype=numpy.uint8),
    numpy.array([[[0], [0],   [255], [255], [255], [0],   [255]]], dtype=numpy.uint8),
    numpy.array([[[0], [0],   [0],   [0],   [255], [255], [255]]], dtype=numpy.uint8)),
  axis=2)

RGB2Y = cv2.cvtColor(RGB, cv2.COLOR_BGR2YCrCb)
print(RGB2Y)
</code>```

```<code>[[[  0 128 128]
  [ 29 107 255]
  [179   0 171]
  [150  21  43]
  [226 149   1]
  [ 76 255  85]
  [255 128 128]]]
</code>```

```<code>% Octave
pkg load image;
RGB = uint8 (cat (3, [0, 255, 255, 0,   0,   0,   255], ...
                     [0, 0,   255, 255, 255, 0,   255], ...
                     [0, 0,   0,   0,   255, 255, 255]));
RGB2Y = rgb2ycbcr(RGB)
</code>```

```<code>RGB2Y =
 ans(:,:,1) =
   16   81  210  145  170   41  235
 ans(:,:,2) =
   128   90   16   54  166  240  128
 ans(:,:,3) =
   128  240  146   34   16  110  128
</code>```

Therefore, if it's a matter of achieving consistency, I would scale the python results using the conversion formula from analog to digital, mentioned in the wikipedia page above i.e.:

If it's a question of "which version is the most appropriate one for the calculation of PSNR", I don't know, but from what I'm reading in the links above, my money would be on the matlab / octave implementation.

Body:
I have implemented a python code for calculating PSNR values of Y channel in YCrCb channel.
I get the PSNR values to be around 35.7dB(for a pair of images)

import cv2, main
import sys

i1 = cv2.imread(sys.argv[1])
i2 = cv2.imread(sys.argv[2])

i1= cv2.cvtColor(i1, cv2.COLOR_BGR2YCrCb)
i2= cv2.cvtColor(i2, cv2.COLOR_BGR2YCrCb)

print(main.psnr(i1[:,:,0], i2[:,:,0]))

In main psnr is defined as:

def psnr(target, ref):
    import cv2
    target_data = numpy.array(target, dtype=numpy.float64)
    ref_data = numpy.array(ref,dtype=numpy.float64)

    diff = ref_data - target_data
    print(diff.shape)
    diff = diff.flatten('C')

    rmse = math.sqrt(numpy.mean(diff ** 2.))

    return 20 * math.log10(255 / rmse)

I got an online implementation(from the paper I am referring to) in matlab
I get PSNR values to be around 37.06dB (for the same pair of images)

function psnr=compute_psnr(im1,im2)
if size(im1, 3) == 3,
    im1 = rgb2ycbcr(im1);
    im1 = im1(:, :, 1);
end

if size(im2, 3) == 3,
    im2 = rgb2ycbcr(im2);
    im2 = im2(:, :, 1);
end

imdff = double(im1) - double(im2);
imdff = imdff(:);

rmse = sqrt(mean(imdff.^2));
psnr = 20*log10(255/rmse)

Can this error be due to errors introduced by numpy or accuracy numpy seems to achieve?

Body:
Your two conversion functions seem to produce wildly different results:

Python output:

Octave output:

which explains the discrepancy.

Octave does mention there are several YCbCr standards:

 The formula used for the conversion is dependent on two constants,
 KB and KR which can be specified individually, or according to
 existing standards:

 "601" (default)
      According to the ITU-R BT.601 (formerly CCIR 601) standard.
      Its values of KB and KR are 0.114 and 0.299 respectively.
 "709" (default)
      According to the ITU-R BT.709 standard.  Its values of KB and
      KR are 0.0722 and 0.2116 respectively.

Maybe the python version is using a different standard? (or maybe it's a BGR vs RGB issue?). In any case, that's where the discrepancy lies, it doesn't seem to be a matter of numpy precision (when those functions are tested separately with identical inputs, they produce the same results).

EDIT:

According to these:

Why is the Y, converted by rgb2ycbcr in the Matlab, in the range [16, 235]?

http://docs.opencv.org/3.1.0/de/d25/imgproc_color_conversions.html#color_convert_rgb_ycrcb

https://en.wikipedia.org/wiki/YCbCr#ITU-R_BT.601_conversion

python (or rather, the opencv library) seems to be outputting the 'analog' (unscaled) version, whereas matlab / octave is outputting the 'digital' (scaled) version.

This is confirmed:

# Python
RGB = numpy.concatenate(
  ( numpy.array([[[0], [255], [255], [0],   [0],   [0],   [255]]], dtype=numpy.uint8),
    numpy.array([[[0], [0],   [255], [255], [255], [0],   [255]]], dtype=numpy.uint8),
    numpy.array([[[0], [0],   [0],   [0],   [255], [255], [255]]], dtype=numpy.uint8)),
  axis=2)

RGB2Y = cv2.cvtColor(RGB, cv2.COLOR_BGR2YCrCb)
print(RGB2Y)

[[[  0 128 128]
  [ 29 107 255]
  [179   0 171]
  [150  21  43]
  [226 149   1]
  [ 76 255  85]
  [255 128 128]]]

% Octave
pkg load image;
RGB = uint8 (cat (3, [0, 255, 255, 0,   0,   0,   255], ...
                     [0, 0,   255, 255, 255, 0,   255], ...
                     [0, 0,   0,   0,   255, 255, 255]));
RGB2Y = rgb2ycbcr(RGB)

RGB2Y =
 ans(:,:,1) =
   16   81  210  145  170   41  235
 ans(:,:,2) =
   128   90   16   54  166  240  128
 ans(:,:,3) =
   128  240  146   34   16  110  128

Therefore, if it's a matter of achieving consistency, I would scale the python results using the conversion formula from analog to digital, mentioned in the wikipedia page above i.e.:

If it's a question of "which version is the most appropriate one for the calculation of PSNR", I don't know, but from what I'm reading in the links above, my money would be on the matlab / octave implementation.


问:
GIT: fatal: Out of memory, malloc failed (tried to allocate 889192448 bytes)
I have this error while pushing my project to tfs GIT.

fatal: Out of memory, malloc failed (tried to allocate 889192448
  bytes)

答: I had the same problem on windows, exept with checkout another branch. Finally, I couldn't either pull or fetch my project beacause I got out of memory error ("try to allocate..." etc). I did the trick with increasing git pack and core limits but it didn't work for me. Finally, I deleted git from computer and install again. Problem was solved. </p>


问:
CSS3 :target on named tag not working
I am having a hard time getting :target to work on a named tag.

The fiddle is here: https://jsfiddle.net/vgcLartp/1

Any ideas why this is not working?

答:
From w3school:

URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element.
  The :target selector can be used to style the current active target element.

:target selector is useful when within an URL is specified (using an anchor  for example) an element in your HTML.

In your case you can use:

```<code>:target {
    visibility: visible;
    opacity: 1;
}
</code>```

Title: CSS3 :target on named tag not working

Body:
From w3school:

URLs with an # followed by an anchor name link to a certain element within a document. The element being linked to is the target element.
  The :target selector can be used to style the current active target element.

:target selector is useful when within an URL is specified (using an anchor  for example) an element in your HTML.

In your case you can use:

:target {
    visibility: visible;
    opacity: 1;
}


问:
Printing values after a cast to a byte array
I'm trying to understand how to debug data that has been serialized into a byte array. The code shows stripped down problem with failed solution trials.

What I'm trying to achieve is to get a print of the whole array member 12345678 insted of just 78.

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

int main()
{
    uint32_t words[2] = {0x12345678, 0x87654321};
    char * struct_array = &words;

    printf("%x \n", *struct_array);   //  78   prints a lsb byte from the first array member
    printf("%lx \n", *struct_array);   // 78   assuming it would print more than a single byte

    //Perhaps it's printing a single byte because of the char pointer.
    printf("%x \n", (uint32_t) *struct_array);   // 78
    printf("%lx \n", (uint32_t) *struct_array);  // 78
    // Nope
}
</code>```

答:
struct_array is of type char*, i. e. a pointer to char. *struct_array then dereferences to a single char (a single byte), so only the first byte in memory occupied by words is looked at. You get 0x78, because obviously your machine is a little endian one, so data is stored in inverse byte order. Casting a char back to uint32_twon't change anything about that - the value is 0x78, it fits into the 32-bit integer, so it stays 0x78.

If you want to get the whole value, you need to read the whole value, i. e. dereferencing a pointer to uint32_t, which means that you need to cast the pointer before dereferencing it:

```<code>*(uint32_t*)struct_array
</code>```

Body:
I'm trying to understand how to debug data that has been serialized into a byte array. The code shows stripped down problem with failed solution trials.

What I'm trying to achieve is to get a print of the whole array member 12345678 insted of just 78.

#include <stdio.h>
#include <stdint.h>
#include <inttypes.h>

int main()
{
    uint32_t words[2] = {0x12345678, 0x87654321};
    char * struct_array = &words;

    printf("%x \n", *struct_array);   //  78   prints a lsb byte from the first array member
    printf("%lx \n", *struct_array);   // 78   assuming it would print more than a single byte

    //Perhaps it's printing a single byte because of the char pointer.
    printf("%x \n", (uint32_t) *struct_array);   // 78
    printf("%lx \n", (uint32_t) *struct_array);  // 78
    // Nope
}

Body:
struct_array is of type char*, i. e. a pointer to char. *struct_array then dereferences to a single char (a single byte), so only the first byte in memory occupied by words is looked at. You get 0x78, because obviously your machine is a little endian one, so data is stored in inverse byte order. Casting a char back to uint32_twon't change anything about that - the value is 0x78, it fits into the 32-bit integer, so it stays 0x78.

If you want to get the whole value, you need to read the whole value, i. e. dereferencing a pointer to uint32_t, which means that you need to cast the pointer before dereferencing it:

*(uint32_t*)struct_array


问:
Changes in Angular component are not transpiled to js
I am developing my first ASP.NET Core application with Angular 2.

The application must have individual user access. Since there is no template in Visual Studio 2017 for Angular applications I generated an Angular project in Powershell with Yoman, opened it in another Visual Studio and copied all the Angular files and folders into my normal Visual Studio project which has the individual user access template generated.

I was able to make Angular work in my project. The three default pages generated by Yoman appear and work. The second one is a page with an increment button and variable. The problem is that if I change the increment in the "counter.component.ts" from this.currentCount++; to this.currentCount+=3; for example, the change is not reflected in the main-client.js file in the dist folder.

I have added the Target lines in the .csproj file and I do not know how to proceed.

What other options are there?

This is what I have https://1drv.ms/u/s!AvPiv6aM2fzRepKV9J_F0-387Zc

I have added "compileOnSave": true and it still doesn't work

Thank you very much for your help!

答:
This is really dumb, but for anyone else that might come to this step, what I was missing was to build the Angular packages in "Startup.cs" (of course)

In Configure method, in the

```<code>if (env.IsDevelopment())
</code>```

these lines:

```<code>app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
     HotModuleReplacement = true
});
</code>```

and in

```<code>app.UseMvc(routes =>
</code>```

these lines

```<code> routes.MapSpaFallbackRoute(
     name: "spa-fallback",
     defaults: new { controller = "Home", action = "Index" });
</code>```

Body:
This is really dumb, but for anyone else that might come to this step, what I was missing was to build the Angular packages in "Startup.cs" (of course)

In Configure method, in the

if (env.IsDevelopment())

these lines:

app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
     HotModuleReplacement = true
});

and in

app.UseMvc(routes =>

these lines

 routes.MapSpaFallbackRoute(
     name: "spa-fallback",
     defaults: new { controller = "Home", action = "Index" });


问:
Why aren't options being overridden?
In my module pattern, options are 'undefined' for some reason.. does anyone see why they aren't being passed in properly?

```<code>Framework.MyModule = (function(options) {
    var defaults = {
        someOption : 1,
        stuff      : 2
    };
    if (!options) {
        var options = defaults;
    } else {
        for (var index in defaults) {
            if (typeof options[index] == 'undefined')
                options[index] = defaults[index];
        }
    }
    var module = {};

    // Initialize
    _something();

    // Private Methods
    function _something() {}

    // Public Methods
    module.click = function() {};

    return module;
})();

... docready function ...

var options = {
  someOption : 9,
  stuff      : 10
};

Framework.MyModule(options);

... end doc ready ...
</code>```

Please see the fiddle: http://jsfiddle.net/kWHEZ/1/

答:
You're executing the function immediately. That function returns module, which is an object, not a function. Did you mean instead to return a function?

Then call it using:

```<code>Framework.MyModule(options);
</code>```

Title: Why aren't options being overridden?

Body:
In my module pattern, options are 'undefined' for some reason.. does anyone see why they aren't being passed in properly?

Framework.MyModule = (function(options) {
    var defaults = {
        someOption : 1,
        stuff      : 2
    };
    if (!options) {
        var options = defaults;
    } else {
        for (var index in defaults) {
            if (typeof options[index] == 'undefined')
                options[index] = defaults[index];
        }
    }
    var module = {};

    // Initialize
    _something();

    // Private Methods
    function _something() {}

    // Public Methods
    module.click = function() {};

    return module;
})();

... docready function ...

var options = {
  someOption : 9,
  stuff      : 10
};

Framework.MyModule(options);

... end doc ready ...

Please see the fiddle: http://jsfiddle.net/kWHEZ/1/

Body:
You're executing the function immediately. That function returns module, which is an object, not a function. Did you mean instead to return a function?

Then call it using:

Framework.MyModule(options);


问:
Get companion class in companion object
Is there a way to get the javaClass of the companion class inside a companion object without knowing it's name?

I suppose I could get it by doing something like this:

```<code>open class TestClass {
    companion object {
        init {
            val clazz = Class.forName(this::class.java.canonicalName.removeSuffix(".Companion"))
        }
    }
}
</code>```

However, this does not work for class InheritingClass : TestClass(). It would still give me TestClass, not InheritingClass.

I was hoping for something more straightforward like this::class.companionClass.

答:
The companion class itself has no reference to the actual class as you can see in this bytecode

```<code>public final class TestClass$Companion {

     private TestClass$Companion() { // <init> //()V
         <localVar:index=0 , name=this , desc=LTestClass$Companion;, sig=null, start=L1, end=L2>

         L1 {
             aload0 // reference to self
             invokespecial java/lang/Object <init>(()V);
             return
         }
         L2 {
         }
     }

     public TestClass$Companion(kotlin.jvm.internal.DefaultConstructorMarker arg0) { // <init> //(Lkotlin/jvm/internal/DefaultConstructorMarker;)V
         <localVar:index=0 , name=this , desc=LTestClass$Companion;, sig=null, start=L1, end=L2>
         <localVar:index=1 , name=$constructor_marker , desc=Lkotlin/jvm/internal/DefaultConstructorMarker;, sig=null, start=L1, end=L2>

         L1 {
             aload0 // reference to self
             invokespecial TestClass$Companion <init>(()V);
             return
         }
         L2 {
         }
     }
}
</code>```

The reference is only the other way around (see decompiled kotlin class)

```<code>public final class TestClass {
    public static final Companion companion = ...
}
</code>```

So you can either do it as you just did by cutting off the .Companion part of the class name or you reference it by hard with TestClass::class.java (what is in my opinion no problem and the best solution)

Title: Get companion class in companion object

Body:
Is there a way to get the javaClass of the companion class inside a companion object without knowing it's name?

I suppose I could get it by doing something like this:

open class TestClass {
    companion object {
        init {
            val clazz = Class.forName(this::class.java.canonicalName.removeSuffix(".Companion"))
        }
    }
}

However, this does not work for class InheritingClass : TestClass(). It would still give me TestClass, not InheritingClass.

I was hoping for something more straightforward like this::class.companionClass.

Body:
The companion class itself has no reference to the actual class as you can see in this bytecode

public final class TestClass$Companion {

     private TestClass$Companion() { // <init> //()V
         <localVar:index=0 , name=this , desc=LTestClass$Companion;, sig=null, start=L1, end=L2>

         L1 {
             aload0 // reference to self
             invokespecial java/lang/Object <init>(()V);
             return
         }
         L2 {
         }
     }

     public TestClass$Companion(kotlin.jvm.internal.DefaultConstructorMarker arg0) { // <init> //(Lkotlin/jvm/internal/DefaultConstructorMarker;)V
         <localVar:index=0 , name=this , desc=LTestClass$Companion;, sig=null, start=L1, end=L2>
         <localVar:index=1 , name=$constructor_marker , desc=Lkotlin/jvm/internal/DefaultConstructorMarker;, sig=null, start=L1, end=L2>

         L1 {
             aload0 // reference to self
             invokespecial TestClass$Companion <init>(()V);
             return
         }
         L2 {
         }
     }
}

The reference is only the other way around (see decompiled kotlin class)

public final class TestClass {
    public static final Companion companion = ...
}

So you can either do it as you just did by cutting off the .Companion part of the class name or you reference it by hard with TestClass::class.java (what is in my opinion no problem and the best solution)


问:
android - how to change the fb logo size on facebook login button
so I have an Android application and I want to do a Facebook login. For that purpose I implemented the Facebook Login button in my layout. It's the following code now:

```<code><com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="20dp"
    android:textSize="25dp"
    />
</code>```

The problem is, that the Facebook logo is too small:

fb logo too small

Is there a way to make it bigger?

Thanks for your help!

答:
Create custom Facebook button and change visibility on the native Facebook button:

```<code><LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <Button
            android:id="@+id/facebookView"
            android:layout_width="300dp"
            android:layout_height="48dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="12dp"
            android:background="@drawable/btn_frame"
            android:gravity="center"
            android:text="@string/Sign_in_facebook_button"
            android:textColor="@color/colorAccent" />

    <com.facebook.login.widget.LoginButton
            android:id="@+id/facebookButton"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible"
            android:layout_marginBottom="12dp" />

 </LinearLayout>
</code>```

Add a listener to your fake button and simulate click:

```<code>facebookView.setOnClickListener(this);
@Override
public void onClick(View v) {
    if (v.getId() == R.id.facebookView){
       facebookButton.performClick();
    }
}
</code>```

Body:
so I have an Android application and I want to do a Facebook login. For that purpose I implemented the Facebook Login button in my layout. It's the following code now:

<com.facebook.login.widget.LoginButton
    android:id="@+id/login_button"
    android:layout_width="300dp"
    android:layout_height="wrap_content"
    android:paddingTop="5dp"
    android:paddingBottom="5dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:layout_gravity="center_horizontal"
    android:layout_marginBottom="20dp"
    android:textSize="25dp"
    />

The problem is, that the Facebook logo is too small:

fb logo too small

Is there a way to make it bigger?

Thanks for your help!

Body:
Create custom Facebook button and change visibility on the native Facebook button:

<LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

    <Button
            android:id="@+id/facebookView"
            android:layout_width="300dp"
            android:layout_height="48dp"
            android:layout_gravity="center_horizontal"
            android:layout_marginBottom="12dp"
            android:background="@drawable/btn_frame"
            android:gravity="center"
            android:text="@string/Sign_in_facebook_button"
            android:textColor="@color/colorAccent" />

    <com.facebook.login.widget.LoginButton
            android:id="@+id/facebookButton"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:visibility="invisible"
            android:layout_marginBottom="12dp" />

 </LinearLayout>

Add a listener to your fake button and simulate click:

facebookView.setOnClickListener(this);
@Override
public void onClick(View v) {
    if (v.getId() == R.id.facebookView){
       facebookButton.performClick();
    }
}


答:
This:

```<code>char * struct_array = &words;
</code>```

makes struct_array into a pointer to char. De-referencing that will give you a char, you can't change that after the fact by casting.

You can of course cast the pointer before dereferencing (but risk undefined behavior):

```<code>printf("%x\n", *(uint32_t *) struct_array);
</code>```

It's of course better to use the proper de-serializing code, and not attempt to brute-force it by pointer dereferencing trickery. If you have a bunch of bytes that you know represent a larger number, just put it together yourself.

To expand on the last point, if this had been an actual array of bytes:

```<code>const uint8_t data[] = { 0x78, 0x56, 0x34, 0x12 };
</code>```

and you wanted to re-assemble those into a 32-bit unsigned integer, assuming little-endian storage you'd do:

```<code>const uint32_t x = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
printf("x de-serialized into 0x%08x\n", x);
</code>```

That would print x de-serialized into 0x12345678, and all of this without violating anything. :)

Title: Printing values after a cast to a byte array

Body:
This:

char * struct_array = &words;

makes struct_array into a pointer to char. De-referencing that will give you a char, you can't change that after the fact by casting.

You can of course cast the pointer before dereferencing (but risk undefined behavior):

printf("%x\n", *(uint32_t *) struct_array);

It's of course better to use the proper de-serializing code, and not attempt to brute-force it by pointer dereferencing trickery. If you have a bunch of bytes that you know represent a larger number, just put it together yourself.

To expand on the last point, if this had been an actual array of bytes:

const uint8_t data[] = { 0x78, 0x56, 0x34, 0x12 };

and you wanted to re-assemble those into a 32-bit unsigned integer, assuming little-endian storage you'd do:

const uint32_t x = data[0] | (data[1] << 8) | (data[2] << 16) | (data[3] << 24);
printf("x de-serialized into 0x%08x\n", x);

That would print x de-serialized into 0x12345678, and all of this without violating anything. :)


问:
About casting and objects
it's simple, i just want a explanation about this:

```<code>internal class B { // Base class
}
internal class D : B { // Derived class
}
</code>```

in other class I wrote:

```<code>B b3 = new Object(); //compilation time error!
</code>```

why??? We suposse that all  classes inherit from "object"

答:
B is more specialized than Object, therefore you cannot assign an Object instance to a B reference. This is because not every Object is actually a B - only the opposite is true.

Let's assume that you have a field x in the class B. When you instantiate an Object, no memory is reserved for this field, and if you could assign it to a reference of type B, it would therefore try to read or write to unallocated memory, which is not allowed (or useful).

Title: About casting and objects

Body:
it's simple, i just want a explanation about this:

internal class B { // Base class
}
internal class D : B { // Derived class
}

in other class I wrote:

B b3 = new Object(); //compilation time error!

why??? We suposse that all  classes inherit from "object"


Title: array group by iteration in scala

Body:
I have a array with data like this.

tagid,timestamp,listner,orgid,suborgid,rssi
[4,1496745915,718,4,3,0.30]
[2,1496745915,3878,4,3,0.20]
[4,1496745918,362,4,3,0.60]
[4,1496745913,362,4,3,0.60]

I want to iterate this array and find the latest 10 seconds timestamp data for each tag & listner.This is my code.

 override def inputSchema: StructType =
 StructType(StructField("time", StringType) :: StructField("tagid", StringType) :: StructField("listener", StringType) :: StructField("rssi", StringType) :: Nil)

   override def initialize(buffer: org.apache.spark.sql.expressions.MutableAggregationBuffer): Unit = {
buffer(0) = Array[String]();
}

override def update(buffer: MutableAggregationBuffer, input: Row): Unit =      {
buffer(0) = buffer.getAs[WrappedArray[String]](0) :+ (input.getAs[String](0)+";"+
  input.getAs[String](1)+";"+input.getAs[String](2));
}

override def merge(buffer1: MutableAggregationBuffer, buffer2: Row): Unit     =  {
buffer1(0) = buffer1.getAs[WrappedArray[String]](0) ++ buffer2.getAs[WrappedArray[String]](0)
}

override def evaluate(buffer: Row): Any = {
val in_array = buffer.getAs[WrappedArray[String]](0);
}

The in_array contains all the data.I dont know how to proceed further .Any help will be appreciated.

Body:
Suppose this is your array

val arr = Array((4,1499340495,718,4,3,0.30),
                (2,1496745915,3878,4,3,0.20),
                (4,1499340495,362,4,3,0.60),
                (4,1496745913,362,4,3,0.60))

java.time.Instant is available in Java 8

import java.time.instant

arr.filter( x => (Instant.now.getEpochSecond - x._2) <= 10 )


问:
Login HTTP client by JavaScript form to ElasticSearch (readonlyrest)
I want to login to my ElasticSearch via HTTP (with readonlyrest plugin installed).

¿Is there any way to do this thing with an HTML form and JavaScript (Angular) code?

```<code><form class="form-horizontal">
      <div class="form-group">
        <label class="control-label col-sm-2" for="email">Username:</label>
        <div class="col-sm-10">
          <input class="form-control" ng-model="username" placeholder="Enter username">
        </div>
      </div>
      <div class="form-group">
        <label class="control-label col-sm-2" for="pwd">Password:</label>
        <div class="col-sm-10">
          <input type="password" class="form-control" placeholder="Enter password" ng-model="password">
        </div>
      </div>
      <div class="form-group">
        <div class="col-sm-offset-2 col-sm-10">
          <button type="submit" class="btn btn-default" ng-click="login()">Submit</button>
        </div>
      </div>
</form>
</code>```

Code of the login (I want to save the login in the browser for future actions):

```<code>$scope.login = function(){
console.log("Login: ", $scope.username, $scope.password)

var clientId = "sample";
var clientSecret = "sample";

var authorizationBasic = window.btoa(clientId + ':' + clientSecret);

var request = new XMLHttpRequest();
request.open('POST', "https://localhost:5601/omu/elasticsearch/_msearch", true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.send("username=sample&password=sample&grant_type=password");

request.onreadystatechange = function () {
    if (request.readyState === 4) {
       alert(request.responseText);
    }
}}
</code>```

Thx

答:
If you're using basic authentication, try to include the credentials in the path

GET http://user:password@elastichost:9200/endpoint

Body:
I want to login to my ElasticSearch via HTTP (with readonlyrest plugin installed).

¿Is there any way to do this thing with an HTML form and JavaScript (Angular) code?

<form class="form-horizontal">

        Username:

          <input class="form-control" ng-model="username" placeholder="Enter username">

        Password:

          <input type="password" class="form-control" placeholder="Enter password" ng-model="password">

          <button type="submit" class="btn btn-default" ng-click="login()">Submit</button>

</form>

Code of the login (I want to save the login in the browser for future actions):

$scope.login = function(){
console.log("Login: ", $scope.username, $scope.password)

var clientId = "sample";
var clientSecret = "sample";

var authorizationBasic = window.btoa(clientId + ':' + clientSecret);

var request = new XMLHttpRequest();
request.open('POST', "https://localhost:5601/omu/elasticsearch/_msearch", true);
request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
request.setRequestHeader('Authorization', 'Basic ' + authorizationBasic);
request.setRequestHeader('Accept', 'application/json');
request.send("username=sample&password=sample&grant_type=password");

request.onreadystatechange = function () {
    if (request.readyState === 4) {
       alert(request.responseText);
    }
}}

Thx


问:
SQL - Salary difference between 2 months (Variance)
There are 2 separate SQL queries that returning NetPay amount MonthWise. I
want to combine them means i want Variance between 2 months
(Month 2 Amount - Month 1 Amount) as output.</p>

```<code>Query - 1
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

Query - 2
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6
</code>```

答:
```<code>DECLARE @month1 INT
DECLARE @month2 INT

SET @month1= 5
SET @month2= 6

Select (a.month1Amount-b.month2Amount) AS Variance from
(Select ISNULL(Sum(EPS.Amount),0) as month1Amount,EPS.Emp_Id
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id =@month1 GROUP BY EPS.Emp_Id)a
INNER JOIN
(Select ISNULL(Sum(EPS.Amount),0) as month2Amount, EPS.Emp_Id
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id =@month2  GROUP BY EPS.Emp_Id)b
on a.Emp_Id=b.Emp_Id
</code>```

You can Provide Month dynamically. Hope this works

Body:
There are 2 separate SQL queries that returning NetPay amount MonthWise. I
want to combine them means i want Variance between 2 months
(Month 2 Amount - Month 1 Amount) as output.

Query - 1
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 5

Query - 2
Select ISNULL(Sum(EPS.Amount),0) as Amount
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id = 6

Body:
DECLARE @month1 INT
DECLARE @month2 INT

SET @month1= 5
SET @month2= 6

Select (a.month1Amount-b.month2Amount) AS Variance from
(Select ISNULL(Sum(EPS.Amount),0) as month1Amount,EPS.Emp_Id
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id =@month1 GROUP BY EPS.Emp_Id)a
INNER JOIN
(Select ISNULL(Sum(EPS.Amount),0) as month2Amount, EPS.Emp_Id
From Payslip EPS
Where EPS.Emp_Id = 5 and EPS.Month_Id =@month2  GROUP BY EPS.Emp_Id)b
on a.Emp_Id=b.Emp_Id

You can Provide Month dynamically. Hope this works