问:
C# - Passing different type of objects through the same method
Original Question

So I have this 3 objects...

```<code>public class obj1
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class obj2
{
  public int AccNum { get; set; }
  public string Name { get; set; }
}

public class obj3
{
  public string Email { get; set; }
  public string Phone { get; set; }
}
</code>```

... and one method that is supposed to receive one of them, after evaluating the object type the program should decide which function to call.

I've tried with generics but it doesn't work as I expected. So far this is what I've got...

```<code>    public class NotificationHelper: INotificationHelper
    {

        public bool SendNotification<TNotInfo>(TNotInfo obj) where TNotInfo : class
        {
            if (contract.GetType() == typeof (obj1))
            {
                var sender = new SendSMS();
                return sender.Send(obj);
            }
            if (contract.GetType() == typeof(obj2))
            {
                var sender = new SendPush();
                return sender.Send(obj);
            }
            else
            {
                var sender = new SendEmail();
                return sender.Send(obj);
            }
        }
    }
</code>```

but I get the error "Cannot convert from TNotInfo to Models.obj1". Is there any way to overcome this issue? Or I have to change my logic?

Appreciate any help, thanks in advance.

*Edit

```<code>using System;

namespace EmailNotifications
{

    public interface IEmailNotification
    {
        void SendEmailNotification();
    }

    public class EmailNotificationA : IEmailNotification
    {

        public void SendEmailNotification(Contract1 a)
        {
            Console.WriteLine($"Sending EmailNotificationA ({a})");
        }
    }

    public class EmailNotificationB : IEmailNotification
    {
        public void SendEmailNotification(Contract2 b)
        {
            Console.WriteLine($"Sending EmailNotificationB ({b})");
        }
    }

    public class EmailNotificationC : IEmailNotification
    {

        public void SendEmailNotification(Contrac3 c)
        {
            Console.WriteLine($"Sending EmailNotificationC ({c})");
        }
    }

    public class EmailNotificationService
    {
        private readonly IEmailNotification _emailNotification;

        public EmailNotificationService(IEmailNotification emailNotification)
        {
            this._emailNotification = emailNotification;
        }

        public void ServiceHelper()
        {
            _emailNotification.SendEmailNotification();
        }
    }
}
</code>```

Above solution is what I was trying to achieve, applying strategy design pattern. But I couldn't manage to make my interface method receive different objects, this is required because each notification has is own implementation. As visible at the none working example above, I have 3 different implementation of the same method all of them receiving different objects. Any idea of how to make this logic work?

答:
Another approach will be overload methods.

Because you have different logic based on the given type. And types have nothing in common (interface/abstract class).

```<code>public class NotificationHelper
{
    public bool SendNotification(obj1 obj)
    {
        var sender = new SendSMS();
        return sender.Send(obj);
    }

    public bool SendNotification(obj2 obj)
    {
        var sender = new SendPush();
        return sender.Send(obj);
    }

    public bool SendNotification(obj3 obj)
    {
        var sender = new SendEmail();
        return sender.Send(obj);
    }
}
</code>```

Then using will be clear enough

```<code>var someObject = GetObjectFromSomeWhere();
var isSuccessful = SendNotification(someObject);
</code>```

Body:
Original Question

So I have this 3 objects...

public class obj1
{
  public int Id { get; set; }
  public string Name { get; set; }
}

public class obj2
{
  public int AccNum { get; set; }
  public string Name { get; set; }
}

public class obj3
{
  public string Email { get; set; }
  public string Phone { get; set; }
}

... and one method that is supposed to receive one of them, after evaluating the object type the program should decide which function to call.

I've tried with generics but it doesn't work as I expected. So far this is what I've got...

    public class NotificationHelper: INotificationHelper
    {

        public bool SendNotification<TNotInfo>(TNotInfo obj) where TNotInfo : class
        {
            if (contract.GetType() == typeof (obj1))
            {
                var sender = new SendSMS();
                return sender.Send(obj);
            }
            if (contract.GetType() == typeof(obj2))
            {
                var sender = new SendPush();
                return sender.Send(obj);
            }
            else
            {
                var sender = new SendEmail();
                return sender.Send(obj);
            }
        }
    }

but I get the error "Cannot convert from TNotInfo to Models.obj1". Is there any way to overcome this issue? Or I have to change my logic?

Appreciate any help, thanks in advance.

*Edit

using System;

namespace EmailNotifications
{

    public interface IEmailNotification
    {
        void SendEmailNotification();
    }

    public class EmailNotificationA : IEmailNotification
    {

        public void SendEmailNotification(Contract1 a)
        {
            Console.WriteLine($"Sending EmailNotificationA ({a})");
        }
    }

    public class EmailNotificationB : IEmailNotification
    {
        public void SendEmailNotification(Contract2 b)
        {
            Console.WriteLine($"Sending EmailNotificationB ({b})");
        }
    }

    public class EmailNotificationC : IEmailNotification
    {

        public void SendEmailNotification(Contrac3 c)
        {
            Console.WriteLine($"Sending EmailNotificationC ({c})");
        }
    }

    public class EmailNotificationService
    {
        private readonly IEmailNotification _emailNotification;

        public EmailNotificationService(IEmailNotification emailNotification)
        {
            this._emailNotification = emailNotification;
        }

        public void ServiceHelper()
        {
            _emailNotification.SendEmailNotification();
        }
    }
}

Above solution is what I was trying to achieve, applying strategy design pattern. But I couldn't manage to make my interface method receive different objects, this is required because each notification has is own implementation. As visible at the none working example above, I have 3 different implementation of the same method all of them receiving different objects. Any idea of how to make this logic work?

Body:
Another approach will be overload methods.

Because you have different logic based on the given type. And types have nothing in common (interface/abstract class).

public class NotificationHelper
{
    public bool SendNotification(obj1 obj)
    {
        var sender = new SendSMS();
        return sender.Send(obj);
    }

    public bool SendNotification(obj2 obj)
    {
        var sender = new SendPush();
        return sender.Send(obj);
    }

    public bool SendNotification(obj3 obj)
    {
        var sender = new SendEmail();
        return sender.Send(obj);
    }
}

Then using will be clear enough

var someObject = GetObjectFromSomeWhere();
var isSuccessful = SendNotification(someObject);


来源: stackexchange

问:
Finder file icon badging (icon overlay) on Mac OS X >= 10.6
I'm searching for a solution to do File icon overlays (icon badging) (like Dropbox does it on mac) with cocoa on Mac.

Does anyone knows a way to do this?

I've searched the Xcode docs and looked into scpplugins source code which is kind of old carbon code.

答:
You can use the following two methods to have icon overlay over the folders/files.

You can use -setIcon:forFile:options: method on NSWorkspace if you want to change the icon of a file or folder in Mac OS X.

However after you apply icon overlay using this method, overlay exits even though you moved that file/folder outside. This may not be the exact solution.

Instead use the Finder Sync Extension target (File - New - Target - Finder Sync Extension) inside your app.

Once you created the extension, your application doesn't have direct communication with this target. In order to activate, use AppleScript command (I don't think there is a better alternative for this.)

To activate

```<code>NSString *pluginPath = [[[NSBundle mainBundle] builtInPlugInsPath] stringByAppendingPathComponent:@"yourextension.appex"];

NSString *pluginkitString = [NSString stringWithFormat:@"pluginkit -e use -a \"%@\"", pluginPath];
system([pluginkitString cStringUsingEncoding:NSUTF8StringEncoding]);
</code>```

Once target activated, there are couple of ways were our application can communicate with that extension. Few of them are:

Using NSDistributedNotificationCenter. This class provides a way to send notifications to objects in other tasks(like the extension here).

Other way is to use:

```<code>[[NSUserDefaults alloc] initWithSuiteName:@"teamid.com.company.test"];
</code>```

Both your application and the target should have common group identifier(i.e "teamid.com.company.test").

For this enable "App Groups" under Target - Capabilities - App Groups and give the identifier like the above (i.e"teamid.com.company.test") were teamid is the id that you will get it from your apple developer portal. Do the same steps for your Extension target as well.

Before to conclude, be sure that extension is activated or not. To check that go to System Preference - Extensions - Your App Finder.
This is the global point were user can enable/disable icon overlay for your application.

ContentLicense: CC BY-SA 4.0

Body:
You can use the following two methods to have icon overlay over the folders/files.

You can use -setIcon:forFile:options: method on NSWorkspace if you want to change the icon of a file or folder in Mac OS X.

However after you apply icon overlay using this method, overlay exits even though you moved that file/folder outside. This may not be the exact solution.

Instead use the Finder Sync Extension target (File - New - Target - Finder Sync Extension) inside your app.

Once you created the extension, your application doesn't have direct communication with this target. In order to activate, use AppleScript command (I don't think there is a better alternative for this.)

To activate

NSString *pluginPath = [[[NSBundle mainBundle] builtInPlugInsPath] stringByAppendingPathComponent:@"yourextension.appex"];

NSString *pluginkitString = [NSString stringWithFormat:@"pluginkit -e use -a \"%@\"", pluginPath];
system([pluginkitString cStringUsingEncoding:NSUTF8StringEncoding]);

Once target activated, there are couple of ways were our application can communicate with that extension. Few of them are:

Using NSDistributedNotificationCenter. This class provides a way to send notifications to objects in other tasks(like the extension here).

Other way is to use:

[[NSUserDefaults alloc] initWithSuiteName:@"teamid.com.company.test"];

Both your application and the target should have common group identifier(i.e "teamid.com.company.test").

For this enable "App Groups" under Target - Capabilities - App Groups and give the identifier like the above (i.e"teamid.com.company.test") were teamid is the id that you will get it from your apple developer portal. Do the same steps for your Extension target as well.

Before to conclude, be sure that extension is activated or not. To check that go to System Preference - Extensions - Your App Finder.
This is the global point were user can enable/disable icon overlay for your application.


