问:
How to use own method on ArrayList in Java?
I have a problem with a task I have to do. I need to create class Company and write few methods (such as hire, fire, etc.) for Employee class objects.
Those are my classes and methods:

```<code>public class Company{
    ArrayList <Employee> alist= new ArrayList<Employee>();

    public void hire(Employee e) {
        int i=0;
        boolean k=false;
        while(i<alist.size()) {
            if (e.getLastName().equals(alist.get(i).getLastName())) {
                k=true;
                i++;
            }
        }
        if (k==false) alist.add(e);
        else System.out.print("Employee already exists");
    }
}

public class Employee{
    protected String lastname; //protected for subclasses
    protected double jobposition;
    public Employee(String lastname,double jobposition) {
        this.lastname=lastname;
        this.jobposition=jobposition;
    }
    public String getLastName() {
        return lastname;
}
</code>```

And subclass which extends Employee:

```<code>public class OfficeWorker extends Employee {
    float pay, bonus;
    public OfficeWorker(String lastname,double jobposition,float pay,float bonus) {
        super(lastname,jobposition);
        this.pay=pay;
        this.bonus=bonus;
    }
}
</code>```

I wanted to use ArrayList to do this, but it crashes in main class and I get message "The method hire(Employee) is undefined for the type ArrayList":

```<code>public static void main(String[]args) {

    ArrayList <Employee> list = new ArrayList <Employee>();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    list.hire(e1);

}
</code>```

Why can't I do this like that?

答:
ArrayList  list = new ArrayList ();
ArrayList  don't have hire method.
In a class you can access the method availabe in that method.And that also depends upon access modifier and where you are aceesing the method.

To access a non-static public method you have to create object and call method on that object

```<code>SomeClass c=new SomeClass();
c.m();
</code>```

For static public method you can call directly

```<code>SomeClass.m();
</code>```

Body:
I have a problem with a task I have to do. I need to create class Company and write few methods (such as hire, fire, etc.) for Employee class objects.
Those are my classes and methods:

public class Company{
    ArrayList <Employee> alist= new ArrayList<Employee>();

    public void hire(Employee e) {
        int i=0;
        boolean k=false;
        while(i<alist.size()) {
            if (e.getLastName().equals(alist.get(i).getLastName())) {
                k=true;
                i++;
            }
        }
        if (k==false) alist.add(e);
        else System.out.print("Employee already exists");
    }
}

public class Employee{
    protected String lastname; //protected for subclasses
    protected double jobposition;
    public Employee(String lastname,double jobposition) {
        this.lastname=lastname;
        this.jobposition=jobposition;
    }
    public String getLastName() {
        return lastname;
}

And subclass which extends Employee:

public class OfficeWorker extends Employee {
    float pay, bonus;
    public OfficeWorker(String lastname,double jobposition,float pay,float bonus) {
        super(lastname,jobposition);
        this.pay=pay;
        this.bonus=bonus;
    }
}

I wanted to use ArrayList to do this, but it crashes in main class and I get message "The method hire(Employee) is undefined for the type ArrayList":

public static void main(String[]args) {

    ArrayList <Employee> list = new ArrayList <Employee>();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    list.hire(e1);

}

Why can't I do this like that?

Body:
ArrayList  list = new ArrayList ();
ArrayList  don't have hire method.
In a class you can access the method availabe in that method.And that also depends upon access modifier and where you are aceesing the method.

To access a non-static public method you have to create object and call method on that object

SomeClass c=new SomeClass();
c.m();

For static public method you can call directly

SomeClass.m();


来源: stackexchange

问:
Tensorboard not able to display all summaries
Since yesterday my Tensorboard doesn't display my scalar values anymore. In particular, I have 4 different scalar summaries but only one of them is displayed. I have tried to inspect the content of my summaries directory and seems that the Tensorboard is able to detect all my summaries. The strange thing is that yesterday was working smoothly.

At the moment I'm executing the Tensorboard in this way:

```<code>tensorboard --logdir=summaries/ --host=127.0.0.1 --inspect
</code>```

And the result is the following:

```<code>======================================================================
Processing event files... (this can take a few minutes)
======================================================================

Found event files in:
summaries/hseq2seq_300_512_1024_1024
summaries/hseq2seq_300_1024_2048_2048
summaries/hseq2seq_300_256_512_512
summaries/hseq2seq_300_128_256_256

These tags are in summaries/hseq2seq_300_512_1024_1024:
audio -
histograms -
images -
scalars
   agent_rewards_summary
   decoder_loss_summary
tensor -
======================================================================

Event statistics for summaries/hseq2seq_300_512_1024_1024:
audio -
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms -
images -
scalars
   first_step           0
   last_step            999999
   max_step             999999
   min_step             0
   num_steps            1000000
   outoforder_steps     []
sessionlog:checkpoint -
sessionlog:start -
sessionlog:stop -
tensor -
======================================================================

These tags are in summaries/hseq2seq_300_1024_2048_2048:
audio -
histograms -
images -
scalars
   agent_rewards_summary
   decoder_loss_summary
tensor -
======================================================================

Event statistics for summaries/hseq2seq_300_1024_2048_2048:
audio -
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms -
images -
scalars
   first_step           0
   last_step            999999
   max_step             999999
   min_step             0
   num_steps            1000000
   outoforder_steps     []
sessionlog:checkpoint -
sessionlog:start -
sessionlog:stop -
tensor -
======================================================================

These tags are in summaries/hseq2seq_300_256_512_512:
audio -
histograms -
images -
scalars
   agent_rewards_summary
   decoder_loss_summary
tensor -
======================================================================

Event statistics for summaries/hseq2seq_300_256_512_512:
audio -
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms -
images -
scalars
   first_step           0
   last_step            999999
   max_step             999999
   min_step             0
   num_steps            1000000
   outoforder_steps     []
sessionlog:checkpoint -
sessionlog:start -
sessionlog:stop -
tensor -
======================================================================

These tags are in summaries/hseq2seq_300_128_256_256:
audio -
histograms -
images -
scalars
   agent_rewards_summary
   decoder_loss_summary
tensor -
======================================================================

Event statistics for summaries/hseq2seq_300_128_256_256:
audio -
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms -
images -
scalars
   first_step           0
   last_step            999999
   max_step             999999
   min_step             0
   num_steps            1000000
   outoforder_steps     []
sessionlog:checkpoint -
sessionlog:start -
sessionlog:stop -
tensor -
======================================================================
```
```

In the following you can find some details about my configuration:

Operating system: MacOS High Sierra (latest update)

Tensorflow version: 1.4.0

Python version: 3.6.3

I have tried with all the browsers that I have namely: Chrome Canary, Firefox and Safari. The result is always the same.

Do you have any ideas? Even if it is not possible to use the Tensorboard at the moment, it will be fine to export this data to CSV. How can I do that?

Thank you!

答:
You are trying to display 4 different records as you can see in:

```<code>Found event files in:
summaries/hseq2seq_300_512_1024_1024
summaries/hseq2seq_300_1024_2048_2048
summaries/hseq2seq_300_256_512_512
summaries/hseq2seq_300_128_256_256
</code>```

This should be either of your 4 subfolders.
Try using something like tensorboard --logdir=summaries/hseq2seq_300_512_1024_1024 --host=127.0.0.1 --inspect instead.

As for the 4 scalars you have defined your inspect result does not agree. There are 6 scalars in 1st, 2nd and 4th subfolder and only 2 in the 3rd. So, there is some inconsistency in what you expect and what you get.

Did you intend to use multiple event files (in different subfolders)? Is that you meant about "4 different scalar summaries"?

ContentLicense: CC BY-SA 3.0

Body:
Since yesterday my Tensorboard doesn't display my scalar values anymore. In particular, I have 4 different scalar summaries but only one of them is displayed. I have tried to inspect the content of my summaries directory and seems that the Tensorboard is able to detect all my summaries. The strange thing is that yesterday was working smoothly.

At the moment I'm executing the Tensorboard in this way:

tensorboard --logdir=summaries/ --host=127.0.0.1 --inspect

And the result is the following:

======================================================================
Processing event files... (this can take a few minutes)
======================================================================

Found event files in:
summaries/hseq2seq_300_512_1024_1024
summaries/hseq2seq_300_1024_2048_2048
summaries/hseq2seq_300_256_512_512
summaries/hseq2seq_300_128_256_256

These tags are in summaries/hseq2seq_300_512_1024_1024:
audio -
histograms -
images -
scalars
   agent_rewards_summary
   decoder_loss_summary
tensor -
======================================================================

Event statistics for summaries/hseq2seq_300_512_1024_1024:
audio -
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms -
images -
scalars
   first_step           0
   last_step            999999
   max_step             999999
   min_step             0
   num_steps            1000000
   outoforder_steps     []
sessionlog:checkpoint -
sessionlog:start -
sessionlog:stop -
tensor -
======================================================================

These tags are in summaries/hseq2seq_300_1024_2048_2048:
audio -
histograms -
images -
scalars
   agent_rewards_summary
   decoder_loss_summary
tensor -
======================================================================

Event statistics for summaries/hseq2seq_300_1024_2048_2048:
audio -
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms -
images -
scalars
   first_step           0
   last_step            999999
   max_step             999999
   min_step             0
   num_steps            1000000
   outoforder_steps     []
sessionlog:checkpoint -
sessionlog:start -
sessionlog:stop -
tensor -
======================================================================

These tags are in summaries/hseq2seq_300_256_512_512:
audio -
histograms -
images -
scalars
   agent_rewards_summary
   decoder_loss_summary
tensor -
======================================================================

Event statistics for summaries/hseq2seq_300_256_512_512:
audio -
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms -
images -
scalars
   first_step           0
   last_step            999999
   max_step             999999
   min_step             0
   num_steps            1000000
   outoforder_steps     []
sessionlog:checkpoint -
sessionlog:start -
sessionlog:stop -
tensor -
======================================================================

These tags are in summaries/hseq2seq_300_128_256_256:
audio -
histograms -
images -
scalars
   agent_rewards_summary
   decoder_loss_summary
tensor -
======================================================================

Event statistics for summaries/hseq2seq_300_128_256_256:
audio -
graph
   first_step           0
   last_step            0
   max_step             0
   min_step             0
   num_steps            1
   outoforder_steps     []
histograms -
images -
scalars
   first_step           0
   last_step            999999
   max_step             999999
   min_step             0
   num_steps            1000000
   outoforder_steps     []
sessionlog:checkpoint -
sessionlog:start -
sessionlog:stop -
tensor -
======================================================================
```

In the following you can find some details about my configuration:

Operating system: MacOS High Sierra (latest update)

Tensorflow version: 1.4.0

Python version: 3.6.3

I have tried with all the browsers that I have namely: Chrome Canary, Firefox and Safari. The result is always the same.

Do you have any ideas? Even if it is not possible to use the Tensorboard at the moment, it will be fine to export this data to CSV. How can I do that?

Thank you!

Body:
You are trying to display 4 different records as you can see in:

Found event files in:
summaries/hseq2seq_300_512_1024_1024
summaries/hseq2seq_300_1024_2048_2048
summaries/hseq2seq_300_256_512_512
summaries/hseq2seq_300_128_256_256

This should be either of your 4 subfolders.
Try using something like tensorboard --logdir=summaries/hseq2seq_300_512_1024_1024 --host=127.0.0.1 --inspect instead.

As for the 4 scalars you have defined your inspect result does not agree. There are 6 scalars in 1st, 2nd and 4th subfolder and only 2 in the 3rd. So, there is some inconsistency in what you expect and what you get.

Did you intend to use multiple event files (in different subfolders)? Is that you meant about "4 different scalar summaries"?


问:
SABRE Single Branded Fare true
I´m using BFM Rest with the property SingleBrandedFare true. Why SABRE is returning multiple marketing airlines in a flyght?

What´s the property in json request I need to pass to SABRE return single Marketing Airlines per flyght?

The poroperty in json (OTA_AirLowFareSearchRQ):

```<code>"PriceRequestInformation": {
            "TPA_Extensions": {
                "BrandedFareIndicators": {
                    "SingleBrandedFare": true,
                    "MultipleBrandedFares": false
                }
            }
        }
</code>```

答:
Branded fares are within one carrier if you look at Lufthansa for example a fare brand would be "Light","Classic","Flex" this has nothing to do with having only one operated flight at once.

What you are looking for i think is operator deduplication:

We use soap - therefore:

```<code><!-- Optional -->
<!-- Repeat Factor=0-1 -->
<!--
Provides the capability to prefer itineraries that are unique if it comes to
the operating flights. This is done by penalizing itineraries with
duplicated operating flights.
<OperatingDuplicate Weight="10">
</OperatingDuplicate>
</code>```

Title: SABRE Single Branded Fare true

Body:
I´m using BFM Rest with the property SingleBrandedFare true. Why SABRE is returning multiple marketing airlines in a flyght?

What´s the property in json request I need to pass to SABRE return single Marketing Airlines per flyght?

The poroperty in json (OTA_AirLowFareSearchRQ):

"PriceRequestInformation": {
            "TPA_Extensions": {
                "BrandedFareIndicators": {
                    "SingleBrandedFare": true,
                    "MultipleBrandedFares": false
                }
            }
        }

Body:
Branded fares are within one carrier if you look at Lufthansa for example a fare brand would be "Light","Classic","Flex" this has nothing to do with having only one operated flight at once.

What you are looking for i think is operator deduplication:

We use soap - therefore:

<!-- Optional -->
<!-- Repeat Factor=0-1 -->
<!--
Provides the capability to prefer itineraries that are unique if it comes to
the operating flights. This is done by penalizing itineraries with
duplicated operating flights.
<OperatingDuplicate Weight="10">
</OperatingDuplicate>


问:
PHP/Symfony 2 - Fetch data from db, edit it and resend to another server
In my symfony 2 app by using a console command I want to fetch data from database table. Looping through I want to change them a bit (e.g multiply some values) and then send it to database on another server (by curl).

How can I set new names of the columns and assign those data to them? And also how to send it as an .sql file?

Just to give you brief notion here is a raw version of my command:

```<code>class MyCommand extends ContainerAwareCommand
{
      private $input;
      private $output;

      protected function configure()
      {
        // my configs
      }

     protected function execute(InputInterface $input, OutputInterface $output)
      {
       $entityManager = $this->getContainer()->get('doctrine')->getManager('default');

       $queryBuilder = $entityManager->createQueryBuilder();
       $query = $queryBuilder
                -> // my query params

       foreach ($query->iterate() as $e)
      {
       // loop through results of the query in order to create a new DB table
      }

     $this->sendData($output);

      }

}
</code>```

Thank you in advance for any help and advises!

答:
You can create another entity manager which connects to a different database. You can see that here, it's a fairly simple yaml config.

Just bring both entity managers (your 'default' and your 'other') then take what data you need and persist / flush to your other db.

Like so:

```<code>class MyCommand extends ContainerAwareCommand
{
      private $input;
      private $output;

      protected function configure()
      {
        // my configs
      }

     protected function execute(InputInterface $input, OutputInterface $output)
      {
       $entityManager = $this->getContainer()->get('doctrine')->getManager('default');
       $otherEntityManager = $this->getContainer()->get('doctrine')->getManager('other');

       $queryBuilder = $entityManager->createQueryBuilder();
       $query = $queryBuilder
                -> // my query params

       foreach ($query->iterate() as $e)
       {
           // loop through results
           $otherEntity = new OtherEntity()
                                ->setFirstProperty($first)
                                ->setSecondProperty($second)
                      ;
           $otherEntityManaer->persist($otherEntity);
       }

      $otherEntityManager->flush();

      }

}
</code>```

Body:
In my symfony 2 app by using a console command I want to fetch data from database table. Looping through I want to change them a bit (e.g multiply some values) and then send it to database on another server (by curl).

How can I set new names of the columns and assign those data to them? And also how to send it as an .sql file?

Just to give you brief notion here is a raw version of my command:

class MyCommand extends ContainerAwareCommand
{
      private $input;
      private $output;

