问:
XML language is backed or front end?
Might be the question is silly, but i don't have any tutor to answer.
so i posted here.

I know XML is backed language . but in android XML is using as a front end language. please tell me is it possible that we can change the front\back end as per our coding language.

and also please share some books for developing a knowledge in java for android

please clarify

答:
XML is just a self-describing language - that's easy for machines as well as humans to read, so for example

```<code><page>
    <button text="press me"/>
</page>
</code>```

is valid XML and can be used to describe a user interface (like HTML or Xaml) or data stored in the back end of a service like this

```<code><books>
    <book title="Catch 22"/>
</books>
</code>```

It's all in how you use it.  Different software platforms use it in different ways.

Title: XML language is backed or front end?

Body:
XML is just a self-describing language - that's easy for machines as well as humans to read, so for example

<page>
    <button text="press me"/>
</page>

is valid XML and can be used to describe a user interface (like HTML or Xaml) or data stored in the back end of a service like this

<books>
    <book title="Catch 22"/>
</books>

It's all in how you use it.  Different software platforms use it in different ways.


来源: stackexchange

问:
Putting current time into label
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.</p>

```<code>NSDate *StrDate = [NSDate date];
        NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
        [Dateformat setDateFormat:@"DD-MM-YYYY"];
        NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
        [UserCntrl.timeDisplay setText:DateStr];
        [Dateformat setDateFormat:@"HH:MM"];
        NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];
</code>```

答:
You have a bug in your code:
Instead of
[Dateformat setDateFormat:@"HH:MM"];
it should be
[Dateformat setTimeFormat:@"HH:MM"];

ContentLicense: CC BY-SA 2.5

Title: Putting current time into label

Body:
Ii am trying to get date and time using date but when i run application it takes first time executed application time and date in short time is not changed.

NSDate *StrDate = [NSDate date];
        NSDateFormatter *Dateformat = [[NSDateFormatter alloc]init];
        [Dateformat setDateFormat:@"DD-MM-YYYY"];
        NSMutableString *DateStr = [Dateformat stringFromDate:StrDate];
        [UserCntrl.timeDisplay setText:DateStr];
        [Dateformat setDateFormat:@"HH:MM"];
        NSMutableString *timeStr=[Dateformat stringFromDate:StrDate];


问:
Creating generic classes and functions in javascript ES06
I'm from java background. I use Generics in java in following way:

```<code>  class ApiResponse<T> {

    T data;

    T getData(){
      return T;
    }
  }
</code>```

I'm unable to use generics in javascript ES06. I wanna know whether it's possible or not creating generic classes?

答:
JavaScript is a dynamically typed language and it doesn't have any generics. You can write a normal function/method, it will work for all types.

P.S. Use Typescript if want to code like you do in Java.

ContentLicense: CC BY-SA 3.0

Body:
I'm from java background. I use Generics in java in following way:

  class ApiResponse<T> {

    T data;

    T getData(){
      return T;
    }
  }

I'm unable to use generics in javascript ES06. I wanna know whether it's possible or not creating generic classes?


问:
unexpected token:where when using spring data jpa with hibernate
I am trying to use spring data jpa and hibernate in my project. I added the annotation @Query in repository, trying to write a hql with a Pageable argument passed in like this:

@Query("select name,code,id from Region where fatherId is NULL or fatherId=''")
Page<Region> findAllRoots(Pageable pageable);

but when I tried to compile and run it, I got unexpected token: where printed on console. Full info is:

Caused by: java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: where near line 1, column 14 [select count(where) from com.nitccs.demo.entity.Region where fatherId is NULL or fatherId='']

How could it ran like this? I am totally confused. Why it is not select count(id) or something? I am sure I got no variable named where in my pojo.

答:
In you above query, you are doing wrong, you are expecting name,code,id and how this will convert into Region object

if you want data with pagination try to use SpringData specifications

click here to have a look on this


问:
Format Android EditText as HH:MM:SS
I have an edit text in android studio, and I want to get a value for hours, minutes, and seconds from the user. How can I start with the edit text saying 00:00:00, and have the user input numbers, but leave the :'s intact?

I'd rather not ask the user to enter the semicolons themselves

答:
You can use MaskedEditText

build.gradle

```<code>dependencies {
    compile 'com.vicmikhailau:MaskedEditText:2.0.3'
}
</code>```

add in xml

```<code><com.vicmikhailau.maskededittext.MaskedEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:mask="your_mask" />
</code>```

Title: Format Android EditText as HH:MM:SS

Body:
You can use MaskedEditText

build.gradle

dependencies {
    compile 'com.vicmikhailau:MaskedEditText:2.0.3'
}

add in xml

<com.vicmikhailau.maskededittext.MaskedEditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:mask="your_mask" />


答: Javascript doesn't have strict typing so there is no need for Generics because all variables can be assigned to any type at any time.</p>

Title: Creating generic classes and functions in javascript ES06


问:
Where does Xcode store .m files of a framework?
In Xcode there are many frameworks (like mkmapkit.framework).

This framework contains only .h (header) files. Where can I find the corresponding .m (implementation) files.

答: You can find them inside Apple's internal source code repositories.  If you work at Apple on an appropriate team, you can check them out.  If you don't, then you're out of luck.</p>


问:
Finding a particular expression in R
```<code>afn(a)
1       pwr_p08_mgr1
2       pwr_p08_asd
3       pwr_p11_mgr1
4       pwr_p11_mgr4
5       pwr_p10_asd
6       scribbles
7       abc_de_p11_wer
8       red-p08
</code>```

<p>I have a function which will return a list of elements like what I labeled above. I want to repeat this for all possible values of a. There are 150 different values. For each of the values I want it to return 3 things. They can be 3 separate functions or all in 1 function. I want to get the periods present and count for each value of a. For the example shown, the period 08 appears 3 times, 10 once, and 11 3 times.  The other thing I need is the fraction of values of a (there are 150) for which each of the periods(01-50) are present. </p>

答:
If we are extracting the first match of numbers and to find the frequency</p>

```<code>library(stringr)
table(str_extract(afn_a, "\\d+"))
</code>```

Title: Finding a particular expression in R

Body:
afn(a)
1       pwr_p08_mgr1
2       pwr_p08_asd
3       pwr_p11_mgr1
4       pwr_p11_mgr4
5       pwr_p10_asd
6       scribbles
7       abc_de_p11_wer
8       red-p08

I have a function which will return a list of elements like what I labeled above. I want to repeat this for all possible values of a. There are 150 different values. For each of the values I want it to return 3 things. They can be 3 separate functions or all in 1 function. I want to get the periods present and count for each value of a. For the example shown, the period 08 appears 3 times, 10 once, and 11 3 times.  The other thing I need is the fraction of values of a (there are 150) for which each of the periods(01-50) are present.

Body:
If we are extracting the first match of numbers and to find the frequency

library(stringr)
table(str_extract(afn_a, "\\d+"))


问:
How do I use GSL in Julia?
the general questión would be how do I to use any library non-standar in Julia, e.g. libraries exported from C, specifically I downloaded the GNU Scientific Library from https://www.gnu.org/software/gsl/, according the Julia Manual I think it can be used, but I readed the INSTALL file from the GSL folder and I tried follow the steps, however I could not finish them because  I did'nt understand some steps.

If anyone could give me some advice to use this library in Julia,  I would appreciate it very much.

some details.

-OS: Windows10
-Julia version: 0.6

答:
In the general case,
calling compiled code is done using ccall

For the case of GSL, for most operations you shouldn't be using GSL.
The (almost all) the functionality provided by GSL is well covered by the Julia standard library or by well maintained julia packages.
Mostly with implementation in pure julia.

Pure julia implementations will normally be basically as fast as the C/Fortran implementations.
Plus they will have other good features like working well with the optimiser,
and supporting custom types via multiple dispatch
For example supporting Dual numbers means that ForwardDiff.jl will just natively allow Auto differentiation to work with them.
For some code ducktyping will even let them work with things like TensorFlow..

As to how to install GSL, I think that is a seperate question from how to use GSL with julia.
Conviently though, if you are in a position you absolutely need to call GSL from julia,
there is already a julia package wrapping it. GSL.jl
And particularly conveniently, it will automatically download and install GSL for you when you run Pkg.add("GSL.jl"),
so you don't have to worry about installing it yourself.
If the package isn't working for you, raise an issue on their repo.