问:
NPM Module - How to leverage the package.json file?
I'm writing a NPM module for a cli-based tool. After someone installs the package, I need to read their package.json file. I know how to read the file in syntax. My question is, how can I consistenly retrieve the package.json file and should I use relative or absolute paths.

So, after installing, my code would reside somewhere inside the node_modules folder:

```<code>package.json // I need to require this file
node_modules/
  ↳ my-package/
    ↳ dist/
      ↳ my-package.js // the actual file running the code
</code>```

Any suggestions/best practices? Or is it just a matter of using the right filepath?

答:
Reading the package.json file is very easy, as you can simply require it:

```<code>var package = require('./path/to/package.json');
</code>```

Finding the right path is what's not so simple.

This is quite a common task and there is no simple way to achieve that with core modules but there are few modules on npm that can help you with that.

find-package-json:

Easily find package.json files that you're searching for. It spiders parent directories for package.json files and correctly reads the results. It follows an ES6 iterator design so it should be easy to implement.

parent-package-json:

Using parent-package-json, you can find the parent package.json, so the package.json of the module that uses your module.

find-and-read-package-json:

Find and read data from a package.json file.

See:

https://www.npmjs.com/package/find-package-json

https://www.npmjs.com/package/parent-package-json

https://www.npmjs.com/package/find-and-read-package-json

ContentLicense: CC BY-SA 3.0

Body:
I'm writing a NPM module for a cli-based tool. After someone installs the package, I need to read their package.json file. I know how to read the file in syntax. My question is, how can I consistenly retrieve the package.json file and should I use relative or absolute paths.

So, after installing, my code would reside somewhere inside the node_modules folder:

package.json // I need to require this file
node_modules/
  ↳ my-package/
    ↳ dist/
      ↳ my-package.js // the actual file running the code

Any suggestions/best practices? Or is it just a matter of using the right filepath?

Body:
Reading the package.json file is very easy, as you can simply require it:

var package = require('./path/to/package.json');

Finding the right path is what's not so simple.

This is quite a common task and there is no simple way to achieve that with core modules but there are few modules on npm that can help you with that.

find-package-json:

Easily find package.json files that you're searching for. It spiders parent directories for package.json files and correctly reads the results. It follows an ES6 iterator design so it should be easy to implement.

parent-package-json:

Using parent-package-json, you can find the parent package.json, so the package.json of the module that uses your module.

find-and-read-package-json:

Find and read data from a package.json file.

See:

https://www.npmjs.com/package/find-package-json

https://www.npmjs.com/package/parent-package-json

https://www.npmjs.com/package/find-and-read-package-json


问:
How to create a 100% memory spike with a bash command
Please let us know how to produce 100% memory usage in Linux.

I know how can we produce 100% CPU Spike but for my testing purpose i need to make 100% memory usage.

Please let me know is there any way to make 100% memory usage

Regards
Arun

答: Keep in mind that 100% memory usage is likely to create an unstable system. But you may get close by using the stress command with the -vm argument. </p>


问:
Move a child array to parent array and change parent/child name
I know probably this was asked before not sure if was in this form but I did tried some replay from what I found here about this and failed.

ok I have this array

```<code>Array
(
    [0] => Array
        (
            [Data3] => Array
                (
                    [id] => 5
                    [category] => Whiskey
                    [name] => Some name
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [Data3] => Array
                (
                    [id] => 4
                    [category] => Tequila
                    [name] => Something Red 75cl
                    [description] => description
                    [image] => sierratequilasilver100.jpg
                    [price] => 92.49
                )

            [ammount] => 2
            [Data_id] => 3
        )

    [2] => Array
        (
            [Data4] => Array
                (
                    [id] => 3
                    [category] => Whiskey
                    [name] => Some name Gold
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 4
        )

    [3] => Array
        (
            [Data4] => Array
                (
                    [id] => 5
                    [category] => Vodka
                    [name] => Something Blue 100 cl
                    [description] => description
                    [image] => Something.jpg
                    [price] => 32.44
                )

            [ammount] => 1
            [Data_id] => 4
        )

)
</code>```

What I would like to be the result is something like this:

```<code>Array
(
    [0] => Array
        (
            [id] => 5
            [category] => Whiskey
            [name] => Some name
            [description] => description
            [image] => asdf.jpg
            [price] => 83.99
            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [id] => 4
            [category] => Tequila
            [name] => Something Red 75cl
            [description] => description
            [image] => sierratequilasilver100.jpg
            [price] => 92.49
            [ammount] => 2
            [Data_id] => 3
        )
    [2] => Array
        (
            [id] => 3
            [category] => Whiskey
            [name] => Some name Gold
            [description] => description
            [image] => asdf.jpg
            [price] => 83.99
            [ammount] => 1
            [Data_id] => 4
        )
    [3] => Array
        (
            [id] => 5
            [category] => Vodka
            [name] => Something Blue 100 cl
            [description] => description
            [image] => Something.jpg
            [price] => 32.44
            [ammount] => 1
            [Data_id] => 4
        )
)
</code>```

or another way I could work with is if I can change Data1, Data2, Data3 and so on ..

can be n Data depends how many producs a user select

into a same name ex simple Data or Info.

ex:

```<code>Array
(
    [0] => Array
        (
            [Info] => Array
                (
                    [id] => 5
                    [category] => Whiskey
                    [name] => Some name
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [Info] => Array
                (
                    [id] => 4
                    [category] => Tequila
                    [name] => Something Red 75cl
                    [description] => description
                    [image] => sierratequilasilver100.jpg
                    [price] => 92.49
                )

            [ammount] => 2
            [Data_id] => 3
        )
</code>```

Any solution will be fine for me.

Thanks and regards

答:
I would do this this way. However I would look to fix why the data is in that structure to begin with.</p>