      protected function configure()
      {
        // my configs
      }

     protected function execute(InputInterface $input, OutputInterface $output)
      {
       $entityManager = $this->getContainer()->get('doctrine')->getManager('default');

       $queryBuilder = $entityManager->createQueryBuilder();
       $query = $queryBuilder
                -> // my query params

       foreach ($query->iterate() as $e)
      {
       // loop through results of the query in order to create a new DB table
      }

     $this->sendData($output);

      }

}

Thank you in advance for any help and advises!

Body:
You can create another entity manager which connects to a different database. You can see that here, it's a fairly simple yaml config.

Just bring both entity managers (your 'default' and your 'other') then take what data you need and persist / flush to your other db.

Like so:

class MyCommand extends ContainerAwareCommand
{
      private $input;
      private $output;

      protected function configure()
      {
        // my configs
      }

     protected function execute(InputInterface $input, OutputInterface $output)
      {
       $entityManager = $this->getContainer()->get('doctrine')->getManager('default');
       $otherEntityManager = $this->getContainer()->get('doctrine')->getManager('other');

       $queryBuilder = $entityManager->createQueryBuilder();
       $query = $queryBuilder
                -> // my query params

       foreach ($query->iterate() as $e)
       {
           // loop through results
           $otherEntity = new OtherEntity()
                                ->setFirstProperty($first)
                                ->setSecondProperty($second)
                      ;
           $otherEntityManaer->persist($otherEntity);
       }

      $otherEntityManager->flush();

      }

}


问:
Two ways to put image into graphics context - which is better?
I've noticed examples of two ways to put images into core graphics.  One is much simpler than the other.  So what's the advantage of the second, more sophisticated, approach?  Is it faster?

example 1

```<code>UIImage *myImage = [UIImage imageNamed:@"picture.png"];
CGRect imageRect = CGRectMake(70, 330, 40, 40);
[myImage drawInRect:imageRect];
[myImage release];
</code>```

example 2

```<code>// Load image from application bundle
NSString* imageFileName = [[[NSBundle mainBundle] resourcePath]         stringByAppendingPathComponent:@"picture.png"];
CGDataProviderRef provider = CGDataProviderCreateWithFilename([imageFileName UTF8String]);
CGImageRef image = CGImageCreateWithPNGDataProvider(provider, NULL, true,      kCGRenderingIntentDefault);
CGDataProviderRelease(provider);

// Draw image
CGContextTranslateCTM(context, 70, 370 );
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, 40, 40), image);
CGImageRelease(image);
</code>```

答:
Directly comparing the two, the advantage of the second method is that it doesn't put the image into the +[UIImage imageNamed:] cache. It's not possible for you to remove images from that cache, so you may be better off not using imageNamed:.

However, you can get the best of both worlds.

First off, use -[NSBundle URLForResource:withExtension:] to get the URL to the image. This simplifies that step over getting the resource directory path or URL and appending the filename to it yourself.

Second, use +[UIImage imageWithContentsOfURL:] to create the image, passing the URL you obtained from the NSBundle.

From there, continue on as in your first example. The total will be only five lines (two of them replacing the first line of your first example).

ContentLicense: CC BY-SA 2.5

Body:
I've noticed examples of two ways to put images into core graphics.  One is much simpler than the other.  So what's the advantage of the second, more sophisticated, approach?  Is it faster?

example 1

UIImage *myImage = [UIImage imageNamed:@"picture.png"];
CGRect imageRect = CGRectMake(70, 330, 40, 40);
[myImage drawInRect:imageRect];
[myImage release];

example 2

// Load image from application bundle
NSString* imageFileName = [[[NSBundle mainBundle] resourcePath]         stringByAppendingPathComponent:@"picture.png"];
CGDataProviderRef provider = CGDataProviderCreateWithFilename([imageFileName UTF8String]);
CGImageRef image = CGImageCreateWithPNGDataProvider(provider, NULL, true,      kCGRenderingIntentDefault);
CGDataProviderRelease(provider);

// Draw image
CGContextTranslateCTM(context, 70, 370 );
CGContextScaleCTM(context, 1.0, -1.0);
CGContextDrawImage(context, CGRectMake(0, 0, 40, 40), image);
CGImageRelease(image);


问:
django 1.5 python set X-Content-Type-Options nosniff
We would like to add X-Content-Type-Options nosniff .

We can't upgrade to newer django version (1.5), so we can't use the SECURE_CONTENT_TYPE_NOSNIFF because we don't have SecurityMiddleware.

Any help is appriciated.

答:
The security middleware came from django-secure, so you could install that.

However, you really should upgrade Django. Django 1.5 is years out of date and insecure.


问:
Password doesn't hash before being saved into the db
I'm developing an app using Node.js, Mongoose, MongoDb, Express.

I'm trying to hash the password before being saved in the db when the user register, but it doesn't seems to work. The password is saved without hashing, any suggestions?

```<code>'use strict'

  let mongoose = require('mongoose')
  let bcrypt = require('bcrypt-nodejs')
   var Schema = mongoose.Schema

    var userSchema = Schema({
     name: { type: String, required: true, unique: true },
     password: { type: String, required: true },
     createdAt: {
     type: Date,
     require: true,
     default: Date.now
    }
   })
   // check if user already exists
   userSchema.path('name').validate(function (name) {
   User.findOne({name}, function (err, user) {
  if (err) {
  console.log('error')
  } if (user) {
  console.log('The user already exists')
    console.log(user)
  }
  })
}, 'The user already exists')

  // password validation

userSchema.path('password').validate(function (password) {
 return password.length >= 6
 }, 'The password must be of minimum length 6 characters.')
var User = mongoose.model('User', userSchema)

 // hashing and adding salt pre save()

   userSchema.pre('save', function (next) {
    bcrypt.genSalt(10, function (err, salt) {
    if (err) {
     return next(err)
     }
    bcrypt.hash(this.password, salt, null, function (err, hash) {
     // Store hash in your password DB.
    if (err) {
      return next(err)
    }
       // set the password to the hash
      this.password = hash
    })
    next()
 })
 })
  module.exports = User
</code>```

答:
next() should be called within bcrypt.hash() method when using callbacks.

For synchronous:

```<code>userSchema.pre('save', (next) => {
   const salt = bcrypt.genSaltSync(10)
   const hash = bcrypt.hashSync(this.password, salt)

   this.password = hash
   next()
})
</code>```

Body:
I'm developing an app using Node.js, Mongoose, MongoDb, Express.

I'm trying to hash the password before being saved in the db when the user register, but it doesn't seems to work. The password is saved without hashing, any suggestions?

'use strict'