(Julia packages tend to be good like that, just installing all their dependencies so you don't have to fiddle around with things. I've been really impressed a few times when colleges have come to me saying "I love R library Foo but I can't using it on windows as I can't get the Fortran backend to work"; and I'll be like "Foo.jl does the same thing using the same fortran backend, also it automatically installs that backend, and does so in a way that just works even on windows.")

Title: How do I use GSL in Julia?


问:
Providing a default value parsing XML with ElementTree when findall() finds no match
Very new to Python, and I am building a project to learn Python. The project involves XML parsing, for which I have used ElementTree.

This is the code I currently have:

```<code>import xml.etree.ElementTree as etree
tree = etree.parse('ar.xml')
root = tree.getroot()

ns = {'nbb': 'http://www.nbb.be/be/fr/pfs/ci/2017-04-01'}

for ass in tree.findall("nbb:Assets[@contextRef='CurrentInstant']", ns):
    assets = ass.text

for pay in tree.findall("nbb:AmountsPayable[@contextRef='CurrentInstant']", ns):
    payables = pay.text

for prov in tree.findall("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns):
    provisions = prov.text

for cap in tree.findall("nbb:IssuedCapital[@contextRef='CurrentInstant']", ns):
    capital = cap.text

print assets
print payables
print provisions
print capital
</code>```

For most XML files, this works perfectly fine.

However, some of the XML files for which I would like to use the code do not have the Element ("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns). In those cases, the following error shows up: name 'provisions' is not defined.

I need to use the variables to make calculations further down the code (for example: assets - provisions), and I would need the value of 'provisions' to be assigned to 0 in the XML files where there is no ("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns) Element.

How should I proceed?

Many thanks!

答:
A for/else clause provides one way to handle this:

```<code>for prov in tree.findall("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns):
    provisions = int(prov.text)
    break
else:
    provisions = 0
</code>```

The else clause is run when break never takes place.

You could also initialize the value, and reassign in the loop:

```<code>provisions = 0
for prov in tree.findall("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns):
    provisions = int(prov.text)
</code>```

Body:
Very new to Python, and I am building a project to learn Python. The project involves XML parsing, for which I have used ElementTree.

This is the code I currently have:

import xml.etree.ElementTree as etree
tree = etree.parse('ar.xml')
root = tree.getroot()

ns = {'nbb': 'http://www.nbb.be/be/fr/pfs/ci/2017-04-01'}

for ass in tree.findall("nbb:Assets[@contextRef='CurrentInstant']", ns):
    assets = ass.text

for pay in tree.findall("nbb:AmountsPayable[@contextRef='CurrentInstant']", ns):
    payables = pay.text

for prov in tree.findall("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns):
    provisions = prov.text

for cap in tree.findall("nbb:IssuedCapital[@contextRef='CurrentInstant']", ns):
    capital = cap.text

print assets
print payables
print provisions
print capital

For most XML files, this works perfectly fine.

However, some of the XML files for which I would like to use the code do not have the Element ("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns). In those cases, the following error shows up: name 'provisions' is not defined.

I need to use the variables to make calculations further down the code (for example: assets - provisions), and I would need the value of 'provisions' to be assigned to 0 in the XML files where there is no ("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns) Element.

How should I proceed?

Many thanks!

Body:
A for/else clause provides one way to handle this:

for prov in tree.findall("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns):
    provisions = int(prov.text)
    break
else:
    provisions = 0

The else clause is run when break never takes place.

You could also initialize the value, and reassign in the loop:

provisions = 0
for prov in tree.findall("nbb:ProvisionsDeferredTaxes[@contextRef='CurrentInstant']", ns):
    provisions = int(prov.text)


问:
Can I determine whether the string can deserialize by newtonsoft?
In my application I'm using newtonsoft to serialize and deserialize object, I want to know is there any built in API to determine that input string can deserialize to specific object or not?

```<code>public TObject Deserialize<TObject>(string serialized)
{
    /// I want check the condition, and if is not serialized string just return default(TObject)
    return JsonConvert.DeserializeObject<TObject>(serialized);
}
</code>```

I don't want to use try catch. Currently I implemented like that but looking to find a way to verify the string before start to deserialize object.

Already I saw this question Deserialize json in a "TryParse" way, but its not my answer cause I don't have any specific schema and JSON format can change dynamically.

答: This thread implements a decent TryParse using the latest package from Newtonsoft.Json.Schema.</p>

Body:
In my application I'm using newtonsoft to serialize and deserialize object, I want to know is there any built in API to determine that input string can deserialize to specific object or not?

public TObject Deserialize<TObject>(string serialized)
{
    /// I want check the condition, and if is not serialized string just return default(TObject)
    return JsonConvert.DeserializeObject<TObject>(serialized);
}

I don't want to use try catch. Currently I implemented like that but looking to find a way to verify the string before start to deserialize object.

Already I saw this question Deserialize json in a "TryParse" way, but its not my answer cause I don't have any specific schema and JSON format can change dynamically.


问:
Email sending in aspnetboilerplate not working
This is the settings:

```<code>AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "abc@xyz.tech");
AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "abc.tech Emailservice");
AddSettingIfNotExists(EmailSettingNames.Smtp.UserName, "abc@xyz.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.Domain, "abc.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.EnableSsl,"false");
AddSettingIfNotExists(EmailSettingNames.Smtp.Host, "webmail.abc.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.Port, "25");
AddSettingIfNotExists(EmailSettingNames.Smtp.Password, "gdfdgd");
AddSettingIfNotExists(EmailSettingNames.Smtp.UseDefaultCredentials, "false");
</code>```

This is the email sending code:

```<code>// See "Update"
</code>```

I am getting this exception:

Bad sequence of commands. The server response was: This mail server
  requires authentication when attempting to send to a non-local e-mail
  address. Please check your mail client settings or contact your
  administrator to verify that the domain or address is defined for this
  server

Update

```<code>public class UserAppService // ...
{
    private readonly UserManager _userManager;
    private readonly RoleManager _roleManager;
    IRepository<User, long> _rep;
    private readonly IRepository<Role> _roleRepository;
    private readonly IPasswordHasher<User> _passwordHasher;
    public readonly IEmailSender _emailSender;

    public UserAppService(
        IRepository<User, long> repository,
        UserManager userManager,
        RoleManager roleManager,
        IRepository<Role> roleRepository,
        IPasswordHasher<User> passwordHasher, IEmailSender em)
        : base(repository)
    {
        _rep = repository;
        _userManager = userManager;
        _roleManager = roleManager;
        _roleRepository = roleRepository;
        _passwordHasher = passwordHasher;
        _emailSender = em;
    }

    [AbpAllowAnonymous]
    public override async Task<UserDto> Create(CreateUserDto input)
    {
        // CheckCreatePermission();

        var user = ObjectMapper.Map<User>(input);

        user.TenantId = AbpSession.TenantId;
        user.Password = _passwordHasher.HashPassword(user, input.Password);
        user.IsEmailConfirmed = false;

        CheckErrors(await _userManager.CreateAsync(user));

        if (input.RoleNames != null)
        {
            CheckErrors(await _userManager.SetRoles(user, input.RoleNames));
        }

        CurrentUnitOfWork.SaveChanges();

        try
        {
            await _emailSender.SendAsync("test@gmail.com", "sdfs", "sdfsd", false);
        }
        catch (Exception ex)
        {
        }

        return MapToEntityDto(user);
    }
}
</code>```

答:
This has nothing to do with aspnetboilerplate. as the error says "This mail server requires authentication when attempting to send to a non-local e-mail address. "

Possible causes:

Email client is not configured for SMTP authentication and the server
is

Firewall or email proxy software is preventing SMTP authentication from occurring

Email client has incorrect credentials configured or does not match server settings.

What you can do is download the application below to test your smtp settings.
http://www.alexnolan.net/software/SMTPProber.htm

Once you send email successfully, use the correct settings in aspnetboilerplate.

Body:
This is the settings:

AddSettingIfNotExists(EmailSettingNames.DefaultFromAddress, "abc@xyz.tech");
AddSettingIfNotExists(EmailSettingNames.DefaultFromDisplayName, "abc.tech Emailservice");
AddSettingIfNotExists(EmailSettingNames.Smtp.UserName, "abc@xyz.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.Domain, "abc.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.EnableSsl,"false");
AddSettingIfNotExists(EmailSettingNames.Smtp.Host, "webmail.abc.tech");
AddSettingIfNotExists(EmailSettingNames.Smtp.Port, "25");
AddSettingIfNotExists(EmailSettingNames.Smtp.Password, "gdfdgd");
AddSettingIfNotExists(EmailSettingNames.Smtp.UseDefaultCredentials, "false");

This is the email sending code:

// See "Update"

I am getting this exception:

Bad sequence of commands. The server response was: This mail server
  requires authentication when attempting to send to a non-local e-mail
  address. Please check your mail client settings or contact your
  administrator to verify that the domain or address is defined for this
  server

Update

public class UserAppService // ...
{
    private readonly UserManager _userManager;
    private readonly RoleManager _roleManager;
    IRepository<User, long> _rep;
    private readonly IRepository<Role> _roleRepository;
    private readonly IPasswordHasher<User> _passwordHasher;
    public readonly IEmailSender _emailSender;

    public UserAppService(
        IRepository<User, long> repository,
        UserManager userManager,
        RoleManager roleManager,
        IRepository<Role> roleRepository,
        IPasswordHasher<User> passwordHasher, IEmailSender em)
        : base(repository)
    {
        _rep = repository;
        _userManager = userManager;
        _roleManager = roleManager;
        _roleRepository = roleRepository;
        _passwordHasher = passwordHasher;
        _emailSender = em;
    }

    [AbpAllowAnonymous]
    public override async Task<UserDto> Create(CreateUserDto input)
    {
        // CheckCreatePermission();

        var user = ObjectMapper.Map<User>(input);

        user.TenantId = AbpSession.TenantId;
        user.Password = _passwordHasher.HashPassword(user, input.Password);
        user.IsEmailConfirmed = false;

        CheckErrors(await _userManager.CreateAsync(user));

        if (input.RoleNames != null)
        {
            CheckErrors(await _userManager.SetRoles(user, input.RoleNames));
        }

        CurrentUnitOfWork.SaveChanges();

        try
        {
            await _emailSender.SendAsync("test@gmail.com", "sdfs", "sdfsd", false);
        }
        catch (Exception ex)
        {
        }

        return MapToEntityDto(user);
    }
}


问:
using pip3: module "importlib._bootstrap" has no attribute "SourceFileLoader"
I have installed pip for python 3.6 on Ubuntu 14. After I run

```<code>sudo apt-get install python3-pip
</code>```

to install pip3, it works very well. However, after installation, when I am trying to run

```<code>pip3 install packagename
</code>```

to install a new package, something strange occurs:

```<code>File "/usr/lib/python3/dist-packages/pkg_resources.py", line 1479, in <module>
 register_loader-type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
AttributeError: module "importlib._bootstrap" has no attribute "SourceFileLoader"
</code>```

It seems that I did nothing wrong, and I really cannot figure out the reason.

答:
Faced the same problem. I think this is because python3.6 and pip3 were installed from different sources.
I suggest using python's inbuilt facility to install pip i.e

```<code>python3 -m ensurepip --upgrade
</code>```

This should install pip3 and pip3.x where x in python3.x.
Same works for python2 also.

Body:
I have installed pip for python 3.6 on Ubuntu 14. After I run

sudo apt-get install python3-pip

to install pip3, it works very well. However, after installation, when I am trying to run

pip3 install packagename

to install a new package, something strange occurs:

File "/usr/lib/python3/dist-packages/pkg_resources.py", line 1479, in <module>
 register_loader-type(importlib_bootstrap.SourceFileLoader, DefaultProvider)
AttributeError: module "importlib._bootstrap" has no attribute "SourceFileLoader"

It seems that I did nothing wrong, and I really cannot figure out the reason.

Body:
Faced the same problem. I think this is because python3.6 and pip3 were installed from different sources.
I suggest using python's inbuilt facility to install pip i.e

python3 -m ensurepip --upgrade

This should install pip3 and pip3.x where x in python3.x.
Same works for python2 also.


问:
How to edit FTP accounts in Jcraft SFTP plugin for Eclipse?
I've been using the jcraft Eclipse SFTP plugin for FTP manipulation for a few months. However I don't know how to delete an existing FTP account or edit details. If I misspell my username/password or I do change my password, my account stays the same forever.

Where are these details saved and how can I change details? Also, I do have one FTP hostname with few different accounts but I am not able to reuse the same hostname twice.

I already tried reinstalling the plugin, changing the workspace and deleting the plugin physically. No effect.

答:
The file you are looking for is:

pathToEclipseWorkspace/.metadata/.plugins/org.eclipse.core.resources/.projects/projectName/org.eclipse.team.core/.deployments

The words in camel-back are things you need to fill in for yourself.

From here, you can delete a "provider" (the one you messed up), then restart Eclipse.  Eclipse should act as if there wasn't a connection in the first place when you try to synchronize again.

I am unsure of whether or not you can edit the details and have Eclipse use the new ones, that will be something you get to test for yourself.


问:
angular 2 function calling inside an http post function
I have a http post function.

```<code>login(){

    var data = {
      email : this.name,
      password : this.pass,
      appId : this.appId
    };
    console.log(data);

    this.http.post(SERVER_URL+"/templatesAuth/authenticateForApp",data)
      .subscribe(function(res){

         let requestParams = {
            "token": res.token,
            "email": data.email,
            "name": res.user.name,
            "phone": res.user.phone,
            "streetNumber": res.user.streetNumber,
            "streetName": res.user.streetName,
            "country": res.user.country,
            "city": res.user.city,
            "zip": res.user.zip,
            "type": 'internal',
            "appId":res.user.appId,
            "registeredUser": res.user.sub
          };

        },
        function(err){
          alert('login failed');
        })

  }
</code>```

inside the function(req){ } I cannot write or use calls like examplearray.push();
im always having an error Cannot read property 'push' of undefined

when I use Local storage functions like.

```<code>this.localStorageService.set('test'+this.appId,(requestParams));
</code>```

error : Cannot read property 'set' of undefined

but I can use them out side of the function(req){ }. couldn't figure-out the problem

is there any way to get the requestParams outside.

答:
Try this</p>

```<code>this.http.post(SERVER_URL+"/templatesAuth/authenticateForApp",data)
  .subscribe((res) => {

     let requestParams = {
        "token": res.token,
        "email": data.email,
        "name": res.user.name,
        "phone": res.user.phone,
        "streetNumber": res.user.streetNumber,
        "streetName": res.user.streetName,
        "country": res.user.country,
        "city": res.user.city,
        "zip": res.user.zip,
        "type": 'internal',
        "appId":res.user.appId,
        "registeredUser": res.user.sub
      };

    },
    function(err){
      alert('login failed');
    })
}
</code>```

Body:
I have a http post function.

login(){

    var data = {
      email : this.name,
      password : this.pass,
      appId : this.appId
    };
    console.log(data);

    this.http.post(SERVER_URL+"/templatesAuth/authenticateForApp",data)
      .subscribe(function(res){

         let requestParams = {
            "token": res.token,
            "email": data.email,
            "name": res.user.name,
            "phone": res.user.phone,
            "streetNumber": res.user.streetNumber,
            "streetName": res.user.streetName,
            "country": res.user.country,
            "city": res.user.city,
            "zip": res.user.zip,
            "type": 'internal',
            "appId":res.user.appId,
            "registeredUser": res.user.sub
          };

        },
        function(err){
          alert('login failed');
        })

  }

inside the function(req){ } I cannot write or use calls like examplearray.push();
im always having an error Cannot read property 'push' of undefined

when I use Local storage functions like.

this.localStorageService.set('test'+this.appId,(requestParams));

error : Cannot read property 'set' of undefined

but I can use them out side of the function(req){ }. couldn't figure-out the problem

is there any way to get the requestParams outside.

Body:
Try this

this.http.post(SERVER_URL+"/templatesAuth/authenticateForApp",data)
  .subscribe((res) => {

     let requestParams = {
        "token": res.token,
        "email": data.email,
        "name": res.user.name,
        "phone": res.user.phone,
        "streetNumber": res.user.streetNumber,
        "streetName": res.user.streetName,
        "country": res.user.country,
        "city": res.user.city,
        "zip": res.user.zip,
        "type": 'internal',
        "appId":res.user.appId,
        "registeredUser": res.user.sub
      };

    },
    function(err){
      alert('login failed');
    })
}


问:
How to print <DummyText> inside html tag using javascript?
I need to show "<>" symbols for my string "DummyText". When i run and inspect the element, it converted to be DOM element in HTML like . This is the code I am trying to do</p>

```<code><p><a href='' title='Survey Link'><DummyText></a></p>
</code>```

答:
Use < and > instead, from here

<DummyText>
```

Body:
I need to show "<>" symbols for my string "DummyText". When i run and inspect the element, it converted to be DOM element in HTML like . This is the code I am trying to do

<DummyText>

Body:
Use &lt; and &gt; instead, from here

<p><a href='' title='Survey Link'>&lt;DummyText&gt;</a></p>


问:
Nativescript - ActivityIndicator not working for a specific chunk of code
I'd like to display an activity-indicator displayed when I do a long process.

I set a model busy flag to true.

I then call a method that returns a Promise - when the promise calls resolve, I then set the busy flag to false in my 'then' handler.

When I wait for the promise to resolve, I expect the Activity Indicator animation to be displayed but it's not.

I checked and made sure the UI set up is correct and it works.

The work that's being done is using nativescript-calendar plugin - I'm adding a few calendar entries.

I commented out  the work that's being done and just went to sleep for a little bit and then called resolve() and the animation worked.

So the Activity Indicator and the Promise mechanism is setup correctly - it's something this plug-in is doing that's causing the AI not to display.

What could cause such a behavior?

I actually edited the Promise work code - put to sleep for about 1 second and then started the calendar work. I see the AI for 1 second and then it freezes.

So it looks like the calendar writes is causing the AI to freeze.

I was under the understanding that Promise work is done in the background and should not effect foreground animation.

答:
I've had a similar issue when using SQLite.

As you haven't explicitly stated that your running the calendar in a worker I am assuming your keeping it in the UI thread (main thread).

Any large amount of work done in the UI thread will cause noticeable lag/delays. So for example you call the activity-indicator then call a process that maxes out the thread, the process finishes the activity indicator goes to be drawn on the screen but then is hidden straight away before it is displayed as the process is finished.

The ideal way to solve this is to move the calendar writes code into a worker (multithread your app) and on success message turn off the activity-indicator.


问:
@import variables for all scss files
in my template.scss on top

@import "variables";
@import "reset";
```
<p>but I get errors on reset.scss</p>
<pre class="lang-bash prettyprint-override"><code>Libsass: Error: Undefined variable: "$baseFontSize".
on line 13 of .../sass/reset.scss
>>          font-size:$baseFontSize;
</code>```

because it doesn't know variables.scss . I had never that problem before with less

variables.scss is my first @import file it should work across all other .scss imported

thanks for helping

答:
Your variables are probably inside a ruleset (selector block) and are thus lexically scoped. Therefore they are not available outside of said block. To circumvent you should either define all variables on the root level of your variables.scss or add the !global modifier to your variables.

```<code>$baseFontSize: 12px !global;
</code>```

ContentLicense: CC BY-SA 4.0

Title: @import variables for all scss files

Body:
in my template.scss on top

@import "variables";
@import "reset";

but I get errors on reset.scss

Libsass: Error: Undefined variable: "$baseFontSize".
on line 13 of .../sass/reset.scss
>>          font-size:$baseFontSize;

because it doesn't know variables.scss . I had never that problem before with less

variables.scss is my first @import file it should work across all other .scss imported

thanks for helping

Body:
Your variables are probably inside a ruleset (selector block) and are thus lexically scoped. Therefore they are not available outside of said block. To circumvent you should either define all variables on the root level of your variables.scss or add the !global modifier to your variables.

$baseFontSize: 12px !global;


问:
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException
I work with a Spring Boot and WebSocket project and I get a error while I tried to persist (save) the Output message. I printed the entities to provide,

```<code>    Inout MessageMessage{id=null, from='Mark', text='I travel to Brazil'}
    Output MessageOutputMessage{id=null, from='Mark', message='I travel to Brazil', topic='Travel', time=Tue Nov 14 10:53:06 BDT 2017}
Hibernate: insert into output_message (from, message, time, topic) values (?, ?, ?, ?)
</code>```

The error message is provided below,

```<code>org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement

Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2803) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3374) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:619) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:273) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:254) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:299) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:317) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, message, time, topic) values ('Mark', 'I travel to Brazil', '2017-11-14 10' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]
</code>```

The controller is here,

```<code>@Controller
public class ChatController {