```<code>$aStartArray =  array(array('Data3'=>array('id'=>1, 'cat'=>2), 'amount' => 1, 'Data_id'=>3));

foreach ($aStartArray as $iPos => $aArray) {

    $aKeys = array_keys($aArray); // fetches all the keys
    $aFirstElement = $aArray[$aKeys[0]]; // Get the first element using first key

    // assign/ overwrite data at the same position
    $aStartArray[$iPos] = array($aFirstElement, 'amount' => $aArray['amount'], 'Data_id' => $aArray['Data_id']);
}

echo "```";
var_dump($aStartArray);
</code>```

Body:
I know probably this was asked before not sure if was in this form but I did tried some replay from what I found here about this and failed.

ok I have this array

Array
(
    [0] => Array
        (
            [Data3] => Array
                (
                    [id] => 5
                    [category] => Whiskey
                    [name] => Some name
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [Data3] => Array
                (
                    [id] => 4
                    [category] => Tequila
                    [name] => Something Red 75cl
                    [description] => description
                    [image] => sierratequilasilver100.jpg
                    [price] => 92.49
                )

            [ammount] => 2
            [Data_id] => 3
        )

    [2] => Array
        (
            [Data4] => Array
                (
                    [id] => 3
                    [category] => Whiskey
                    [name] => Some name Gold
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 4
        )

    [3] => Array
        (
            [Data4] => Array
                (
                    [id] => 5
                    [category] => Vodka
                    [name] => Something Blue 100 cl
                    [description] => description
                    [image] => Something.jpg
                    [price] => 32.44
                )

            [ammount] => 1
            [Data_id] => 4
        )

)

What I would like to be the result is something like this:

Array
(
    [0] => Array
        (
            [id] => 5
            [category] => Whiskey
            [name] => Some name
            [description] => description
            [image] => asdf.jpg
            [price] => 83.99
            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [id] => 4
            [category] => Tequila
            [name] => Something Red 75cl
            [description] => description
            [image] => sierratequilasilver100.jpg
            [price] => 92.49
            [ammount] => 2
            [Data_id] => 3
        )
    [2] => Array
        (
            [id] => 3
            [category] => Whiskey
            [name] => Some name Gold
            [description] => description
            [image] => asdf.jpg
            [price] => 83.99
            [ammount] => 1
            [Data_id] => 4
        )
    [3] => Array
        (
            [id] => 5
            [category] => Vodka
            [name] => Something Blue 100 cl
            [description] => description
            [image] => Something.jpg
            [price] => 32.44
            [ammount] => 1
            [Data_id] => 4
        )
)

or another way I could work with is if I can change Data1, Data2, Data3 and so on ..

can be n Data depends how many producs a user select

into a same name ex simple Data or Info.

ex:

Array
(
    [0] => Array
        (
            [Info] => Array
                (
                    [id] => 5
                    [category] => Whiskey
                    [name] => Some name
                    [description] => description
                    [image] => asdf.jpg
                    [price] => 83.99
                )

            [ammount] => 1
            [Data_id] => 3
        )

    [1] => Array
        (
            [Info] => Array
                (
                    [id] => 4
                    [category] => Tequila
                    [name] => Something Red 75cl
                    [description] => description
                    [image] => sierratequilasilver100.jpg
                    [price] => 92.49
                )

            [ammount] => 2
            [Data_id] => 3
        )

Any solution will be fine for me.

Thanks and regards

Body:
I would do this this way. However I would look to fix why the data is in that structure to begin with.

$aStartArray =  array(array('Data3'=>array('id'=>1, 'cat'=>2), 'amount' => 1, 'Data_id'=>3));

foreach ($aStartArray as $iPos => $aArray) {

    $aKeys = array_keys($aArray); // fetches all the keys
    $aFirstElement = $aArray[$aKeys[0]]; // Get the first element using first key

    // assign/ overwrite data at the same position
    $aStartArray[$iPos] = array($aFirstElement, 'amount' => $aArray['amount'], 'Data_id' => $aArray['Data_id']);
}

echo "<pre>";
var_dump($aStartArray);


问:
Handle change event not working for input types?
I am new to react… my handle change event is not working while typing text into an input. How do I go about fixing that? I want to handle both inputs with the same handle change.

```<code>import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            first_name:'',
            last_name:''
        }
    }
    handleChange(e){
        var first_name = e.target.first_name
        var last_name = e.target.last_name
        var state = this.state
        state[first_name] = e.target.value
        state[last_name] = e.target.value
        this.setState(state)
    }
    render() {
        return (
          <div>
              <TextField hint text="First Name" id="user_first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
              <TextField hint text="Last Name" id="user_last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />
          </div>
        )
    }
}
</code>```

答:
I think, issue is you are updating both the fields by the same value, write it like this:

```<code>handleChange(e){
    var obj = {}
    obj[e.target.name] = e.target.value
    this.setState(obj);
}
</code>```

And assign the same name as the state variable names, like this:

```<code><TextField ... name='first_name' value={this.state.first_name} onChange={this.handleChange.bind(this)}/>
<TextField ... name='last_name' value={this.state.last_name} onChange={this.handleChange.bind(this)}   />
</code>```

Use this:

```<code>class Settings extends React.Component {

  constructor(props) {
    super(props)
     this.state = {
      first_name:'',
      last_name:''
    }
  }

  handleChange(e){
    let obj = {};
    obj[e.target.name] = e.target.value;
    this.setState(obj);
  }

  render() {
    return (
      <div>
        <TextField hintText="First Name" id="first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="first_name" size="30" type="text" value={this.state.first_name} />
        <TextField hinText="Last Name" id="last_name" floatingLabelFixed="editprofile" name="last_name" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />
      </div>
  )}
}
</code>```

Body:
I am new to react… my handle change event is not working while typing text into an input. How do I go about fixing that? I want to handle both inputs with the same handle change.

import React from 'react'
import TextField from 'material-ui/TextField'
class Settings extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            first_name:'',
            last_name:''
        }
    }
    handleChange(e){
        var first_name = e.target.first_name
        var last_name = e.target.last_name
        var state = this.state
        state[first_name] = e.target.value
        state[last_name] = e.target.value
        this.setState(state)
    }
    render() {
        return (

              <TextField hint text="First Name" id="user_first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="user[first_name]" size="30" type="text" value={this.state.first_name} />
              <TextField hint text="Last Name" id="user_last_name" floatingLabelFixed="editprofile" name="user[last_name]" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />

        )
    }
}

Body:
I think, issue is you are updating both the fields by the same value, write it like this:

handleChange(e){
    var obj = {}
    obj[e.target.name] = e.target.value
    this.setState(obj);
}

And assign the same name as the state variable names, like this:

<TextField ... name='first_name' value={this.state.first_name} onChange={this.handleChange.bind(this)}/>
<TextField ... name='last_name' value={this.state.last_name} onChange={this.handleChange.bind(this)}   />

Use this:

class Settings extends React.Component {

  constructor(props) {
    super(props)
     this.state = {
      first_name:'',
      last_name:''
    }
  }

  handleChange(e){
    let obj = {};
    obj[e.target.name] = e.target.value;
    this.setState(obj);
  }

  render() {
    return (
      <div>
        <TextField hintText="First Name" id="first_name" floatingLabelFixed="editprofile" onChange={this.handleChange.bind(this)} name="first_name" size="30" type="text" value={this.state.first_name} />
        <TextField hinText="Last Name" id="last_name" floatingLabelFixed="editprofile" name="last_name" onChange={this.handleChange.bind(this)} size="30" type="text" value={this.state.last_name} />
      </div>
  )}
}


问:
Write a String to a File in the Assets Folder
I have a .txt file in my Assets folder.
I tried using
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(getAssets().open("---.txt")));

I get an error underlining (getAssets().open("---.txt"))); Saying

OutputStreamWriter(java.io.OutputStream) in OutputStreamWriter cannot be applied to (java.io.InputStream)

I don't know how to write to this file, and I need help. It would also be good if I knew how to erase everything that's already in that file and write in a blank file...(Sorry for being unclear).

I know I can do this using PrintWriter on PC, but I am learning Android now.

答:
You cannot write any files to assets or any raw dir.

Where will it be located in the Android file system. So write your txt file in internal OR external storage.


问:
How we call Fragment from this java class?
I have to call fragment from this class and also want to send Array list in fragment
    I am Storing firebase notification in arraylist</p>

```<code>public class DataManager{

    private static volatile DataManager dataManager;

    public DataManager() {

    }

    public static DataManager factory() {
        if (dataManager == null) {
            synchronized (DataManager.class) {
                if (dataManager == null) {
                    dataManager = new DataManager();
                }
            }
            dataManager = new DataManager();
        }
        return dataManager;
    }

    public ArrayList<NotIfModel> notIfArray = new ArrayList<>();

}
</code>```

答:
Try This:</p>

```<code>public DataManager(FragmentManager fragmentManager) {
   Fragment fragment = new DetailFragment();
   fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
   fragmentManager.beginTransaction().add(android.R.id.content, fragment).commit();
}
</code>```

Body:
I have to call fragment from this class and also want to send Array list in fragment
    I am Storing firebase notification in arraylist

public class DataManager{

    private static volatile DataManager dataManager;

    public DataManager() {

    }

    public static DataManager factory() {
        if (dataManager == null) {
            synchronized (DataManager.class) {
                if (dataManager == null) {
                    dataManager = new DataManager();
                }
            }
            dataManager = new DataManager();
        }
        return dataManager;
    }

    public ArrayList<NotIfModel> notIfArray = new ArrayList<>();

}

Body:
Try This:

public DataManager(FragmentManager fragmentManager) {
   Fragment fragment = new DetailFragment();
   fragmentManager.popBackStack(null, FragmentManager.POP_BACK_STACK_INCLUSIVE);
   fragmentManager.beginTransaction().add(android.R.id.content, fragment).commit();
}


问:
nginx / 413 Request Entity Too Large
When I'm trying to upload a file on my server I get this error:

413 Request Entity Too Large

Which ofcourse means my file is too large. So i've done a quick google search and came accross this:

open:

```<code>/etc/nginx/nginx.conf
</code>```

Edit:

```<code># set client body size to 2M #
client_max_body_size 2M;
</code>```

However I don't have that code in my nginx.conf file? Did this recently change? Can't find nothing about it

Thanks

答: client_max_body_size default value is 1 MB. RTM

Title: nginx / 413 Request Entity Too Large

Body:
When I'm trying to upload a file on my server I get this error:

413 Request Entity Too Large

Which ofcourse means my file is too large. So i've done a quick google search and came accross this:

open:

/etc/nginx/nginx.conf

Edit:

# set client body size to 2M #
client_max_body_size 2M;

However I don't have that code in my nginx.conf file? Did this recently change? Can't find nothing about it

Thanks


问:
Convert Fixed format Rpg code to free format
Hi I need to convert fixed format code to Free format as per my companies coding standard instructions. I dont even understand what the below means except that some date movement and conversions are happening..

```<code>C     *ISO          MOVE      BCEXDT        MDYDATE
C                   MOVE      MDYDATE       PEXPDATT
C     *ISO          MOVE      BCSTDT        MDYDATE
C                   MOVE      MDYDATE       PSTRDAT
</code>```

Field definitions below:

```<code>BCEXDT         8S 0
BCSTDT         8S 0
D  MDYDATE        S               D   DATFMT(*MDY)
</code>```

答:
The two move operations for which you have shown the definitions can be converted like this:

```<code>C     *ISO          MOVE      BCEXDT        MDYDATE
C     *ISO          MOVE      BCSTDT        MDYDATE
</code>```

to

```<code>MDYDate = %date(bcexdt: *ISO);
MDYDate = %date(bcstdt: *ISO);
</code>```

Note that MDYDate is a date field, and has the same internal format as every other date field. The DATFMT(*MDY) keyword only defines how the field is represented externally by default when loaded into (or from) a character or numeric field. It also sets limits on allowable values. In the case of *MDY, those limits are 01-01-1940 to 12-31-2039. Notice that the values in BCEXDT and BCSTDT are *ISO format, and the values limits are different for those fields. Specifically 0001-01-01 to 9999-12-31. So you could get errors when attempting to assign the *ISO date to a *MDY date field.

The two moves I haven't converted for you would be done in one of the following ways.

If the targets are date fields:

```
pexpdatt = MDYDate;
pstrdat = MDYDate;
```

If the targets are numeric fields:

```
pexpdatt = %dec(MDYDate);
pstrdat = %dec(MDYDate);
```

If the targets are character fields:

```
pexpdatt = %char(MDYDate);
pstrdat = %char(MDYDate);
```

%dec() and %char() will assign the date fields in *MDY format since it was not explicitly specified in the assignment, and the date fields have DATFMT(*MDY).

Body:
Hi I need to convert fixed format code to Free format as per my companies coding standard instructions. I dont even understand what the below means except that some date movement and conversions are happening..

C     *ISO          MOVE      BCEXDT        MDYDATE
C                   MOVE      MDYDATE       PEXPDATT
C     *ISO          MOVE      BCSTDT        MDYDATE
C                   MOVE      MDYDATE       PSTRDAT

Field definitions below:

BCEXDT         8S 0
BCSTDT         8S 0
D  MDYDATE        S               D   DATFMT(*MDY)

Body:
The two move operations for which you have shown the definitions can be converted like this:

C     *ISO          MOVE      BCEXDT        MDYDATE
C     *ISO          MOVE      BCSTDT        MDYDATE

to

MDYDate = %date(bcexdt: *ISO);
MDYDate = %date(bcstdt: *ISO);

Note that MDYDate is a date field, and has the same internal format as every other date field. The DATFMT(*MDY) keyword only defines how the field is represented externally by default when loaded into (or from) a character or numeric field. It also sets limits on allowable values. In the case of *MDY, those limits are 01-01-1940 to 12-31-2039. Notice that the values in BCEXDT and BCSTDT are *ISO format, and the values limits are different for those fields. Specifically 0001-01-01 to 9999-12-31. So you could get errors when attempting to assign the *ISO date to a *MDY date field.

The two moves I haven't converted for you would be done in one of the following ways.

If the targets are date fields:

pexpdatt = MDYDate;
pstrdat = MDYDate;

If the targets are numeric fields:

pexpdatt = %dec(MDYDate);
pstrdat = %dec(MDYDate);

If the targets are character fields:

pexpdatt = %char(MDYDate);
pstrdat = %char(MDYDate);

%dec() and %char() will assign the date fields in *MDY format since it was not explicitly specified in the assignment, and the date fields have DATFMT(*MDY).


问:
MKPinAnnotationView: Are there more than three colors available?
According to the Apple docs, MKPinAnnotationView's pin color is available in red, green and purple. Is there any way to get other colors also? I've found nothing in the docs.</p>

答: Neither of the posted solutions work 100% if you are using the pin drop animation. Cannonade's solution is very neat because it allows the pin to still have both kinds of ends (the sharp point when falling and the one with the circular paper ripple) but unfortunately a glimpse of the original pin head colour can be seen when the pin bounces as it hits the map. yonel's solution of replacing the whole pin image means the pin falls with the circular paper ripple before it's even hit the map!</p>

ContentLicense: CC BY-SA 2.5


问:
Delay Request in ASP.NET Application
How can I delay HTTP requests addressing a ASP.NET application?

The delay have to be before processing the request at the server.

Additionally I like to select which request ought to have the delay.

Why do I want the delay?

Some requests throw an exception in the KernelBase.dll.
Delaying the requests grants the application some time to initialize the data so that the exception is not thrown any more.

答:
From what i understand about your requirement, i will be tempted to add some sort of spin wait in Application BeginRequest event handler.
You can choose whether to invoke the timer, based on conditions in the request or state of the application(includes data initialization state) at that moment.</p>

Title: Delay Request in ASP.NET Application


问:
Secure URL/page for AnonUser to update a model field - Django Rest framework
I have a model called Lead which represents my possible future_customer.

In order to update a boolean field called is_approved in this model, I'm sending an email to the Lead's email ID along with a URL and this URL will take you to a page in my website where it asks for Approval.

How do I deal with permissions in Django Rest framework views? There is no django user associated with Lead model and I cannot use any authentication related classes.

Obscured url along with AllowAny permission is good enough?

答:
What generally happens in a normal scenario for validation of emails is that they generate a unique token for the corresponding email. Then they when the user clicks on the email. He is taken to a page where there could be form submit which takes to a POST page or just validates directly.

The only security is that the unique id is just unique and there is a very rare chance for someone generate those id's via brute-force. That's the only security. You can add a expire also that makes the link valid only for few days.

You find the corresponding email associated with the same and update is_approved field accordingly.

Your model and view should look something like this.

```<code>class Lead(models.Model):
    email = models.EmailField()
    unique_id = models.CharField(default=uuid.uuid4)
    is_approved = models.BooleanField(default=False)

    def get_absolute_url(self):
        return reverse('lead_verification', kwargs={'unique_id': self.unique_id})