  let mongoose = require('mongoose')
  let bcrypt = require('bcrypt-nodejs')
   var Schema = mongoose.Schema

    var userSchema = Schema({
     name: { type: String, required: true, unique: true },
     password: { type: String, required: true },
     createdAt: {
     type: Date,
     require: true,
     default: Date.now
    }
   })
   // check if user already exists
   userSchema.path('name').validate(function (name) {
   User.findOne({name}, function (err, user) {
  if (err) {
  console.log('error')
  } if (user) {
  console.log('The user already exists')
    console.log(user)
  }
  })
}, 'The user already exists')

  // password validation

userSchema.path('password').validate(function (password) {
 return password.length >= 6
 }, 'The password must be of minimum length 6 characters.')
var User = mongoose.model('User', userSchema)

 // hashing and adding salt pre save()

   userSchema.pre('save', function (next) {
    bcrypt.genSalt(10, function (err, salt) {
    if (err) {
     return next(err)
     }
    bcrypt.hash(this.password, salt, null, function (err, hash) {
     // Store hash in your password DB.
    if (err) {
      return next(err)
    }
       // set the password to the hash
      this.password = hash
    })
    next()
 })
 })
  module.exports = User

Body:
next() should be called within bcrypt.hash() method when using callbacks.

For synchronous:

userSchema.pre('save', (next) => {
   const salt = bcrypt.genSaltSync(10)
   const hash = bcrypt.hashSync(this.password, salt)

   this.password = hash
   next()
})


问:
Uncaught TypeError: $(...).leanModal is not a function at HTMLDocument.<anonymous>
I'm using Materialize css library and laravel to create a Survey application:
here is my html code:

```<code><div id="doDelete" class="modal bottom-sheet">
        <div class="modal-content">
          <div class="container">
            <div class="row">
              <h4>Are you sure?</h4>
              <p>Do you wish to delete this survey called "{{ $survey->title }}"?</p>
              <div class="modal-footer">
                <a href="/survey/{{ $survey->id }}/delete" class=" modal-action waves-effect waves-light btn-flat red-text">Yep yep!</a>
                <a class=" modal-action modal-close waves-effect waves-light green white-text btn">No, stop!</a>
              </div>
            </div>
          </div>
        </div>
      </div>
</code>```

and init.js code:

```<code>$(document).ready(function() {
  $('.collapsible').collapsible({
    accordion: false
  });

 $('.modal-trigger').leanModal();

  $(document).on('click', '.delete-option', function() {
    $(this).parent(".input-field").remove();
  });
</code>```

but I have this error when trying to execute delete function

```<code>init.js:6 Uncaught TypeError: $(...).leanModal is not a function
    at HTMLDocument.<anonymous> (init.js:6)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at Function.ready (jquery.min.js:2)
    at HTMLDocument.I (jquery.min.js:2)
</code>```

also I include  init.js and jquery.min.js

```<code> <script src="{{ URL::asset('jquery.min.js') }}"></script>
    {!! MaterializeCSS::include_js() !!}
    <script src="{{ URL::asset('init.js') }}"></script>
</code>```

any help please !! thanks.

答:
```<code>               <section class="new">
                    <center><h2 class="text center">RECENT-PROJECT</h2></center>
                    <div id="carousel">
                            <img src="carousel 11.jpg" id="item-11"/>
                            <img src=" carousel image4.jpg" id="item-4"/>
                            <img src="image8.jpg" id="item-8"/>
                            <img src="image9.jpg" id="item-9"/>
                             <img src="image13.jpg" id="item-13"/>
                             <img src="image15.jpg" id="item-15"/>
                             <img src="images 12.jpg" id="item-12"/>
                             <img src="images 14.jpg" id="item-14"/>
                             <img src="image16.jpg" id="item-9"/>
                        </div>

                        <script>
                                $(document).ready(function () {
                                  var carousel = $("#carousel").waterwheelCarousel({
                                    flankingItems: 3,
                                  });

                                  $('#prev').bind('click', function () {
                                    carousel.prev();
                                    return false
                                  });

                                  $('#next').bind('click', function () {
                                    carousel.next();
                                    return false;
                                  });
                                });
                            </script>
                    </section>
</code>```

Body:
I'm using Materialize css library and laravel to create a Survey application:
here is my html code:

Are you sure?

Do you wish to delete this survey called "{{ $survey->title }}"?

                id }}/delete" class=" modal-action waves-effect waves-light btn-flat red-text">Yep yep!
                No, stop!

and init.js code:

$(document).ready(function() {
  $('.collapsible').collapsible({
    accordion: false
  });

 $('.modal-trigger').leanModal();

  $(document).on('click', '.delete-option', function() {
    $(this).parent(".input-field").remove();
  });

but I have this error when trying to execute delete function

init.js:6 Uncaught TypeError: $(...).leanModal is not a function
    at HTMLDocument.<anonymous> (init.js:6)
    at j (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at Function.ready (jquery.min.js:2)
    at HTMLDocument.I (jquery.min.js:2)

also I include  init.js and jquery.min.js

    {!! MaterializeCSS::include_js() !!}

any help please !! thanks.


问:
CSS pseudo element tooltip has the same width as the original element
Here i got the code.

body {
 padding: 5px 10px;
 background-color: #E5E2D9FF;
}

abbr {position: relative}

abbr:hover:after {
  content: attr(title);
  position: absolute;
  color: #FFFFFFD7;
  background-color: #0000009C;
  padding: 2px 5px;
  bottom: 0; right: 0;
  transform: translate(100%, 100%);
  border-radius: 0 5px 5px 5px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>CSS Tooltips</h1>
 <h2>Simple tooltip</h2>
 <h3>With 'abbr' tag</h3>
 <p><abbr title="This is a simple tooltip">Lorem</abbr> ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati ea quae iste, voluptates nihil nesciunt laboriosam saepe magnam, odio molestiae architecto! Reprehenderit exercitationem magnam, illo possimus vero ducimus, commodi magni!</p></code>```

I want that the :after pseudo element's width is different from the original element.

Thanks :)

答:
Just set a width to pseudoelement.

    body {
     padding: 5px 10px;
     background-color: #E5E2D9FF;
    }

    abbr {position: relative}

    abbr:hover:after {
      content: attr(title);
      position: absolute;
      color: #FFFFFFD7;
      background-color: #0000009C;
      padding: 2px 5px;
      bottom: 0; right: 0;
      transform: translate(100%, 100%);
      border-radius: 0 5px 5px 5px;
      white-space: nowrap;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><h1>CSS Tooltips</h1>
<h2>Simple tooltip</h2>
<h3>With 'abbr' tag</h3>
<p><abbr title="This is a simple tooltip">Lorem</abbr> ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati ea quae iste, voluptates nihil nesciunt laboriosam saepe magnam, odio molestiae architecto! Reprehenderit exercitationem magnam, illo possimus vero ducimus, commodi magni!</p></code>```

Of course, you can set max/min-width, combine with non-width and white-space: no-wrap if you have just short texts with unknown width and want them on one line, etc.

Body:
Here i got the code.

body {
 padding: 5px 10px;
 background-color: #E5E2D9FF;
}

abbr {position: relative}

abbr:hover:after {
  content: attr(title);
  position: absolute;
  color: #FFFFFFD7;
  background-color: #0000009C;
  padding: 2px 5px;
  bottom: 0; right: 0;
  transform: translate(100%, 100%);
  border-radius: 0 5px 5px 5px;
}

CSS Tooltips

Simple tooltip

With 'abbr' tag

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati ea quae iste, voluptates nihil nesciunt laboriosam saepe magnam, odio molestiae architecto! Reprehenderit exercitationem magnam, illo possimus vero ducimus, commodi magni!

I want that the :after pseudo element's width is different from the original element.

Thanks :)

Body:
Just set a width to pseudoelement.

    body {
     padding: 5px 10px;
     background-color: #E5E2D9FF;
    }

    abbr {position: relative}

    abbr:hover:after {
      content: attr(title);
      position: absolute;
      color: #FFFFFFD7;
      background-color: #0000009C;
      padding: 2px 5px;
      bottom: 0; right: 0;
      transform: translate(100%, 100%);
      border-radius: 0 5px 5px 5px;
      white-space: nowrap;
    }

<h1>CSS Tooltips</h1>
<h2>Simple tooltip</h2>
<h3>With 'abbr' tag</h3>
<p><abbr title="This is a simple tooltip">Lorem</abbr> ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati ea quae iste, voluptates nihil nesciunt laboriosam saepe magnam, odio molestiae architecto! Reprehenderit exercitationem magnam, illo possimus vero ducimus, commodi magni!</p>

Of course, you can set max/min-width, combine with non-width and white-space: no-wrap if you have just short texts with unknown width and want them on one line, etc.


问:
iframe how to use parent javascript file in iframe
I am having two html file Parent.html & Child.html.
Parent.html imports jquery.js file and Child.html in iframe.

Parent.html

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script>
$('body').click(function() {
 alert("asdgaskdj");
});
</script>
</head>
<body>
<!--Parent do  some thing-->
<iframe id="workspace"  style="width:100%;height:100%;overflow:auto;" src="Child.html">
</iframe>
</body>
</html>
</code>```

Child.html

```<code><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
$('body').click(function() {
 alert("asdgaskdj");
});
</script>
</head>
<body>
<!--child do some thing-->
</body>
</html>
</code>```

My qustion is already jquery has been imported by Parent.html
Should i import it again in Child.html

if i dont import in Child.html it shows $ is undefined.

Parent.html already imported 255KB of js file.
Child.html also want to do the same.
If it does then again 255kb of file has to be downloaded from the server.
Is any other way to reach the solution.

Plz HELP !!!!!

答:
You don't want to include the jQuery plugin again in child.html.

Just insert window.parent before $ to access parent jQuery plugin.

Child.html

```<code><script>
  window.parent.$('body').click(function(){
      alert("asdgaskdj");
  });
</script>
</code>```

Body:
I am having two html file Parent.html & Child.html.
Parent.html imports jquery.js file and Child.html in iframe.

Parent.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Child.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

My qustion is already jquery has been imported by Parent.html
Should i import it again in Child.html

if i dont import in Child.html it shows $ is undefined.

Parent.html already imported 255KB of js file.
Child.html also want to do the same.
If it does then again 255kb of file has to be downloaded from the server.
Is any other way to reach the solution.

Plz HELP !!!!!

Body:
You don't want to include the jQuery plugin again in child.html.

Just insert window.parent before $ to access parent jQuery plugin.

Child.html

<script>
  window.parent.$('body').click(function(){
      alert("asdgaskdj");
  });
</script>


问:
Ionic2: Making a get request in a service with HttpClient gets undefined on component
When I try to make a GET request using a service I can print successfully the response inside this service (data.service.ts) but when I try to get this on a component, it gets undefined (send.component.ts)

data.service.ts

```<code>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map']

@Injectable()
export class DataService {

    getBusiness(){
        this.http.get('http://127.0.0.1/business').subscribe(data => {
            this.BUSINESS = data;
            return this.BUSINESS;
        });
    }

    constructor(private http:HttpClient){}

}
</code>```

send.component.ts

```<code>import { DataService } from '../../app/data.service';

@Component({
  selector: 'page-send',
  templateUrl: 'send.html'
})
export class SendPage {

  constructor(private dataService:DataService) {
    this.title = navParams.get('title');

    console.log(dataService.getBusiness())
  }
}
</code>```

JSON response:

```<code>[{
    "_id": "5a0cf90cf3de893b000b8e3b",
    "name": "business2",
    "boxes": ["dasdsadsdasbox", "dsadajhhgbox"],
    "users": ["user2"],
    "deleted": false
}, {
    "_id": "5a0cf90cf3de893b321321",
    "name": "business1",
    "boxes": ["dasds321321box", "ds321321hgbox"],
    "users": ["user1"],
    "deleted": false
}]
</code>```

Why does it happens and how to fix it?

Thank you!

答:
try below code :

data.service.ts

```<code>getBusiness(){
       return new Promise(resolve => {
           this.http.get('http://127.0.0.1/business')
             .subscribe(data => {
               resolve(data.json());
             });
         });
}
</code>```

send.component.ts

```<code>constructor(private dataService:DataService) {
    this.title = navParams.get('title');
    dataService.getBusiness().then(res => {
       console.log('Responce =>'res);
    })
  }
</code>```

Body:
When I try to make a GET request using a service I can print successfully the response inside this service (data.service.ts) but when I try to get this on a component, it gets undefined (send.component.ts)

data.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import 'rxjs/add/operator/map']

@Injectable()
export class DataService {

    getBusiness(){
        this.http.get('http://127.0.0.1/business').subscribe(data => {
            this.BUSINESS = data;
            return this.BUSINESS;
        });
    }

    constructor(private http:HttpClient){}

}

send.component.ts

import { DataService } from '../../app/data.service';

@Component({
  selector: 'page-send',
  templateUrl: 'send.html'
})
export class SendPage {

  constructor(private dataService:DataService) {
    this.title = navParams.get('title');

    console.log(dataService.getBusiness())
  }
}

JSON response:

[{
    "_id": "5a0cf90cf3de893b000b8e3b",
    "name": "business2",
    "boxes": ["dasdsadsdasbox", "dsadajhhgbox"],
    "users": ["user2"],
    "deleted": false
}, {
    "_id": "5a0cf90cf3de893b321321",
    "name": "business1",
    "boxes": ["dasds321321box", "ds321321hgbox"],
    "users": ["user1"],
    "deleted": false
}]

Why does it happens and how to fix it?

Thank you!

Body:
try below code :

data.service.ts

getBusiness(){
       return new Promise(resolve => {
           this.http.get('http://127.0.0.1/business')
             .subscribe(data => {
               resolve(data.json());
             });
         });
}

send.component.ts

constructor(private dataService:DataService) {
    this.title = navParams.get('title');
    dataService.getBusiness().then(res => {
       console.log('Responce =>'res);
    })
  }


问:
How to make vim pretend to have a flat source directory from a complex tree?
I often find myself working in projects with directory structures similar to this:

```<code>a/
  x/
    file1.h
  y/
    file2.h
  z/
    file3.h
b/
  u/
    file4.cpp
    file5.h
  v/
    file6.cpp
    file7.cpp
  w/
</code>```

where source files are spread over all the directories.

I have a shortcut such that saying Ctrl+n opens a :tabnew prompt, but I still find it cumbersome to find the file I want myself by just typing/auto-completing the directories, as I have to remember where a particular file that I want to open lives.

Can I get vim to pretend the entire directory structure to be flat, or rather do a find and then open? I'd like to still have auto completion.
Of course, there could be name clashes in theory, but for most cases you wont have files of the same name in separate directories even if you technically could.

So what I want is for the source directory to appear as if it looked like this:

```<code>    file1.h
    file2.h
    file3.h
    file4.cpp
    file5.h
    file6.cpp
    file7.cpp
</code>```

Allowing me to type something like :magiccommand f<TAB>2<TAB> to open a/y/file2.h.

答:
There exists several fuzzyfinders that help to accomplish that -- I even wrote one a long time ago.

You can also stick to vanilla Vim and use starstar: :sp **/f*2<tab>.

If you set 'path' correctly, you could also type :find +sp f<tab> (it doesn't seem to work with :tabedit though).

Body:
I often find myself working in projects with directory structures similar to this:

a/
  x/
    file1.h
  y/
    file2.h
  z/
    file3.h
b/
  u/
    file4.cpp
    file5.h
  v/
    file6.cpp
    file7.cpp
  w/

where source files are spread over all the directories.

I have a shortcut such that saying Ctrl+n opens a :tabnew prompt, but I still find it cumbersome to find the file I want myself by just typing/auto-completing the directories, as I have to remember where a particular file that I want to open lives.

Can I get vim to pretend the entire directory structure to be flat, or rather do a find and then open? I'd like to still have auto completion.
Of course, there could be name clashes in theory, but for most cases you wont have files of the same name in separate directories even if you technically could.

So what I want is for the source directory to appear as if it looked like this:

    file1.h
    file2.h
    file3.h
    file4.cpp
    file5.h
    file6.cpp
    file7.cpp

Allowing me to type something like :magiccommand f<TAB>2<TAB> to open a/y/file2.h.


问:
Remove border in bottom of the react-native Picker
I have a problem trying to remove the bottom border from the default Picker in react-native.

My code:

```<code><Picker
  style={styles.pickerStyle}
  selectedValue={this.state.registerType}
  onValueChange={(item) => this.setState({registerType:item})}>
  <Picker.Item label="Vælg emne" value="choose" />
  {registerTypes}
</Picker>
</code>```

On the image below you can see what I want to remove:

I have tried to use the underlineColorAndroid='transparent' properties as you will do in the TextInput tag, but it diden't work. Any suggestions?

答: I know it was an easy fix, but a part of my design was to change the background color in the Picker and then the border is hidden behind I guess.</p>

Body:
I have a problem trying to remove the bottom border from the default Picker in react-native.

My code:

<Picker
  style={styles.pickerStyle}
  selectedValue={this.state.registerType}
  onValueChange={(item) => this.setState({registerType:item})}>
  <Picker.Item label="Vælg emne" value="choose" />
  {registerTypes}
</Picker>

On the image below you can see what I want to remove:

I have tried to use the underlineColorAndroid='transparent' properties as you will do in the TextInput tag, but it diden't work. Any suggestions?


问:
nopcommerce 3.80 ender-blocking JavaScript and CSS in above-the-fold content
I'm using the "async" property of Html.AppendScriptParts method in nopcommerce 3.80 like that Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js",false,true);

The google PageSpeed Tools give it a high score which is i expected:

But it seems effect to the other functionalities of website (nivo slider, ajax filter which comes from Seven Spikes plugin,... )

I'm not using js and css bundling feature in nopcommerce.
Can you guys please tell me what is the best solution in my scenarior now ?
Any helps are very appriciated.
Thank you so much.

Here is my code of _Root.head.cshtml:

```<code>@using Nop.Core.Domain.Common;
@using Nop.Core.Domain.Seo
@using Nop.Core.Infrastructure;
@{
    var displayMiniProfiler = EngineContext.Current.Resolve<Nop.Core.Domain.StoreInformationSettings>().DisplayMiniProfilerInPublicStore;

    Html.AppendScriptParts("~/Scripts/public.ajaxcart.js");
    Html.AppendScriptParts("~/Scripts/public.common.js");
    Html.AppendScriptParts("~/Scripts/jquery-migrate-1.2.1.min.js");
    Html.AppendScriptParts("~/Scripts/jquery-ui-1.10.3.custom.min.js");
    Html.AppendScriptParts("~/Scripts/jquery.validate.unobtrusive.min.js");
    Html.AppendScriptParts("~/Scripts/jquery.validate.min.js");
    Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js",false,true);
    var commonSettings = EngineContext.Current.Resolve<CommonSettings>();
    if (commonSettings.RenderXuaCompatible)
    {
        Html.AppendHeadCustomParts(string.Format("<meta http-equiv=\"X-UA-Compatible\" content=\"{0}\"/>", commonSettings.XuaCompatibleValue));
    }
    var seoSettings = EngineContext.Current.Resolve<SeoSettings>();
    if (!string.IsNullOrEmpty(seoSettings.CustomHeadTags))
    {
        Html.AppendHeadCustomParts(seoSettings.CustomHeadTags);
    }
}
<!DOCTYPE html>
<html@(this.ShouldUseRtlTheme() ? Html.Raw(" dir=\"rtl\"") : null) @Html.NopPageCssClasses()>
<head>
    <title>@Html.NopTitle()</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
    <meta name="description" content="@(Html.NopMetaDescription())" />
    <meta name="keywords" content="@(Html.NopMetaKeywords())" />
    <meta name="generator" content="nopCommerce" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    @Html.NopHeadCustom()
    @Html.Partial("Head")
    @Html.Widget("head_html_tag")
    @Html.NopCssFiles(this.Url, ResourceLocation.Head)
    @Html.NopScripts(this.Url, ResourceLocation.Head)
    @Html.NopCanonicalUrls()
    @Html.Action("RssHeaderLink", "News")
    @Html.Action("RssHeaderLink", "Blog")
    @Html.Action("Favicon", "Common")
    @if (displayMiniProfiler)
    {
        @StackExchange.Profiling.MiniProfiler.RenderIncludes()
    }
</head>
<body>
    @RenderBody()
    @Html.NopCssFiles(this.Url, ResourceLocation.Foot)
    @Html.NopScripts(this.Url, ResourceLocation.Foot)

</body>
</html>
</code>```

答:
First, it's not related to Seven Spikes plugins. This issue is because of async behavior. When you make jquery file to an async, it means application will not wait to load that file and going to load next js file. But other js file are depended on first main file, and that's way you're getting errors.

Let's understand it with current scenario, the default code is:

```<code>Html.AppendScriptParts("~/Scripts/public.ajaxcart.js");
Html.AppendScriptParts("~/Scripts/public.common.js");
Html.AppendScriptParts("~/Scripts/jquery-migrate-1.2.1.min.js");
Html.AppendScriptParts("~/Scripts/jquery-ui-1.10.3.custom.min.js");
Html.AppendScriptParts("~/Scripts/jquery.validate.unobtrusive.min.js");
Html.AppendScriptParts("~/Scripts/jquery.validate.min.js");
Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js");
</code>```

In this case the order of js files are:

Now load jquery min js file asynchronously.

```<code>Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js", false, true);
</code>```

And check console:

With this change you will get an error(s).

To resolve this issue, you have to load js min file in one particular order on basis of dependency.

Side Note: this issue is with default code too!! I've tested with nopCommerce 3.80 and 3.90

Body:
I'm using the "async" property of Html.AppendScriptParts method in nopcommerce 3.80 like that Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js",false,true);

The google PageSpeed Tools give it a high score which is i expected:

But it seems effect to the other functionalities of website (nivo slider, ajax filter which comes from Seven Spikes plugin,... )

I'm not using js and css bundling feature in nopcommerce.
Can you guys please tell me what is the best solution in my scenarior now ?
Any helps are very appriciated.
Thank you so much.

Here is my code of _Root.head.cshtml:

@using Nop.Core.Domain.Common;
@using Nop.Core.Domain.Seo
@using Nop.Core.Infrastructure;
@{
    var displayMiniProfiler = EngineContext.Current.Resolve<Nop.Core.Domain.StoreInformationSettings>().DisplayMiniProfilerInPublicStore;

    Html.AppendScriptParts("~/Scripts/public.ajaxcart.js");
    Html.AppendScriptParts("~/Scripts/public.common.js");
    Html.AppendScriptParts("~/Scripts/jquery-migrate-1.2.1.min.js");
    Html.AppendScriptParts("~/Scripts/jquery-ui-1.10.3.custom.min.js");
    Html.AppendScriptParts("~/Scripts/jquery.validate.unobtrusive.min.js");
    Html.AppendScriptParts("~/Scripts/jquery.validate.min.js");
    Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js",false,true);
    var commonSettings = EngineContext.Current.Resolve<CommonSettings>();
    if (commonSettings.RenderXuaCompatible)
    {
        Html.AppendHeadCustomParts(string.Format("<meta http-equiv=\"X-UA-Compatible\" content=\"{0}\"/>", commonSettings.XuaCompatibleValue));
    }
    var seoSettings = EngineContext.Current.Resolve<SeoSettings>();
    if (!string.IsNullOrEmpty(seoSettings.CustomHeadTags))
    {
        Html.AppendHeadCustomParts(seoSettings.CustomHeadTags);
    }
}
<!DOCTYPE html>

    <title>@Html.NopTitle()</title>
    <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />
    <meta name="description" content="@(Html.NopMetaDescription())" />
    <meta name="keywords" content="@(Html.NopMetaKeywords())" />
    <meta name="generator" content="nopCommerce" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    @Html.NopHeadCustom()
    @Html.Partial("Head")
    @Html.Widget("head_html_tag")
    @Html.NopCssFiles(this.Url, ResourceLocation.Head)
    @Html.NopScripts(this.Url, ResourceLocation.Head)
    @Html.NopCanonicalUrls()
    @Html.Action("RssHeaderLink", "News")
    @Html.Action("RssHeaderLink", "Blog")
    @Html.Action("Favicon", "Common")
    @if (displayMiniProfiler)
    {
        @StackExchange.Profiling.MiniProfiler.RenderIncludes()
    }

    @RenderBody()
    @Html.NopCssFiles(this.Url, ResourceLocation.Foot)
    @Html.NopScripts(this.Url, ResourceLocation.Foot)

Body:
First, it's not related to Seven Spikes plugins. This issue is because of async behavior. When you make jquery file to an async, it means application will not wait to load that file and going to load next js file. But other js file are depended on first main file, and that's way you're getting errors.

Let's understand it with current scenario, the default code is:

Html.AppendScriptParts("~/Scripts/public.ajaxcart.js");
Html.AppendScriptParts("~/Scripts/public.common.js");
Html.AppendScriptParts("~/Scripts/jquery-migrate-1.2.1.min.js");
Html.AppendScriptParts("~/Scripts/jquery-ui-1.10.3.custom.min.js");
Html.AppendScriptParts("~/Scripts/jquery.validate.unobtrusive.min.js");
Html.AppendScriptParts("~/Scripts/jquery.validate.min.js");
Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js");

In this case the order of js files are:

Now load jquery min js file asynchronously.

Html.AppendScriptParts("~/Scripts/jquery-1.10.2.min.js", false, true);

And check console:

With this change you will get an error(s).

To resolve this issue, you have to load js min file in one particular order on basis of dependency.

Side Note: this issue is with default code too!! I've tested with nopCommerce 3.80 and 3.90


问:
Property '...' is declared but never used
I have many unused params for my functions and constructors, usualy, an underscore does the trick

1) but here I still get the error message

I tried this (or adding an underscore)

```<code>/* tslint:disable-next-line:no-unused-variable */
constructor(private el: ElementRef) {  }
</code>```

with no luck

2) how do we deal with parameters that are only used in the templates, such errors will be triggered ?

I have to console.log to faint using a variable

thanks

答:
Just set your variable as public

```<code>constructor(public el: ElementRef) {  }
</code>```

Source : https://github.com/palantir/tslint/issues/3094

ContentLicense: CC BY-SA 4.0

Body:
I have many unused params for my functions and constructors, usualy, an underscore does the trick

1) but here I still get the error message

I tried this (or adding an underscore)

/* tslint:disable-next-line:no-unused-variable */
constructor(private el: ElementRef) {  }

with no luck

2) how do we deal with parameters that are only used in the templates, such errors will be triggered ?

I have to console.log to faint using a variable

thanks

Body:
Just set your variable as public

constructor(public el: ElementRef) {  }

Source : https://github.com/palantir/tslint/issues/3094


问:
Protect Direct Line Secret in Botframework for Web Client
I have my bot ready and working with Direct Line Secret in WebChat (by passing &s=SECRET in URL) and on other channels.

I am interested in the integration of front-end Custom Chat Application using Direct Line ClientJS (link at bottom).

After going through the documentation on Bot Framework I came to know that it can be done in 2 ways:

Pass Direct Line secret from front-end Chat Application in ClientJS

Passing Token from front-end Chat Application (But, this requires Direct Line Secret to be passed to generate token first time)

As I develop bots for my clients with their respective use-cases which
need to be kept private with client servers.

So, anybody having Direct Line Secret can easily obtain Bots Logic (i.e Not actual code, but what answer bot replies to particular question) by just passing that Direct Line secret in Microsoft Bot Framework provided WebChat client (by passing s=SECRET in URL)

So, basically, how do I hide the secret from others?

Direct Line Client : https://github.com/Microsoft/BotBuilder-Samples/tree/master/Node/core-DirectLine

Authentication Mechanism : https://learn.microsoft.com/en-us/bot-framework/rest-api/bot-framework-rest-direct-line-3-0-authentication

Programming Languages:

FrontEnd - Angular.js with Typescript

Backend - Node.js on Heroku

答:
Indeed, you you need put the secret altogether for direct line but there are ways you can handle in you bot code to avoid using to other people.

Follow the below steps:

```<code>1) you can pass the domain where you want to implement with user login context.
2) login context will go in bot code and will be check server side that the user which is logged in having authorized to access or to use your chat bot.
3) Restrict your bot to that particular domain.
4) Check authentication in bot using sign in feature via card.
</code>```

I hope above liners will help you.
do let me know in case you need more help.

Body:
Indeed, you you need put the secret altogether for direct line but there are ways you can handle in you bot code to avoid using to other people.

Follow the below steps:

1) you can pass the domain where you want to implement with user login context.
2) login context will go in bot code and will be check server side that the user which is logged in having authorized to access or to use your chat bot.
3) Restrict your bot to that particular domain.
4) Check authentication in bot using sign in feature via card.

I hope above liners will help you.
do let me know in case you need more help.


问:
How do I solve this segmentation fault : 11 error for the following code?
This is an algorithm in which I am trying to solve the 2-SAT problem using local search. However, I seem to be getting a segmentation fault : 11. The problem starts from the main code after for ( int i =0; i<upper_limit; i++).

How can I fix this error?

```<code>#include <fstream>
#include <iostream>
#include<math.h>
#include <map>
#include <vector>
#include <set>
#include <random>
#include <math.h>

