问:
Azure AD open BearerStrategy "TypeError: self.success is not a function"
I asked this at https://github.com/AzureAD/passport-azure-ad/issues/427 but have had no response.  I feel it is a bug that is preventing me from completing my work so I am reaching farther and wider to get an answer.  Is it something I'm doing or a bug?

I am writing the question different to I had before since I have done some more investigation in to the problem (I will indicate where the differences start).

Passport-Azure-AD version 4.1.0 - https://www.npmjs.com/package/passport-azure-ad#52-bearerstrategy

I have set this up from the documentation:

```<code>setup() {
    const findById = (id, fn) => {
        for (let i = 0, len = this.users.length; i < len; i++) {
            const user = this.users[i];
            if (user.sub === id) {
                logger.info('Found user: ', user);
                return fn(null, user);
            }
        }
        return fn(null, null);
    };

    this.bearerStrategy = new BearerStrategy(jwtOptions,
        (token: ITokenPayload, done: VerifyCallback) => {
            findById(token.oid, (err, user) => {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    // 'Auto-registration'
                    logger.info('User was added automatically as they were new. Their oid is: ', token.oid);
                    this.users.push(token);
                    this.owner = token.oid;
                    return done(null, token);
                }
                this.owner = token.oid;
                return done(null, user, token);
            });
        }
    );
    console.log(`setup bearerStrategy`);
}
</code>```

The jwtOptions I use are:

The options are like this:

```<code>const jwtOptions = {
    identityMetadata: 'https://login.microsoftonline.com/xyz/v2.0/.well-known/openid-configuration',
    clientID: '0123456789',
    loggingLevel: 'info',
    loggingNoPII: false,
    passReqToCallback: false
};
</code>```

And run authentication (from middlewhere) using the following:

```<code>authenticate(request: express.Request) {
    this.bearerStrategy.authenticate(request, {session: false});
}
</code>```

NOTE That this is different to the doco since what they had doesn't work.

It fails on the line:

```<code> return done(null, token);
</code>```

With:

```<code>[2019-05-29T13:49:33.479] [INFO ] [AUTHSERVICE_LOGGER] - User was added automatically as they were new. Their oid is:  123

.../translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:565
        return self.success(user, info);
                    ^
TypeError: self.success is not a function
    at verified (/Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:565:21)
    at findById (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:106:32)
    at findById (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:87:20)
    at Strategy.bearerStrategy.passport_azure_ad_1.BearerStrategy [as _verify] (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:97:17)
    at jwt.verify (/Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:363:19)
    at /Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/jsonWebToken.js:80:16
    at process._tickCallback (internal/process/next_tick.js:61:11)
</code>```

From here is different compared to original post

If I put a breakpoint in the code, the self Object in BearerStrategy.js where the error is:

```<code>{
  "name": "oauth-bearer",
  "_options": {
    "identityMetadata": "https://login.microsoftonline.com/xyz/v2.0/.well-known/openid-configuration",
    "clientID": "0123456789",
    "loggingLevel": "info",
    "loggingNoPII": false,
    "passReqToCallback": false,
    "clockSkew": 300,
    "validateIssuer": true,
    "allowMultiAudiencesInToken": false,
    "audience": [
      "1234",
      "spn:1234"
    ],
    "isB2C": false,
    "_isCommonEndpoint": false,
    "_verify" = (token, done) => {...},
    "__proto__" = Strategy(...,
  }
}
</code>```

And under __proto__ are:

```<code> authenticate = function authenticateStrategy(req, options) {
 constructor = function Strategy(options, verifyFn) {
 failWithLog = function(message) {
 jwtVerify = function jwtVerifyFunc(req, token, metadata, optionsToValidate, done) {
 loadMetadata = function(params, next) {
</code>```

You can see there is no success in Passport-Azure-Ad.  It does define a failWithLog https://github.com/AzureAD/passport-azure-ad/blob/e9684341920ac8ac41c55a1e7150d1765dced809/lib/bearerstrategy.js#L600 - did they forget to add the others?