    @Autowired
    private OutputMessageService outputMessageService;

    @Autowired
    private MessageService messageService;

    @MessageMapping("/chat/{topic}")
    @SendTo("/topic/messages")
    public OutputMessage send(@DestinationVariable("topic") String topic,
                              Message message) throws Exception {

        OutputMessage outputMessage = new OutputMessage(message.getFrom(), message.getText(), topic);

        System.out.println("Inout Message" + message.toString());
        System.out.println("Output Message" + outputMessage.toString());

        outputMessageService.save(outputMessage);
        messageService.save(message);

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

The OutputMessage entity is provided,

```<code>@Entity
public class OutputMessage {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String from;
    private String message;
    private String topic;
    private Date time = new Date();

    public OutputMessage() {
    }

    public OutputMessage(String from, String message, String topic) {
        this.from = from;
        this.message = message;
        this.topic = topic;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public Date getTime() {
        return time;
    }

    @Override
    public String toString() {
        return "OutputMessage{" +
                "id=" + id +
                ", from='" + from + '\'' +
                ", message='" + message + '\'' +
                ", topic='" + topic + '\'' +
                ", time=" + time +
                '}';
    }
}
</code>```

The repository,

```<code>public interface OutputMessageRepository extends CrudRepository<OutputMessage, Long> {
}
</code>```

The service implementation,

```<code>@Service
public class OutputMessageServiceImpl implements OutputMessageService {

    @Autowired
    private OutputMessageRepository omRepository;

    @Override
    public List<OutputMessage> findAll() {
        return (List<OutputMessage>) omRepository.findAll();
    }

    @Override
    public void save(OutputMessage outputMessage) {
        omRepository.save(outputMessage);
    }
}
</code>```

What is the issue here?

答: Possibly happening due to your field name from please add hibernate.globally_quoted_identifiers=true property and try again. This will quote all the database identifiers.

Body:
I work with a Spring Boot and WebSocket project and I get a error while I tried to persist (save) the Output message. I printed the entities to provide,

    Inout MessageMessage{id=null, from='Mark', text='I travel to Brazil'}
    Output MessageOutputMessage{id=null, from='Mark', message='I travel to Brazil', topic='Travel', time=Tue Nov 14 10:53:06 BDT 2017}
Hibernate: insert into output_message (from, message, time, topic) values (?, ?, ?, ?)

The error message is provided below,

org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement

Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:207) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.dialect.identity.GetGeneratedKeysDelegate.executeAndExtract(GetGeneratedKeysDelegate.java:57) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:42) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2803) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3374) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:81) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:619) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:273) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:254) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:299) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:317) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:272) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:178) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:109) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:67) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:189) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:132) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:58) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:775) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:748) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:753) ~[hibernate-core-5.0.11.Final.jar:5.0.11.Final]
    at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1146) ~[hibernate-entitymanager-5.0.11.Final.jar:5.0.11.Final]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_144]
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_144]

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from, message, time, topic) values ('Mark', 'I travel to Brazil', '2017-11-14 10' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method) ~[na:1.8.0_144]
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62) ~[na:1.8.0_144]
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45) ~[na:1.8.0_144]
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423) ~[na:1.8.0_144]