using namespace std;

bool check_clause(short &logic,bool x1,bool x2)
{
    switch(logic)
        {
            case 0:
                return ( (not x1) or (not x2) );
            case 1:
                return ( (not x1) or x2 );
                break;
            case 2:
                return ( x1 or (not x2) );
                break;
            case 3:
                return( x1 or x2 );
                break;
        }
        return false;
}

int check_logic(vector<int> & elem)
{
    short logic=0;
    //Creating logic flag to construct teach clause Eg. x or !x2 = (10)(bin)= (2)(decimal)
    for(int j =1; j>=0;j--)
    {
        if (elem[j]>0)
        {
            logic+=pow(2,1-j);
        }
    }
    return logic;
}

vector <int> check_assignment(map <int,bool> &assignment,map <int, vector<int> > &data)
{   int count=0;
    vector <int> unsatisfied;
    for (auto elem: data)
    {   //Variables for both vertex indices for clause and the logic flag
        int first_vertex=abs(elem.second[0]);
        int second_vertex=abs(elem.second[1]);
        short logic=check_logic(elem.second);

        //Retrieving randomly generated boolean variables for first and second vertex of current clause
        bool x1 = assignment[first_vertex];
        bool x2 = assignment[second_vertex];
        bool answer=check_clause(logic,x1,x2);

        if (answer==false)
        {
            unsatisfied.push_back(count);
        }
        count+=1;

    }

    return unsatisfied;
}

bool isKeyInMap(int number, map <int,vector<int> > & dictionary)
{
    if (dictionary.find(number)==dictionary.end())
    {
        return false;
    }
    else
    {
        return true;
    }
}