class LeadVerificationView(APIView):

    def post(self, unique_id):
        lead = Lead.objects.get(unique_id=unique_id)
        lead.is_approved = True
        lead.save()
</code>```

Body:
What generally happens in a normal scenario for validation of emails is that they generate a unique token for the corresponding email. Then they when the user clicks on the email. He is taken to a page where there could be form submit which takes to a POST page or just validates directly.

The only security is that the unique id is just unique and there is a very rare chance for someone generate those id's via brute-force. That's the only security. You can add a expire also that makes the link valid only for few days.

You find the corresponding email associated with the same and update is_approved field accordingly.

Your model and view should look something like this.

class Lead(models.Model):
    email = models.EmailField()
    unique_id = models.CharField(default=uuid.uuid4)
    is_approved = models.BooleanField(default=False)

    def get_absolute_url(self):
        return reverse('lead_verification', kwargs={'unique_id': self.unique_id})

class LeadVerificationView(APIView):

    def post(self, unique_id):
        lead = Lead.objects.get(unique_id=unique_id)
        lead.is_approved = True
        lead.save()


问:
How can I validate on the client if I use MVC validation but posting a JSON object?
I'm developing a ASP.NET Core web application where I'm using DataAnnotations to decorate my view model with validation attributes. When I open a detail page with my inputs, I see that Core added the HTML5 validation attributes to the rendered HTML (i.e. data-val="true").

However, I wrote custom client-side code when the user clicks on the Save button like this:

```<code>    $(document).on("click", "#SaveAsset", function (event) {
        event.preventDefault();
        Asset.Save();
    });
</code>```

I also have a Save function defined like this:

```<code>window.Asset.Save = function () {

    var postData = {
        'Id': $("#Id").val(),
        'SerialNumber': $("#SerialNumber").val(),
        'PartNumber': $("#PartNumber").val(),
        'assetTypeId': $("#AssetTypeId").val()
    };

    $.post('/Asset/SaveAsset', postData);
}
</code>```

I need to validate on the client side first before calling $.post but I'm confused about how to do it. Microsoft shows that the unobtrusive javascript works automatically when you use it with forms. But I'm not using the HTML form element to submit my page. So how can I trigger the HTML5 validation attributes?

I added the links to jquery.validate.js and jquery.validate.unobtrusive.js. Right now, if I click the Save button the data is sent to the server and the controller checks the ModelState. But it shouldn't even be sending anything to the server. The client should stop the validation.

Should I even stop doing it this way? For example, creating my postData JSON object by getting the val() of each input.

Should I use the form element? I stopped using it because my page has hundreds of inputs so I was worried I would have problems. This way, I have control over each input.

答:
Use a javascript solution like jQuery Validation Plugin to validate data before sending to the server. Otherwise, send the data to the server, and return a the errors with a bad request if validation fails.

Eg.

```<code>Return BadRequest(string[]{"Name is required", "Id must me a number"});
</code>```

then capture the errors and shoe to the user

Body:
I'm developing a ASP.NET Core web application where I'm using DataAnnotations to decorate my view model with validation attributes. When I open a detail page with my inputs, I see that Core added the HTML5 validation attributes to the rendered HTML (i.e. data-val="true").

However, I wrote custom client-side code when the user clicks on the Save button like this:

    $(document).on("click", "#SaveAsset", function (event) {
        event.preventDefault();
        Asset.Save();
    });

I also have a Save function defined like this:

window.Asset.Save = function () {

    var postData = {
        'Id': $("#Id").val(),
        'SerialNumber': $("#SerialNumber").val(),
        'PartNumber': $("#PartNumber").val(),
        'assetTypeId': $("#AssetTypeId").val()
    };

    $.post('/Asset/SaveAsset', postData);
}

I need to validate on the client side first before calling $.post but I'm confused about how to do it. Microsoft shows that the unobtrusive javascript works automatically when you use it with forms. But I'm not using the HTML form element to submit my page. So how can I trigger the HTML5 validation attributes?

I added the links to jquery.validate.js and jquery.validate.unobtrusive.js. Right now, if I click the Save button the data is sent to the server and the controller checks the ModelState. But it shouldn't even be sending anything to the server. The client should stop the validation.

Should I even stop doing it this way? For example, creating my postData JSON object by getting the val() of each input.

Should I use the form element? I stopped using it because my page has hundreds of inputs so I was worried I would have problems. This way, I have control over each input.

Body:
Use a javascript solution like jQuery Validation Plugin to validate data before sending to the server. Otherwise, send the data to the server, and return a the errors with a bad request if validation fails.

Eg.

Return BadRequest(string[]{"Name is required", "Id must me a number"});

then capture the errors and shoe to the user


问:
Sort a list by a function results
I want to sort a list by the results of functions that are contained in list items. How would go about doing that?

Here is an example. Let's say I have a following object:

```<code>Public Class MyListObject
    Public MyText1 As String
    Public MyText2 As String

    Public Function AddSuffix(ByVal MySuffix As String) As String
        Return Mytext1 & MySuffix
    End Function

End Class
</code>```

(massively oversimplified for the sake of example)

After that I have a list of these objects:

```<code>Dim ResultList As New List(Of MyListObject)
</code>```

Now, for example, to sort the list by the field MyText1 value, I used this:

```<code>ResultList = ResultList.OrderBy(Function(x) GetType(MyListObject).GetField("MyText1").GetValue(x)).ToList
</code>```

(used reflection, so I can pass the field name as a string)

How can I sort this list by the function AddSuffix result and simultaneously pass the parameter MySuffix?

I imagine it would look something like this, but obviously this doesn't work

```<code>ResultList = ResultList.OrderBy(Function(x) GetType(MyListObject).GetField("AddSuffix(""_myCustomSuffix"")").GetValue(x)).ToList
</code>```

PS. I realize, that in this example the function is pretty much meaningless. The actual code is much more complex and that function does return different sortable data for each list item.

答:
I am guessing you have a pretty good reason to use reflection, but I would recommend avoiding it even if you have too many fields and methods.

```<code>ResultList = ResultList.OrderBy(Function(o) o.AddSuffix("_myCustomSuffix")).ToList
</code>```

The VB way of calling a method by name is something like this (also not tested)

```<code>ResultList = ResultList.OrderBy(Function(o) CallByName(o,
                        "AddSuffix", CallType.Method, "_myCustomSuffix")).ToList