The controller is here,

@Controller
public class ChatController {

    @Autowired
    private OutputMessageService outputMessageService;

    @Autowired
    private MessageService messageService;

    @MessageMapping("/chat/{topic}")
    @SendTo("/topic/messages")
    public OutputMessage send(@DestinationVariable("topic") String topic,
                              Message message) throws Exception {

        OutputMessage outputMessage = new OutputMessage(message.getFrom(), message.getText(), topic);

        System.out.println("Inout Message" + message.toString());
        System.out.println("Output Message" + outputMessage.toString());

        outputMessageService.save(outputMessage);
        messageService.save(message);

        return outputMessage;
    }
}

The OutputMessage entity is provided,

@Entity
public class OutputMessage {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String from;
    private String message;
    private String topic;
    private Date time = new Date();

    public OutputMessage() {
    }

    public OutputMessage(String from, String message, String topic) {
        this.from = from;
        this.message = message;
        this.topic = topic;
    }

    public String getFrom() {
        return from;
    }

    public void setFrom(String from) {
        this.from = from;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getTopic() {
        return topic;
    }

    public void setTopic(String topic) {
        this.topic = topic;
    }

    public Date getTime() {
        return time;
    }

    @Override
    public String toString() {
        return "OutputMessage{" +
                "id=" + id +
                ", from='" + from + '\'' +
                ", message='" + message + '\'' +
                ", topic='" + topic + '\'' +
                ", time=" + time +
                '}';
    }
}

The repository,

public interface OutputMessageRepository extends CrudRepository<OutputMessage, Long> {
}

The service implementation,

@Service
public class OutputMessageServiceImpl implements OutputMessageService {

    @Autowired
    private OutputMessageRepository omRepository;

    @Override
    public List<OutputMessage> findAll() {
        return (List<OutputMessage>) omRepository.findAll();
    }

    @Override
    public void save(OutputMessage outputMessage) {
        omRepository.save(outputMessage);
    }
}

What is the issue here?


问:
Dump a pandas DataFrame which contains column name as "name" to mysql table
I am trying to dump my crawled data to mysql using pandas and to_sql.

I am approaching in two ways
1>

```<code>{# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
import os
from pandas.io import sql
import MySQLdb

columns_list= ['persons','c_number','name']
df = pd.DataFrame()
file_name = "/home/*****/****/data.xlsx"
data = pd.read_excel(file_name)
df = df.append(data)
df.columns = columns_list
engine=create_engine('mysql+mysqldb://root:root@localhost:3306/database_name?charset=utf8&use_unicode=1', echo=False)
con = MySQLdb.connect(host="localhost",user="user_name",passwd="password",                db="database_name")
df.to_sql(con=con, name='table_name',if_exists='replace',flavor='mysql')}
</code>```

Here I am getting TypeError: to_sql() got multiple values for keyword argument 'name' error

2>

```<code>import numpy as np
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
import os

columns_list= ['persons','c_number','name']
df = pd.DataFrame()
file_name = "data.xlsx"
data = pd.read_excel(file_name)
df = df.append(data)
df_n = pd.DataFrame()
df = df_n.append(df_new)
df = np.array_split(df, 100)
for x in range(len(df_new)):
    print x
    engine = create_engine('mysql+mysqldb://user_name:password@localhost:3306/database_name?charset=utf8&use_unicode=1', echo=False)
    df[x].to_sql(name='table_name', con=engine, if_exists = 'append', index=False)
    engine.dispose()
</code>```

This way I am able to dump the data but name field I am getting Null in all records.

Is there a way to dump the data using column name "name"

答:
I have faced the similar situation before and i don't know the exact reason why it happens but here is something that worked for me.

I read the dataframe with read_excel like you have done, and re-written the excel file with modified column names.

```<code> writer = pd.ExcelWriter("data_new.xlsx")
 data.to_excel(writer,'sheet1')
 writer.save()
</code>```

Then i pushed to the database. I hope it works for you too.

Body:
I am trying to dump my crawled data to mysql using pandas and to_sql.

I am approaching in two ways
1>

{# -*- coding: utf-8 -*-
import numpy as np
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
import os
from pandas.io import sql
import MySQLdb

columns_list= ['persons','c_number','name']
df = pd.DataFrame()
file_name = "/home/*****/****/data.xlsx"
data = pd.read_excel(file_name)
df = df.append(data)
df.columns = columns_list
engine=create_engine('mysql+mysqldb://root:root@localhost:3306/database_name?charset=utf8&use_unicode=1', echo=False)
con = MySQLdb.connect(host="localhost",user="user_name",passwd="password",                db="database_name")
df.to_sql(con=con, name='table_name',if_exists='replace',flavor='mysql')}

Here I am getting TypeError: to_sql() got multiple values for keyword argument 'name' error

2>

import numpy as np
import pandas as pd
import MySQLdb
from sqlalchemy import create_engine
import os

columns_list= ['persons','c_number','name']
df = pd.DataFrame()
file_name = "data.xlsx"
data = pd.read_excel(file_name)
df = df.append(data)
df_n = pd.DataFrame()
df = df_n.append(df_new)
df = np.array_split(df, 100)
for x in range(len(df_new)):
    print x
    engine = create_engine('mysql+mysqldb://user_name:password@localhost:3306/database_name?charset=utf8&use_unicode=1', echo=False)
    df[x].to_sql(name='table_name', con=engine, if_exists = 'append', index=False)
    engine.dispose()

This way I am able to dump the data but name field I am getting Null in all records.

Is there a way to dump the data using column name "name"

Body:
I have faced the similar situation before and i don't know the exact reason why it happens but here is something that worked for me.

I read the dataframe with read_excel like you have done, and re-written the excel file with modified column names.