int main()
{
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(0,1);
    map <int, vector<int> > data;
    map<int,vector<int> >::iterator it;
    vector<int> row(2,0);
    ifstream file_read("2sat1.txt");
    int a;
    int n;
    file_read>>n;
    cout<<n<<endl;
    map <int, vector<int> > positives;
    map <int, vector<int> > negatives;
    int count=0;

    while (file_read>>a)
    {
        row[0]=a;
        file_read>>a;
        row[1]=a;
        data[count].insert(data[count].end(),row.begin(),row.end());

        for (auto element: row)
        {
            if (element<0)
                {
                    negatives[ -element ].push_back(count);
                }
            else
            {
                positives[ element ].push_back(count);
            }

        }

        count++;
    }

    int n_rows=positives.size();
    int incl_count=0;

    vector <int> deletionList;
    set <int> inclset;
    // cout<<isKeyInMap(200001,positives)<<endl;

    for (int i =1; i<=n;i++)
    {
        bool pos_entry=isKeyInMap(i,positives);
        bool neg_entry=isKeyInMap(i,negatives);

        if ( pos_entry != neg_entry )
        {
            if (pos_entry==true)
            {
                deletionList.insert(deletionList.end(),positives[i].begin(),positives[i].end());
            }
            else
            {
                deletionList.insert(deletionList.end(),negatives[i].begin(),negatives[i].end());
            }
        }
        else if ((pos_entry==neg_entry) and (pos_entry==true))
        {

            inclset.insert(i);
        }

    }
    cout<<"Inclusion set size: "<<inclset.size()<<endl;
    int incl_size=inclset.size();

    set <int> deletionSet(deletionList.begin(),deletionList.end());
    cout<<"Set Size: "<<deletionSet.size()<<endl;
    // sort(deletionList.begin(),deletionList.end());

    for (auto i=deletionSet.rbegin(); i!=deletionSet.rend();++i)
    {

        for (auto item: data[*i])
        {
            cout<<item<<" ";
        }
        it=data.find(*i);
        if (it!=data.end())
        {
            data.erase(it);
        }
        else
        {
            cout<<"Not found!"<<endl;
        }

    }
    cout<<data.size()<<endl;

    map <int,bool> assignment;
    int upper_limit= (int) ceil ( log2(incl_size) );
    long local_iter_size= 2*pow(incl_size,2);

    for (auto elem: inclset)
    {
        assignment[elem]=(bool) dis(gen);
    }

    for ( int i =0; i<upper_limit; i++)
    {

        for (auto elem: inclset)
        {
            assignment[elem]= (bool) dis(gen);

        }

        for (auto elem: assignment)
        {
            cout<<elem.first<<":"<<elem.second<<endl;
        }
        cout<<"Size of assignment: "<<assignment.size()<<endl;

        for (int j=0; j<local_iter_size; j++)
        {
            cout<<"Okay "<<j<<endl;
            vector <int> unsatisfied;
            unsatisfied = check_assignment(assignment,data);

            if (unsatisfied.empty())
            {
                cout<<"Yay, we win!";
                return 0;
            }

            int pick_random= unsatisfied[rand()% unsatisfied.size()];
            vector <int> record= data[pick_random];
            short logic=check_logic(record);
            int first_vertex=abs(record[0]);
            int second_vertex=abs(record[1]);
            bool x1=assignment[first_vertex];
            bool x2= assignment[second_vertex];

            if (check_clause(logic,not x1,x2)==true)
            {
                assignment[first_vertex]
                = not x1;
            }
            else
            {
                assignment[second_vertex]=not x2;
            }
            cout<<"Number of unfulfilled clauses: "<<unsatisfied.size()<<endl;
        }

    }

}
</code>```

答:
```<code>if (answer==false)
        {
            unsatisfied.push_back(count);
        }
        count+=1;
</code>```

This clause found in check_clause function has an error. We are supposed to push the index of the key for the clause not satisfied i.e., unsatisfied.push_back(elem.first). Due to this error, the program tries to access indices outside the range of the vector unsatisfied.

Now, the code works fine.

Body:
This is an algorithm in which I am trying to solve the 2-SAT problem using local search. However, I seem to be getting a segmentation fault : 11. The problem starts from the main code after for ( int i =0; i<upper_limit; i++).

How can I fix this error?

#include <fstream>
#include <iostream>
#include<math.h>
#include <map>
#include <vector>
#include <set>
#include <random>
#include <math.h>

using namespace std;

bool check_clause(short &logic,bool x1,bool x2)
{
    switch(logic)
        {
            case 0:
                return ( (not x1) or (not x2) );
            case 1:
                return ( (not x1) or x2 );
                break;
            case 2:
                return ( x1 or (not x2) );
                break;
            case 3:
                return( x1 or x2 );
                break;
        }
        return false;
}

int check_logic(vector<int> & elem)
{
    short logic=0;
    //Creating logic flag to construct teach clause Eg. x or !x2 = (10)(bin)= (2)(decimal)
    for(int j =1; j>=0;j--)
    {
        if (elem[j]>0)
        {
            logic+=pow(2,1-j);
        }
    }
    return logic;
}

vector <int> check_assignment(map <int,bool> &assignment,map <int, vector<int> > &data)
{   int count=0;
    vector <int> unsatisfied;
    for (auto elem: data)
    {   //Variables for both vertex indices for clause and the logic flag
        int first_vertex=abs(elem.second[0]);
        int second_vertex=abs(elem.second[1]);
        short logic=check_logic(elem.second);

        //Retrieving randomly generated boolean variables for first and second vertex of current clause
        bool x1 = assignment[first_vertex];
        bool x2 = assignment[second_vertex];
        bool answer=check_clause(logic,x1,x2);

        if (answer==false)
        {
            unsatisfied.push_back(count);
        }
        count+=1;

    }

    return unsatisfied;
}

bool isKeyInMap(int number, map <int,vector<int> > & dictionary)
{
    if (dictionary.find(number)==dictionary.end())
    {
        return false;
    }
    else
    {
        return true;
    }
}

int main()
{
    random_device rd;
    mt19937 gen(rd());
    uniform_int_distribution<> dis(0,1);
    map <int, vector<int> > data;
    map<int,vector<int> >::iterator it;
    vector<int> row(2,0);
    ifstream file_read("2sat1.txt");
    int a;
    int n;
    file_read>>n;
    cout<<n<<endl;
    map <int, vector<int> > positives;
    map <int, vector<int> > negatives;
    int count=0;

    while (file_read>>a)
    {
        row[0]=a;
        file_read>>a;
        row[1]=a;
        data[count].insert(data[count].end(),row.begin(),row.end());

        for (auto element: row)
        {
            if (element<0)
                {
                    negatives[ -element ].push_back(count);
                }
            else
            {
                positives[ element ].push_back(count);
            }

        }

        count++;
    }

    int n_rows=positives.size();
    int incl_count=0;

    vector <int> deletionList;
    set <int> inclset;
    // cout<<isKeyInMap(200001,positives)<<endl;

    for (int i =1; i<=n;i++)
    {
        bool pos_entry=isKeyInMap(i,positives);
        bool neg_entry=isKeyInMap(i,negatives);

        if ( pos_entry != neg_entry )
        {
            if (pos_entry==true)
            {
                deletionList.insert(deletionList.end(),positives[i].begin(),positives[i].end());
            }
            else
            {
                deletionList.insert(deletionList.end(),negatives[i].begin(),negatives[i].end());
            }
        }
        else if ((pos_entry==neg_entry) and (pos_entry==true))
        {

            inclset.insert(i);
        }

    }
    cout<<"Inclusion set size: "<<inclset.size()<<endl;
    int incl_size=inclset.size();

    set <int> deletionSet(deletionList.begin(),deletionList.end());
    cout<<"Set Size: "<<deletionSet.size()<<endl;
    // sort(deletionList.begin(),deletionList.end());

    for (auto i=deletionSet.rbegin(); i!=deletionSet.rend();++i)
    {

        for (auto item: data[*i])
        {
            cout<<item<<" ";
        }
        it=data.find(*i);
        if (it!=data.end())
        {
            data.erase(it);
        }
        else
        {
            cout<<"Not found!"<<endl;
        }

    }
    cout<<data.size()<<endl;

    map <int,bool> assignment;
    int upper_limit= (int) ceil ( log2(incl_size) );
    long local_iter_size= 2*pow(incl_size,2);

    for (auto elem: inclset)
    {
        assignment[elem]=(bool) dis(gen);
    }

    for ( int i =0; i<upper_limit; i++)
    {

        for (auto elem: inclset)
        {
            assignment[elem]= (bool) dis(gen);

        }

        for (auto elem: assignment)
        {
            cout<<elem.first<<":"<<elem.second<<endl;
        }
        cout<<"Size of assignment: "<<assignment.size()<<endl;

        for (int j=0; j<local_iter_size; j++)
        {
            cout<<"Okay "<<j<<endl;
            vector <int> unsatisfied;
            unsatisfied = check_assignment(assignment,data);

            if (unsatisfied.empty())
            {
                cout<<"Yay, we win!";
                return 0;
            }

            int pick_random= unsatisfied[rand()% unsatisfied.size()];
            vector <int> record= data[pick_random];
            short logic=check_logic(record);
            int first_vertex=abs(record[0]);
            int second_vertex=abs(record[1]);
            bool x1=assignment[first_vertex];
            bool x2= assignment[second_vertex];

            if (check_clause(logic,not x1,x2)==true)
            {
                assignment[first_vertex]
                = not x1;
            }
            else
            {
                assignment[second_vertex]=not x2;
            }
            cout<<"Number of unfulfilled clauses: "<<unsatisfied.size()<<endl;
        }

    }

}

Body:
if (answer==false)
        {
            unsatisfied.push_back(count);
        }
        count+=1;

This clause found in check_clause function has an error. We are supposed to push the index of the key for the clause not satisfied i.e., unsatisfied.push_back(elem.first). Due to this error, the program tries to access indices outside the range of the vector unsatisfied.

Now, the code works fine.


问:
How to use own method on ArrayList in Java?
I have a problem with a task I have to do. I need to create class Company and write few methods (such as hire, fire, etc.) for Employee class objects.
Those are my classes and methods:

```<code>public class Company{
    ArrayList <Employee> alist= new ArrayList<Employee>();

    public void hire(Employee e) {
        int i=0;
        boolean k=false;
        while(i<alist.size()) {
            if (e.getLastName().equals(alist.get(i).getLastName())) {
                k=true;
                i++;
            }
        }
        if (k==false) alist.add(e);
        else System.out.print("Employee already exists");
    }
}