</code>```

Title: Sort a list by a function results

Body:
I want to sort a list by the results of functions that are contained in list items. How would go about doing that?

Here is an example. Let's say I have a following object:

Public Class MyListObject
    Public MyText1 As String
    Public MyText2 As String

    Public Function AddSuffix(ByVal MySuffix As String) As String
        Return Mytext1 & MySuffix
    End Function

End Class

(massively oversimplified for the sake of example)

After that I have a list of these objects:

Dim ResultList As New List(Of MyListObject)

Now, for example, to sort the list by the field MyText1 value, I used this:

ResultList = ResultList.OrderBy(Function(x) GetType(MyListObject).GetField("MyText1").GetValue(x)).ToList

(used reflection, so I can pass the field name as a string)

How can I sort this list by the function AddSuffix result and simultaneously pass the parameter MySuffix?

I imagine it would look something like this, but obviously this doesn't work

ResultList = ResultList.OrderBy(Function(x) GetType(MyListObject).GetField("AddSuffix(""_myCustomSuffix"")").GetValue(x)).ToList

PS. I realize, that in this example the function is pretty much meaningless. The actual code is much more complex and that function does return different sortable data for each list item.

Body:
I am guessing you have a pretty good reason to use reflection, but I would recommend avoiding it even if you have too many fields and methods.

ResultList = ResultList.OrderBy(Function(o) o.AddSuffix("_myCustomSuffix")).ToList

The VB way of calling a method by name is something like this (also not tested)

ResultList = ResultList.OrderBy(Function(o) CallByName(o,
                        "AddSuffix", CallType.Method, "_myCustomSuffix")).ToList


问:
How to use next and previous button to display some images in each

How to use a next and a previous button to show some images in every
-element?

答:
you must make image tags and next write these:

```<code> <ul>
          <li id="image1" style="display:block"><img src="resources/images/larges/01.jpg"></li>
    <li id="image2" style="display:none">
<img src="resources/images/larges/02.jpg"></li>
</ul>

        <img style='cursor:pointer;' onclick="showDiv(1)" src="">
        <img style='cursor:pointer;' onclick="showDiv(2)" src="">
        <button type="button" onclick="showDiv(currentImage - 1)">Pre</button>
        <button type="button" onclick="showDiv(currentImage + 1)">Next</button>
        <script>
        var currentImage = 1;
        function showDiv(which) {
    //set display none for all image element
           for(i = 0; i < 13; i++) {
              document.getElementById("image"+i).style.display="none";
           }
           //in the next 2 lines, you make sure which isn't lower than 1, and isn't greater than the number of images
           if(which < 1) which = 1;
           if(which > 13) which = 13;
    //set display block for current Image by element id
           document.getElementById("image" + which).style.display = "block";
           currentImage = which;
        } </script>
</code>```

for next ul you just need change id of li tags.

Title: How to use next and previous button to display some images in each <ul>

Body:
you must make image tags and next write these:

 <ul>
          <li id="image1" style="display:block"><img src="resources/images/larges/01.jpg"></li>
    <li id="image2" style="display:none">
<img src="resources/images/larges/02.jpg"></li>
</ul>

        <img style='cursor:pointer;' onclick="showDiv(1)" src="">
        <img style='cursor:pointer;' onclick="showDiv(2)" src="">
        <button type="button" onclick="showDiv(currentImage - 1)">Pre</button>
        <button type="button" onclick="showDiv(currentImage + 1)">Next</button>
        <script>
        var currentImage = 1;
        function showDiv(which) {
    //set display none for all image element
           for(i = 0; i < 13; i++) {
              document.getElementById("image"+i).style.display="none";
           }
           //in the next 2 lines, you make sure which isn't lower than 1, and isn't greater than the number of images
           if(which < 1) which = 1;
           if(which > 13) which = 13;
    //set display block for current Image by element id
           document.getElementById("image" + which).style.display = "block";
           currentImage = which;
        } </script>

for next ul you just need change id of li tags.


问:
How to show multiple values in an input element using Angular JS
I have an array of months like this

```<code>Array[0]
0
:
"January"
1
:
"February"
2
:
"March"
</code>```

Now I need to show all three values of this array in one input element.
like

How can I do this using angular js. Please help

here's the html

```<code><div class="col-md-4">
                <div asterick class="form-group" ng-class="{'form-group has-success': !error['months'] && (submitted), 'form-group has-error': (error['months']) && (submitted)}">
                    <label for="months">Months</label>
                    <input type="hidden" name="year" ng-model="data.year" value="">
                    <input type="text" name="months" id="months" ng-model="data.months" class="form-control" ng-required="true">
                    <span class="er-block" ng-show="monthlyReportFormPage.months.$touched && monthlyReportFormPage.months.$error.required">Please select months.</span>
                    <span ng-show="error.months" class="er-block">{{error.months}}</span>
                </div>
            </div>
</code>```

答:
There're plenty of options:

I would recommend to take a look at Bootstrap Tags Input.

HTML:

```<code><input type="text" value="html,input,tag" data-role="tagsinput"></input>
</code>```

CSS:

```<code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/dist/bootstrap-tagsinput.css">
</code>```

JS:

```<code><script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.js"></script>
</code>```

RESULT:

OR jQuery Tags Input Plugin by XOXCO:

OR you can do it using pure javascript. Here's an example.

Body:
I have an array of months like this

Array[0]
0
:
"January"
1
:
"February"
2
:
"March"

Now I need to show all three values of this array in one input element.
like

How can I do this using angular js. Please help

here's the html

                    Months
                    <input type="hidden" name="year" ng-model="data.year" value="">
                    <input type="text" name="months" id="months" ng-model="data.months" class="form-control" ng-required="true">
                    Please select months.
                    {{error.months}}

Body:
There're plenty of options:

I would recommend to take a look at Bootstrap Tags Input.

HTML:

<input type="text" value="html,input,tag" data-role="tagsinput"></input>

CSS:

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" href="http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/dist/bootstrap-tagsinput.css">

JS:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="http://bootstrap-tagsinput.github.io/bootstrap-tagsinput/dist/bootstrap-tagsinput.min.js"></script>

RESULT:

OR jQuery Tags Input Plugin by XOXCO:

OR you can do it using pure javascript. Here's an example.


问:
Architecture for Authentication/Authorization of Mobile and Web Users
This seems to be a reoccurring problem for me as I seem to gravitate around mobile applications the last few years. I want to authenticate and authorize mobile users in addition to web users. I need to make this seamless enough so that users can ease into having a web account without causing interruption to their data. I want the solution to be architectural in topic, not specific to any language/framework.

Requirements/Assumptions

Mobile users must be able to use the native application without a login, including for contributing content (marking favorites, uploading photos, etc).

Mobile user should be securely and uniquely authenticating to the web service even without specifying account credentials.

Mobile user may have multiple devices, which will be unaware of each other.

Mobile user should be able to Register/Login, which should roll in any content into the account's ownership. This "synchronization" should occur with each account that is subsequently logged in.

It should not matter whether an account was created on mobile or web.

Architectures Considered

NO SHIRT, NO SHOES, NO LOGIN = NO CONTRIBUTION. Require login to contribute content of any kind. This prevents the need to "synchronize" device accounts with a master account. Simply require a single username/password + tokens in order for devices to login. Server objects: User, Role

Multi-device self-authentication. Server negotiates with device and hands it credentials which the device stores. Each device self-authenticates and is associated with an anonymous account until Register/Login occurs. If Register occurs, anonymous account is converted into known account. If Login occurs, content from anonymous account is moved over to known account and then thrown away. Devices that lose the self-authentication details will get new authentication details, and the previous anonymous account is abandoned (and then hopefully later thrown away) and not restorable since it was never converted into a known account. Server objects: User, Role, Device

What do you think is a good solution? One of these, or something else?

答:
I think this is being looked at from the wrong direction.  Define an identity on the server as being defined by an arbitrary value.  Probably just a DB sequence.  Associate any demographic information (name, email...) and usage history with this identity.

Separately, define an authentication entity on the server.  This could be a user/password.  It could be a device GUID/UUID.  It could be a federated ID like OpenID.  A given identity can have (and often will in your use-case) multiple associated authentication-entities.  Very possibly multiple authentication-identities of the same type.  (e.g. GUID for my smartphone, GUID for my iPad...)

Your front-ends (whether web or app-based), use a defined API to authenticate a user; using whichever of the mechanisms that front-end supports.

In some cases (particularly the native app), the presentation of an unknown ID triggers the creation of a new identity.  However, as someone pointed out, in this situation you should ask the user if they want to connect to an existing identity.  They need to provide authentication as that identity (once) in order to establish that connection.

One other point, whatever the server uses to uniquely specify an identity should be a value that is never provided to a client.  Clients only know about the authentication mechanism and its data.  That is, the GUID/UUID, username/password,...

In addition to the techniques listed above, something like OAuth is more secure than a locally-generated GUID.  Those are one of a: easily-determined or b: easily-lost.  If the value is highly predictable (say telephone #) it is easily spoofed.  If it is generated at runtime and includes a hard-to-predict value like the hash of the current time when it is first generated, then it must be stored on the device and can be easily lost if the device is wiped.  Good GUIDs can be generated, but they are often very type-of-device specific.  Things like device serial numbers retrieved from ROM, IMEIs,...  This is readily doable.  But, is a lot more specific-device dependent than I'd likely be comfortable with.

The biggest real hurdle I see in this whole approach is that it will be awkward to allow an existing device-only (no username/password) user to sit down at a PC browser and connect to his existing account.


问:
.gitignore existing file without deleting it from repo
Can I tell Git to ignore changes in some tracked file when commiting a folder? So that, for example, if I decide to ignore 'private.conf', it wouldn't stage it for commit if I do 'git commit .', but it would be normally working if I explicitly tell it to 'git commit private.conf'.

Please also take in account that

I know that I can just explicitly tell git which files to commit each time (e.g. "git commit source1.c source2.c"), but that's extremely convenient for me. Instead of that, I'd tell git to commit all files but 'private.conf'.

Some stackoverflow topics suggest to rename private.conf to private.conf.template, then run 'git rm --cached private.conf'. For some reasons that's also unconvenient for me. Please don't suggest me that. Thanks.

I know that I can also do 'git update-index --assume-unchanged private.conf' - and this would do exactly what I want, but only for my local git repository. What I'm searching for is a way to do that for remote branch (and all git repositories cloned from that remote branch as well).

答:
No, this is not possible. A tracked file is a tracked file and cannot be ignored.

Btw. using --assume-unchanged is rather dangerous, because you tell Git that his file is not changed and it will treat it like that, meaning Git can at any time discard you local changes if you switch branches, rebase, merge or similar.

If you want a files changes not being tracked, you need to delete it from the repository, like the suggestion with the .template file or .sample like I usually name such files.


问:
How to initialize variable without value
I want to show value inside Textview. But problem is that its showing 0 in my Textview. It is coming from int total=0. I am doing setText but its not giving value I want.

If I remove 0 and keep int total then it's showing variable total is not initialized. If I initialize it then it shows that value in Textview.

```<code>public int getTotal(ArrayList<Integer> price){
    int total=0;
    for(int i=0;i<price.size();i++){
        total= total+Integer.parseInt(String.valueOf(price.get(i)));
    }
    return total;
}