 writer = pd.ExcelWriter("data_new.xlsx")
 data.to_excel(writer,'sheet1')
 writer.save()

Then i pushed to the database. I hope it works for you too.


问:
Unable to Apply CSS style to SVG text element
I noticed that when you append text with JS, some styling rules work and others cease to work. To be specific, consider my css style rule that creates a border-bottom on hover...

var svg = d3.select('body')
        .append('svg')
        .attr('height',200)
        .attr('width',200);

svg.append('a')
    .append('text')
    .html('This is not a text.')
    .attr('font-size', '14px')
    .attr('class', 'content-text-1')
    .attr('x', 10)
    .attr('y', 20);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content-text-1:hover {
    border-bottom: 1px solid blue;
}</code>```

```

I don't believe this a "asynchronous" type of issue, because when I create other things, such as, svg rects or circles (just to name a few), they can be styled after the fact.

Question: What is causing the border-bottom not to show?

答:
Give div instead of svg beacause svg have its unique identity it's not supported border-bottom.

var div = d3.select('body')
        .append('div')
        .attr('height',200)
        .attr('width',200);

div.append('a')
    .append('text')
    .html('This is not a text.')
    .attr('font-size', '14px')
    .attr('class', 'content-text-1')
    .attr('x', 10)
    .attr('y', 20);```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.content-text-1:hover {
    border-bottom: 1px solid blue;
}</code>```

```

Body:
I noticed that when you append text with JS, some styling rules work and others cease to work. To be specific, consider my css style rule that creates a border-bottom on hover...

var svg = d3.select('body')
        .append('svg')
        .attr('height',200)
        .attr('width',200);

svg.append('a')
    .append('text')
    .html('This is not a text.')
    .attr('font-size', '14px')
    .attr('class', 'content-text-1')
    .attr('x', 10)
    .attr('y', 20);

.content-text-1:hover {
    border-bottom: 1px solid blue;
}

I don't believe this a "asynchronous" type of issue, because when I create other things, such as, svg rects or circles (just to name a few), they can be styled after the fact.

Question: What is causing the border-bottom not to show?

Body:
Give div instead of svg beacause svg have its unique identity it's not supported border-bottom.

var div = d3.select('body')
        .append('div')
        .attr('height',200)
        .attr('width',200);

div.append('a')
    .append('text')
    .html('This is not a text.')
    .attr('font-size', '14px')
    .attr('class', 'content-text-1')
    .attr('x', 10)
    .attr('y', 20);

.content-text-1:hover {
    border-bottom: 1px solid blue;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<body>
</body>


问:
How to auto-select the first option in a dropdown list using jquery?
I'm having trouble auto-selecting the first option in a dropdown list.

I've tried using attr and val function (see this jdfiddle link for an example) and it just wouldn't work. As a a test, my example has an  alert code that displays the .text() for the first option and this works fine. So my selector is working.

Thanks a lot!

sample HTML code:

```<code><select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>
<br>
<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select>
</code>```

sample JS  code:

```<code>$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $("#rt option:first-child").attr("selected", "selected");
    //$("#rt option:first-child").val("blank");
});
</code>```

答:
Try this

```<code>$('select>option:eq(1)').prop('selected', true);
</code>```

see this is what you are looking for it seems.

Body:
I'm having trouble auto-selecting the first option in a dropdown list.

I've tried using attr and val function (see this jdfiddle link for an example) and it just wouldn't work. As a a test, my example has an  alert code that displays the .text() for the first option and this works fine. So my selector is working.

Thanks a lot!

sample HTML code:

<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>

<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select>

sample JS  code:

$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $("#rt option:first-child").attr("selected", "selected");
    //$("#rt option:first-child").val("blank");
});

Body:
Try this

$('select>option:eq(1)').prop('selected', true);

see this is what you are looking for it seems.


问:
How to get a list of all the blobs in a container in Azure?
I have the account name and account key of a storage account in Azure. I need to get a list of all the blobs in a container in that account. (The "$logs" container).

I am able to get the information of a specific blob using the CloudBlobClient class but can't figure out how to get a list of all the blobs within the $logs container.

答:
Since you container name is $logs, so i think your blob type is append blob. Here's a method to get all blobs and return IEnumerable:

```<code>    private static CloudBlobClient _blobClient = CloudStorageAccount.Parse("connectionstring").CreateCloudBlobClient();
    public IEnumerable<CloudAppendBlob> GetBlobs()
    {
        var container = _blobClient.GetContainerReference("$logs");
        BlobContinuationToken continuationToken = null;

        do
        {
            var response = container.ListBlobsSegmented(string.Empty, true, BlobListingDetails.None, new int?(), continuationToken, null, null);
            continuationToken = response.ContinuationToken;
            foreach (var blob in response.Results.OfType<CloudAppendBlob>())
            {
                yield return blob;
            }
        } while (continuationToken != null);
    }