public class Employee{
    protected String lastname; //protected for subclasses
    protected double jobposition;
    public Employee(String lastname,double jobposition) {
        this.lastname=lastname;
        this.jobposition=jobposition;
    }
    public String getLastName() {
        return lastname;
}
</code>```

And subclass which extends Employee:

```<code>public class OfficeWorker extends Employee {
    float pay, bonus;
    public OfficeWorker(String lastname,double jobposition,float pay,float bonus) {
        super(lastname,jobposition);
        this.pay=pay;
        this.bonus=bonus;
    }
}
</code>```

I wanted to use ArrayList to do this, but it crashes in main class and I get message "The method hire(Employee) is undefined for the type ArrayList":

```<code>public static void main(String[]args) {

    ArrayList <Employee> list = new ArrayList <Employee>();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    list.hire(e1);

}
</code>```

Why can't I do this like that?

答:
hire() method is defined as part of Company Class.
it should be as below.</p>

```<code>Company xyz = new Company();
xyz.hire(e1);
</code>```

Body:
I have a problem with a task I have to do. I need to create class Company and write few methods (such as hire, fire, etc.) for Employee class objects.
Those are my classes and methods:

public class Company{
    ArrayList <Employee> alist= new ArrayList<Employee>();

    public void hire(Employee e) {
        int i=0;
        boolean k=false;
        while(i<alist.size()) {
            if (e.getLastName().equals(alist.get(i).getLastName())) {
                k=true;
                i++;
            }
        }
        if (k==false) alist.add(e);
        else System.out.print("Employee already exists");
    }
}

public class Employee{
    protected String lastname; //protected for subclasses
    protected double jobposition;
    public Employee(String lastname,double jobposition) {
        this.lastname=lastname;
        this.jobposition=jobposition;
    }
    public String getLastName() {
        return lastname;
}

And subclass which extends Employee:

public class OfficeWorker extends Employee {
    float pay, bonus;
    public OfficeWorker(String lastname,double jobposition,float pay,float bonus) {
        super(lastname,jobposition);
        this.pay=pay;
        this.bonus=bonus;
    }
}

I wanted to use ArrayList to do this, but it crashes in main class and I get message "The method hire(Employee) is undefined for the type ArrayList":

public static void main(String[]args) {

    ArrayList <Employee> list = new ArrayList <Employee>();
    Employee e1 = new OfficeWorker("Smith",0.5,2000,50);
    list.hire(e1);

}

Why can't I do this like that?

Body:
hire() method is defined as part of Company Class.
it should be as below.

Company xyz = new Company();
xyz.hire(e1);


问:
How to add margin between EditText and Soft Keyboard?
I want to add 10dp margin between EditText and Soft Keyboard.

Here is my XML:

```<code><RelativeLayout
    android:id="@+id/BottomLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/bottom_glass" >

    <EditText
        android:id="@+id/message"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/grey"
        android:ems="10"
        android:layout_marginBottom="10dp"
        android:hint="Enter Message"
        android:textColor="#ffffff" >

    </EditText>

    <ImageButton
        android:id="@+id/sendMessageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/message"
        android:background="@android:color/transparent"
        android:src="@drawable/sendselector" />

    <ImageButton
        android:id="@+id/imageButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginRight="20dp"
        android:layout_toLeftOf="@+id/message"
        android:background="@android:color/transparent"
        android:src="@drawable/sendmediaselector" />

</RelativeLayout>
</code>```

Here is my onCreate() :

```<code>    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    messageText.setOnTouchListener(new OnTouchListener(){

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                            ((Swipe)getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED);
                    return false;
                }});
</code>```

I am using viewpager and full screen theme. The following EditText is in my 3rd fragment.

I've used android:windowSoftInputMode="adjustResize|adjustPan" and android:windowSoftInputMode="adjustResize", but nothing happened.

答:
Try to add your RelativeLayout in ScrollView, and then add code below:

```<code>editTextField.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // TODO Auto-generated method stub
        if (hasFocus)
             scrollView.scrollBy(0, 150);

    });
</code>```

Body:
I want to add 10dp margin between EditText and Soft Keyboard.

Here is my XML:

<RelativeLayout
    android:id="@+id/BottomLayout"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:background="@drawable/bottom_glass" >

    <EditText
        android:id="@+id/message"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:background="@drawable/grey"
        android:ems="10"
        android:layout_marginBottom="10dp"
        android:hint="Enter Message"
        android:textColor="#ffffff" >

    </EditText>

    <ImageButton
        android:id="@+id/sendMessageButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginLeft="20dp"
        android:layout_toRightOf="@+id/message"
        android:background="@android:color/transparent"
        android:src="@drawable/sendselector" />

    <ImageButton
        android:id="@+id/imageButton2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_marginRight="20dp"
        android:layout_toLeftOf="@+id/message"
        android:background="@android:color/transparent"
        android:src="@drawable/sendmediaselector" />

</RelativeLayout>

Here is my onCreate() :

    getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
    messageText.setOnTouchListener(new OnTouchListener(){

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                            ((Swipe)getActivity()).getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_UNSPECIFIED);
                    return false;
                }});

I am using viewpager and full screen theme. The following EditText is in my 3rd fragment.

I've used android:windowSoftInputMode="adjustResize|adjustPan" and android:windowSoftInputMode="adjustResize", but nothing happened.

Body:
Try to add your RelativeLayout in ScrollView, and then add code below:

editTextField.setOnFocusChangeListener(new OnFocusChangeListener() {

    @Override
    public void onFocusChange(View v, boolean hasFocus) {
        // TODO Auto-generated method stub
        if (hasFocus)
             scrollView.scrollBy(0, 150);

    });


问:
Using document.getElementsByClassName in Testcafe
I have a menu that always has the same structure, but the IDs can change from one installation to another. the only thing that stays the same is the heading (in my case "Plugins"). I call the document.getElementsByClassName function with a Selector inside my test:

```<code>var slides = Selector(() =>{
    return document.getElementsByClassName("c-p-header-text");
});
</code>```

Every heading of an menu element has the c-p-header-text class. Here is what a menu heading element looks like:

```<code><div id="ext-comp-1002" class="c-p c-tree c-p-collapsed" style="width: auto;">
     <div class="c-p-header c-unselectable c-accordion-hd" id="ext-gen135" style="cursor: pointer;">
        <div class="c-tool c-tool-toggle" id="ext-gen140"> </div>
        <img src="/backEnd/images/s.gif" class="c-p-inline-icon order"><span class="c-p-header-text" id="ext-gen150">Plugins</span>
     </div>
</code>```

It would be easy to use await t.click("#ext-gen150") but it is not safe that it is always this id.

here is what i tried:

```<code>await t
    .click('#sites__db');
var slides = Selector(() =>{
    return document.getElementsByClassName("c-p-header-text");
});
console.log("[DEBUG]" + slides);
console.log("[DEBUG] found " + slides.length + " elements");
for(var i = 0; i < slides.length; i++)
{
    var txtOfCurrElem = slides.item(i).innerText;
    console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}
</code>```

Running this test give me the following output:

```<code>[DEBUG]function __$$clientFunction$$() {
        var testRun = builder.getBoundTestRun() || _testRunTracker2.default.resolveContextTestRun();
        var callsite = (0, _getCallsite.getCallsiteForMethod)(builder.callsiteNames.execution);
        var args = [];

        // OPTIMIZATION: don't leak `arguments` object.
        for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
        }return builder._executeCommand(args, testRun, callsite);
    }
[DEBUG] found 0 elements
</code>```

The plan is to find the element (with the heading "Plugins") and then click on it when the test continuous.

答:
You don't have to use document.getElementsByClassName in this case. You can just use CSS class selector instead:

```<code>var slides = Selector('.c-p-header-text');
</code>```

You should use the count property when dealing with an array of Selectors. docs. Also, element properties, like exists, count, and DOM node state properties are Promisified, so when you use them not in t.expect, you should use the await keyword:

```<code>var count = await slides.length;

console.log("[DEBUG] found " + count + " elements");

for(var i = 0; i < count; i++)
{
    var txtOfCurrElem = await slides.nth(i).innerText;
    console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}
</code>```

Body:
I have a menu that always has the same structure, but the IDs can change from one installation to another. the only thing that stays the same is the heading (in my case "Plugins"). I call the document.getElementsByClassName function with a Selector inside my test:

var slides = Selector(() =>{
    return document.getElementsByClassName("c-p-header-text");
});

Every heading of an menu element has the c-p-header-text class. Here is what a menu heading element looks like:

        Plugins

It would be easy to use await t.click("#ext-gen150") but it is not safe that it is always this id.

here is what i tried:

await t
    .click('#sites__db');
var slides = Selector(() =>{
    return document.getElementsByClassName("c-p-header-text");
});
console.log("[DEBUG]" + slides);
console.log("[DEBUG] found " + slides.length + " elements");
for(var i = 0; i < slides.length; i++)
{
    var txtOfCurrElem = slides.item(i).innerText;
    console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}

Running this test give me the following output:

[DEBUG]function __$$clientFunction$$() {
        var testRun = builder.getBoundTestRun() || _testRunTracker2.default.resolveContextTestRun();
        var callsite = (0, _getCallsite.getCallsiteForMethod)(builder.callsiteNames.execution);
        var args = [];

        // OPTIMIZATION: don't leak `arguments` object.
        for (var i = 0; i < arguments.length; i++) {
            args.push(arguments[i]);
        }return builder._executeCommand(args, testRun, callsite);
    }
[DEBUG] found 0 elements

The plan is to find the element (with the heading "Plugins") and then click on it when the test continuous.

Body:
You don't have to use document.getElementsByClassName in this case. You can just use CSS class selector instead:

var slides = Selector('.c-p-header-text');

You should use the count property when dealing with an array of Selectors. docs. Also, element properties, like exists, count, and DOM node state properties are Promisified, so when you use them not in t.expect, you should use the await keyword:

var count = await slides.length;

console.log("[DEBUG] found " + count + " elements");

for(var i = 0; i < count; i++)
{
    var txtOfCurrElem = await slides.nth(i).innerText;
    console.log("[DEBUG "+ i +"] Text: " + txtOfCurrElem);
}


问:
How to Implement SSO on existing tomcat web application
I have a tomcat 7 setup with oldApp.war and newApp.war deployed on it. Both the applications share the same login credentials for users on the database.

I can access the apps using https://localhost/oldApp and https:localhost/newApp respectively.

My oldApp is a Spring MVC java application and when the user is logged into the oldApp I want to have a link which will take the user into the newApp without asking for the login credentials.

I want to know how to implement SSO to do this. I preferably don't want to run any external service to handle this.

Thanks in advance.

答:
I have managed this with the Tomcat's SSO Valve:

Put SSO Valve within Host (localhost) element of server.xml file:

<Host appBase="webapps" autoDeploy="true" name="localhost" unpackWARs="true"> <Valve className="org.apache.catalina.authenticator.SingleSignOn" /> </Host>

Add users and roles (eg. in tomcat_users.xml):

<user username="user1" password="user1" roles="employee"/>

In web-app element of your app's web.xml file, add security constraints:

<security-constraint> <web-resource-collection> <web-resource-name>App name</web-resource-name> <url-pattern>/*</url-pattern> </web-resource-collection> <auth-constraint> <role-name>employee</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>FORM</auth-method> <realm-name>file</realm-name> <form-login-config> <form-login-page>/login.jsp</form-login-page> <form-error-page>/error.jsp</form-error-page> </form-login-config> </login-config> <security-role> <role-name>employee</role-name> </security-role>

That's it. Now, log in to the one of your apps, and you should be logged in to other apps.

Of course, you should not use a plain text password in the production, this is just a quick example. You shoud consider Digest authentication, as well as configuring SSL on Tomcat.

I hope this will help someone!

P.S. if you store users in the SQL database, please check my comment below this answer.


问:
Split column into two new columns in Pandas
I have a dataframe with 4 columns with value like this:

```<code>value_1
over 1 - 42 -> take this ; over 3 - 4
over 3 - 26 -> take this ; over 3 - 45
over 5 - 25 -> take this ; over 2 - 80
</code>```

And I need to make two column from each of them by splitting by ';'.
And when I try this:

```<code>s = df['value_1'].apply(lambda x: x.split(';'))
df['value_left'] = s.apply(lambda x: x[0])
df['value_right'] = s.apply(lambda x: x[1])
</code>```

Or this:

```<code>f['new_value1'] = df['value_1']
df['value_1_right'] = None
df['value_1_right'].update(df.new_band_bandw_1.apply(lambda x: x.str.split(';')[1]
                      if len(x.str.split()) == 2 else None))