textViewamount=(TextView)findViewById(R.id.amountdisplay);
textViewamount.setText(" "+getTotal(price));
</code>```

答:
you should change your line:</p>

```<code>for(int i=0;i<price.size();i++)
{
total = total+Integer.parseInt(String.valueOf(price.get(i)));
}
to:
for(int i=0;i<price.size();i++)
{
total+= (price.get(i)).intValue());
}
</code>```

Body:
I want to show value inside Textview. But problem is that its showing 0 in my Textview. It is coming from int total=0. I am doing setText but its not giving value I want.

If I remove 0 and keep int total then it's showing variable total is not initialized. If I initialize it then it shows that value in Textview.

public int getTotal(ArrayList<Integer> price){
    int total=0;
    for(int i=0;i<price.size();i++){
        total= total+Integer.parseInt(String.valueOf(price.get(i)));
    }
    return total;
}

textViewamount=(TextView)findViewById(R.id.amountdisplay);
textViewamount.setText(" "+getTotal(price));

Body:
you should change your line:

for(int i=0;i<price.size();i++)
{
total = total+Integer.parseInt(String.valueOf(price.get(i)));
}
to:
for(int i=0;i<price.size();i++)
{
total+= (price.get(i)).intValue());
}


问:
How to round up result of dividing
```<code>finalResult = Math.Ceiling(result = (x - y) / (z - 1));
</code>```

I am trying to get whole rounded number. finalResult and result are double. Others are int. And well... not working.
I would appreciate some help. Thank you.

答:
Since x, y and z are all int, then the division will be done as integer and will be truncated.

To avoid that, simply cast like so:

```<code>finalResult = Math.Ceiling(result = (x - y) / (double)(z - 1));
</code>```

(I'm assuming here you want to round up, so if the result of the division was, say, 1.00001, you'd want the rounded result to be 2.0.)

Title: How to round up result of dividing

Body:
finalResult = Math.Ceiling(result = (x - y) / (z - 1));

I am trying to get whole rounded number. finalResult and result are double. Others are int. And well... not working.
I would appreciate some help. Thank you.

Body:
Since x, y and z are all int, then the division will be done as integer and will be truncated.

To avoid that, simply cast like so:

finalResult = Math.Ceiling(result = (x - y) / (double)(z - 1));

(I'm assuming here you want to round up, so if the result of the division was, say, 1.00001, you'd want the rounded result to be 2.0.)


问:
Add and show list product in cart codeigniter
I have a problem when I add some products to cart, but then when I want to fetch contents of the cart I find it is empty.

this is my controller :

```<code>public function add_to_cart(){

    $insert_data = array(
     'id' => $this->input->post('id'),
     'name' => $this->input->post('name'),
     'price' => $this->input->post('price'),
     'qty' => $this->input->post('qty') );

     // This function add items into cart.
    $this->cart->insert($insert_data);

}
</code>```

and this is my form to add new product to cart :

```<code><div class="button-group">
                  <form method="POST" action="<?php echo base_url().'add_to_cart'; ?>">
                  <div style="display:none">
                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />
                  </div>
                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                    <input type="number" name="qty" id="<?php echo $ligneBase->id;?>">
                    <input type="hidden" name="name" value="<?php echo $ligneBase->name;?>">
                    <input type="hidden"  name="price"  value="<?php echo $ligneBase->price;?>">
                    <input type="hidden"  name="id"  value="<?php echo $ligneBase->id;?>">
                      <input class="add_cart" type="submit" value="Add to cart">
                      <div class="add-to-links">
                  </form>
                </div>
</code>```

and this is my cart in header.php :

```<code><table class="table">
                <tbody>
                <div id="text">
                  <?php $cart_check = $this->cart->contents();

                  // If cart is empty, this will show below message.
                  if(empty($cart_check)) {
                  echo '<h4 align="center">No Product in cart, To add products to your shopping cart click on "Add to Cart" Button</h4>';
                  } ?>
                </div>

                  <?php
                     $cart = $this->cart->contents();
                     foreach($cart as $indice => $ligneBase){
                  ?>
                  <tr>
                    <td class="text-center"><a href="product.html"><img class="img-thumbnail" title="Xitefun Causal Wear Fancy Shoes" alt="Xitefun Causal Wear Fancy Shoes" src="image/product/sony_vaio_1-50x50.jpg"></a></td>
                    <td class="text-left"><a href="product.html"><?php echo $ligneBase->id;?></a></td>
                    <td class="text-right">x 1</td>
                    <td class="text-right"><?php echo $ligneBase->name;?> </td>
                    <td class="text-center"><button class="btn btn-danger btn-xs remove" title="Remove" onClick="" type="button"><i class="fa fa-times"></i></button></td>
                  </tr>

                <?php
                  }
                ?>

                </tbody>
              </table>
</code>```

答:
my workout in your code

my controller

```<code>public function workout()
    {

        if($this->input->post())
        {
            //echo "```"; print_r($this->input->post());

            $insert_data = array(
     'id' => $this->input->post('id'),
     'name' => $this->input->post('name'),
     'price' => $this->input->post('price'),
     'qty' => $this->input->post('qty') );

            $this->cart->insert($insert_data);

            echo "```"; print_r($this->cart->contents());

            exit();
        }

        $this->load->view('workout');
    }
</code>```

my view

```<code><form method="POST" action="<?php echo base_url().'welcome/workout'; ?>">
                    <input type="number" name="qty" id="1002">
                    <input type="hidden" name="name" value="Mobile">
                    <input type="hidden"  name="price"  value="300">
                    <input type="hidden"  name="id"  value="1002">
                      <input class="add_cart" type="submit" value="Add to cart">
                      <div class="add-to-links">
                  </form>
</code>```

and my output is

```<code>Array
(
    [fba9d88164f3e2d9109ee770223212a0] => Array
        (
            [id] => 1002
            [name] => Mobile
            [price] => 300
            [qty] => 24
            [rowid] => fba9d88164f3e2d9109ee770223212a0
            [subtotal] => 7200
        )

)
</code>```

works fine

and your error is in displaying foreach

```<code><table class="table">
                <tbody>
                <div id="text">
                  <?php $cart_check = $this->cart->contents();

                  // If cart is empty, this will show below message.
                  if(empty($cart_check)) {
                  echo '<h4 align="center">No Product in cart, To add products to your shopping cart click on "Add to Cart" Button</h4>';
                  } ?>
                </div>

                  <?php
                     $cart = $this->cart->contents();
                     foreach($cart as $indice => $ligneBase){
                  ?>
                  <tr>
                    <td class="text-center"><a href="product.html"><img class="img-thumbnail" title="Xitefun Causal Wear Fancy Shoes" alt="Xitefun Causal Wear Fancy Shoes" src="image/product/sony_vaio_1-50x50.jpg"></a></td>
                    <td class="text-left"><a href="product.html"><?php echo $ligneBase->id;?></a></td>
                    <td class="text-right">x 1</td>
                    <td class="text-right"><?php echo $ligneBase->name;?> </td>
                    <td class="text-center"><button class="btn btn-danger btn-xs remove" title="Remove" onClick="" type="button"><i class="fa fa-times"></i></button></td>
                  </tr>

                <?php
                  }
                ?>

                </tbody>
              </table>
</code>```

change it to

```<code><table class="table">
                    <tbody>
                    <div id="text">
                      <?php $cart_check = $this->cart->contents();

                      // If cart is empty, this will show below message.
                      if(empty($cart_check)) {
                      echo '<h4 align="center">No Product in cart, To add products to your shopping cart click on "Add to Cart" Button</h4>';
                      } ?>
                    </div>

                      <?php
                         $cart = $this->cart->contents();
                         foreach($cart as $indice => $ligneBase){
                      ?>
                      <tr>
                        <td class="text-center"><a href="product.html"><img class="img-thumbnail" title="Xitefun Causal Wear Fancy Shoes" alt="Xitefun Causal Wear Fancy Shoes" src="image/product/sony_vaio_1-50x50.jpg"></a></td>
                        <td class="text-left"><a href="product.html"><?php echo $ligneBase['id'];?></a></td>
                        <td class="text-right">x 1</td>
                        <td class="text-right"><?php echo $ligneBase['name'];?> </td>
                        <td class="text-center"><button class="btn btn-danger btn-xs remove" title="Remove" onClick="" type="button"><i class="fa fa-times"></i></button></td>
                      </tr>

                    <?php
                      }
                    ?>

                    </tbody>
                  </table>