</code>```

The method can be asynchronous, just use ListBlobsSegmentedAsync. One thing you need to note is the argument useFlatBlobListing need to be true which means that ListBlobs will return a flat list of files as opposed to a hierarchical list.

Body:
Since you container name is $logs, so i think your blob type is append blob. Here's a method to get all blobs and return IEnumerable:

    private static CloudBlobClient _blobClient = CloudStorageAccount.Parse("connectionstring").CreateCloudBlobClient();
    public IEnumerable<CloudAppendBlob> GetBlobs()
    {
        var container = _blobClient.GetContainerReference("$logs");
        BlobContinuationToken continuationToken = null;

        do
        {
            var response = container.ListBlobsSegmented(string.Empty, true, BlobListingDetails.None, new int?(), continuationToken, null, null);
            continuationToken = response.ContinuationToken;
            foreach (var blob in response.Results.OfType<CloudAppendBlob>())
            {
                yield return blob;
            }
        } while (continuationToken != null);
    }

The method can be asynchronous, just use ListBlobsSegmentedAsync. One thing you need to note is the argument useFlatBlobListing need to be true which means that ListBlobs will return a flat list of files as opposed to a hierarchical list.


问:
Unit test angular 1 directive with $on
Within this directive, I want to test the following:

```<code>$scope.$on('loggedMsg', function(){
   if($scope.users.length){
       $scope.callingFn();
   }
});
</code>```

I am able to emit loggedMsg and with $scope.apply(), it will call the $scope.callingFn(). Is there a way to not actually call $scope.callingFn, but just spy on it? I am using mocha and sinon to write these unit tests. Is what I am suggesting possible?

```<code>describe('testing directive', function(){
   const elemScope = element.isolateScope;
   it('should trigger callingFn if loggedMsg is emitted', function(){
       scope.$emit('loggedMsg');
       scope.$apply();
       //elemScope.callingFn will be called due to the apply. Is there a way to just spy on that fn being called?
   }
});
</code>```

答:
When you use Sinon to stub a function, calling that (now stubbed) function will not call the original.

Stubs also support the full Spy API, meaning we can use a Stub to make sure the original method doesn't get called and also see under what conditions it was called (such as how many times, with what parameters).

Using your example test:

```<code>describe('testing directive', function(){
   const scope = element.isolateScope;
   it('should trigger callingFn if loggedMsg is emitted', function(){
       const stub = sinon.stub(scope, 'callingFn');
       scope.$emit('loggedMsg');
       scope.$apply();
       assert(stub.called);
   });
});
</code>```

Documentation reference: http://sinonjs.org/releases/v4.1.2/stubs/

Title: Unit test angular 1 directive with $on

Body:
Within this directive, I want to test the following:

$scope.$on('loggedMsg', function(){
   if($scope.users.length){
       $scope.callingFn();
   }
});

I am able to emit loggedMsg and with $scope.apply(), it will call the $scope.callingFn(). Is there a way to not actually call $scope.callingFn, but just spy on it? I am using mocha and sinon to write these unit tests. Is what I am suggesting possible?

describe('testing directive', function(){
   const elemScope = element.isolateScope;
   it('should trigger callingFn if loggedMsg is emitted', function(){
       scope.$emit('loggedMsg');
       scope.$apply();
       //elemScope.callingFn will be called due to the apply. Is there a way to just spy on that fn being called?
   }
});

Body:
When you use Sinon to stub a function, calling that (now stubbed) function will not call the original.

Stubs also support the full Spy API, meaning we can use a Stub to make sure the original method doesn't get called and also see under what conditions it was called (such as how many times, with what parameters).

Using your example test:

describe('testing directive', function(){
   const scope = element.isolateScope;
   it('should trigger callingFn if loggedMsg is emitted', function(){
       const stub = sinon.stub(scope, 'callingFn');
       scope.$emit('loggedMsg');
       scope.$apply();
       assert(stub.called);
   });
});

Documentation reference: http://sinonjs.org/releases/v4.1.2/stubs/


问:
Unable to invoke localhost https REST service in Ballerinalang and give a timeout error?
I've implemented a Ballerina(ballerina 0.91) service to invoke https REST service which running on localhost. I used http:ClientConnector to call that service. This is my sample code.

```<code>http:ClientConnector clientConnector = create http:ClientConnector("https://localhost:9445/");
string token = "admin:admin";
string auth = utils:base64encode(token);
message request = {};
messages:setHeader(request,"Basic ",auth);
message response = clientConnector.get("bpmn/runtime/process-instances/",request);
</code>```

By the way here I interact with a business process in WSO2 EI.

The problem is when I call this service normally it didn't respond or gave an error like below.

```<code>error: ballerina.lang.errors:Error, message: failed to invoke 'get' action in ClientConnector. response was not received within sender timeout of 180 seconds
    at ballerina.net.http:ClientConnector.get(<native>:0)
    at org.wso2.ballerina.connectors.basicauth:ClientConnector.get(org/wso2/ballerina/connectors/basicauth/ClientConnector.bal:28)
    at .:main(MainFile.bal:21)
</code>```

答:
Here is a working sample for 0.95.0. I'm using postman basic auth endpoint: </p>

```<code>import ballerina.net.http;
function main(string[] args) {
   endpoint<http:HttpClient> httpConnector{
       create http:HttpClient("https://postman-echo.com",{});
   }
http:Request req = {};
http:Response resp = {};
req.addHeader("Authorization", "Basic cG9zdG1hbjpwYXNzd29yZA==");
resp,_ = httpConnector.get("/basic-auth",req);
println("Auth request:");
println(resp.getJsonPayload());
}
</code>```

Body:
I've implemented a Ballerina(ballerina 0.91) service to invoke https REST service which running on localhost. I used http:ClientConnector to call that service. This is my sample code.

http:ClientConnector clientConnector = create http:ClientConnector("https://localhost:9445/");
string token = "admin:admin";
string auth = utils:base64encode(token);
message request = {};
messages:setHeader(request,"Basic ",auth);
message response = clientConnector.get("bpmn/runtime/process-instances/",request);

By the way here I interact with a business process in WSO2 EI.

The problem is when I call this service normally it didn't respond or gave an error like below.

error: ballerina.lang.errors:Error, message: failed to invoke 'get' action in ClientConnector. response was not received within sender timeout of 180 seconds
    at ballerina.net.http:ClientConnector.get(<native>:0)
    at org.wso2.ballerina.connectors.basicauth:ClientConnector.get(org/wso2/ballerina/connectors/basicauth/ClientConnector.bal:28)
    at .:main(MainFile.bal:21)

Body:
Here is a working sample for 0.95.0. I'm using postman basic auth endpoint:

import ballerina.net.http;
function main(string[] args) {
   endpoint<http:HttpClient> httpConnector{
       create http:HttpClient("https://postman-echo.com",{});
   }
http:Request req = {};
http:Response resp = {};
req.addHeader("Authorization", "Basic cG9zdG1hbjpwYXNzd29yZA==");
resp,_ = httpConnector.get("/basic-auth",req);
println("Auth request:");
println(resp.getJsonPayload());
}


问:
how to used IN & Between Clause in YII ACtive Record?
I want write a Following Query in Active record .

```<code>SELECT *
FROM `User`
WHERE `UserId`
IN ( 6, 7, 8, 9 ) ;
</code>```

Thanks

答:
Either you can use addInCondition or you can also use compare method.

```<code> $criteria = new CDbCriteria();
 $criteria->compare('UserId',array(6,7,8,9));
 $userDataObj = User::model()->findAll($criteria);
</code>```

Body:
I want write a Following Query in Active record .

SELECT *
FROM `User`
WHERE `UserId`
IN ( 6, 7, 8, 9 ) ;

Thanks

Body:
Either you can use addInCondition or you can also use compare method.

 $criteria = new CDbCriteria();
 $criteria->compare('UserId',array(6,7,8,9));
 $userDataObj = User::model()->findAll($criteria);


问:
Creating generic classes and functions in javascript ES06
I'm from java background. I use Generics in java in following way:

```<code>  class ApiResponse<T> {

    T data;

    T getData(){
      return T;
    }
  }
</code>```

I'm unable to use generics in javascript ES06. I wanna know whether it's possible or not creating generic classes?

答:
You can use Typescript for this purpose.

https://www.typescriptlang.org/docs/handbook/generics.html

Body:
I'm from java background. I use Generics in java in following way:

  class ApiResponse<T> {

    T data;

    T getData(){
      return T;
    }
  }

I'm unable to use generics in javascript ES06. I wanna know whether it's possible or not creating generic classes?


问:
Status 404 returned while using httr::POST() on Microsoft Text Analysis API
I am trying to use the Microsoft Cognitive APIs through R to process text data. I have created an account and acquired the key. The code is as follows. I have not included the key for privacy reasons.

```<code>library(httr)
library(jsonlite)
library(data.table)
library(dplyr)

cogapikey <- "xxxx"
cogapi <- "https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0"
text=c("is this english?"
       ,"tak er der mere kage"
       ,"merci beaucoup"
       ,"guten morgen"
       ,"bonjour"
       ,"merde"
       ,"That's terrible"
       ,"R is awesome")
df <- data_frame(id=1:length(text),text)
mydata<- list(documents=df)

# language detection
## construct a request
response <- POST(cogapi,add_headers(`Ocp-Apim-Subscription-Key`=cogapikey),
                 body=toJSON(mydata))
print(response)
</code>```

Upon printing the response variable, I get the following.

```<code>Response [https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0]
  Date: 2017-11-04 13:29
  Status: 404
  Content-Type: application/json
  Size: 54 B
</code>```

I am trying to replicate the tutorial given here.
My session information is as follows

```<code>R version 3.4.0 (2017-04-21)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RCurl_1.95-4.8      bitops_1.0-6        dplyr_0.7.4         data.table_1.10.4-3 jsonlite_1.5
[6] httr_1.3.1          tm_0.7-1            NLP_0.1-11          tidytext_0.1.4

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.13      compiler_3.4.0    plyr_1.8.4        bindr_0.1         tokenizers_0.1.4  tools_3.4.0
 [7] tibble_1.3.4      nlme_3.1-131      lattice_0.20-35   pkgconfig_2.0.1   rlang_0.1.2       Matrix_1.2-9
[13] psych_1.7.8       curl_3.0          parallel_3.4.0    bindrcpp_0.2      janeaustenr_0.1.5 stringr_1.2.0
[19] grid_3.4.0        glue_1.2.0        R6_2.2.2          foreign_0.8-67    reshape2_1.4.2    tidyr_0.7.2
[25] purrr_0.2.4       magrittr_1.5      SnowballC_0.5.1   assertthat_0.2.0  mnormt_1.5-5      stringi_1.1.5
[31] slam_0.1-40       broom_0.4.2
</code>```

I was wondering if there is an additional prerequisite tool/package I should install? Thank You in advance!

答:
Seems the endpoint needs correction here. It should be:

```<code>cogapi <- "https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0/languages"
</code>```

/langauges is missing in the endpoint.

Body:
I am trying to use the Microsoft Cognitive APIs through R to process text data. I have created an account and acquired the key. The code is as follows. I have not included the key for privacy reasons.

library(httr)
library(jsonlite)
library(data.table)
library(dplyr)

cogapikey <- "xxxx"
cogapi <- "https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0"
text=c("is this english?"
       ,"tak er der mere kage"
       ,"merci beaucoup"
       ,"guten morgen"
       ,"bonjour"
       ,"merde"
       ,"That's terrible"
       ,"R is awesome")
df <- data_frame(id=1:length(text),text)
mydata<- list(documents=df)

# language detection
## construct a request
response <- POST(cogapi,add_headers(`Ocp-Apim-Subscription-Key`=cogapikey),
                 body=toJSON(mydata))
print(response)

Upon printing the response variable, I get the following.

Response [https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0]
  Date: 2017-11-04 13:29
  Status: 404
  Content-Type: application/json
  Size: 54 B

I am trying to replicate the tutorial given here.
My session information is as follows

R version 3.4.0 (2017-04-21)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Sierra 10.12.6

Matrix products: default
BLAS: /System/Library/Frameworks/Accelerate.framework/Versions/A/Frameworks/vecLib.framework/Versions/A/libBLAS.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.4/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

other attached packages:
[1] RCurl_1.95-4.8      bitops_1.0-6        dplyr_0.7.4         data.table_1.10.4-3 jsonlite_1.5
[6] httr_1.3.1          tm_0.7-1            NLP_0.1-11          tidytext_0.1.4

loaded via a namespace (and not attached):
 [1] Rcpp_0.12.13      compiler_3.4.0    plyr_1.8.4        bindr_0.1         tokenizers_0.1.4  tools_3.4.0
 [7] tibble_1.3.4      nlme_3.1-131      lattice_0.20-35   pkgconfig_2.0.1   rlang_0.1.2       Matrix_1.2-9
[13] psych_1.7.8       curl_3.0          parallel_3.4.0    bindrcpp_0.2      janeaustenr_0.1.5 stringr_1.2.0
[19] grid_3.4.0        glue_1.2.0        R6_2.2.2          foreign_0.8-67    reshape2_1.4.2    tidyr_0.7.2
[25] purrr_0.2.4       magrittr_1.5      SnowballC_0.5.1   assertthat_0.2.0  mnormt_1.5-5      stringi_1.1.5
[31] slam_0.1-40       broom_0.4.2

I was wondering if there is an additional prerequisite tool/package I should install? Thank You in advance!

Body:
Seems the endpoint needs correction here. It should be:

cogapi <- "https://westcentralus.api.cognitive.microsoft.com/text/analytics/v2.0/languages"

/langauges is missing in the endpoint.


答:
try with $('select[name=rt] option:eq(2)').attr('selected', 'selected'); second option to select because first option - Select a fruit - is default selected so no any change in select

and if you select first option so use option:eq(1)

$(document).ready(function() {
  $("select#rs").on("change", function() {
    //$("#rt option:first-child").attr("selected", "selected");
    $('select[name=rt] option:eq(2)').attr('selected', 'selected');
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>
<br>
<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select></code>```

Title: How to auto-select the first option in a dropdown list using jquery?

Body:
try with $('select[name=rt] option:eq(2)').attr('selected', 'selected'); second option to select because first option - Select a fruit - is default selected so no any change in select

and if you select first option so use option:eq(1)

$(document).ready(function() {
  $("select#rs").on("change", function() {
    //$("#rt option:first-child").attr("selected", "selected");
    $('select[name=rt] option:eq(2)').attr('selected', 'selected');
  });
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>
<br>
<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select>


问:
How do I reverse each word in a sentence string like "I love computer science" using c++
I am trying to reverse each word in the sentence that I input.

For example:
Input= I love computer Science

Output = I evol retupmoc ecneicS

But this is what actually outputs with the input from above:

Output = ecneicS retupmoc evol I

I  don't know how to fix it please help. Thank you vert much.

```<code>#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     for (int i=0; i < sentence.length()/2; i++)
     {
        swap (sentence [i], sentence [sentence.length()-i-1]);
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2=temp
}
</code>```

答:
update of your code to reverse every word in a sentence:</p>

```<code>#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     int word_begin = 0;
     for (int i=0; i <=sentence.length(); i++)
     {

         if (!isalpha(sentence[i]))
         {

             for (int j = word_begin; j < (i - (i - word_begin)/2); j++)
             {
                 swap(sentence[j], sentence[i - j + word_begin - 1]);
             }

             word_begin = i + 1;
         }
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2 = temp;
}
</code>```

Body:
I am trying to reverse each word in the sentence that I input.

For example:
Input= I love computer Science

Output = I evol retupmoc ecneicS

But this is what actually outputs with the input from above:

Output = ecneicS retupmoc evol I

I  don't know how to fix it please help. Thank you vert much.

#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     for (int i=0; i < sentence.length()/2; i++)
     {
        swap (sentence [i], sentence [sentence.length()-i-1]);
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2=temp
}

Body:
update of your code to reverse every word in a sentence:

#include <iostream>
#include <string>
using namespace std;

// Prototype
void swap (char&, char&);
int main()
{

// Vars
string sentence;

// Input
cout << "Welcome to Reverse-the-words" << endl;
cout << "Enter your sentence, word, or phrase" << endl;
getline(cin,sentence);

     int word_begin = 0;
     for (int i=0; i <=sentence.length(); i++)
     {

         if (!isalpha(sentence[i]))
         {

             for (int j = word_begin; j < (i - (i - word_begin)/2); j++)
             {
                 swap(sentence[j], sentence[i - j + word_begin - 1]);
             }

             word_begin = i + 1;
         }
     }

// Output
cout << "Your phrase with all of the words reversed is " << endl;
cout << sentence << endl ;

return 0;
}

void swap(char &v1, char &v2)
{
    char temp;
    temp = v1;
    v1= v2;
    v2 = temp;
}


问:
Can we make an array containing pairs?
I am new to stl and i came across a question where it is required to store a lot of pairs having same characteristics (like:- (string,int)) together. Can we store pairs in array and if so how? Thanks in advance..</p>

答:
You can try something like:</p>

```<code>struct demo
{
  string str;
  int i;
};

std::array<demo, 5> arr;  //for fixed size array of 5 elements
std::vector<demo> vec;    //for dynamic size arrays
</code>```

Title: Can we make an array containing pairs?

Body:
You can try something like:

struct demo
{
  string str;
  int i;
};

std::array<demo, 5> arr;  //for fixed size array of 5 elements
std::vector<demo> vec;    //for dynamic size arrays


问:
What is the "*all* format in lua file:read() means?
I maintain some old code written in LUA, there are some snippet I could not understand,

```<code>    local f = io.open("someFile.lua", "r");
    local szFileContent = "return {};";
    if f then
        szFileContent = f:read("*all");
        f:close();
    end
</code>```

The format used in read function is something weird, I see the format *a, and *l in lua51 manual https://www.lua.org/manual/5.1/manual.html#pdf-file:read,
but not the *all format

答:
in the function read from  liolib.c only the first two ('*' and 'a') characters are checked, the rest of the string is ignored:</p>

```<code>// ...
const char *p = lua_tostring(L, n);
luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
switch (p[1]) {
  case 'n':  /* number */
    success = read_number(L, f);
    break;
  case 'l':  /* line */
    success = read_line(L, f);
    break;
  case 'a':  /* file */
    read_chars(L, f, ~((size_t)0));  /* read MAX_SIZE_T chars */
    success = 1; /* always success */
    break;
  default:
    return luaL_argerror(L, n, "invalid format");
 //...
</code>```

Body:
I maintain some old code written in LUA, there are some snippet I could not understand,

    local f = io.open("someFile.lua", "r");
    local szFileContent = "return {};";
    if f then
        szFileContent = f:read("*all");
        f:close();
    end

The format used in read function is something weird, I see the format *a, and *l in lua51 manual https://www.lua.org/manual/5.1/manual.html#pdf-file:read,
but not the *all format

Body:
in the function read from  liolib.c only the first two ('*' and 'a') characters are checked, the rest of the string is ignored:

// ...
const char *p = lua_tostring(L, n);
luaL_argcheck(L, p && p[0] == '*', n, "invalid option");
switch (p[1]) {
  case 'n':  /* number */
    success = read_number(L, f);
    break;
  case 'l':  /* line */
    success = read_line(L, f);
    break;
  case 'a':  /* file */
    read_chars(L, f, ~((size_t)0));  /* read MAX_SIZE_T chars */
    success = 1; /* always success */
    break;
  default:
    return luaL_argerror(L, n, "invalid format");
 //...


问:
How to use a custom Parameter with SqlDataSource
I want to add a GridView control to one of my views that is backed by a SqlDataSource. The SelectCommand query is parametrized on the aspnet_Users.UserId GUID for the currently-logged-in user, so I need a way to pass the user ID as a parameter.

I read How to utilize ASP.NET current user name in SqlParameter without code-behind and decided to create a custom Parameter named UserIdParameter:

```<code>namespace MyApp.Web
{
    public class UserIdParameter : Parameter
    {
        public UserIdParameter(string name)
            : base(name)
        {
        }

        protected UserIdParameter(UserIdParameter parameter)
            : base(parameter)
        {
        }

        protected override Parameter Clone()
        {
            return new UserIdParameter(this);
        }

        protected override object Evaluate(HttpContext context, Control control)
        {
            return Membership.GetUser().ProviderUserKey;
        }
    }
}
</code>```

In the ASPX view I then added:

```<code><%@ Register TagPrefix="my" Namespace="MyApp.Web" %>
</code>```

in a line after the <%@ Page ... %> line as well as:

```<code>    <SelectParameters>
        <my:UserIdParameter Name="UserId" />
    </SelectParameters>
</code>```

within the asp:SqlDataSource element.

Unfortunately I get a Parser Error ("An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.") with the following highlighted in red:

```<code>        <my:UserIdParameter Name="UserId" />
</code>```

Visual Web Developer 2010 Express is also informing me that "Element 'UserIdParameter' is not a known element. This can occur if there is a compilation error in the Web site, or the web.config file is missing."

Do I need to modify Web.config in some way? If not, what do I need to do to be able to use my custom UserIdParameter parameter?

答:
I figured out the problem. The custom UserIdParameter class needed to be in a separate assembly and it needed a no-arguments constructor.

The steps that worked for me were:

Create a new ASP.NET Server Control project and add it to the current solution. (I named this new project MyApp.Web.UI.WebControls).

Add the following class:

```<code>using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyApp.Web.UI.WebControls
{
    public class UserIdParameter : Parameter
    {
        public UserIdParameter()
        {
        }

        public UserIdParameter(UserIdParameter userIdParameter)
            : base(userIdParameter)
        {
        }

        protected override Parameter Clone()
        {
            return new UserIdParameter(this);
        }

        protected override object Evaluate(HttpContext context, Control control)
        {
            return Membership.GetUser().ProviderUserKey;
        }
    }
}
</code>```

Build the MyApp.Web.UI.WebControls assembly. Reference it from the ASP.NET web project (named MyApp.Web in my case).

Add to Web.config:

```<code><pages>
      <controls>
        <add tagPrefix="my" assembly="MyApp.Web.UI.WebControls" namespace="MyApp.Web.UI.WebControls"/>
      </controls>
      <!-- ... -->
</pages>
</code>```

This registers the controls library site-wide. (Note that the pages element is within the system.web element.)

Use the following in the SelectParameters element of the SqlDataSource:

```<code><my:UserIdParameter Name="UserGuid" DbType="Guid" />
</code>```

(No need for <%@ Register ... %>)

Body:
I want to add a GridView control to one of my views that is backed by a SqlDataSource. The SelectCommand query is parametrized on the aspnet_Users.UserId GUID for the currently-logged-in user, so I need a way to pass the user ID as a parameter.

I read How to utilize ASP.NET current user name in SqlParameter without code-behind and decided to create a custom Parameter named UserIdParameter:

namespace MyApp.Web
{
    public class UserIdParameter : Parameter
    {
        public UserIdParameter(string name)
            : base(name)
        {
        }

        protected UserIdParameter(UserIdParameter parameter)
            : base(parameter)
        {
        }

        protected override Parameter Clone()
        {
            return new UserIdParameter(this);
        }

        protected override object Evaluate(HttpContext context, Control control)
        {
            return Membership.GetUser().ProviderUserKey;
        }
    }
}

In the ASPX view I then added:

<%@ Register TagPrefix="my" Namespace="MyApp.Web" %>

in a line after the <%@ Page ... %> line as well as:

    <SelectParameters>
        <my:UserIdParameter Name="UserId" />
    </SelectParameters>

within the asp:SqlDataSource element.

Unfortunately I get a Parser Error ("An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.") with the following highlighted in red:

        <my:UserIdParameter Name="UserId" />

Visual Web Developer 2010 Express is also informing me that "Element 'UserIdParameter' is not a known element. This can occur if there is a compilation error in the Web site, or the web.config file is missing."

Do I need to modify Web.config in some way? If not, what do I need to do to be able to use my custom UserIdParameter parameter?

Body:
I figured out the problem. The custom UserIdParameter class needed to be in a separate assembly and it needed a no-arguments constructor.

The steps that worked for me were:

Create a new ASP.NET Server Control project and add it to the current solution. (I named this new project MyApp.Web.UI.WebControls).

Add the following class:

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace MyApp.Web.UI.WebControls
{
    public class UserIdParameter : Parameter
    {
        public UserIdParameter()
        {
        }

        public UserIdParameter(UserIdParameter userIdParameter)
            : base(userIdParameter)
        {
        }

        protected override Parameter Clone()
        {
            return new UserIdParameter(this);
        }

        protected override object Evaluate(HttpContext context, Control control)
        {
            return Membership.GetUser().ProviderUserKey;
        }
    }
}

Build the MyApp.Web.UI.WebControls assembly. Reference it from the ASP.NET web project (named MyApp.Web in my case).

Add to Web.config:

<pages>
      <controls>
        <add tagPrefix="my" assembly="MyApp.Web.UI.WebControls" namespace="MyApp.Web.UI.WebControls"/>
      </controls>
      <!-- ... -->
</pages>

This registers the controls library site-wide. (Note that the pages element is within the system.web element.)

Use the following in the SelectParameters element of the SqlDataSource:

<my:UserIdParameter Name="UserGuid" DbType="Guid" />

(No need for <%@ Register ... %>)


问:
How to print <DummyText> inside html tag using javascript?
I need to show "<>" symbols for my string "DummyText". When i run and inspect the element, it converted to be DOM element in HTML like . This is the code I am trying to do</p>

```<code><p><a href='' title='Survey Link'><DummyText></a></p>
</code>```

答:
For HTML you have to encode special characters:

<DummyText>
```

Body:
I need to show "<>" symbols for my string "DummyText". When i run and inspect the element, it converted to be DOM element in HTML like . This is the code I am trying to do

<DummyText>

Body:
For HTML you have to encode special characters:

<p><a href='' title='Survey Link'>&lt;DummyText&gt;</a></p>


问:
How can I choose randomly a drawable resource (picture) and set it as a background of a button?
I'm new with Android and StackOverflow. I accept all kind of recommendations while learning how to post correctly. My native language is not English, so please be patient if I don't write well.

I am making a game and what I have to do is to set bakcground in a specific moment of the game; 6 ramdom picture from drawable resources should be picked to set to 12 buttons I have in the UI (each one of the 6 ramdom pictures should be set to two different buttons).

What I don't know to do is how to set the images ramdonly and how to know in which button they were set. Being honest, I don't know how to start with it.

Thanks

答:
here is how you can set random images to one login button

```<code>Integer images[]={
                R.drawable.animlogo,
                R.drawable.ablogin,
                R.drawable.normalbtnbackground
        };

        Random r=new Random();
        loginbtn.setBackgroundColor(images[r.nextInt(3)]);
</code>```

hope this will work for you.

Body:
here is how you can set random images to one login button

Integer images[]={
                R.drawable.animlogo,
                R.drawable.ablogin,
                R.drawable.normalbtnbackground
        };

        Random r=new Random();
        loginbtn.setBackgroundColor(images[r.nextInt(3)]);

hope this will work for you.


答:
Instead of first-child, you need to use eq().

Below code will always auto-select first fruit whenever you select any car from the dropdown:

$("#rs").on("change", function() {
  $("#rt option:eq(1)").prop("selected", true);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>
<br>
<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select></code>```

Body:
I'm having trouble auto-selecting the first option in a dropdown list.

I've tried using attr and val function (see this jdfiddle link for an example) and it just wouldn't work. As a a test, my example has an  alert code that displays the .text() for the first option and this works fine. So my selector is working.

Thanks a lot!

sample HTML code:

<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>

<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select>

sample JS  code:

$("#rs").on("change", function() {
    alert("rt: "+$("#rt option:first-child").text());
    $("#rt option:first-child").attr("selected", "selected");
    //$("#rt option:first-child").val("blank");
});

Body:
Instead of first-child, you need to use eq().

Below code will always auto-select first fruit whenever you select any car from the dropdown:

$("#rs").on("change", function() {
  $("#rt option:eq(1)").prop("selected", true);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="rt" name="rt" style="width: 300px;">
  <option value="blank" selected="selected">- Select a fruit -</option>
  <option value="20270">Apple</option>
  <option value="20271">Banana</option>
  <option value="20273">Grapes</option>
</select>
<br>
<select id="rs" name="rs" style="width: 300px;">
  <option value="blank" selected="selected">- Select a car -</option>
  <option value="20226">Toyota</option>
  <option value="20227">Chevy</option>
  <option value="20228">Mazda</option>
</select>


问:
Different colors for different facet subgroups in R
I have the following R code to generate a twins heights plot faceted by cohort and zygosity:

```<code>heights_plot = twinData %>%
ggplot(mapping = aes(ht1, ht2)) + geom_point() + facet_grid(cohort ~ zygosity)
+ ggtitle("Cohort and Zygosity Facet Plot by Similarity")
heights_plot
</code>```

If I want to have, say, the upper left and bottom right subgroups be red and leave the others as is, how would I do this?

答:
I would probably add a flag to the dataset and then do color = flag in geom_point

```<code>twinData$flag <- ifelse((twinData$cohort == 'younger' & twinData$zygosity == 'DZOS') |
(twinData$cohort == 'older' & twinData$zygosity == 'MZFF'), 1, 0) %>%
    as.factor()

twinData %>% ggplot(mapping = aes(ht1, ht2)) +
geom_point(aes(colour = flag, fill = flag)) +
scale_fill_manual(values = c("black", "red")) +
scale_colour_manual(values = c("black", "red")) +
facet_grid(cohort ~ zygosity) +
ggtitle("Cohort and Zygosity Facet Plot by Similarity")
</code>```

You might need to flip the red and black but you should be able to utilize this code.

Body:
I have the following R code to generate a twins heights plot faceted by cohort and zygosity:

heights_plot = twinData %>%
ggplot(mapping = aes(ht1, ht2)) + geom_point() + facet_grid(cohort ~ zygosity)
+ ggtitle("Cohort and Zygosity Facet Plot by Similarity")
heights_plot

If I want to have, say, the upper left and bottom right subgroups be red and leave the others as is, how would I do this?

Body:
I would probably add a flag to the dataset and then do color = flag in geom_point

twinData$flag <- ifelse((twinData$cohort == 'younger' & twinData$zygosity == 'DZOS') |
(twinData$cohort == 'older' & twinData$zygosity == 'MZFF'), 1, 0) %>%
    as.factor()

twinData %>% ggplot(mapping = aes(ht1, ht2)) +
geom_point(aes(colour = flag, fill = flag)) +
scale_fill_manual(values = c("black", "red")) +
scale_colour_manual(values = c("black", "red")) +
facet_grid(cohort ~ zygosity) +
ggtitle("Cohort and Zygosity Facet Plot by Similarity")

You might need to flip the red and black but you should be able to utilize this code.