Passport defines these others (https://github.com/jaredhanson/passport/blob/1c8ede35a334d672024e14234f023a87bdccaac2/lib/middleware/authenticate.js#L230) however they are in a closure and never exposed. Nor is the parent Strategy object that they are defined on.  The only connection with the outside is through the exposed authenticate method https://github.com/jaredhanson/passport/blob/1c8ede35a334d672024e14234f023a87bdccaac2/lib/middleware/authenticate.js#L70

However as seen, Passport-Azure-Ad defines it's own authenticate method (https://github.com/AzureAD/passport-azure-ad/blob/e9684341920ac8ac41c55a1e7150d1765dced809/lib/bearerstrategy.js#L372) and never calls the passsport one.

To me it looks like it never worked.

Can anyone confirm or disagree?

I will update the post at https://github.com/AzureAD/passport-azure-ad/issues/427 to refer to this.

Next I am going to git bisect the repository to see if I can find a change where those missing methods used to be defined or something else that stands out.

答:
I can confirm that as my code was written it would never work.  There were two main issues:

Pass parameters

As per my comment against the question, i neglected to provide information in the question since I didn't think it was relevant.  But it is.

I am using TSED - TypeScript Express Decorators (https://tsed.io) and it replaces express middleware code like:

```<code>   server.get('/api/tasks', passport.authenticate('oauth-bearer', { session: false }), listTasks);
</code>```

With an annotated middleware class - https://tsed.io/docs/middlewares.html

So now the call to passport.authenticate() is in the use() method like this as I showed before (THIS IS INCORRECT):

```<code>@OverrideMiddleware(AuthenticatedMiddleware)
export class UserAuthMiddleware implements IMiddleware {
    constructor(@Inject() private authService: AuthService) {
    }

    public use(
        @EndpointInfo() endpoint: EndpointMetadata,
        @Request() request: express.Request,
        @Response() response: express.Response,
        @Next() next: express.NextFunction
    ) {
        const options = endpoint.get(AuthenticatedMiddleware) || {};
        Passport.authenticate('oauth-bearer', {session: false});  // <-- WRONG
        if (!request.isAuthenticated()) {
            throw new Forbidden('Forbidden');
        }
        next();
    }
}
</code>```

What I neglected to consider is that express middleware is passed the request object.  So what I actually needed to have was:

```<code>        Passport.authenticate('oauth-bearer', {session: false})(request, response, next);  // <-- CORRECT
</code>```

Must use Passport.use()

The documentation is misleading.  Given I'm not overly savy with Passport I didn't think much about this.

The doco (http://www.passportjs.org/packages/passport-azure-ad/) (at 5.2.1.1 Sample using the BearerStrategy) says to use:

```<code>var bearerStrategy = new BearerStrategy(options,
  function(token, done) {
    log.info('verifying the user');
    log.info(token, 'was the token retreived');
    findById(token.oid, function(err, user) {
      if (err) {
        return done(err);
      }
      if (!user) {
        // "Auto-registration"
        log.info('User was added automatically as they were new. Their oid is: ', token.oid);
        users.push(token);
        owner = token.oid;
        return done(null, token);
      }
      owner = token.oid;
      return done(null, user, token);
    });
  }
);
</code>```

I am aware that when other strategies are described (such as the 5.1 OIDCStrategy on the same page):

```<code>passport.use(new OIDCStrategy({
    identityMetadata: config.creds.identityMetadata,
    clientID: config.creds.clientID,
    ...
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    ...
  }
));
</code>```

They use passport.use.  I thought about the difference (when i first saw it) for 1/2 a second and concluded that the AAD BearerStrategy handles things differently given the login is done by Azure using their msal.js library.  And I didn't revisit this until Fix # 1 above didn't fix the problem.

I conclude that the TSED project needs to update their documentation / samples (I will do this for them); and the Passport Azure AD project needs to update their doco.

There are still some issues and I don't know who is at fault.  I wrote about these at Passport-Azure-Ad in TSED framework seems to run asynchronously.

Body:
I asked this at https://github.com/AzureAD/passport-azure-ad/issues/427 but have had no response.  I feel it is a bug that is preventing me from completing my work so I am reaching farther and wider to get an answer.  Is it something I'm doing or a bug?

I am writing the question different to I had before since I have done some more investigation in to the problem (I will indicate where the differences start).

Passport-Azure-AD version 4.1.0 - https://www.npmjs.com/package/passport-azure-ad#52-bearerstrategy

I have set this up from the documentation:

setup() {
    const findById = (id, fn) => {
        for (let i = 0, len = this.users.length; i < len; i++) {
            const user = this.users[i];
            if (user.sub === id) {
                logger.info('Found user: ', user);
                return fn(null, user);
            }
        }
        return fn(null, null);
    };

    this.bearerStrategy = new BearerStrategy(jwtOptions,
        (token: ITokenPayload, done: VerifyCallback) => {
            findById(token.oid, (err, user) => {
                if (err) {
                    return done(err);
                }
                if (!user) {
                    // 'Auto-registration'
                    logger.info('User was added automatically as they were new. Their oid is: ', token.oid);
                    this.users.push(token);
                    this.owner = token.oid;
                    return done(null, token);
                }
                this.owner = token.oid;
                return done(null, user, token);
            });
        }
    );
    console.log(`setup bearerStrategy`);
}

The jwtOptions I use are:

The options are like this:

const jwtOptions = {
    identityMetadata: 'https://login.microsoftonline.com/xyz/v2.0/.well-known/openid-configuration',
    clientID: '0123456789',
    loggingLevel: 'info',
    loggingNoPII: false,
    passReqToCallback: false
};

And run authentication (from middlewhere) using the following:

authenticate(request: express.Request) {
    this.bearerStrategy.authenticate(request, {session: false});
}

NOTE That this is different to the doco since what they had doesn't work.

It fails on the line:

 return done(null, token);

With:

[2019-05-29T13:49:33.479] [INFO ] [AUTHSERVICE_LOGGER] - User was added automatically as they were new. Their oid is:  123

.../translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:565
        return self.success(user, info);
                    ^
TypeError: self.success is not a function
    at verified (/Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:565:21)
    at findById (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:106:32)
    at findById (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:87:20)
    at Strategy.bearerStrategy.passport_azure_ad_1.BearerStrategy [as _verify] (/Users/bbos/dev/dhs/translate/translateboard/server/src/services/AuthService.ts:97:17)
    at jwt.verify (/Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/bearerstrategy.js:363:19)
    at /Users/bbos/dev/dhs/translate/translateboard/node_modules/passport-azure-ad/lib/jsonWebToken.js:80:16
    at process._tickCallback (internal/process/next_tick.js:61:11)

From here is different compared to original post

If I put a breakpoint in the code, the self Object in BearerStrategy.js where the error is:

{
  "name": "oauth-bearer",
  "_options": {
    "identityMetadata": "https://login.microsoftonline.com/xyz/v2.0/.well-known/openid-configuration",
    "clientID": "0123456789",
    "loggingLevel": "info",
    "loggingNoPII": false,
    "passReqToCallback": false,
    "clockSkew": 300,
    "validateIssuer": true,
    "allowMultiAudiencesInToken": false,
    "audience": [
      "1234",
      "spn:1234"
    ],
    "isB2C": false,
    "_isCommonEndpoint": false,
    "_verify" = (token, done) => {...},
    "__proto__" = Strategy(...,
  }
}

And under __proto__ are:

 authenticate = function authenticateStrategy(req, options) {
 constructor = function Strategy(options, verifyFn) {
 failWithLog = function(message) {
 jwtVerify = function jwtVerifyFunc(req, token, metadata, optionsToValidate, done) {
 loadMetadata = function(params, next) {

You can see there is no success in Passport-Azure-Ad.  It does define a failWithLog https://github.com/AzureAD/passport-azure-ad/blob/e9684341920ac8ac41c55a1e7150d1765dced809/lib/bearerstrategy.js#L600 - did they forget to add the others?

Passport defines these others (https://github.com/jaredhanson/passport/blob/1c8ede35a334d672024e14234f023a87bdccaac2/lib/middleware/authenticate.js#L230) however they are in a closure and never exposed. Nor is the parent Strategy object that they are defined on.  The only connection with the outside is through the exposed authenticate method https://github.com/jaredhanson/passport/blob/1c8ede35a334d672024e14234f023a87bdccaac2/lib/middleware/authenticate.js#L70

However as seen, Passport-Azure-Ad defines it's own authenticate method (https://github.com/AzureAD/passport-azure-ad/blob/e9684341920ac8ac41c55a1e7150d1765dced809/lib/bearerstrategy.js#L372) and never calls the passsport one.

To me it looks like it never worked.

Can anyone confirm or disagree?

I will update the post at https://github.com/AzureAD/passport-azure-ad/issues/427 to refer to this.

Next I am going to git bisect the repository to see if I can find a change where those missing methods used to be defined or something else that stands out.

Body:
I can confirm that as my code was written it would never work.  There were two main issues:

Pass parameters

As per my comment against the question, i neglected to provide information in the question since I didn't think it was relevant.  But it is.

I am using TSED - TypeScript Express Decorators (https://tsed.io) and it replaces express middleware code like:

   server.get('/api/tasks', passport.authenticate('oauth-bearer', { session: false }), listTasks);

With an annotated middleware class - https://tsed.io/docs/middlewares.html

So now the call to passport.authenticate() is in the use() method like this as I showed before (THIS IS INCORRECT):

@OverrideMiddleware(AuthenticatedMiddleware)
export class UserAuthMiddleware implements IMiddleware {
    constructor(@Inject() private authService: AuthService) {
    }

    public use(
        @EndpointInfo() endpoint: EndpointMetadata,
        @Request() request: express.Request,
        @Response() response: express.Response,
        @Next() next: express.NextFunction
    ) {
        const options = endpoint.get(AuthenticatedMiddleware) || {};
        Passport.authenticate('oauth-bearer', {session: false});  // <-- WRONG
        if (!request.isAuthenticated()) {
            throw new Forbidden('Forbidden');
        }
        next();
    }
}

What I neglected to consider is that express middleware is passed the request object.  So what I actually needed to have was:

        Passport.authenticate('oauth-bearer', {session: false})(request, response, next);  // <-- CORRECT

Must use Passport.use()

The documentation is misleading.  Given I'm not overly savy with Passport I didn't think much about this.

The doco (http://www.passportjs.org/packages/passport-azure-ad/) (at 5.2.1.1 Sample using the BearerStrategy) says to use:

var bearerStrategy = new BearerStrategy(options,
  function(token, done) {
    log.info('verifying the user');
    log.info(token, 'was the token retreived');
    findById(token.oid, function(err, user) {
      if (err) {
        return done(err);
      }
      if (!user) {
        // "Auto-registration"
        log.info('User was added automatically as they were new. Their oid is: ', token.oid);
        users.push(token);
        owner = token.oid;
        return done(null, token);
      }
      owner = token.oid;
      return done(null, user, token);
    });
  }
);

I am aware that when other strategies are described (such as the 5.1 OIDCStrategy on the same page):

passport.use(new OIDCStrategy({
    identityMetadata: config.creds.identityMetadata,
    clientID: config.creds.clientID,
    ...
  },
  function(iss, sub, profile, accessToken, refreshToken, done) {
    ...
  }
));

They use passport.use.  I thought about the difference (when i first saw it) for 1/2 a second and concluded that the AAD BearerStrategy handles things differently given the login is done by Azure using their msal.js library.  And I didn't revisit this until Fix # 1 above didn't fix the problem.

I conclude that the TSED project needs to update their documentation / samples (I will do this for them); and the Passport Azure AD project needs to update their doco.

There are still some issues and I don't know who is at fault.  I wrote about these at Passport-Azure-Ad in TSED framework seems to run asynchronously.


来源: stackexchange

问:
How can i use Spark Context?
I assign the value as sc = pyspark.SparkContext(). It run and doesnt respond for so long on jupyter notebook as asteric sign appears and doesnt show any error or so.

I tried sc = SparkContext()

```<code>import pyspark
import os
from pyspark import SparkContext, SparkConf
sc = pyspark.SparkContext()  # At this part it don't respond
from pyspark.sql import SQLContext
sqlc = SQLContext(sc)
</code>```

It should go on.

答:
For Python,

```<code>from pyspark import SparkContext
sc = SparkContext(appName = "test")
</code>```

But since you're working on pyspark version 2+ , you dont need to initialize spark context. You can create a spark session and directly work on it.

SPARK 2.0.0 onwards, SparkSession provides a single point of entry to interact with underlying Spark functionality and allows programming Spark with DataFrame and Dataset APIs. All the functionality available with sparkContext are also available in sparkSession.

In order to use APIs of SQL, HIVE, and Streaming, no need to create separate contexts as sparkSession includes all the APIs.

To configure a spark session,

```<code>session = SparkSession.builder.getOrCreate()
</code>```

ContentLicense: CC BY-SA 4.0

Title: How can i use Spark Context?

Body:
I assign the value as sc = pyspark.SparkContext(). It run and doesnt respond for so long on jupyter notebook as asteric sign appears and doesnt show any error or so.

I tried sc = SparkContext()

import pyspark
import os
from pyspark import SparkContext, SparkConf
sc = pyspark.SparkContext()  # At this part it don't respond
from pyspark.sql import SQLContext
sqlc = SQLContext(sc)

It should go on.

Body:
For Python,

from pyspark import SparkContext
sc = SparkContext(appName = "test")

But since you're working on pyspark version 2+ , you dont need to initialize spark context. You can create a spark session and directly work on it.

SPARK 2.0.0 onwards, SparkSession provides a single point of entry to interact with underlying Spark functionality and allows programming Spark with DataFrame and Dataset APIs. All the functionality available with sparkContext are also available in sparkSession.

In order to use APIs of SQL, HIVE, and Streaming, no need to create separate contexts as sparkSession includes all the APIs.

To configure a spark session,

session = SparkSession.builder.getOrCreate()


问:
How to break a long line with math operators?
For example

```<code>int abcdefghijklmn = aaaaaaaaaaaa   / bbbaaaaaaaa   * ccccaaaaaaaa   - aaaaaaaaaaaa * asdfasdfasdfasdf;
</code>```

where to break?

Is there any guidance to do that?

Or is it safe to break anywhere?

```<code>int abcdefghijklmn = aaaaaaaaaaaa   /
   bbbaaaaaaaa   * ccccaaaaaaaa   - aaaaaaaaaaaa * asdfasdfasdfasdf;

int abcdefghijklmn = aaaaaaaaaaaa
   /   bbbaaaaaaaa   * ccccaaaaaaaa   - aaaaaaaaaaaa * asdfasdfasdfasdf;
</code>```

Do I need to put backslash in the end ?

答:
I always put operators in the beginning if I have to break the line</p>

```<code>int abcdefghijklmn = aaaaaaaaaaaa
   /   bbbaaaaaaaa
   * ccccaaaaaaaa
   - aaaaaaaaaaaa
   * asdfasdfasdfasdf;
</code>```

Body:
For example

int abcdefghijklmn = aaaaaaaaaaaa   / bbbaaaaaaaa   * ccccaaaaaaaa   - aaaaaaaaaaaa * asdfasdfasdfasdf;

where to break?

Is there any guidance to do that?

Or is it safe to break anywhere?

int abcdefghijklmn = aaaaaaaaaaaa   /
   bbbaaaaaaaa   * ccccaaaaaaaa   - aaaaaaaaaaaa * asdfasdfasdfasdf;

int abcdefghijklmn = aaaaaaaaaaaa
   /   bbbaaaaaaaa   * ccccaaaaaaaa   - aaaaaaaaaaaa * asdfasdfasdfasdf;

Do I need to put backslash in the end ?

Body:
I always put operators in the beginning if I have to break the line

int abcdefghijklmn = aaaaaaaaaaaa
   /   bbbaaaaaaaa
   * ccccaaaaaaaa
   - aaaaaaaaaaaa
   * asdfasdfasdfasdf;


问:
Connection error accessing Sage Timberline Accounting with PHP and ODBC on Windows
I'm trying to connect to a Sage Timberline Accounting database on my Windows 2003 Server using PHP 5.3. I have PHP correctly installed with IIS as fastcgi. I have a system DSN setup in ODBC Manager and correctly configured for the Timberline database.

Here is my PHP script.

```<code><?php

$conn = odbc_connect("Timberline ODBC","user", "password");

?>
</code>```

I get the following error:

Warning: odbc_connect(): SQL error: [Sage Timberline Office][Sage Timberline Office ODBC Driver][DRM File Library]Invalid account name., SQL state 08001 in SQLConnect in C:\Inetpub\wwwroot\index.php on line 3

It doesn't matter what valid Timberline username and password combination I try.

Can anyone help?

答:
Not sure if this is still a question or not...but you do realize that a pervasive SQL connection is to a index file that then has index references to the other information?  Better known as a flat-file database structure.

As such, there is no clean cut way to make the connection.  I am working on a similar problem with bridging my MSSQL server to the Timberline Database and it is not as clean cut as you would think.

Have you tried loading the Timberline Driver onto the webserver or into the application in question for consumption?  Sage has not made it easy for you to access this information at all and if i have my 2 cents to say about this application suite, i would suggest against it at ALL cost.

So far here is a connection string that works, via VS2k5.  It is a DSN string but connection string none the less.  Problem i am having is dissoicating the DSN part from the connection string and getting it to work properly.

```<code>DSN=<whatever>;uid=<userid>;dbq=<PathToDirectory>;codepage=1252;
maxcolsupport=1536;dictionarymode=0;standardmode=0;shortennames=1;databasetype=1
</code>```

This is supposed to work for ADO, but cant get it to work properly:

```<code>Provider=MSDASQL.1;Driver={Timberline Data};dbq=<PathToDirectory>;
uid=<userid>;pwd=<password>;codepage=1252
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to connect to a Sage Timberline Accounting database on my Windows 2003 Server using PHP 5.3. I have PHP correctly installed with IIS as fastcgi. I have a system DSN setup in ODBC Manager and correctly configured for the Timberline database.

Here is my PHP script.

<?php

$conn = odbc_connect("Timberline ODBC","user", "password");

?>

I get the following error:

Warning: odbc_connect(): SQL error: [Sage Timberline Office][Sage Timberline Office ODBC Driver][DRM File Library]Invalid account name., SQL state 08001 in SQLConnect in C:\Inetpub\wwwroot\index.php on line 3

It doesn't matter what valid Timberline username and password combination I try.

Can anyone help?

Body:
Not sure if this is still a question or not...but you do realize that a pervasive SQL connection is to a index file that then has index references to the other information?  Better known as a flat-file database structure.

As such, there is no clean cut way to make the connection.  I am working on a similar problem with bridging my MSSQL server to the Timberline Database and it is not as clean cut as you would think.

Have you tried loading the Timberline Driver onto the webserver or into the application in question for consumption?  Sage has not made it easy for you to access this information at all and if i have my 2 cents to say about this application suite, i would suggest against it at ALL cost.

So far here is a connection string that works, via VS2k5.  It is a DSN string but connection string none the less.  Problem i am having is dissoicating the DSN part from the connection string and getting it to work properly.

DSN=<whatever>;uid=<userid>;dbq=<PathToDirectory>;codepage=1252;
maxcolsupport=1536;dictionarymode=0;standardmode=0;shortennames=1;databasetype=1

This is supposed to work for ADO, but cant get it to work properly:

Provider=MSDASQL.1;Driver={Timberline Data};dbq=<PathToDirectory>;
uid=<userid>;pwd=<password>;codepage=1252

ContentLicense: CC BY-SA 3.0


问:
How to fix this schema markup, I am getting the error code Duplicate key found
Can you please help me fix this Schema markup. When testing on Google Structured Data Testing tool, I am getting the error code:

Duplicate key found in object declaration on line 119

```<code><!-- JSON-LD markup generated by Google Structured Data Markup Helper. -->
<script type="application/ld+json">
{
  "@context" : "http://socialwetalk.me",
  "@type" : "LocalBusiness",
 "name" : "SocialWeTalk",
  "image" : [ "http://socialwetalk.me/wp-content/uploads/2019/03/macbook_mockup-1.png", "http://socialwetalk.me/wp-content/uploads/2018/08/service-summary-2.png" ],
"priceRange" : "$450 - $850",
  "telephone" : "+961 76 020 274",
  "email" : "info@socialwetalk.me",
  "address" : {
    "@type" : "PostalAddress",
    "streetAddress" : "Hamra, Jeanne d'Arc",
    "addressLocality" : "Beirut"
  },
  "geo" : {
    "@type" : "GeoCoordinates",
    "latitude" : "33.897835",
    "longitude" : "35.481523"
  },
"@type":"Review",
"itemReviewed":{"@type":"Product","name":"SocialWeTalk"}
"reviewRating":{"@type":"Rating","ratingValue":4.5,"bestRating":5}
"author":{"@type":"Person","name":"Samir Tutunji"}
"reviewBody":"SocialWeTalk helped us understand where our customers are coming from, and came up with an innovative concept online to keep them coming..."}
}
</script>
</code>```

I am using Google Structured Data testing tool to validate my work

答:
Its fixed and reformatted</p>

```<code><!-- JSON-LD markup generated by Google Structured Data Markup Helper. -->
<script type="application/ld+json">
{
  "@context" : "http://schema.org",
  "@type" : "LocalBusiness",
  "name" : "SocialWeTalk",
  "image" : [ "http://socialwetalk.me/wp-content/uploads/2019/03/macbook_mockup-1.png", "http://socialwetalk.me/wp-content/uploads/2018/08/service-summary-2.png" ],
  "priceRange" : "$450 - $850",
  "telephone" : "+961 76 020 274",
  "email" : "info@socialwetalk.me",
  "address" : {
    "@type" : "PostalAddress",
    "streetAddress" : "Hamra, Jeanne d'Arc",
    "addressLocality" : "Beirut"
  },
  "review" : [
    {
    "@type" : "Review",
    "author" : {
      "@type" : "Person",
      "name" : "Pro Retrofits"
    },
    "reviewBody" : "We love our clients"
  }, {
    "@type" : "Review",
    "author" : {
      "@type" : "Person",
      "name" : "Crunch"
    },
    "reviewBody" : "We love our clients"
    }, {
    "@type" : "Review",
    "author" : {
      "@type" : "Person",
      "name" : "SocialWeTalk"
    }],
  "geo" : {
    "@type" : "GeoCoordinates",
    "latitude" : "33.897835",
    "longitude" : "35.481523"
  }
  }
 </script>
<script type="application/ld+json">
{
    "@context":"http://socialwetalk.me","@type":"Review",
    "itemReviewed":{"@type":"Product","name":"SocialWeTalk"},
    "reviewRating":{"@type":"Rating","ratingValue":4.5,"bestRating":5},
    "author":{"@type":"Person","name":"Samir Tutunji"},
    "reviewBody":"SocialWeTalk helped us understand where our customers are coming from, and came up with an innovative concept online to keep them coming..."}
</script>
</code>```

Body:
Can you please help me fix this Schema markup. When testing on Google Structured Data Testing tool, I am getting the error code:

Duplicate key found in object declaration on line 119

I am using Google Structured Data testing tool to validate my work

Body:
Its fixed and reformatted

<!-- JSON-LD markup generated by Google Structured Data Markup Helper. -->
<script type="application/ld+json">
{
  "@context" : "http://schema.org",
  "@type" : "LocalBusiness",
  "name" : "SocialWeTalk",
  "image" : [ "http://socialwetalk.me/wp-content/uploads/2019/03/macbook_mockup-1.png", "http://socialwetalk.me/wp-content/uploads/2018/08/service-summary-2.png" ],
  "priceRange" : "$450 - $850",
  "telephone" : "+961 76 020 274",
  "email" : "info@socialwetalk.me",
  "address" : {
    "@type" : "PostalAddress",
    "streetAddress" : "Hamra, Jeanne d'Arc",
    "addressLocality" : "Beirut"
  },
  "review" : [
    {
    "@type" : "Review",
    "author" : {
      "@type" : "Person",
      "name" : "Pro Retrofits"
    },
    "reviewBody" : "We love our clients"
  }, {
    "@type" : "Review",
    "author" : {
      "@type" : "Person",
      "name" : "Crunch"
    },
    "reviewBody" : "We love our clients"
    }, {
    "@type" : "Review",
    "author" : {
      "@type" : "Person",
      "name" : "SocialWeTalk"
    }],
  "geo" : {
    "@type" : "GeoCoordinates",
    "latitude" : "33.897835",
    "longitude" : "35.481523"
  }
  }
 </script>
<script type="application/ld+json">
{
    "@context":"http://socialwetalk.me","@type":"Review",
    "itemReviewed":{"@type":"Product","name":"SocialWeTalk"},
    "reviewRating":{"@type":"Rating","ratingValue":4.5,"bestRating":5},
    "author":{"@type":"Person","name":"Samir Tutunji"},
    "reviewBody":"SocialWeTalk helped us understand where our customers are coming from, and came up with an innovative concept online to keep them coming..."}
</script>


问:
Why paths of length return 0 using Pytorch?
This function return error which is same as below while the paths is correct. Am I misunderstanding how paths works? (This snippet is from github-repo)

```<code>paths = paths[::skip_frame]

ValueError: slice step cannot be zero
</code>```

Here is the main function:

```<code> def make_gif(paths, gif_path, max_frame=50, prefix=""):
      import imagei

paths.sort()
skip_frame = len(paths) // max_frame

paths = paths[::skip_frame]

images = [imageio.imread(path) for path in paths]
max_h, max_w, max_c = np.max(
        np.array([image.shape for image in images]), 0)
</code>```

Here is how function called:

```<code>parser = argparse.ArgumentParser()
parser.add_argument("--model_name", type=str)
parser.add_argument("--max_frame", type=int, default=50)
parser.add_argument("--output", type=str, default="sampe.gif")
parser.add_argument("--title", type=str, default="")

if __name__ == "__main__":
    args = parser.parse_args()

    paths = glob(f"./logs/{args.model_name}/networks/*.png")

    make_gif(paths, args.output,
            max_frame=args.max_frame,
            prefix=f"{args.title}\n" if args.title else "")
</code>```

答: You get this error because your skip_frame is zero. Make sure it's value is at least one.

Body:
This function return error which is same as below while the paths is correct. Am I misunderstanding how paths works? (This snippet is from github-repo)

paths = paths[::skip_frame]

ValueError: slice step cannot be zero

Here is the main function:

 def make_gif(paths, gif_path, max_frame=50, prefix=""):
      import imagei

paths.sort()
skip_frame = len(paths) // max_frame

paths = paths[::skip_frame]

images = [imageio.imread(path) for path in paths]
max_h, max_w, max_c = np.max(
        np.array([image.shape for image in images]), 0)

Here is how function called:

parser = argparse.ArgumentParser()
parser.add_argument("--model_name", type=str)
parser.add_argument("--max_frame", type=int, default=50)
parser.add_argument("--output", type=str, default="sampe.gif")
parser.add_argument("--title", type=str, default="")

if __name__ == "__main__":
    args = parser.parse_args()

    paths = glob(f"./logs/{args.model_name}/networks/*.png")

    make_gif(paths, args.output,
            max_frame=args.max_frame,
            prefix=f"{args.title}\n" if args.title else "")


问:
How to fix 'htaccess redirect entire site to maintenace, except one IP'
I'm trying to redirect an entire site to a maintenance page while I do some work on it. I want my IP to be the only one to view the site. I've tried

```<code>Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !=123.456.789
RewriteRule .* http://www.example.com/maintenance.html [R=302,L]
</code>```

And this is my latest ( I need to allow one .png image)

```<code>Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !=200.300,70.9
RewriteCond %{REQUEST_URI} !(\.png)$ [NC]
RewriteCond %{REQUEST_URI} !^/rebrand-underway\.html$
RewriteRule ^(.*)$ /rebrand-underway.html [R=302,L]
</code>```

This code is kind of working, as its redirecting properly. However I can't access the actual site from my ip address. So I suspect the IP I'm putting in the code is wrong, but I've tried every one I can find googling 'whats my ip', and through network settings on my computer, but nothing works.

Does anyone have any ideas? If I'm right, how might I find the correct IP?

Thanks

答:
It can be set as below for IP :

```<code>RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000
</code>```

Body:
I'm trying to redirect an entire site to a maintenance page while I do some work on it. I want my IP to be the only one to view the site. I've tried

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !=123.456.789
RewriteRule .* http://www.example.com/maintenance.html [R=302,L]

And this is my latest ( I need to allow one .png image)

Options +FollowSymlinks
RewriteEngine on
RewriteCond %{REMOTE_ADDR} !=200.300,70.9
RewriteCond %{REQUEST_URI} !(\.png)$ [NC]
RewriteCond %{REQUEST_URI} !^/rebrand-underway\.html$
RewriteRule ^(.*)$ /rebrand-underway.html [R=302,L]

This code is kind of working, as its redirecting properly. However I can't access the actual site from my ip address. So I suspect the IP I'm putting in the code is wrong, but I've tried every one I can find googling 'whats my ip', and through network settings on my computer, but nothing works.

Does anyone have any ideas? If I'm right, how might I find the correct IP?

Thanks

Body:
It can be set as below for IP :

RewriteCond %{REMOTE_ADDR} !^123\.456\.789\.000


问:
How to concise this code? Get an array's property (title) by a second array's shared property (_id)
The following code works but how can I make it more concise?
In two arrays, we have a common property (_id). With this property, I get a property from array 2.
More specific:
Array 'movies' contains items movie with properties '_id' and 'title'.
Array 'favoritemovies' contains only '_id'.
I want to return the user's list of favorite movies as titles. </p>

```<code>var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

var movieTitles = [];

for (var i = 0; i < favoritemovies.length; i++) {
    var favMovies = movies.filter(movie => movie._id == favoritemovies[i])

movieTitles.push(favMovies);

var movieTitlesFlat = movieTitles.flat();
}

for (var i = 0; i < favoritemovies.length; i++) {
  console.log(movieTitlesFlat[i].title);
}
</code>```

答:
```<code>var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

var movieTitles = movies.filter( (e)=> favoritemovies.includes(e._id));

movieTitles.forEach( (e)=> console.log(e.title));
</code>```

Body:
The following code works but how can I make it more concise?
In two arrays, we have a common property (_id). With this property, I get a property from array 2.
More specific:
Array 'movies' contains items movie with properties '_id' and 'title'.
Array 'favoritemovies' contains only '_id'.
I want to return the user's list of favorite movies as titles.

var favoritemovies = [1111,3333];

const movies = [
    {_id:1111, title: 'movie1'},
    {_id:2222, title: 'movie2'},
    {_id:3333, title: 'movie3'},
];

var movieTitles = [];

for (var i = 0; i < favoritemovies.length; i++) {
    var favMovies = movies.filter(movie => movie._id == favoritemovies[i])

movieTitles.push(favMovies);

var movieTitlesFlat = movieTitles.flat();
}

for (var i = 0; i < favoritemovies.length; i++) {
  console.log(movieTitlesFlat[i].title);
}


问:
Can't simulate values extreme enough in Monte Carlo
I have a biological dataset of 576 genes of interest and their assigned functional categories. I also have the assigned functional categories for all of the genes in the genome of the species I am working with. This allows me to set up a weighted, random, draw where I can pick 576 genes/functional assignments from the genome and see what the distributions are for the various functional categories. I have repeated this 1 million times which seems like overkill; however, for one of my categories, I am currently unable to simulate a value as extreme as I have in the genes of interest.

To provide context, the functional category (let's go with "A") represents 14% of the genome and 28% of the genes of interest. The highest value I've simulated is 22.92% for category A, and the 97.5% confidence interval is at 17.19%. This is giving me trouble when I go to calculate the p-value as I am doing that empirically, i.e. (number of values simulated for A that exceed the value of A for the genes of interest)/(total number of simulations), so my p-value is just zero.

```<code>len([i for i in probs_dict["A"] if i > target_per])/total_sims
</code>```

Is there a different way to calculate p-values here or to represent the high degree of over-representation?

答:
It might be appropriate to add a 1 to your numerator and nominator. See this paper for example. This prevents p = 0 from ever happening. So your p-value formulation would become:</p>

```<code>(1 + len([i for i in probs_dict["A"] if i > target_per]))/(1 + total_sims)
</code>```

Body:
I have a biological dataset of 576 genes of interest and their assigned functional categories. I also have the assigned functional categories for all of the genes in the genome of the species I am working with. This allows me to set up a weighted, random, draw where I can pick 576 genes/functional assignments from the genome and see what the distributions are for the various functional categories. I have repeated this 1 million times which seems like overkill; however, for one of my categories, I am currently unable to simulate a value as extreme as I have in the genes of interest.

To provide context, the functional category (let's go with "A") represents 14% of the genome and 28% of the genes of interest. The highest value I've simulated is 22.92% for category A, and the 97.5% confidence interval is at 17.19%. This is giving me trouble when I go to calculate the p-value as I am doing that empirically, i.e. (number of values simulated for A that exceed the value of A for the genes of interest)/(total number of simulations), so my p-value is just zero.

len([i for i in probs_dict["A"] if i > target_per])/total_sims

Is there a different way to calculate p-values here or to represent the high degree of over-representation?

Body:
It might be appropriate to add a 1 to your numerator and nominator. See this paper for example. This prevents p = 0 from ever happening. So your p-value formulation would become:

(1 + len([i for i in probs_dict["A"] if i > target_per]))/(1 + total_sims)


问:
c# WPF button link to user control page
I have a MainWindow which only have a button , How do i link this button to a user control page ( home.xaml) ? i am new to WPF
in my mainwindow :

```<code><Button Height="100" Name="btnHome" Width="103" Click="btnHome_Click"/>
</code>```

in my mainwindow.cs:

```<code>    private void btnHome_Click(object sender, RoutedEventArgs e)
    {
        var home = new home();
        home.Show();
    }
</code>```

but it doesnt work . home.xaml is my user control page that i want to link to by clicking on the button in mainwindow.

答:
Use this code on button and set your usercontrol name or path in uri.</p>

```<code>private void btn_Click(object sender, RoutedEventArgs e)
{
    NavigationService.GetNavigationService(this)
       .Navigate(new Uri("/UserControls/GameDetails.xaml", UriKind.RelativeOrAbsolute));
}
</code>```

Title: c# WPF button link to user control page

Body:
I have a MainWindow which only have a button , How do i link this button to a user control page ( home.xaml) ? i am new to WPF
in my mainwindow :

<Button Height="100" Name="btnHome" Width="103" Click="btnHome_Click"/>

in my mainwindow.cs:

    private void btnHome_Click(object sender, RoutedEventArgs e)
    {
        var home = new home();
        home.Show();
    }

but it doesnt work . home.xaml is my user control page that i want to link to by clicking on the button in mainwindow.

Body:
Use this code on button and set your usercontrol name or path in uri.

private void btn_Click(object sender, RoutedEventArgs e)
{
    NavigationService.GetNavigationService(this)
       .Navigate(new Uri("/UserControls/GameDetails.xaml", UriKind.RelativeOrAbsolute));
}


问:
ERROR: Workspace has a .git repository, but it appears to be corrupt
I am not able to pull the code from Github through jenkins. I did try to switch the git plugins in jenkins but it didn't work. No idea what the issue is..Some pointers for this would be helpful..
 Am i missing some plugins or ami using plugins with the wrong version?

Started by user anonymous
Building in workspace /var/lib/jenkins/jobs/TestGitCon/workspace
Checkout:workspace / /var/lib/jenkins/jobs/TestGitCon/workspace - hudson.remoting.LocalChannel@37ff3f85
Using strategy: Default
ERROR: Workspace has a .git repository, but it appears to be corrupt.
hudson.plugins.git.GitException: Error performing command: usr/bin/git rev-parse --verify HEAD
 at hudson.plugins.git.GitAPI.launchCommandIn(GitAPI.java:904)
 at hudson.plugins.git.GitAPI.launchCommand(GitAPI.java:858)
 at hudson.plugins.git.GitAPI.launchCommand(GitAPI.java:868)
 at hudson.plugins.git.GitAPI.validateRevision(GitAPI.java:326)
 at hudson.plugins.git.GitAPI.hasGitRepo(GitAPI.java:125)
 at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:1005)
 at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:986)
 at hudson.FilePath.act(FilePath.java:981)
 at hudson.FilePath.act(FilePath.java:959)
 at hudson.plugins.git.GitSCM.determineRevisionToBuild(GitSCM.java:986)
 at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1142)
 at hudson.model.AbstractProject.checkout(AbstractProject.java:1265)
 at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:622)
 at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
 at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:528)
 at hudson.model.Run.execute(Run.java:1759)
 at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
 at hudson.model.ResourceController.execute(ResourceController.java:89)
 at hudson.model.Executor.run(Executor.java:240)
Caused by: java.io.IOException: Cannot run program "usr/bin/git" (in directory "/var/lib/jenkins/jobs/TestGitCon/workspace"): error=2, No such file or directory
 at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
 at hudson.Proc$LocalProc.<init>(Proc.java:244)
 at hudson.Proc$LocalProc.<init>(Proc.java:216)
 at hudson.Launcher$LocalLauncher.launch(Launcher.java:803)
 at hudson.Launcher$ProcStarter.start(Launcher.java:381)
 at hudson.Launcher$ProcStarter.join(Launcher.java:388)
 at hudson.plugins.git.GitAPI.launchCommandIn(GitAPI.java:885)
 ... 18 more
Caused by: java.io.IOException: error=2, No such file or directory
 at java.lang.UNIXProcess.forkAndExec(Native Method)
 at java.lang.UNIXProcess.<init>(UNIXProcess.java:186)
 at java.lang.ProcessImpl.start(ProcessImpl.java:130)
 at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)
 ... 24 more
Cloning the remote Git repository
Cloning repository git@github.com:RosettaCommons/main.git
Error trying to determine the git version: Error performing command: usr/bin/git --version
Assuming 1.6
Fetching upstream changes from git@github.com:RosettaCommons/main.git
ERROR: Problem fetching from origin / origin - could be unavailable. Continuing anyway.
hudson.plugins.git.GitException: Error performing command: usr/bin/git fetch -t git@github.com:RosettaCommons/main.git +refs/heads/*:refs/remotes/origin/*
 at hudson.plugins.git.GitAPI.launchCommandIn(GitAPI.java:904)
 at hudson.plugins.git.GitAPI.launchCommand(GitAPI.java:858)
 at hudson.plugins.git.GitAPI.fetch(GitAPI.java:200)
 at hudson.plugins.git.GitAPI.fetch(GitAPI.java:1105)
 at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:1064)
 at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:986)
 at hudson.FilePath.act(FilePath.java:981)
 at hudson.FilePath.act(FilePath.java:959)
 at hudson.plugins.git.GitSCM.determineRevisionToBuild(GitSCM.java:986)
 at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1142)
 at hudson.model.AbstractProject.checkout(AbstractProject.java:1265)
 at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:622)
 at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
 at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:528)
 at hudson.model.Run.execute(Run.java:1759)
 at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
 at hudson.model.ResourceController.execute(ResourceController.java:89)
 at hudson.model.Executor.run(Executor.java:240)
Caused by: java.io.IOException: Cannot run program "usr/bin/git" (in directory "/var/lib/jenkins/jobs/TestGitCon/workspace"): error=2, No such file or directory
 at java.lang.ProcessBuilder.start(ProcessBuilder.java:1047)
 at hudson.Proc$LocalProc.<init>(Proc.java:244)
 at hudson.Proc$LocalProc.<init>(Proc.java:216)
 at hudson.Launcher$LocalLauncher.launch(Launcher.java:803)
 at hudson.Launcher$ProcStarter.start(Launcher.java:381)
 at hudson.Launcher$ProcStarter.join(Launcher.java:388)
 at hudson.plugins.git.GitAPI.launchCommandIn(GitAPI.java:885)
 ... 17 more
Caused by: java.io.IOException: error=2, No such file or directory
 at java.lang.UNIXProcess.forkAndExec(Native Method)
 at java.lang.UNIXProcess.<init>(UNIXProcess.java:186)
 at java.lang.ProcessImpl.start(ProcessImpl.java:130)
 at java.lang.ProcessBuilder.start(ProcessBuilder.java:1028)
 ... 23 more
ERROR: Could not fetch from any repository
FATAL: Could not fetch from any repository
hudson.plugins.git.GitException: Could not fetch from any repository
 at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:1076)
 at hudson.plugins.git.GitSCM$2.invoke(GitSCM.java:986)
 at hudson.FilePath.act(FilePath.java:981)
 at hudson.FilePath.act(FilePath.java:959)
 at hudson.plugins.git.GitSCM.determineRevisionToBuild(GitSCM.java:986)
 at hudson.plugins.git.GitSCM.checkout(GitSCM.java:1142)
 at hudson.model.AbstractProject.checkout(AbstractProject.java:1265)
 at hudson.model.AbstractBuild$AbstractBuildExecution.defaultCheckout(AbstractBuild.java:622)
 at jenkins.scm.SCMCheckoutStrategy.checkout(SCMCheckoutStrategy.java:86)
 at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:528)
 at hudson.model.Run.execute(Run.java:1759)
 at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
 at hudson.model.ResourceController.execute(ResourceController.java:89)
 at hudson.model.Executor.run(Executor.java:240)```

答:
I had the same error, but in my case the reason was different. Actually, I had used curl command in a shell script file and then I had to create a Docker image out it.
So to make the Docker image able to execute the curl command I had to install the Curl. And I had written the below code in Docker file

```<code>RUN apt-get update && \
apt-get install -y curl && \
</code>```

But when I committed my code, the Jenkins build got failed with the same message ERROR: Workspace has a .git repository, but it appears to be corrupt

And the fix was that I had to add --no-install-recommends in the install curl command. Like this

```<code>RUN apt-get update && \
apt-get install -y --no-install-recommends curl && \
</code>```

The reason for that is Ubuntu installs recommended but not suggested packages. So, Ubuntu was trying to add some unwanted but maybe, recommended package which somehow was failing the build.

Body:
I had the same error, but in my case the reason was different. Actually, I had used curl command in a shell script file and then I had to create a Docker image out it.
So to make the Docker image able to execute the curl command I had to install the Curl. And I had written the below code in Docker file

RUN apt-get update && \
apt-get install -y curl && \

But when I committed my code, the Jenkins build got failed with the same message ERROR: Workspace has a .git repository, but it appears to be corrupt

And the fix was that I had to add --no-install-recommends in the install curl command. Like this

RUN apt-get update && \
apt-get install -y --no-install-recommends curl && \

The reason for that is Ubuntu installs recommended but not suggested packages. So, Ubuntu was trying to add some unwanted but maybe, recommended package which somehow was failing the build.


问:
compare string column with other column by row wise
I have a data frame as below,how to compare values from 2 columns.i.e row 1 has common string("SZY")in both col a & b and extra in string in col a (ABC)
for row 5 common string is "BNM" and extra strings in both col a and b.

```<code>a=c("ABC,SZY","XYZ",NA,NA,"ABC,BNM,JKL","DEF","XCV")
b=c("SZY","XYZ,IOP","QWE",NA,"BNM,JKL,STU","DEF","HJK")
df = data.frame(a,b)
</code>```

output should be as follows

```<code>output = c("COMMON+column_a","COMMON+column_b","DIFFERENT",NA,"COMMON+column_a+column_b","COMMON","DIFFERENT")
df = cbind(df,output)
</code>```

答:
Here is another one in base R,</p>

```<code>vapply(strsplit(do.call(paste, df), " |,"), function(x)
                               toString(unique(x[x != 'NA'])), character(1L))

#[1] "ABC, SZY"    "XYZ, IOP"    "QWE"    ""    "ABC, BNM, JKL, STU" "DEF"   "XCV, HJK"
</code>```

Body:
I have a data frame as below,how to compare values from 2 columns.i.e row 1 has common string("SZY")in both col a & b and extra in string in col a (ABC)
for row 5 common string is "BNM" and extra strings in both col a and b.

a=c("ABC,SZY","XYZ",NA,NA,"ABC,BNM,JKL","DEF","XCV")
b=c("SZY","XYZ,IOP","QWE",NA,"BNM,JKL,STU","DEF","HJK")
df = data.frame(a,b)

output should be as follows

output = c("COMMON+column_a","COMMON+column_b","DIFFERENT",NA,"COMMON+column_a+column_b","COMMON","DIFFERENT")
df = cbind(df,output)

Body:
Here is another one in base R,

vapply(strsplit(do.call(paste, df), " |,"), function(x)
                               toString(unique(x[x != 'NA'])), character(1L))

#[1] "ABC, SZY"    "XYZ, IOP"    "QWE"    ""    "ABC, BNM, JKL, STU" "DEF"   "XCV, HJK"


问:
Subtract Col A - Col B in pandas dataframe
I have two string columns in a dataframe and I'm looking to subtract common words in B from A.

```<code>A ->  Stack Overlflow is great

B -> stack great

A-B -> overflow is
</code>```

I have tried the following code. But it only works if the column B has one word.

```<code>df['A-B'] = [' '.join(set(a.split())-set(b.split())) for a, b in zip(df['A'], df['B'])]
</code>```

Is there any change I can make so that it works when B has multiple words?

答:
You can use np.setdiff1d():

```<code>df['A-B']=df.apply(lambda x: ' '.join(np.setdiff1d(x['A'].lower().split(),
                                        x['B'].lower().split())),axis=1)
print(df)
</code>```

```<code>                          A            B           A-B
0  Stack Overlflow is great  stack great  is overlflow
</code>```

Your solution is almost there,just add series.str.lower() when zipping them:

```<code>df['A-B']=[' '.join(set(a.split())-set(b.split()))
        for a, b in zip(df['A'].str.lower(), df['B'].str.lower())]
</code>```

Incase the series has duplicate strings, use OrderedDict which helps removing dupes as set() but maintaining the order too:

```<code>df = pd.DataFrame({'A': ['Stack Overlflow is great is great'], 'B': ['stack great']})
                                  A            B
0  Stack Overlflow is great is great  stack great
</code>```

```<code>from collections import OrderedDict
df['A-B']=[' '.join([ele for ele in OrderedDict.fromkeys(a) if ele not in b ])
 for a,b in zip(df.A.str.lower().str.split(),df.B.str.lower().str.split())]
print(df)
</code>```

```<code>                                   A            B           A-B
0  Stack Overlflow is great is great  stack great  overlflow is
</code>```

Body:
I have two string columns in a dataframe and I'm looking to subtract common words in B from A.

A ->  Stack Overlflow is great

B -> stack great

A-B -> overflow is

I have tried the following code. But it only works if the column B has one word.

df['A-B'] = [' '.join(set(a.split())-set(b.split())) for a, b in zip(df['A'], df['B'])]

Is there any change I can make so that it works when B has multiple words?

Body:
You can use np.setdiff1d():

df['A-B']=df.apply(lambda x: ' '.join(np.setdiff1d(x['A'].lower().split(),
                                        x['B'].lower().split())),axis=1)
print(df)

                          A            B           A-B
0  Stack Overlflow is great  stack great  is overlflow

Your solution is almost there,just add series.str.lower() when zipping them:

df['A-B']=[' '.join(set(a.split())-set(b.split()))
        for a, b in zip(df['A'].str.lower(), df['B'].str.lower())]

Incase the series has duplicate strings, use OrderedDict which helps removing dupes as set() but maintaining the order too:

df = pd.DataFrame({'A': ['Stack Overlflow is great is great'], 'B': ['stack great']})
                                  A            B
0  Stack Overlflow is great is great  stack great

from collections import OrderedDict
df['A-B']=[' '.join([ele for ele in OrderedDict.fromkeys(a) if ele not in b ])
 for a,b in zip(df.A.str.lower().str.split(),df.B.str.lower().str.split())]
print(df)

                                   A            B           A-B
0  Stack Overlflow is great is great  stack great  overlflow is


问:
compare java hash map key with the string
I want to compare a string with key value of a hashmap.

private Map<String, Integer> map1= new HashMap<>();
 map1.put("User1" , 100);
 map1.put("User2" , 200);
 map1.put("User3" , 300);

public void test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equals(user)) {
          System.out.println("yes");
        }else{
          System.out.println("no");
        }
    }
}
```

<p>yet my code is not working and i get answer no even when user is in map, any idea what is the problem?</p>

<p>I changed the code a bit but the given answer is still no:</p>

<pre class="lang-java prettyprint-override"><code>
import java.util.*;

public class A1 {

 private static Map<String, Integer> map1= new HashMap<>();

 public static boolean test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equalsIgnoreCase(user)) {
          return true;
        }
    }
    return false;
}

    public static void main(String[] args) {
        map1.put("User1" , 100);
        map1.put("User2" , 200);
        map1.put("User3" , 300);
        if(test("User1" , 100)){
                  System.out.println("yes");
        }else{
          System.out.println("no");
        }
    }
}

</code>```

@Jason ty

map1.containsKey(user)
```

worked.

答:
```<code>public static boolean test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equalsIgnoreCase(user)) {
          return true;
        }else{
          return false;
        }
    }
    return false;
</code>```

This loop always returns on its first iteration, so it will only return true if the first key matches.

It's the same as:

```<code>Iterator<String> it = map1.keySet().iterator();
return it.hasNext() && it.next().equalsIgnoreCase(user);
</code>```

If you want to keep searching until you find a matching key, remove the return false; inside the loop.

Body:
I want to compare a string with key value of a hashmap.

private Map<String, Integer> map1= new HashMap<>();
 map1.put("User1" , 100);
 map1.put("User2" , 200);
 map1.put("User3" , 300);

public void test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equals(user)) {
          System.out.println("yes");
        }else{
          System.out.println("no");
        }
    }
}

yet my code is not working and i get answer no even when user is in map, any idea what is the problem?

I changed the code a bit but the given answer is still no:

import java.util.*;

public class A1 {

 private static Map<String, Integer> map1= new HashMap<>();

 public static boolean test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equalsIgnoreCase(user)) {
          return true;
        }
    }
    return false;
}

    public static void main(String[] args) {
        map1.put("User1" , 100);
        map1.put("User2" , 200);
        map1.put("User3" , 300);
        if(test("User1" , 100)){
                  System.out.println("yes");
        }else{
          System.out.println("no");
        }
    }
}

@Jason ty

map1.containsKey(user)

worked.

Body:
public static boolean test(String user, int size) {
    for(String key : map1.keySet()) {
        if (key.equalsIgnoreCase(user)) {
          return true;
        }else{
          return false;
        }
    }
    return false;

This loop always returns on its first iteration, so it will only return true if the first key matches.

It's the same as:

Iterator<String> it = map1.keySet().iterator();
return it.hasNext() && it.next().equalsIgnoreCase(user);

If you want to keep searching until you find a matching key, remove the return false; inside the loop.


问:
How to overlay several plots
I would like to plot in one graph 3 different occupancy patterns: a.) when both male and female are working; b.) only male working; c.) only female working.

I created 3 different data.frames using facet

The structure of the first data.frame (both male and female is working) is:

```<code>   structure(list(time = c("04:00", "04:15", "04:30", "04:45", "05:00",
"05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30",
"08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15",
"10:30", "10:45", "11:00", "11:15"), day = c("Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday"
), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
"Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
"Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(102, 110, 116, 120, 148, 152, 188, 204, 318, 348,
    418, 442, 752, 816, 1064, 1144, 1836, 1942, 2402, 2524, 3240,
    3324, 3486, 3520, 3594, 3592, 3596, 3568, 3594, 3626), size_f = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"), class = "factor")), row.names = c(NA, 30L), class = "data.frame")
</code>```

The structure of the second data.frame (male is working) is:

```<code>dput(head(melted_WkSTiWeekM , 30))
structure(list(time = c("04:00", "04:15", "04:30", "04:45", "05:00",
"05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30",
"08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15",
"10:30", "10:45", "11:00", "11:15"), day = c("Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday"
), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
"Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
"Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(56, 58, 64, 68, 84, 84, 104, 114, 172, 196, 224,
    238, 410, 442, 560, 604, 930, 968, 1188, 1230, 1576, 1620,
    1692, 1706, 1740, 1746, 1752, 1740, 1736, 1756), size_f = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"), class = "factor")), row.names = c(NA, 30L), class = "data.frame")
</code>```

The structure of the second data.frame (female is working) is:

```<code>structure(list(time = c("04:00", "04:15", "04:30", "04:45", "05:00",
"05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30",
"08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15",
"10:30", "10:45", "11:00", "11:15"), day = c("Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday"
), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
"Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
"Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(46, 52, 52, 52, 64, 68, 84, 90, 146, 152, 194,
    204, 342, 374, 504, 540, 906, 974, 1214, 1294, 1664, 1704,
    1794, 1814, 1854, 1846, 1844, 1828, 1858, 1870), size_f = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"), class = "factor")), row.names = c(NA, 30L), class = "data.frame")
</code>```

After this I created a

```<code>melted_WkSTiWeekAll=cbind(melted_WkSTiWeek,melted_WkSTiWeekM,melted_WkSTiWeekF)

structure(list(time = c("04:00", "04:15", "04:30", "04:45", "05:00"
), day = c("Monday", "Monday", "Monday", "Monday", "Monday"),
    variable = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("Shifts on Monday",
    "Shifts on Tuesday", "Shifts on Wednesday", "Shifts on Thursday",
    "Shifts on Friday", "Shifts on Saturday", "Shifts on Sunday"
    ), class = "factor"), value = c(102, 110, 116, 120, 148),
    size_f = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"), class = "factor"), time = c("04:00", "04:15",
    "04:30", "04:45", "05:00"), day = c("Monday", "Monday", "Monday",
    "Monday", "Monday"), variable = structure(c(1L, 1L, 1L, 1L,
    1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
    "Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
    "Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(56, 58, 64, 68, 84), size_f = structure(c(1L, 1L,
    1L, 1L, 1L), .Label = c("Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday", "Sunday"), class = "factor"),
    time = c("04:00", "04:15", "04:30", "04:45", "05:00"), day = c("Monday",
    "Monday", "Monday", "Monday", "Monday"), variable = structure(c(1L,
    1L, 1L, 1L, 1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
    "Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
    "Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(46, 52, 52, 52, 64), size_f = structure(c(1L, 1L,
    1L, 1L, 1L), .Label = c("Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday", "Sunday"), class = "factor")), row.names = c(NA,
5L), class = "data.frame")
</code>```

The variable time, day, variable and size_f are similar.

I would like to plot 3 graph together in the same plot. But I have no clue how to this

Using the suggested facet the following plot

Plot1

Plot2

Plot3

How to move forward

I would like to create a pot like this

答:
You can do it by merging your dataframes together and tag them as All, Male, and Female accordingly. Then you can use that tag for grouping(coloring) within your ggplot function.

Using geom_bar and position = "identity" you will get bars on top of each other and to remove the space between the bars (to mimic density plots look) width is set to 1. alpha can be used to alter the transparency of fill colors.

And to get a separate plot for each day of the week we can use facet_wrap(~day).

library(tidyverse)

melted_WkSTiWeekAll <- bind_rows(list(All=melted_WkSTiWeek,
                                      Male=melted_WkSTiWeekM,
                                      Female=melted_WkSTiWeekF),
                                                                .id = 'source')

ggplot(melted_WkSTiWeekAll, aes(x=time, y=value, fill=source)) +
  geom_bar(stat="identity", position = "identity", alpha=.3, width=1) +
  facet_wrap(~day)
```

Note that here we only get one facet as the data provided only has entries for Monday.

Created on 2019-05-31 by the reprex package (v0.3.0)

Title: How to overlay several plots

Body:
I would like to plot in one graph 3 different occupancy patterns: a.) when both male and female are working; b.) only male working; c.) only female working.

I created 3 different data.frames using facet

The structure of the first data.frame (both male and female is working) is:

   structure(list(time = c("04:00", "04:15", "04:30", "04:45", "05:00",
"05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30",
"08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15",
"10:30", "10:45", "11:00", "11:15"), day = c("Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday"
), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
"Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
"Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(102, 110, 116, 120, 148, 152, 188, 204, 318, 348,
    418, 442, 752, 816, 1064, 1144, 1836, 1942, 2402, 2524, 3240,
    3324, 3486, 3520, 3594, 3592, 3596, 3568, 3594, 3626), size_f = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"), class = "factor")), row.names = c(NA, 30L), class = "data.frame")

The structure of the second data.frame (male is working) is:

dput(head(melted_WkSTiWeekM , 30))
structure(list(time = c("04:00", "04:15", "04:30", "04:45", "05:00",
"05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30",
"08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15",
"10:30", "10:45", "11:00", "11:15"), day = c("Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday"
), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
"Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
"Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(56, 58, 64, 68, 84, 84, 104, 114, 172, 196, 224,
    238, 410, 442, 560, 604, 930, 968, 1188, 1230, 1576, 1620,
    1692, 1706, 1740, 1746, 1752, 1740, 1736, 1756), size_f = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"), class = "factor")), row.names = c(NA, 30L), class = "data.frame")

The structure of the second data.frame (female is working) is:

structure(list(time = c("04:00", "04:15", "04:30", "04:45", "05:00",
"05:15", "05:30", "05:45", "06:00", "06:15", "06:30", "06:45",
"07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30",
"08:45", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15",
"10:30", "10:45", "11:00", "11:15"), day = c("Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday",
"Monday", "Monday", "Monday", "Monday", "Monday", "Monday", "Monday"
), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
"Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
"Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(46, 52, 52, 52, 64, 68, 84, 90, 146, 152, 194,
    204, 342, 374, 504, 540, 906, 974, 1214, 1294, 1664, 1704,
    1794, 1814, 1854, 1846, 1844, 1828, 1858, 1870), size_f = structure(c(1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
    1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"), class = "factor")), row.names = c(NA, 30L), class = "data.frame")

After this I created a

melted_WkSTiWeekAll=cbind(melted_WkSTiWeek,melted_WkSTiWeekM,melted_WkSTiWeekF)

structure(list(time = c("04:00", "04:15", "04:30", "04:45", "05:00"
), day = c("Monday", "Monday", "Monday", "Monday", "Monday"),
    variable = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("Shifts on Monday",
    "Shifts on Tuesday", "Shifts on Wednesday", "Shifts on Thursday",
    "Shifts on Friday", "Shifts on Saturday", "Shifts on Sunday"
    ), class = "factor"), value = c(102, 110, 116, 120, 148),
    size_f = structure(c(1L, 1L, 1L, 1L, 1L), .Label = c("Monday",
    "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday",
    "Sunday"), class = "factor"), time = c("04:00", "04:15",
    "04:30", "04:45", "05:00"), day = c("Monday", "Monday", "Monday",
    "Monday", "Monday"), variable = structure(c(1L, 1L, 1L, 1L,
    1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
    "Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
    "Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(56, 58, 64, 68, 84), size_f = structure(c(1L, 1L,
    1L, 1L, 1L), .Label = c("Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday", "Sunday"), class = "factor"),
    time = c("04:00", "04:15", "04:30", "04:45", "05:00"), day = c("Monday",
    "Monday", "Monday", "Monday", "Monday"), variable = structure(c(1L,
    1L, 1L, 1L, 1L), .Label = c("Shifts on Monday", "Shifts on Tuesday",
    "Shifts on Wednesday", "Shifts on Thursday", "Shifts on Friday",
    "Shifts on Saturday", "Shifts on Sunday"), class = "factor"),
    value = c(46, 52, 52, 52, 64), size_f = structure(c(1L, 1L,
    1L, 1L, 1L), .Label = c("Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday", "Sunday"), class = "factor")), row.names = c(NA,
5L), class = "data.frame")

The variable time, day, variable and size_f are similar.

I would like to plot 3 graph together in the same plot. But I have no clue how to this

Using the suggested facet the following plot

Plot1

Plot2

Plot3

How to move forward

I would like to create a pot like this

Body:
You can do it by merging your dataframes together and tag them as All, Male, and Female accordingly. Then you can use that tag for grouping(coloring) within your ggplot function.

Using geom_bar and position = "identity" you will get bars on top of each other and to remove the space between the bars (to mimic density plots look) width is set to 1. alpha can be used to alter the transparency of fill colors.

And to get a separate plot for each day of the week we can use facet_wrap(~day).

library(tidyverse)

melted_WkSTiWeekAll <- bind_rows(list(All=melted_WkSTiWeek,
                                      Male=melted_WkSTiWeekM,
                                      Female=melted_WkSTiWeekF),
                                                                .id = 'source')

ggplot(melted_WkSTiWeekAll, aes(x=time, y=value, fill=source)) +
  geom_bar(stat="identity", position = "identity", alpha=.3, width=1) +
  facet_wrap(~day)

Note that here we only get one facet as the data provided only has entries for Monday.

Created on 2019-05-31 by the reprex package (v0.3.0)


问:
Have I converted this php sample for Facebook authentication correctly into c#?
I'm trying to write a c# version of some php sample code for Facebook authentication which I found here: http://developers.facebook.com/docs/guides/web/ The php in the example is:

```<code>define('YOUR_APP_ID', 'your app id ');
define('YOUR_APP_SECRET', 'your app secret');

function get_facebook_cookie($app_id, $app_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
  ksort($args);
  $payload = '';
  foreach ($args as $key => $value) {
    if ($key != 'sig') {
      $payload .= $key . '=' . $value;
    }
  }
  if (md5($payload . $app_secret) != $args['sig']) {
    return null;
  }
  return $args;
}
</code>```

And my C# version is:

```<code>private bool CheckFacebookAuthentication()
{
    var appSecret = "??????????";
    var appId = "?????";
    var cookie = Request.Cookies["fbs_" + appId];

    var payload = "";
    foreach (var key in cookie.Values.AllKeys.OrderBy(x => x))
    {
        if (key != "sig")
        {
            payload += key.Trim("\"".ToCharArray()) + "=" + cookie.Values[key].Trim("\"".ToCharArray());
        }
    }

    if (cookie.Values["sig"] == FormsAuthentication.HashPasswordForStoringInConfigFile(payload + appSecret, "md5"))
    {
        return true;
    }
    return false;
}
</code>```

I appreciate that my c# version is not doing quite the same thing as the php i.e. it is just checking that the signature is valid and returning a boolean indicating this; whereas the php is returning an array if it is valid.

But the issue I have is that my c# version is not validating cookies that I would expect to be valid.  My experience of php is limited, so I expect I have misinterpreted something from the php example when writing my c# version.

Is there anything obviously wrong with my c# interpretation of this php?

答:
Yes, that is the correct translation, but you could replace "\"".ToCharArray() with just '\"'

Also, there is a pretty good SDK written in C# for Facebook here: http://facebooksdk.codeplex.com/

That is if you want to look at some more example code.

I've worked a lot with Facebook's Graph APIs and C#, so if there is anything specific you need help with, feel free to ask :)

Body:
I'm trying to write a c# version of some php sample code for Facebook authentication which I found here: http://developers.facebook.com/docs/guides/web/ The php in the example is:

define('YOUR_APP_ID', 'your app id ');
define('YOUR_APP_SECRET', 'your app secret');

function get_facebook_cookie($app_id, $app_secret) {
  $args = array();
  parse_str(trim($_COOKIE['fbs_' . $app_id], '\\"'), $args);
  ksort($args);
  $payload = '';
  foreach ($args as $key => $value) {
    if ($key != 'sig') {
      $payload .= $key . '=' . $value;
    }
  }
  if (md5($payload . $app_secret) != $args['sig']) {
    return null;
  }
  return $args;
}

And my C# version is:

private bool CheckFacebookAuthentication()
{
    var appSecret = "??????????";
    var appId = "?????";
    var cookie = Request.Cookies["fbs_" + appId];

    var payload = "";
    foreach (var key in cookie.Values.AllKeys.OrderBy(x => x))
    {
        if (key != "sig")
        {
            payload += key.Trim("\"".ToCharArray()) + "=" + cookie.Values[key].Trim("\"".ToCharArray());
        }
    }

    if (cookie.Values["sig"] == FormsAuthentication.HashPasswordForStoringInConfigFile(payload + appSecret, "md5"))
    {
        return true;
    }
    return false;
}

I appreciate that my c# version is not doing quite the same thing as the php i.e. it is just checking that the signature is valid and returning a boolean indicating this; whereas the php is returning an array if it is valid.

But the issue I have is that my c# version is not validating cookies that I would expect to be valid.  My experience of php is limited, so I expect I have misinterpreted something from the php example when writing my c# version.

Is there anything obviously wrong with my c# interpretation of this php?


问:
Particles do not appear on the particles div
I'm trying to use particles.js as a background for a website. Currently, the particles div is present, but the particles do not appear. How could i fix this?

index.html

```<code><!DOCTYPE html>
<html lang="en">
<head>
    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
    <div id="particles-js"></div>
    <script type="text/javascript" src="./particles.js-master/demo/js/app.js"></script>
    <script type="text/javascript" src="./particles.js-master/particles.js"></script>
</body>
</html>
</code>```

style.css

```<code>body {
    background: #000;
    margin: 0;
    padding: 0;
    height: 100vh;
}

#particles-js {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</code>```

I know that particles-js is present because changing its background color makes an affect on the page.

答:
You need to add the particles js config as well for it to work. You can create and download the json config from https://vincentgarreau.com/particles.js/

```<code><script type="text/javascript">
 particlesJS("particles-js",<strong>Your JSON here</strong>);
</script>
</code>```

For example my json might look like:

```<code> {
 "particles": {
 "number": {
 "value": 80,
 "density": {
 "enable": true,
 "value_area": 800
 }
 },
 "color": {
 "value": "#ffffff"
 },
 "shape": {
 "type": "circle",
 "stroke": {
 "width": 0,
 "color": "#000000"
 },
 "polygon": {
 "nb_sides": 5
 },
 "image": {
 "src": "img/github.svg",
 "width": 100,
 "height": 100
 }
 },
 "opacity": {
 "value": 0.5,
 "random": false,
 "anim": {
 "enable": false,
 "speed": 1,
 "opacity_min": 0.1,
 "sync": false
 }
 },
 "size": {
 "value": 3,
 "random": true,
 "anim": {
 "enable": false,
 "speed": 40,
 "size_min": 0.1,
 "sync": false
 }
 },
 "line_linked": {
 "enable": true,
 "distance": 150,
 "color": "#ffffff",
 "opacity": 0.4,
 "width": 1
 },
 "move": {
 "enable": true,
 "speed": 6,
 "direction": "none",
 "random": false,
 "straight": false,
 "out_mode": "out",
 "bounce": false,
 "attract": {
 "enable": false,
 "rotateX": 600,
 "rotateY": 1200
 }
 }
 },
 "interactivity": {
 "detect_on": "canvas",
 "events": {
 "onhover": {
 "enable": true,
 "mode": "repulse"
 },
 "onclick": {
 "enable": true,
 "mode": "push"
 },
 "resize": true
 },
 "modes": {
 "grab": {
 "distance": 400,
 "line_linked": {
 "opacity": 1
 }
 },
 "bubble": {
 "distance": 400,
 "size": 40,
 "duration": 2,
 "opacity": 8,
 "speed": 3
 },
 "repulse": {
 "distance": 200,
 "duration": 0.4
 },
 "push": {
 "particles_nb": 4
 },
 "remove": {
 "particles_nb": 2
 }
 }
 },
 "retina_detect": true
}
</code>```

Body:
I'm trying to use particles.js as a background for a website. Currently, the particles div is present, but the particles do not appear. How could i fix this?

index.html

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">
    <meta charset="UTF-8">
    <title>Title</title>

style.css

body {
    background: #000;
    margin: 0;
    padding: 0;
    height: 100vh;
}

#particles-js {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

I know that particles-js is present because changing its background color makes an affect on the page.

Body:
You need to add the particles js config as well for it to work. You can create and download the json config from https://vincentgarreau.com/particles.js/

<script type="text/javascript">
 particlesJS("particles-js",<strong>Your JSON here</strong>);
</script>

For example my json might look like:

 {
 "particles": {
 "number": {
 "value": 80,
 "density": {
 "enable": true,
 "value_area": 800
 }
 },
 "color": {
 "value": "#ffffff"
 },
 "shape": {
 "type": "circle",
 "stroke": {
 "width": 0,
 "color": "#000000"
 },
 "polygon": {
 "nb_sides": 5
 },
 "image": {
 "src": "img/github.svg",
 "width": 100,
 "height": 100
 }
 },
 "opacity": {
 "value": 0.5,
 "random": false,
 "anim": {
 "enable": false,
 "speed": 1,
 "opacity_min": 0.1,
 "sync": false
 }
 },
 "size": {
 "value": 3,
 "random": true,
 "anim": {
 "enable": false,
 "speed": 40,
 "size_min": 0.1,
 "sync": false
 }
 },
 "line_linked": {
 "enable": true,
 "distance": 150,
 "color": "#ffffff",
 "opacity": 0.4,
 "width": 1
 },
 "move": {
 "enable": true,
 "speed": 6,
 "direction": "none",
 "random": false,
 "straight": false,
 "out_mode": "out",
 "bounce": false,
 "attract": {
 "enable": false,
 "rotateX": 600,
 "rotateY": 1200
 }
 }
 },
 "interactivity": {
 "detect_on": "canvas",
 "events": {
 "onhover": {
 "enable": true,
 "mode": "repulse"
 },
 "onclick": {
 "enable": true,
 "mode": "push"
 },
 "resize": true
 },
 "modes": {
 "grab": {
 "distance": 400,
 "line_linked": {
 "opacity": 1
 }
 },
 "bubble": {
 "distance": 400,
 "size": 40,
 "duration": 2,
 "opacity": 8,
 "speed": 3
 },
 "repulse": {
 "distance": 200,
 "duration": 0.4
 },
 "push": {
 "particles_nb": 4
 },
 "remove": {
 "particles_nb": 2
 }
 }
 },
 "retina_detect": true
}


答:
Example df is:

>>> df = pd.DataFrame({'A': ['Stack Overlflow is great'], 'B': ['stack great']})

And you can use apply:

```<code>>>> df['A-B'] = df.apply(lambda x: ' '.join([i for i in x[0].split() if i.lower() not in x[1].split()]), axis=1)
>>> df
                          A            B           A-B
0  Stack Overlflow is great  stack great  Overlflow is
>>>
</code>```

Title: Subtract Col A - Col B in pandas dataframe

Body:
Example df is:

>>> df = pd.DataFrame({'A': ['Stack Overlflow is great'], 'B': ['stack great']})

And you can use apply:

>>> df['A-B'] = df.apply(lambda x: ' '.join([i for i in x[0].split() if i.lower() not in x[1].split()]), axis=1)
>>> df
                          A            B           A-B
0  Stack Overlflow is great  stack great  Overlflow is
>>>


问:
save file from data in nodejs
i have this object from multer lib

```<code>var myfiledata = { fieldname: 'file_comic',
  originalname: 'leoncino.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  buffer: <Buffer ff d8 ff e2 02 1c 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 02 0c 6c 63 6d 73 02 10 00 00 6d 6e 74 72 52 47 42 20 58 59 5a 20 07 dc 00 01 00 19 ... >,
  size: 74448 }
</code>```

I would save this file on harddisk

I would like to use a statement similar to this one

```<code>fs.writeFile("./test.png", myfiledata.buffer, 'binary');
</code>```

答:
Provide the buffer data to writeStream. If you want the file to be saved at different path, provide the path in fs.createWriteStream('./uploads/' + req.file.originalname):

```<code>app.post('/upload', multer.single('file'), (req, res) => {
    var fileWriteStream = fs.createWriteStream(req.file.originalname);
    fileWriteStream.on('finish', () => {
        console.log('file saved successfully');
        res.send({ message: 'file saved successfully' })
    })
    fileWriteStream.end(req.file.buffer)
})
</code>```

Title: save file from data in nodejs

Body:
i have this object from multer lib

var myfiledata = { fieldname: 'file_comic',
  originalname: 'leoncino.jpg',
  encoding: '7bit',
  mimetype: 'image/jpeg',
  buffer: <Buffer ff d8 ff e2 02 1c 49 43 43 5f 50 52 4f 46 49 4c 45 00 01 01 00 00 02 0c 6c 63 6d 73 02 10 00 00 6d 6e 74 72 52 47 42 20 58 59 5a 20 07 dc 00 01 00 19 ... >,
  size: 74448 }

I would save this file on harddisk

I would like to use a statement similar to this one

fs.writeFile("./test.png", myfiledata.buffer, 'binary');

Body:
Provide the buffer data to writeStream. If you want the file to be saved at different path, provide the path in fs.createWriteStream('./uploads/' + req.file.originalname):

app.post('/upload', multer.single('file'), (req, res) => {
    var fileWriteStream = fs.createWriteStream(req.file.originalname);
    fileWriteStream.on('finish', () => {
        console.log('file saved successfully');
        res.send({ message: 'file saved successfully' })
    })
    fileWriteStream.end(req.file.buffer)
})


问:
How can I code a Javascript Alert to only populate once per web session?
I am creating a website for my final and have coded an "adult content" alert on my homepage. I am trying to get the site to populate that message only once per session but right now it populates every time you go to the homepage.

The class is HTML and CSS but we were asked to include one basic javascript code and the "alert" seemed most appropriate. I have tried googling this question different ways to get help but it's mostly providing information that is above a very very basic level of javascript.

This is my current code:

```<code><script>
alert("WARNING! Adult Language and Content! The following is intended for
immature adults only. Viewer Discretion is Advised.")
</script>
</code>```

This is the site:
http://mysite.du.edu/~mdarienz/index.html

Since this is for a final, I don't need the code to fix it but if you could maybe steer me in the right direction for how to approach it I would greatly appreciate it.

答:
You can use localStorage, the stored data is saved across browser sessions.And, data stored in localStorage has no expiration time (not like sessionStorage)

Please change your code to this

```<code><script>
    var seenIt = localStorage.getItem('seenIt')
    if(string.isNullOrEmpty(seenIt)){
        alert("WARNING! Adult Language and Content! The following is intended for immature adults only.Viewer Discretion is Advised.");
        localStorage.setItem('seenIt', "yes");
}
</script>
</code>```

Body:
I am creating a website for my final and have coded an "adult content" alert on my homepage. I am trying to get the site to populate that message only once per session but right now it populates every time you go to the homepage.

The class is HTML and CSS but we were asked to include one basic javascript code and the "alert" seemed most appropriate. I have tried googling this question different ways to get help but it's mostly providing information that is above a very very basic level of javascript.

This is my current code:

This is the site:
http://mysite.du.edu/~mdarienz/index.html

Since this is for a final, I don't need the code to fix it but if you could maybe steer me in the right direction for how to approach it I would greatly appreciate it.

Body:
You can use localStorage, the stored data is saved across browser sessions.And, data stored in localStorage has no expiration time (not like sessionStorage)

Please change your code to this

<script>
    var seenIt = localStorage.getItem('seenIt')
    if(string.isNullOrEmpty(seenIt)){
        alert("WARNING! Adult Language and Content! The following is intended for immature adults only.Viewer Discretion is Advised.");
        localStorage.setItem('seenIt', "yes");
}
</script>


问:
Scrolling wpf datagrid to particular row and focus that row
My requirement is to scroll through wpf data grid and reach to particular row and focus that row

I am using the below code to achieve it . Scrolling to particular row is working smoothly but few times focus not work

```<code>  private void FocusNextRow()
  {
             int index = indexOfRowsToHighlight[indexOfRowToFocus];
             MessagesDataGrid.SelectedItem = MessagesDataGrid.Items[index];
             MessagesDataGrid.ScrollIntoView(MessagesDataGrid.SelectedItem);
             Thread.Sleep(200);
             MessagesDataGrid.SelectionUnit = DataGridSelectionUnit.FullRow;
             DataGridRow row = MessagesDataGrid.ItemContainerGenerator.ContainerFromIndex(index)  as DataGridRow;
             DataGridCell cell = GetCell(MessagesDataGrid, row, 0);
             cell.Focus();
   }
   private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
   {
        if (rowContainer != null)
        {
              DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
              // try to get the cell but it may possibly be virtualized
              DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
              if (cell == null)
              {
                  cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
              }
               return cell;
            }

             return null;
        }

        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
           for(int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
           {
               DependencyObject child = VisualTreeHelper.GetChild(obj, i);
               if (child != null && child is T)
                      return (T)child;
               else
               {
                     T childOfChild = FindVisualChild<T>(child);
                      if (childOfChild != null)
                           return childOfChild;
               }
            }
                    return null;
        }
</code>```

Out of 100 times 90 times focus is working but few times randomly it does not work

答:
I find two solution for this problem
1. Disable row virtualization property of data grid . But its seriously going to impact the performance.
2. Check whether FindVisualChild() ables to find the row container or not , if not then in that scenario calls rowcontainer.ApplyTemplate() method , this method ApplyTemplate() ensures your row is created in the visual tree. its more efficient way of doing</p>

Body:
My requirement is to scroll through wpf data grid and reach to particular row and focus that row

I am using the below code to achieve it . Scrolling to particular row is working smoothly but few times focus not work

  private void FocusNextRow()
  {
             int index = indexOfRowsToHighlight[indexOfRowToFocus];
             MessagesDataGrid.SelectedItem = MessagesDataGrid.Items[index];
             MessagesDataGrid.ScrollIntoView(MessagesDataGrid.SelectedItem);
             Thread.Sleep(200);
             MessagesDataGrid.SelectionUnit = DataGridSelectionUnit.FullRow;
             DataGridRow row = MessagesDataGrid.ItemContainerGenerator.ContainerFromIndex(index)  as DataGridRow;
             DataGridCell cell = GetCell(MessagesDataGrid, row, 0);
             cell.Focus();
   }
   private static DataGridCell GetCell(DataGrid dataGrid, DataGridRow rowContainer, int column)
   {
        if (rowContainer != null)
        {
              DataGridCellsPresenter presenter = FindVisualChild<DataGridCellsPresenter>(rowContainer);
              // try to get the cell but it may possibly be virtualized
              DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
              if (cell == null)
              {
                  cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);
              }
               return cell;
            }

             return null;
        }

        private static T FindVisualChild<T>(DependencyObject obj) where T : DependencyObject
        {
           for(int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
           {
               DependencyObject child = VisualTreeHelper.GetChild(obj, i);
               if (child != null && child is T)
                      return (T)child;
               else
               {
                     T childOfChild = FindVisualChild<T>(child);
                      if (childOfChild != null)
                           return childOfChild;
               }
            }
                    return null;
        }

Out of 100 times 90 times focus is working but few times randomly it does not work


问:
Why do I get this error inserting a character into a MATLAB matrix?
I am constructing a 16x16 matrix, consisting of just letters in MATLAB. I tried for example:

```<code>for i=1:2:3
    C(i,2)=char('B');
end
</code>```

to place the letter 'B' in its corresponding place in the matrix. However this gives a value of 66 in the matrix instead of just the letter 'B'. What is going wrong?

答:
If I do

```<code>for i=1:3
    C(i)=char('A');
end
</code>```

I get C=AAA, as you'd expect. I suspect the reason why you're getting the decimal value of the char is because you might have preallocated C as C=zeros(16). MATLAB initialized the array as numeric type and accordingly, when you replaced an element with a char, it promptly converted it to its numeric value.

A better approach would be to use cells and then convert it to a matrix.

```<code>C=cell(4,4);%# create an empty 4x4 cell
for i=1:16
    C{i}=char('A');
end

C=

    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'
</code>```

Now use cell2mat to convert it to a matrix:

```<code>Cmatrix=cell2mat(C)

Cmatrix=

    AAAA
    AAAA
    AAAA
    AAAA
</code>```

Normally, I wouldn't use loops, but I don't know your exact requirements, so I've shown an example as per your question.

Body:
I am constructing a 16x16 matrix, consisting of just letters in MATLAB. I tried for example:

for i=1:2:3
    C(i,2)=char('B');
end

to place the letter 'B' in its corresponding place in the matrix. However this gives a value of 66 in the matrix instead of just the letter 'B'. What is going wrong?

Body:
If I do

for i=1:3
    C(i)=char('A');
end

I get C=AAA, as you'd expect. I suspect the reason why you're getting the decimal value of the char is because you might have preallocated C as C=zeros(16). MATLAB initialized the array as numeric type and accordingly, when you replaced an element with a char, it promptly converted it to its numeric value.

A better approach would be to use cells and then convert it to a matrix.

C=cell(4,4);%# create an empty 4x4 cell
for i=1:16
    C{i}=char('A');
end

C=

    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'
    'A'    'A'    'A'    'A'

Now use cell2mat to convert it to a matrix:

Cmatrix=cell2mat(C)

Cmatrix=

    AAAA
    AAAA
    AAAA
    AAAA

Normally, I wouldn't use loops, but I don't know your exact requirements, so I've shown an example as per your question.