</code>```

Body:
I have a problem when I add some products to cart, but then when I want to fetch contents of the cart I find it is empty.

this is my controller :

public function add_to_cart(){

    $insert_data = array(
     'id' => $this->input->post('id'),
     'name' => $this->input->post('name'),
     'price' => $this->input->post('price'),
     'qty' => $this->input->post('qty') );

     // This function add items into cart.
    $this->cart->insert($insert_data);

}

and this is my form to add new product to cart :

                  <form method="POST" action="<?php echo base_url().'add_to_cart'; ?>">

                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash();?>" />

                  <input type="hidden" name="<?php echo $this->security->get_csrf_token_name(); ?>" value="<?php echo $this->security->get_csrf_hash(); ?>">
                    <input type="number" name="qty" id="<?php echo $ligneBase->id;?>">
                    <input type="hidden" name="name" value="<?php echo $ligneBase->name;?>">
                    <input type="hidden"  name="price"  value="<?php echo $ligneBase->price;?>">
                    <input type="hidden"  name="id"  value="<?php echo $ligneBase->id;?>">
                      <input class="add_cart" type="submit" value="Add to cart">

                  </form>

and this is my cart in header.php :

                  <?php $cart_check = $this->cart->contents();

                  // If cart is empty, this will show below message.
                  if(empty($cart_check)) {
                  echo '
No Product in cart, To add products to your shopping cart click on "Add to Cart" Button
';
                  } ?>

                  <?php
                     $cart = $this->cart->contents();
                     foreach($cart as $indice => $ligneBase){
                  ?>

                    <?php echo $ligneBase->id;?>
                    x 1
                    <?php echo $ligneBase->name;?>
                    <button class="btn btn-danger btn-xs remove" title="Remove" onClick="" type="button"></button>

                <?php
                  }
                ?>

Body:
my workout in your code

my controller

public function workout()
    {

        if($this->input->post())
        {
            //echo "<pre>"; print_r($this->input->post());

            $insert_data = array(
     'id' => $this->input->post('id'),
     'name' => $this->input->post('name'),
     'price' => $this->input->post('price'),
     'qty' => $this->input->post('qty') );

            $this->cart->insert($insert_data);

            echo "<pre>"; print_r($this->cart->contents());

            exit();
        }

        $this->load->view('workout');
    }

my view

<form method="POST" action="<?php echo base_url().'welcome/workout'; ?>">
                    <input type="number" name="qty" id="1002">
                    <input type="hidden" name="name" value="Mobile">
                    <input type="hidden"  name="price"  value="300">
                    <input type="hidden"  name="id"  value="1002">
                      <input class="add_cart" type="submit" value="Add to cart">
                      <div class="add-to-links">
                  </form>

and my output is

Array
(
    [fba9d88164f3e2d9109ee770223212a0] => Array
        (
            [id] => 1002
            [name] => Mobile
            [price] => 300
            [qty] => 24
            [rowid] => fba9d88164f3e2d9109ee770223212a0
            [subtotal] => 7200
        )

)

works fine

and your error is in displaying foreach

<table class="table">
                <tbody>
                <div id="text">
                  <?php $cart_check = $this->cart->contents();

                  // If cart is empty, this will show below message.
                  if(empty($cart_check)) {
                  echo '<h4 align="center">No Product in cart, To add products to your shopping cart click on "Add to Cart" Button</h4>';
                  } ?>
                </div>

                  <?php
                     $cart = $this->cart->contents();
                     foreach($cart as $indice => $ligneBase){
                  ?>
                  <tr>
                    <td class="text-center"><a href="product.html"><img class="img-thumbnail" title="Xitefun Causal Wear Fancy Shoes" alt="Xitefun Causal Wear Fancy Shoes" src="image/product/sony_vaio_1-50x50.jpg"></a></td>
                    <td class="text-left"><a href="product.html"><?php echo $ligneBase->id;?></a></td>
                    <td class="text-right">x 1</td>
                    <td class="text-right"><?php echo $ligneBase->name;?> </td>
                    <td class="text-center"><button class="btn btn-danger btn-xs remove" title="Remove" onClick="" type="button"><i class="fa fa-times"></i></button></td>
                  </tr>

                <?php
                  }
                ?>

                </tbody>
              </table>

change it to

<table class="table">
                    <tbody>
                    <div id="text">
                      <?php $cart_check = $this->cart->contents();

                      // If cart is empty, this will show below message.
                      if(empty($cart_check)) {
                      echo '<h4 align="center">No Product in cart, To add products to your shopping cart click on "Add to Cart" Button</h4>';
                      } ?>
                    </div>

                      <?php
                         $cart = $this->cart->contents();
                         foreach($cart as $indice => $ligneBase){
                      ?>
                      <tr>
                        <td class="text-center"><a href="product.html"><img class="img-thumbnail" title="Xitefun Causal Wear Fancy Shoes" alt="Xitefun Causal Wear Fancy Shoes" src="image/product/sony_vaio_1-50x50.jpg"></a></td>
                        <td class="text-left"><a href="product.html"><?php echo $ligneBase['id'];?></a></td>
                        <td class="text-right">x 1</td>
                        <td class="text-right"><?php echo $ligneBase['name'];?> </td>
                        <td class="text-center"><button class="btn btn-danger btn-xs remove" title="Remove" onClick="" type="button"><i class="fa fa-times"></i></button></td>
                      </tr>

                    <?php
                      }
                    ?>

                    </tbody>
                  </table>


问:
Pulling twitter followers data using selenium chrome webdriver in python? Not able to load all the followers
I am trying to pull twitter followers data using Selenium chrome webdriver and BeautifulSoup for a account that has 80K followers.
I am facing two issues in my script :

1) While scrolling till the bottom of the page to get the entire page source after all the followers are loaded, my script does not scroll all the way to the bottom. It stops scrolling in between after loading a random number of followers and then start traversing each followers profile to get their data. I want it to load all the followers on the page and then start traversing the profiles.

2) My second issue is every time I run the script it would try to scroll to the bottom one by one till all the followers are loaded and then start pulling data by parsing one follower data at a time. This would take 4 to 5 days to fetch all the followers data in my case(80K followers). Is there any better way to do this.

Here is my script :

from bs4 import BeautifulSoup
import sys
import os,re
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from os import listdir
from os.path import isfile, join

print "Running for chrome."

chromedriver=sys.argv[1]
download_path=sys.argv[2]
os.system('killall -9 "Google Chrome"')
try:
 os.environ["webdriver.chrome.driver"]=chromedriver
 chromeOptions = webdriver.ChromeOptions()
 prefs = {"download.default_directory" : download_path}
 chromeOptions.add_experimental_option("prefs",prefs)
 driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chromeOptions)
 driver.implicitly_wait(20)
 driver.maximize_window()
except Exception as err:
 print "Error:Failed to open chrome."
 print "Error: ",err
 driver.stop_client()
 driver.close()

#opening the web page
try:
 driver.get('https://twitter.com/login')
except Exception as err:
 print "Error:Failed to open url."
 print "Error: ",err
 driver.stop_client()
 driver.close()

username = driver.find_element_by_xpath("//input[@name='session[username_or_email]' and @class='js-username-field email-input js-initial-focus']")
password = driver.find_element_by_xpath("//input[@name='session[password]' and @class='js-password-field']")

username.send_keys("###########")
password.send_keys("###########")
driver.find_element_by_xpath("//button[@type='submit']").click()
#os.system('killall -9 "Google Chrome"')
driver.get('https://twitter.com/sadserver/followers')

followers_link=driver.page_source  #follwer page 18at a time
soup=BeautifulSoup(followers_link,'html.parser')

output=open('twitter_follower_sadoperator.csv','a')
output.write('Name,Twitter_Handle,Location,Bio,Join_Date,Link'+'\n')
div = soup.find('div',{'class':'GridTimeline-items has-items'})
bref = div.findAll('a',{'class':'ProfileCard-bg js-nav'})
name_list=[]
lastHeight = driver.execute_script("return document.body.scrollHeight")

for _ in xrange(0, followers_count/followers_per_page + 1):
        driver.execute_script("window.scrollTo(0, document.body.scrollHeight);")
        time.sleep(5)
        newHeight = driver.execute_script("return document.body.scrollHeight")
        if newHeight == lastHeight:
                followers_link=driver.page_source  #follwer page 18at a time
                soup=BeautifulSoup(followers_link,'html.parser')
                div = soup.find('div',{'class':'GridTimeline-items has-items'})
                bref = div.findAll('a',{'class':'ProfileCard-bg js-nav'})
                for name in bref:
                        name_list.append(name['href'])
                break
        lastHeight = newHeight
        followers_link=''

print len(name_list)

for x in range(0,len(name_list)):
        #print name['href']
        #print name.text
        driver.stop_client()
        driver.get('https://twitter.com'+name_list[x])
        page_source=driver.page_source
        each_soup=BeautifulSoup(page_source,'html.parser')
        profile=each_soup.find('div',{'class':'ProfileHeaderCard'})

        try:
                name = profile.find('h1',{'class':'ProfileHeaderCard-name'}).find('a').text
                if name:
                        output.write('"'+name.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in name:',e

        try:
                handle=profile.find('h2',{'class':'ProfileHeaderCard-screenname u-inlineBlock u-dir'}).text
                if handle:
                        output.write('"'+handle.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in handle:',e

        try:
                location = profile.find('div',{'class':'ProfileHeaderCard-location'}).text
                if location:
                        output.write('"'+location.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in location:',e

        try:
                bio=profile.find('p',{'class':'ProfileHeaderCard-bio u-dir'}).text
                if bio:
                        output.write('"'+bio.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in bio:',e

        try:
                joinDate = profile.find('div',{'class':'ProfileHeaderCard-joinDate'}).text
                if joinDate:
                        output.write('"'+joinDate.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in joindate:',e

        try:
                url =  [check.find('a') for check in profile.find('div',{'class':'ProfileHeaderCard-url'}).findAll('span')][1]
                if url:
                        output.write('"'+url['href'].strip().encode('utf-8')+'"'+'\n')
                else:
                        output.write(' '+'\n')
        except Exception as e:
                output.write(' '+'\n')
                print 'Error in url:',e

output.close()

os.system("kill -9 `ps -deaf | grep chrome | awk '{print $2}'`")```