</code>```

I got the same error: List index out of range. What is the problem, is it possible that the values are in some kind of list?

Any kind of solution is welcomed. Thanks

答:
Another way with string partition i.e

```<code>df[['val1','val2']] = df[0].str.partition(';').iloc[:,0::2]

                                     0                       val1          val2
0    over 1 - 42 -> take this ; over 3 - 4  over 1 - 42 -> take this     over 3 - 4
1   over 3 - 26 -> take this ; over 3 - 45  over 3 - 26 -> take this     over 3 - 45
2  over 5 - 25 -> take this ; over; 2 - 80  over 5 - 25 -> take this     over; 2 - 80
</code>```

Body:
I have a dataframe with 4 columns with value like this:

value_1
over 1 - 42 -> take this ; over 3 - 4
over 3 - 26 -> take this ; over 3 - 45
over 5 - 25 -> take this ; over 2 - 80

And I need to make two column from each of them by splitting by ';'.
And when I try this:

s = df['value_1'].apply(lambda x: x.split(';'))
df['value_left'] = s.apply(lambda x: x[0])
df['value_right'] = s.apply(lambda x: x[1])

Or this:

f['new_value1'] = df['value_1']
df['value_1_right'] = None
df['value_1_right'].update(df.new_band_bandw_1.apply(lambda x: x.str.split(';')[1]
                      if len(x.str.split()) == 2 else None))

I got the same error: List index out of range. What is the problem, is it possible that the values are in some kind of list?

Any kind of solution is welcomed. Thanks

Body:
Another way with string partition i.e

df[['val1','val2']] = df[0].str.partition(';').iloc[:,0::2]

                                     0                       val1          val2
0    over 1 - 42 -> take this ; over 3 - 4  over 1 - 42 -> take this     over 3 - 4
1   over 3 - 26 -> take this ; over 3 - 45  over 3 - 26 -> take this     over 3 - 45
2  over 5 - 25 -> take this ; over; 2 - 80  over 5 - 25 -> take this     over; 2 - 80


问:
Event tracking + new window
I spent half a day on this and i still cant figure out how to track outbound links i open i a new window!

i can track the event

i can open the link in a new window

Problem: i'm opening 2 new windows

my code:

```<code> <script>
  var trackOutboundLink = function(url) {
  ga('send', 'event', 'outbound', 'click', url, {
  'transport': 'beacon',
  'hitCallback': function(){window.open(url, '_blank');}
  });
  }
 </script>

 <a href="http://www.example.com" target="_blank" onclick="trackOutboundLink('http://www.example.com');">Check out example.com</a>
</code>```

答:
Quite an old question, but still might help someone with my solution.

```<code>function trackOutboundLink(url) {
    var params = {};
    params.hitCallback = function () {
        window.open(url);
    }
    ga("send", "event", "outbound", "click", url, params);
    return false;
}
</code>```

It works on mobile and no 2 new windows on desktop.

Usage:

```<code><a href="http://www.example.url" target="_blank" onclick="trackOutboundLink('http://www.example.url');">
</code>```

Title: Event tracking + new window

Body:
I spent half a day on this and i still cant figure out how to track outbound links i open i a new window!

i can track the event

i can open the link in a new window

Problem: i'm opening 2 new windows

my code:

 Check out example.com

Body:
Quite an old question, but still might help someone with my solution.

function trackOutboundLink(url) {
    var params = {};
    params.hitCallback = function () {
        window.open(url);
    }
    ga("send", "event", "outbound", "click", url, params);
    return false;
}

It works on mobile and no 2 new windows on desktop.

Usage:

<a href="http://www.example.url" target="_blank" onclick="trackOutboundLink('http://www.example.url');">


问:
Searching pip in python(xy)
Today I fully installed Python(xy) on my machine. Now I'm still lacking the package sphinx-intl, so that I was trying to install it with pip sphinx-intl.

Unfortunately, I was not able to find the pip.exe in the Python27 directory.

Where do I have to search for this program?

答:
You many need to install pip. Find the instructions here -

https://pip.pypa.io/en/stable/installing/

Title: Searching pip in python(xy)


问:
Django 1.10 Postgres JSONField extract specific keys
I have a Postgres based JSONField in my model.

```<code>class MyModel(models.Model):
    data = JSONField(default=dict)
</code>```

The JSON sample is like:

```<code>{
    'key1': 'val1',
    'key2': 'val2'
}
</code>```

I have multiple objects of the model, let's say ~50.

I am trying to query for only the key1 inside data and want to get a list of all the distinct values of the key1.

How can I do that? Please note I am using Django 1.10.

答:
You can use KeyTransform for that</p>

```<code>MyModel.objects.annotate(key1=KeyTransform('key1', 'data')).distinct('key1').values_list('key1', flat=True)
</code>```

Body:
I have a Postgres based JSONField in my model.

class MyModel(models.Model):
    data = JSONField(default=dict)

The JSON sample is like:

{
    'key1': 'val1',
    'key2': 'val2'
}

I have multiple objects of the model, let's say ~50.

I am trying to query for only the key1 inside data and want to get a list of all the distinct values of the key1.

How can I do that? Please note I am using Django 1.10.

Body:
You can use KeyTransform for that

MyModel.objects.annotate(key1=KeyTransform('key1', 'data')).distinct('key1').values_list('key1', flat=True)


问:
How avoid having double loop?
From healthkit, I will receive some datas, for example steps data.

I save in my server this datas. Il have then an array of datas:

1.- startDate, endDate, value

2.- startDate, endDate, value

etc

It can be very lot of values in my server.

Then I get the values in the Healthkit. I have lot of values. Values who are in the server and new values.

I want to upload to the server only the new values.

I do so:

```<code>for each value in my server {
    for each value in healthkit{
        if(startDate, endDate and value are not equal to the value in the server){
            then save the value in the server
        }
    }
}
</code>```

The algo will work, but it's very very slow. I can have lot of values in the two systems. Most of them the same in the two places.

Have you an idea how to do better?

I cannot save a flag in the healthKit.

I'm using ionic with angular 4 and typescript.

答:
I think I need a bit more context to understand the problem. By "new" values, are you including entries that have been modified, or just new entries that have been added?

If you only need the new values, and they are being added to the end of the array on the client side, then you can just take them from the end of the array.

```<code>const new_count = healthkit.length - myserver.length, // number of new entries
index_start = healthkit.length - new_count, // index in healthkit array where new entries start
new_values = healthkit.slice(index_start); // new array containing only new entries

addNewValues(new_values);
</code>```

Now you have the new values in a separate array, and you can update them to the server.

If it is the case that you do need to update values that have changed, you can iterate over both arrays (only once, and at the same time) and find the differences. I am going to assume that the entries are in the same index for both arrays. I'm also assuming the "value" key is the only one you want to compare. You can do the following to find the values that have been modified.

```<code>const modified_values = [];
myserver.forEach(function(entry, i) { // iterate over server array
    let healthkit_entry = healthkit[i]; // get healthkit entry with same index
    if(entry.value !== healthkit_entry.value) { // see if value has changed
        modified_values.push(healthkit_entry); // if changed, add to modified array
    }
});

updateModifiedValues(modified_values);
</code>```

Now the modified_values array has all of the modified entries from the healthkit array.

Title: How avoid having double loop?

Body:
From healthkit, I will receive some datas, for example steps data.

I save in my server this datas. Il have then an array of datas:

1.- startDate, endDate, value

2.- startDate, endDate, value

etc

It can be very lot of values in my server.

Then I get the values in the Healthkit. I have lot of values. Values who are in the server and new values.

I want to upload to the server only the new values.

I do so:

for each value in my server {
    for each value in healthkit{
        if(startDate, endDate and value are not equal to the value in the server){
            then save the value in the server
        }
    }
}

The algo will work, but it's very very slow. I can have lot of values in the two systems. Most of them the same in the two places.

Have you an idea how to do better?

I cannot save a flag in the healthKit.

I'm using ionic with angular 4 and typescript.

Body:
I think I need a bit more context to understand the problem. By "new" values, are you including entries that have been modified, or just new entries that have been added?

If you only need the new values, and they are being added to the end of the array on the client side, then you can just take them from the end of the array.

const new_count = healthkit.length - myserver.length, // number of new entries
index_start = healthkit.length - new_count, // index in healthkit array where new entries start
new_values = healthkit.slice(index_start); // new array containing only new entries

addNewValues(new_values);

Now you have the new values in a separate array, and you can update them to the server.

If it is the case that you do need to update values that have changed, you can iterate over both arrays (only once, and at the same time) and find the differences. I am going to assume that the entries are in the same index for both arrays. I'm also assuming the "value" key is the only one you want to compare. You can do the following to find the values that have been modified.

const modified_values = [];
myserver.forEach(function(entry, i) { // iterate over server array
    let healthkit_entry = healthkit[i]; // get healthkit entry with same index
    if(entry.value !== healthkit_entry.value) { // see if value has changed
        modified_values.push(healthkit_entry); // if changed, add to modified array
    }
});

updateModifiedValues(modified_values);

Now the modified_values array has all of the modified entries from the healthkit array.