答:
I did t he implementation as mentioned by alecxe in his answer but still my script is not parsing all the followers. It is still loading random number of followers. Can't seem to get to the bottom of this. Can someone please try and run this on their end to see if they are able to load all the followers. Here's the modified script :

from bs4 import BeautifulSoup
import sys
import os,re
import time
from selenium import webdriver
from selenium.webdriver.support.ui import Select
from selenium.webdriver.common.keys import Keys
from os import listdir
from os.path import isfile, join

print "Running for chrome."

chromedriver=sys.argv[1]
download_path=sys.argv[2]
os.system('killall -9 "Google Chrome"')
try:
 os.environ["webdriver.chrome.driver"]=chromedriver
 chromeOptions = webdriver.ChromeOptions()
 prefs = {"download.default_directory" : download_path}
 chromeOptions.add_experimental_option("prefs",prefs)
 driver = webdriver.Chrome(executable_path=chromedriver, chrome_options=chromeOptions)
 driver.implicitly_wait(20)
 driver.maximize_window()
except Exception as err:
 print "Error:Failed to open chrome."
 print "Error: ",err
 driver.stop_client()
 driver.close()

#opening the web page
try:
 driver.get('https://twitter.com/login')
except Exception as err:
 print "Error:Failed to open url."
 print "Error: ",err
 driver.stop_client()
 driver.close()

username = driver.find_element_by_xpath("//input[@name='session[username_or_email]' and @class='js-username-field email-input js-initial-focus']")
password = driver.find_element_by_xpath("//input[@name='session[password]' and @class='js-password-field']")

username.send_keys("*****************")
password.send_keys("*****************")
driver.find_element_by_xpath("//button[@type='submit']").click()
#os.system('killall -9 "Google Chrome"')
driver.get('https://twitter.com/sadoperator/followers')

followers_link=driver.page_source  #follwer page 18at a time
soup=BeautifulSoup(followers_link,'html.parser')

output=open('twitter_follower_sadoperator.csv','a')
output.write('Name,Twitter_Handle,Location,Bio,Join_Date,Link'+'\n')
div = soup.find('div',{'class':'GridTimeline-items has-items'})
bref = div.findAll('a',{'class':'ProfileCard-bg js-nav'})
name_list=[]
lastHeight = driver.execute_script("return document.body.scrollHeight")

followers_link=driver.page_source  #follwer page 18at a time
soup=BeautifulSoup(followers_link,'html.parser')

followers_per_page = 18
followers_count = 15777

for _ in xrange(0, followers_count/followers_per_page + 1):
        driver.execute_script("window.scrollTo(0, 7755000);")
        time.sleep(2)
        newHeight = driver.execute_script("return document.body.scrollHeight")
        if newHeight == lastHeight:
                followers_link=driver.page_source  #follwer page 18at a time
                soup=BeautifulSoup(followers_link,'html.parser')
                div = soup.find('div',{'class':'GridTimeline-items has-items'})
                bref = div.findAll('a',{'class':'ProfileCard-bg js-nav'})
                for name in bref:
                        name_list.append(name['href'])
                break
        lastHeight = newHeight
        followers_link=''

print len(name_list)

'''
for x in range(0,len(name_list)):
        #print name['href']
        #print name.text
        driver.stop_client()
        driver.get('https://twitter.com'+name_list[x])
        page_source=driver.page_source
        each_soup=BeautifulSoup(page_source,'html.parser')
        profile=each_soup.find('div',{'class':'ProfileHeaderCard'})

        try:
                name = profile.find('h1',{'class':'ProfileHeaderCard-name'}).find('a').text
                if name:
                        output.write('"'+name.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in name:',e

        try:
                handle=profile.find('h2',{'class':'ProfileHeaderCard-screenname u-inlineBlock u-dir'}).text
                if handle:
                        output.write('"'+handle.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in handle:',e

        try:
                location = profile.find('div',{'class':'ProfileHeaderCard-location'}).text
                if location:
                        output.write('"'+location.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in location:',e

        try:
                bio=profile.find('p',{'class':'ProfileHeaderCard-bio u-dir'}).text
                if bio:
                        output.write('"'+bio.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in bio:',e

        try:
                joinDate = profile.find('div',{'class':'ProfileHeaderCard-joinDate'}).text
                if joinDate:
                        output.write('"'+joinDate.strip().encode('utf-8')+'"'+',')
                else:
                        output.write(' '+',')
        except Exception as e:
                output.write(' '+',')
                print 'Error in joindate:',e

        try:
                url =  [check.find('a') for check in profile.find('div',{'class':'ProfileHeaderCard-url'}).findAll('span')][1]
                if url:
                        output.write('"'+url['href'].strip().encode('utf-8')+'"'+'\n')
                else:
                        output.write(' '+'\n')
        except Exception as e:
                output.write(' '+'\n')
                print 'Error in url:',e

output.close()
'''

os.system("kill -9 `ps -deaf | grep chrome | awk '{print $2}'`")```


问:
How to fetch the data from the master table in model and use in another model in laravel?

Here is my one model name "Department"

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
    //
     protected $table = 'dept_master';
}
</code>```

and the controller of the department is

namespace App\Http\Controllers;

```<code>use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Department;

class DepartmentController extends Controller
{
    public function departmentsName()
    {

        $departments = DB::table('dept_master')->orderBy('edesc','ASC')->get();
        return $departments;
    }
}
</code>```

and another model grievance register

```<code><?php

    namespace App;
    //namespace Models;

    use Illuminate\Database\Eloquent\Model;

    class GrievanceRegister extends Model
    {

    }
</code>```

and the grievance controller is

```<code><?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\GrievanceRegister;
use App\Department;

class GrievanceRegisterController extends Controller
{
   public function show()
   {
  $departments = Department::orderBy('edesc','ASC')->get();
  return view('griev_reg_form', array('departments' => $departments));
}

}

   ?>
</code>```

and in the view file

```<code> <select name="departments"> <?php foreach($departments as $result)
                {
                    ?> <option value="<?php echo $result->deptcode; ?>"><?php echo $result->edesc; ?></option>  <?php   }       ?>
                    </select>
</code>```

Is it a correct way to call one model data from another model and
  controller. Please correct me if am wrong.

答:
I am not sure concept of model and controllers are clear to you.

I try my best to explain a bit here.

So Model is used to communicate with a table.

In you case, I am guessing by seeing you code is that, you have a table named: departments so that is why you will have a model Department with help of which you can save, update, delete or extract data from departments table.

```<code><?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
     protected $fillable = ['name'];
}
</code>```

again its better to have first alphabet capital case.

$fillable variable defines what fields in table are mass assignable. See reference here for Lravel 5.4

Now I have assumed that you have id and name field in your table departments

Now in your controller you are referring to some table: dept_master which doesn't make sense.

You controller should be like this:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Department;

use App\department;

class DepartmentController extends Controller
{
    public function departmentsName()
    {
        $departments = Department::orderBy('edesc','ASC')->get();
        return $departments;
    }
}
</code>```

I dont know what you are trying to achieve with $table variable in your model which contains string dept_master and what is this table dept_master.

I have explained the concept of model and controller.

Have model for each and every table and access them anywhere from any controller via models. Its as simple as it is.

And as I mentioned in my answers to your previous questions. Follow snake_case plural for table names and camelCase singular with exception of first alphabet capital for model names.

Body:
Here is my one model name "Department"

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
    //
     protected $table = 'dept_master';
}

and the controller of the department is

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\Department;

class DepartmentController extends Controller
{
    public function departmentsName()
    {

        $departments = DB::table('dept_master')->orderBy('edesc','ASC')->get();
        return $departments;
    }
}

and another model grievance register

<?php

    namespace App;
    //namespace Models;

    use Illuminate\Database\Eloquent\Model;

    class GrievanceRegister extends Model
    {

    }

and the grievance controller is

<?php

namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

use App\GrievanceRegister;
use App\Department;

class GrievanceRegisterController extends Controller
{
   public function show()
   {
  $departments = Department::orderBy('edesc','ASC')->get();
  return view('griev_reg_form', array('departments' => $departments));
}

}

   ?>

and in the view file

 <select name="departments"> <?php foreach($departments as $result)
                {
                    ?> <option value="<?php echo $result->deptcode; ?>"><?php echo $result->edesc; ?></option>  <?php   }       ?>
                    </select>

Is it a correct way to call one model data from another model and
  controller. Please correct me if am wrong.

Body:
I am not sure concept of model and controllers are clear to you.

I try my best to explain a bit here.

So Model is used to communicate with a table.

In you case, I am guessing by seeing you code is that, you have a table named: departments so that is why you will have a model Department with help of which you can save, update, delete or extract data from departments table.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Department extends Model
{
     protected $fillable = ['name'];
}

again its better to have first alphabet capital case.

$fillable variable defines what fields in table are mass assignable. See reference here for Lravel 5.4

Now I have assumed that you have id and name field in your table departments

Now in your controller you are referring to some table: dept_master which doesn't make sense.

You controller should be like this:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

use App\Http\Requests;
use App\Http\Controllers\Controller;
use App\Department;

use App\department;

class DepartmentController extends Controller
{
    public function departmentsName()
    {
        $departments = Department::orderBy('edesc','ASC')->get();
        return $departments;
    }
}

I dont know what you are trying to achieve with $table variable in your model which contains string dept_master and what is this table dept_master.

I have explained the concept of model and controller.

Have model for each and every table and access them anywhere from any controller via models. Its as simple as it is.

And as I mentioned in my answers to your previous questions. Follow snake_case plural for table names and camelCase singular with exception of first alphabet capital for model names.