问:
Sending email from Spring Boot application using Gmail
I have studied the following question  and answers:
Spring Boot - Could not connect to SMTP host: smtp.gmail.com, port: 25, response: 421

I want to do the same thing - send email from a Spring Boot application using the Gmail servers.

My config is this:

```<code>spring.mail.host = smtp.gmail.com
spring.mail.username = ***@otherdomain
spring.mail.password = ***
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
spring.mail.properties.mail.smtp.ssl.enable = true
</code>```

This has been copied from the other question, only the username and password have been changed for my needs. The only different thing about my scienario as that the domain of the email address is not gmail.com.

My Email Client class is:

```<code>@Service
public class MailClient {

  @Autowired
  private JavaMailSender mailSender;

  public void prepareAndSend(String recipient, String message) {
    MimeMessagePreparator messagePreparator = mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom("me@otherdomain.org.uk");
        messageHelper.setTo(recipient);
        messageHelper.setSubject("Sample mail subject");
        messageHelper.setText(message);
    };
    mailSender.send(messagePreparator);
  }
}
</code>```

My exception is:

```<code>Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. g78sm6788965wrd.11 - gsmtp
</code>```

答:
To answer my own question in case anyone else finds it useful:

The required set of properties is this:

```<code>spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=****
spring.mail.password=****
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true
</code>```

You also need to provide the JavaMailSender yourself and set additional properties:

```<code>@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(587);

    mailSender.setUsername("***");
    mailSender.setPassword("***");

    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");

    return mailSender;
}
</code>```

Not sure why I needed to repeat the config, but that worked for me. Reference: baeldung.com

ContentLicense: CC BY-SA 4.0

Body:
I have studied the following question  and answers:
Spring Boot - Could not connect to SMTP host: smtp.gmail.com, port: 25, response: 421

I want to do the same thing - send email from a Spring Boot application using the Gmail servers.

My config is this:

spring.mail.host = smtp.gmail.com
spring.mail.username = ***@otherdomain
spring.mail.password = ***
spring.mail.properties.mail.smtp.auth = true
spring.mail.properties.mail.smtp.starttls.enable=true
spring.mail.properties.mail.smtp.socketFactory.port = 465
spring.mail.properties.mail.smtp.socketFactory.class = javax.net.ssl.SSLSocketFactory
spring.mail.properties.mail.smtp.socketFactory.fallback = false
spring.mail.properties.mail.smtp.ssl.enable = true

This has been copied from the other question, only the username and password have been changed for my needs. The only different thing about my scienario as that the domain of the email address is not gmail.com.

My Email Client class is:

@Service
public class MailClient {

  @Autowired
  private JavaMailSender mailSender;

  public void prepareAndSend(String recipient, String message) {
    MimeMessagePreparator messagePreparator = mimeMessage -> {
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage);
        messageHelper.setFrom("me@otherdomain.org.uk");
        messageHelper.setTo(recipient);
        messageHelper.setSubject("Sample mail subject");
        messageHelper.setText(message);
    };
    mailSender.send(messagePreparator);
  }
}

My exception is:

Failed message 1: com.sun.mail.smtp.SMTPSendFailedException: 530 5.7.0 Must issue a STARTTLS command first. g78sm6788965wrd.11 - gsmtp

Body:
To answer my own question in case anyone else finds it useful:

The required set of properties is this:

spring.mail.host=smtp.gmail.com
spring.mail.port=587
spring.mail.username=****
spring.mail.password=****
spring.mail.properties.mail.smtp.auth=true
spring.mail.properties.mail.smtp.starttls.enable=true

You also need to provide the JavaMailSender yourself and set additional properties:

@Bean
public JavaMailSender getJavaMailSender() {
    JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
    mailSender.setHost("smtp.gmail.com");
    mailSender.setPort(587);

    mailSender.setUsername("***");
    mailSender.setPassword("***");

    Properties props = mailSender.getJavaMailProperties();
    props.put("mail.transport.protocol", "smtp");
    props.put("mail.smtp.auth", "true");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.debug", "true");

    return mailSender;
}

Not sure why I needed to repeat the config, but that worked for me. Reference: baeldung.com


来源: stackexchange

问:
Using typings definitions in Angular2 app
I'm new to typescript and working on an Angular 2 app. I need to access some js libraries with type definitions available from definitelytyped. I installed the dependencies using typings. But can't figure out how to access them in my app components.

More specifically, say I install the angular-toastr  library:

```<code>npm install angular-toastr  --save
typings install angular-toastr  --ambient --save
</code>```

This installs the angular-toastr dependency to /typings/main/ambient/angular-toastr/angular-toastr.d.ts

I then added the reference to this to my main.d.ts file in the /typings folder.

```<code>/// <reference path="main/ambient/angular-toastr/angular-toastr.d.ts" />
</code>```

After this, I try to reference it directly in my components, but haven't quite figured out how to.

Are there any other steps I missed? And how would I import it into a component and use the methods provided?

Thanks

答:
I was experimenting the same and I was able to add two type definition files and use it successfully. So let me share what I did.

Step 1: Install npm install typings --global
Step 2: typings install dt~lodash --global --save or

use direct path from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/index.d.ts

to install.

Once installed, we need to refer the base reference file into out tsconfig.json file.

```<code>"files": [
        "typings/index.d.ts"
    ]
</code>```

Now we can start using the third party libraries as,

```<code>import * as $ from 'jquery';
import * as _ from "lodash";
</code>```

Add to any ts file where we need to use the librabry features.

And Result is,

ContentLicense: CC BY-SA 3.0

Body:
I'm new to typescript and working on an Angular 2 app. I need to access some js libraries with type definitions available from definitelytyped. I installed the dependencies using typings. But can't figure out how to access them in my app components.

More specifically, say I install the angular-toastr  library:

npm install angular-toastr  --save
typings install angular-toastr  --ambient --save

This installs the angular-toastr dependency to /typings/main/ambient/angular-toastr/angular-toastr.d.ts

I then added the reference to this to my main.d.ts file in the /typings folder.

/// <reference path="main/ambient/angular-toastr/angular-toastr.d.ts" />

After this, I try to reference it directly in my components, but haven't quite figured out how to.

Are there any other steps I missed? And how would I import it into a component and use the methods provided?

Thanks

Body:
I was experimenting the same and I was able to add two type definition files and use it successfully. So let me share what I did.

Step 1: Install npm install typings --global
Step 2: typings install dt~lodash --global --save or

use direct path from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/lodash/index.d.ts

to install.

Once installed, we need to refer the base reference file into out tsconfig.json file.

"files": [
        "typings/index.d.ts"
    ]

Now we can start using the third party libraries as,

import * as $ from 'jquery';
import * as _ from "lodash";

Add to any ts file where we need to use the librabry features.

And Result is,


问:
C# - LINQ - Sum a field from other table
I need to join two tables (Movimientos and Cuentas), group by CuentasId and make a SUM of Movimientos.Monto

Movimientos has a CuentasId to join this, and I can get the data from Cuentas but can not get the Sum.

This is my best approach, any help will be preciated, I'm a little confused with the syntax. Thanks in advance and kind regards,

```<code>          var cuentas = (from mov in _data.Movimientos
                               join ct in _data.Cuentas
                               on mov.CuentasId equals ct.CuentasId
                               where ct.IsDeleted == 0 && mov.IsDeleted == 0
                               group ct by new
                               {
                                   CuentasId = ct.CuentasId,
                                   Alias = ct.Alias,
                                   Moneda = ct.Monedas.Nombre,
                                   Signo = ct.Monedas.Signo,
                                  Banco = ct.Bancos.Nombre
                               } into ctg
                               select new
                               {
                                   Alias = ctg.Key.Alias,
                                   Moneda = ctg.Key.Moneda,
                                   Signo = ctg.Key.Signo,
                                   Banco = ctg.Key.Banco,
                                   Monto = ctg.Sum(mov.Monto)
                               }
                                ).ToList();
</code>```

答:
You need to group the value you want to sum like this

```<code>group mov.Monto by new { ..... } into ctg
</code>```

Then ctg will be a collection of mov.Monto values grouped by your list of properties of ct and you'd just call Sum on ctg in your select

```<code>Monto = ctg.Sum()
</code>```

So your new query would be

```<code>var cuentas = (from mov in _data.Movimientos
               join ct in _data.Cuentas
               on mov.CuentasId equals ct.CuentasId
               where ct.IsDeleted == 0 && mov.IsDeleted == 0
               group mov.Monto by new
               {
                   CuentasId = ct.CuentasId,
                   Alias = ct.Alias,
                   Moneda = ct.Monedas.Nombre,
                   Signo = ct.Monedas.Signo,
                   Banco = ct.Bancos.Nombre
               } into ctg
               select new
               {
                   Alias = ctg.Key.Alias,
                   Moneda = ctg.Key.Moneda,
                   Signo = ctg.Key.Signo,
                   Banco = ctg.Key.Banco,
                   Monto = ctg.Sum()
               }).ToList();
</code>```

Body:
I need to join two tables (Movimientos and Cuentas), group by CuentasId and make a SUM of Movimientos.Monto

Movimientos has a CuentasId to join this, and I can get the data from Cuentas but can not get the Sum.

This is my best approach, any help will be preciated, I'm a little confused with the syntax. Thanks in advance and kind regards,

          var cuentas = (from mov in _data.Movimientos
                               join ct in _data.Cuentas
                               on mov.CuentasId equals ct.CuentasId
                               where ct.IsDeleted == 0 && mov.IsDeleted == 0
                               group ct by new
                               {
                                   CuentasId = ct.CuentasId,
                                   Alias = ct.Alias,
                                   Moneda = ct.Monedas.Nombre,
                                   Signo = ct.Monedas.Signo,
                                  Banco = ct.Bancos.Nombre
                               } into ctg
                               select new
                               {
                                   Alias = ctg.Key.Alias,
                                   Moneda = ctg.Key.Moneda,
                                   Signo = ctg.Key.Signo,
                                   Banco = ctg.Key.Banco,
                                   Monto = ctg.Sum(mov.Monto)
                               }
                                ).ToList();

Body:
You need to group the value you want to sum like this

group mov.Monto by new { ..... } into ctg

Then ctg will be a collection of mov.Monto values grouped by your list of properties of ct and you'd just call Sum on ctg in your select

Monto = ctg.Sum()

So your new query would be

var cuentas = (from mov in _data.Movimientos
               join ct in _data.Cuentas
               on mov.CuentasId equals ct.CuentasId
               where ct.IsDeleted == 0 && mov.IsDeleted == 0
               group mov.Monto by new
               {
                   CuentasId = ct.CuentasId,
                   Alias = ct.Alias,
                   Moneda = ct.Monedas.Nombre,
                   Signo = ct.Monedas.Signo,
                   Banco = ct.Bancos.Nombre
               } into ctg
               select new
               {
                   Alias = ctg.Key.Alias,
                   Moneda = ctg.Key.Moneda,
                   Signo = ctg.Key.Signo,
                   Banco = ctg.Key.Banco,
                   Monto = ctg.Sum()
               }).ToList();


问:
Android and Lambda
I need to integrate some code with extensive usage of Java lambda functions.
Several restrictions I have demand that I develop my project using Eclipse Mars, with the latest ADT plugin, and not Android Studio.

The problem is that using Lambda functions demands using 1.8 JDK compliance, but if set so, I get this message:

```<code>Android requires compiler compliance level 5.0 or 6.0. Found '1.8' instead.
</code>```

How can the two live together in harmony?

Edit:
This is not a a duplicate of the questions suggested, as I'm asking about ADT Eclipse, and since the last update in that question, Android does support Java 8, so no only is this not a duplicate, but that question is now (after 1.5 yrs after the last update) obsolete.

答:
UPDATE: Since a few days, Android Studio 3.0 is out on stable. It officially supports a subset of Java 8 features, lambda expressions among them.

According to this Android Developers Blogpost from March 14th, 2017, google

decided to add support for Java 8 language features directly into the current javac and dx set of tools, and deprecate the Jack toolchain. With this new direction, existing tools and plugins dependent on the Java class file format should continue to work. Moving forward, Java 8 language features will be natively supported by the Android build system. We're aiming to launch this as part of Android Studio in the coming weeks, and we wanted to share this decision early with you.

So we probably won't have to wait much longer for Java 8 in Android Studio.

Title: Android and Lambda

Body:
I need to integrate some code with extensive usage of Java lambda functions.
Several restrictions I have demand that I develop my project using Eclipse Mars, with the latest ADT plugin, and not Android Studio.

The problem is that using Lambda functions demands using 1.8 JDK compliance, but if set so, I get this message:

Android requires compiler compliance level 5.0 or 6.0. Found '1.8' instead.

How can the two live together in harmony?

Edit:
This is not a a duplicate of the questions suggested, as I'm asking about ADT Eclipse, and since the last update in that question, Android does support Java 8, so no only is this not a duplicate, but that question is now (after 1.5 yrs after the last update) obsolete.


问:
matching occurrence of opposite number in a list python
I have a list such has

```<code>results = [100, 100, -100, 100, -100, -100]
</code>```

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

```<code>[0, 2], [1, 4], [3, 5]
</code>```

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

答:
This should work:</p>

```<code>results = [100, 100, -100, 100, -100, -100]

solution = []
for i, x in enumerate(results):
    if x > 0 and isinstance(x, int):
        y = results.index(-x)
        results[results.index(-x)] = 'found'
        solution.append([i,y])

print solution
</code>```

Body:
I have a list such has

results = [100, 100, -100, 100, -100, -100]

I would like to figure out the first occurrence of the opposite number. so first 100 would be match with the first -100, the second 100 would be match with the second -100.

I would like to have position as output such has:

[0, 2], [1, 4], [3, 5]

i.e : [0,2] represent the results[0] and  results[2]  where first occurrence of 100 is match with the first occurrence of -100

edit : you can assume there will always be the same amount of positive / negative and that the list will only contain 1 number

any help would be appricated

Body:
This should work:

results = [100, 100, -100, 100, -100, -100]

solution = []
for i, x in enumerate(results):
    if x > 0 and isinstance(x, int):
        y = results.index(-x)
        results[results.index(-x)] = 'found'
        solution.append([i,y])

print solution


问:
excel vba arrayformula with filtered range too long
I'm trying to apply an ArrayFormula to a filtered range - i.e. add 2 to each cell in filtered set rng and paste result into neighbor cell of rng2 - like this:

```<code> Set rng = Range("M2:M" & Cells(Rows.Count, "M").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
 Set rng2 = rng.Offset(0, 1)
 rng2.FormulaArray = "=" & rng.Address & "+ 2"
</code>```

This gives an error
"Unable to set the FormulaArray property of the Range class"

which means the string is too long (greater than 255).
rng.Address is

```<code>$M$28,$M$480,$M$874:$M$875,$M$889,$M$1111,$M$1302,$M$1410,$M$1413:$M$1415,$M$1994,$M$2319,$M$2322:$M$2323,$M$2327:$M$2329,$M$2385,$M$2884,$M$3049,$M$3130,$M$3192,$M$3242,$M$3287:$M$3288,$M$3406,$M$3418,$M$3423,$M$3610,$M$4001,$M$4008,$M$4104,$M$4145,$M$4374
</code>```

I've seen some posts using the replace formula but this may be a different case here:

rng will change in each iteration of a for loop as different filter are applied

The rng.address method does not capture all cells: I can see in the filtered excel that after $M$4374, there are more cells in this range. I used MsgBox(rng.address) to see all cells in that range... Is there a way to see all cells in that range, or is there a character cap for rng.address?

答:
This solves the problem without using ArrayFormula</p>

```<code>Set rng = Range("M2:M" & Cells(Rows.Count, "M").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
 Set rng2 = rng.Offset(0, 1)
 rng2.FormulaR1C1 = "= RC[-1] + 2"
</code>```

Body:
I'm trying to apply an ArrayFormula to a filtered range - i.e. add 2 to each cell in filtered set rng and paste result into neighbor cell of rng2 - like this:

 Set rng = Range("M2:M" & Cells(Rows.Count, "M").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
 Set rng2 = rng.Offset(0, 1)
 rng2.FormulaArray = "=" & rng.Address & "+ 2"

This gives an error
"Unable to set the FormulaArray property of the Range class"

which means the string is too long (greater than 255).
rng.Address is

$M$28,$M$480,$M$874:$M$875,$M$889,$M$1111,$M$1302,$M$1410,$M$1413:$M$1415,$M$1994,$M$2319,$M$2322:$M$2323,$M$2327:$M$2329,$M$2385,$M$2884,$M$3049,$M$3130,$M$3192,$M$3242,$M$3287:$M$3288,$M$3406,$M$3418,$M$3423,$M$3610,$M$4001,$M$4008,$M$4104,$M$4145,$M$4374

I've seen some posts using the replace formula but this may be a different case here:

rng will change in each iteration of a for loop as different filter are applied

The rng.address method does not capture all cells: I can see in the filtered excel that after $M$4374, there are more cells in this range. I used MsgBox(rng.address) to see all cells in that range... Is there a way to see all cells in that range, or is there a character cap for rng.address?

Body:
This solves the problem without using ArrayFormula

Set rng = Range("M2:M" & Cells(Rows.Count, "M").End(xlUp).Row).SpecialCells(xlCellTypeVisible)
 Set rng2 = rng.Offset(0, 1)
 rng2.FormulaR1C1 = "= RC[-1] + 2"


问:
How to get generic argument name via reflection
given generic class

```<code>class Foo<TData> { }
</code>```

and concrete type

```<code>var type = typeof(Foo<string>) //Fpp`[System.String]
var genericType = type.GetGenericTypeDefinition(); //Foo`1[TData]
</code>```

I would like to get "TData". Or the other way: Get the value of the generic argument based on generic argument name:

```<code>GetGenericArgumentType(typeof(Foo<string>), "TData") //should return System.String
</code>```

答:
Ok, based on this article: https://msdn.microsoft.com/en-us/library/system.type.getgenericparameterconstraints(v=vs.110).aspx</p>

```<code>Type def = typeof(Foo<>);
Type[] defparams = def.GetGenericArguments();
Console.WriteLine(defParams[0].Name); // writes "TData"
Console.WriteLine(defParams[0].GenericParameterPosition); // writes 0

Type concreteDef = typeof(Foo<string>)
Type[] concreteDefParams = concreteDef.GetGenericArguments();
Console.WriteLine(concreteDefParams[0].FullName); // writes "System.String"
</code>```

Body:
given generic class

class Foo<TData> { }

and concrete type

var type = typeof(Foo<string>) //Fpp`[System.String]
var genericType = type.GetGenericTypeDefinition(); //Foo`1[TData]

I would like to get "TData". Or the other way: Get the value of the generic argument based on generic argument name:

GetGenericArgumentType(typeof(Foo<string>), "TData") //should return System.String

Body:
Ok, based on this article: https://msdn.microsoft.com/en-us/library/system.type.getgenericparameterconstraints(v=vs.110).aspx

Type def = typeof(Foo<>);
Type[] defparams = def.GetGenericArguments();
Console.WriteLine(defParams[0].Name); // writes "TData"
Console.WriteLine(defParams[0].GenericParameterPosition); // writes 0

Type concreteDef = typeof(Foo<string>)
Type[] concreteDefParams = concreteDef.GetGenericArguments();
Console.WriteLine(concreteDefParams[0].FullName); // writes "System.String"


问:
Clear mailboxes using Exchange Management Shell based on AD Logon Name (SAMAccountName?)
I have a CSV containing 150 - 200 AD logon names (SAMAccountNames?) and I need to loop through each user and clear their mailboxes.

I can do that using this command

```<code>Search-Mailbox -Identity "<MailboxOrMailUserIdParameter>" -DeleteContent -force
</code>```

But the issue is that I need to be able to use the AD logon names, as I don't have the Identity?

答:
If you are importing the SamAccountName and you used that to create each alias for your mailboxes, then I would do something like this:

```<code>$names = get-content C:\path.of.csv

foreach($name in $names){
     search-mailbox -identity $name -deletecontent -force
}
</code>```

If your logon names do not match the alias of the mailbox, you need to figure out what attribute you used to populate that field.  Then, you can use the same foreach loop to iterate through your AD objects to find the right attribute.  Export that list and then try the search-mailbox using that.

Body:
I have a CSV containing 150 - 200 AD logon names (SAMAccountNames?) and I need to loop through each user and clear their mailboxes.

I can do that using this command

Search-Mailbox -Identity "<MailboxOrMailUserIdParameter>" -DeleteContent -force

But the issue is that I need to be able to use the AD logon names, as I don't have the Identity?

Body:
If you are importing the SamAccountName and you used that to create each alias for your mailboxes, then I would do something like this:

$names = get-content C:\path.of.csv

foreach($name in $names){
     search-mailbox -identity $name -deletecontent -force
}

If your logon names do not match the alias of the mailbox, you need to figure out what attribute you used to populate that field.  Then, you can use the same foreach loop to iterate through your AD objects to find the right attribute.  Export that list and then try the search-mailbox using that.


问:
how to deploy elasticsearch in predix?
I am trying to deploy elasticsearch in predix, I tried to push the downloaded elasticsearch folder into predix with the following manifest.

```<code>---
applications:
- name: elastic-search-test3
  buildpack: java_buildpack
  # path: target/elstic-search-test-1.0.0.jar
  command: elasticsearch-5.2.2/bin/elasticsearch -f
  #timeout : 180
</code>```

am getting error like port should not be hard coded, should need to use $PORT.

then I tried to set to set the port and  host in elasticsearch config as follows

```<code>http.port: ${VCAP_APP_PORT}
network.host: ${VCAP_APP_HOST}
</code>```

but no luck.

Can someone point to solution to deploy elasticsearch on predix?

答:
You should use CF_INSTANCE_* variables instead of depreciated VCAP_APP_* DEA ones on newer CF versions.

More on https://docs.cloudfoundry.org/devguide/deploy-apps/environment-variable.html

Title: how to deploy elasticsearch in predix?

Body:
I am trying to deploy elasticsearch in predix, I tried to push the downloaded elasticsearch folder into predix with the following manifest.

---
applications:
- name: elastic-search-test3
  buildpack: java_buildpack
  # path: target/elstic-search-test-1.0.0.jar
  command: elasticsearch-5.2.2/bin/elasticsearch -f
  #timeout : 180

am getting error like port should not be hard coded, should need to use $PORT.

then I tried to set to set the port and  host in elasticsearch config as follows

http.port: ${VCAP_APP_PORT}
network.host: ${VCAP_APP_HOST}

but no luck.

Can someone point to solution to deploy elasticsearch on predix?


问:
How to setup Sublime Text 3 to build script with MSYS bash?
Hi i would like to know how to setup sublime text 3 build system to execute bash script threw MSYS bash.

I have try the following build system :

```<code>{
    "cmd"       : ["bash", "$file"],
    "selector"  : "source.shell",
    "path"      : "C:/MinGW/msys/1.0/bin"
}
</code>```

It does look to work, but it can't find gcc, i have try to add multiple path this way :

```<code>    "path"      : "C:/MinGW/msys/1.0/bin:C:/MinGW/bin"
</code>```

But the C: looks to break the thing.
I have also try this :

```<code>    "path"      : ["C:/MinGW/msys/1.0/bin", "C:/MinGW/bin"]
</code>```

But it fail also as path is waiting for a string only

```<code>     "path"      :"C\:/MinGW/msys/1.0/bin:C\:/MinGW/bin"
     "path"      :"C:/MinGW/msys/1.0/bin\:C:/MinGW/bin"
     "path"      :"${C:/MinGW/msys/1.0/bin}:${C:/MinGW/bin}"
</code>```

Also fail ...

```<code>     "path"      : "/c/MinGW/msys/1.0/bin:/c/MinGW/bin"
     "path"      : "/MinGW/msys/1.0/bin:/MinGW/bin"
</code>```

Same for those ...

Any working suggestion would be greatly appreciated.

答:
To install msys bash with sublime text 3 you just have to copy this in
  a new build system:

```<code>{
    "cmd"       : ["bash", "$file"],
    "selector"  : "source.shell",

    "windows": {
        "path"  : "$path;c:\\mingw\\bin;c:\\mingw\\msys\\1.0\\bin",
        "cmd"   : ["bash", "--login", "-i", "-c", "cd \"$file_path\"; \"$file\""]
    },

    "osx": {
        "path"  : "$PATH:/usr/local/bin:/usr/X11R6/bin:/opt/X11/bin:/usr/texbin"
    }
}
</code>```

thanks to macite :

https://github.com/macite/sublimebashbuildsystem/blob/master/Bash.sublime-build

Body:
Hi i would like to know how to setup sublime text 3 build system to execute bash script threw MSYS bash.

I have try the following build system :

{
    "cmd"       : ["bash", "$file"],
    "selector"  : "source.shell",
    "path"      : "C:/MinGW/msys/1.0/bin"
}

It does look to work, but it can't find gcc, i have try to add multiple path this way :

    "path"      : "C:/MinGW/msys/1.0/bin:C:/MinGW/bin"

But the C: looks to break the thing.
I have also try this :

    "path"      : ["C:/MinGW/msys/1.0/bin", "C:/MinGW/bin"]

But it fail also as path is waiting for a string only

     "path"      :"C\:/MinGW/msys/1.0/bin:C\:/MinGW/bin"
     "path"      :"C:/MinGW/msys/1.0/bin\:C:/MinGW/bin"
     "path"      :"${C:/MinGW/msys/1.0/bin}:${C:/MinGW/bin}"

Also fail ...

     "path"      : "/c/MinGW/msys/1.0/bin:/c/MinGW/bin"
     "path"      : "/MinGW/msys/1.0/bin:/MinGW/bin"

Same for those ...

Any working suggestion would be greatly appreciated.

Body:
To install msys bash with sublime text 3 you just have to copy this in
  a new build system:

{
    "cmd"       : ["bash", "$file"],
    "selector"  : "source.shell",

    "windows": {
        "path"  : "$path;c:\\mingw\\bin;c:\\mingw\\msys\\1.0\\bin",
        "cmd"   : ["bash", "--login", "-i", "-c", "cd \"$file_path\"; \"$file\""]
    },

    "osx": {
        "path"  : "$PATH:/usr/local/bin:/usr/X11R6/bin:/opt/X11/bin:/usr/texbin"
    }
}

thanks to macite :

https://github.com/macite/sublimebashbuildsystem/blob/master/Bash.sublime-build


问:
how to select values from 3 tables + count()
I have three Tables :

```<code>tbl_Publisher [Publisher_ID, addr,account-num,...,city];
tbl_Title [Title_ID, frequency, publisher,.., Publisher_ID];
tbl_Invoice [Invoice_ID, ordered_Date,...,Title_ID];
</code>```

I would like to return a list of Titles by Publisher and each Title has the count number of Invoices it contains. in one result set.
I'm using a stored procedure as following :

```<code>PROCEDURE [dbo].[usp_GetTitlesbyPublisher]
    -- Add the parameters for the stored procedure here
    @PublisherID INT

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.

    -- Insert statements for procedure here
    SELECT Title_ID,TitleName,pub_type,Frequency , Holdings ,tbl_Title.publisher ,section ,tbl_Title.Publisher_ID  from tbl_Title, tbl_Publisher
    where tbl_Title.Publisher_ID = tbl_Publisher.Publisher_ID
    and @PublisherID = tbl_Publisher.Publisher_ID

END
</code>```

How can I return the number of Invoice by each Title ?

答:
You can probably accomplish this with a GROUP BY:

```<code>SELECT  t.Title_ID, t.TitleName, p.pub_type,
        t.Frequency, Holdings, t.publisher, section,
        t.Publisher_ID, count(i.Invoice_ID) as NoOfInvoices
from tbl_Title t
inner join tbl_Publisher p on t.Publisher_ID = p.Publisher_ID
left join tbl_Invoice i  on i.Title_ID = t.Title_ID
where @PublisherID = p.Publisher_ID
group by t.Title_ID, t.TitleName, p.pub_type, t.Frequency,
        Holdings, t.publisher, section, t.Publisher_ID
</code>```

Body:
I have three Tables :

tbl_Publisher [Publisher_ID, addr,account-num,...,city];
tbl_Title [Title_ID, frequency, publisher,.., Publisher_ID];
tbl_Invoice [Invoice_ID, ordered_Date,...,Title_ID];

I would like to return a list of Titles by Publisher and each Title has the count number of Invoices it contains. in one result set.
I'm using a stored procedure as following :

PROCEDURE [dbo].[usp_GetTitlesbyPublisher]
    -- Add the parameters for the stored procedure here
    @PublisherID INT

AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.

    -- Insert statements for procedure here
    SELECT Title_ID,TitleName,pub_type,Frequency , Holdings ,tbl_Title.publisher ,section ,tbl_Title.Publisher_ID  from tbl_Title, tbl_Publisher
    where tbl_Title.Publisher_ID = tbl_Publisher.Publisher_ID
    and @PublisherID = tbl_Publisher.Publisher_ID

END

How can I return the number of Invoice by each Title ?

Body:
You can probably accomplish this with a GROUP BY:

SELECT  t.Title_ID, t.TitleName, p.pub_type,
        t.Frequency, Holdings, t.publisher, section,
        t.Publisher_ID, count(i.Invoice_ID) as NoOfInvoices
from tbl_Title t
inner join tbl_Publisher p on t.Publisher_ID = p.Publisher_ID
left join tbl_Invoice i  on i.Title_ID = t.Title_ID
where @PublisherID = p.Publisher_ID
group by t.Title_ID, t.TitleName, p.pub_type, t.Frequency,
        Holdings, t.publisher, section, t.Publisher_ID


问:
Why point closeness is differing from scatter plot to hexbin plot?
Please look at Hexbin and scatterplots: http://imgur.com/a/2oR68

Why in Hexbinplot, points donot touch each other whereas in scatterplot it clearly touches the close points ?

I expected my hexbin plot comes up like this: https://bl.ocks.org/mbostock/4248145 but it didnot.

I am using d3.hexbin plugin.

The only code that is differing from Hexbin plot to scatter plot (I am dealing with same dataset) apart from little bit of scaling is:

For Hexbin:

```<code> var color = d3.scale.linear()
                .range(["white", "steelblue"])
                .interpolate(d3.interpolateLab);

var hexbin = d3.hexbin()
               .extent([[0,0],[size - padding , padding]])
               .radius();

hexbin.x(function(d,i){return x(subdata[0][i]);})
hexbin.y(function(d,i){return y(subdata[0][i]);})

svg.append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("class", "mesh")
    .attr("width", w)
    .attr("height", size);

svg.append("g")
    .attr("clip-path", "url(#clip)")
    .selectAll(".hexagon")
    .data(hexbin(datum))
    .enter()
    .append("path")
    .attr("class", "hexagon")
    .attr("d", hexbin.hexagon())
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
    .style("fill", function(d) { return color(d.length); });
</code>```

For scatterplot:

```<code> svg.selectAll("circle")
.data(datum)
.enter()
.append("circle")
.style("fill", "steelblue")
.attr("cx", function (d, i) {
    return x(subdata[0][i]);
})
.attr("cy", function (d,i) {
    return y(subdata[0][i]);
})
.attr("r", 3)
</code>```

Where am i doing wrong ?

Edit1: Included some fraction of code under Hexbin

答:
If you set...

```<code>.attr("d", hexbin.hexagon(5))
//radius value here ------^
</code>```

..., the hexagons will touch only if you set the same value in the hexabin generator:

```<code>var hexbin = d3.hexbin()
    .radius(5)//same value here
    .extent([[0, 0], [width, height]]);
</code>```

According to your result, I believe that was not the case. Thus, the solution can be simply removing that value:

```<code>.attr("d", hexbin.hexagon())
//no radius here --------^
</code>```

Body:
Please look at Hexbin and scatterplots: http://imgur.com/a/2oR68

Why in Hexbinplot, points donot touch each other whereas in scatterplot it clearly touches the close points ?

I expected my hexbin plot comes up like this: https://bl.ocks.org/mbostock/4248145 but it didnot.

I am using d3.hexbin plugin.

The only code that is differing from Hexbin plot to scatter plot (I am dealing with same dataset) apart from little bit of scaling is:

For Hexbin:

 var color = d3.scale.linear()
                .range(["white", "steelblue"])
                .interpolate(d3.interpolateLab);

var hexbin = d3.hexbin()
               .extent([[0,0],[size - padding , padding]])
               .radius();

hexbin.x(function(d,i){return x(subdata[0][i]);})
hexbin.y(function(d,i){return y(subdata[0][i]);})

svg.append("clipPath")
    .attr("id", "clip")
    .append("rect")
    .attr("class", "mesh")
    .attr("width", w)
    .attr("height", size);

svg.append("g")
    .attr("clip-path", "url(#clip)")
    .selectAll(".hexagon")
    .data(hexbin(datum))
    .enter()
    .append("path")
    .attr("class", "hexagon")
    .attr("d", hexbin.hexagon())
    .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
    .style("fill", function(d) { return color(d.length); });

For scatterplot:

 svg.selectAll("circle")
.data(datum)
.enter()
.append("circle")
.style("fill", "steelblue")
.attr("cx", function (d, i) {
    return x(subdata[0][i]);
})
.attr("cy", function (d,i) {
    return y(subdata[0][i]);
})
.attr("r", 3)

Where am i doing wrong ?

Edit1: Included some fraction of code under Hexbin

Body:
If you set...

.attr("d", hexbin.hexagon(5))
//radius value here ------^

..., the hexagons will touch only if you set the same value in the hexabin generator:

var hexbin = d3.hexbin()
    .radius(5)//same value here
    .extent([[0, 0], [width, height]]);

According to your result, I believe that was not the case. Thus, the solution can be simply removing that value:

.attr("d", hexbin.hexagon())
//no radius here --------^


问:
Coq makefile "Top." Prefix
I am using the automatic Coq 8.5 makefile generator. This makefile prefixes all modules by "Top." .
Now let's say you run a lot of files by make and then want to change/debug some file in the IDE.
Then the annoying fact is that Coq complains it cannot find the compiled other files, because in the IDE  it assumes the names without the "Top" prefix.
I tried to tweak the makefile to get rid of this prefix. But I always ended in some error message of the make.
Can someone show me either how to remove "Top" prefix in make or tell the IDE to use the "Top" prefix.</p>

答:
This is annoying indeed. In order to avoid that kind of annoyance, always start your _CoqProject with a line listing options:

```<code>-Q . MyProject
</code>```

To note: the options you can put on the first line of your _CoqProject are the ones listed when calling coqtop -help.

Title: Coq makefile "Top." Prefix

Body:
This is annoying indeed. In order to avoid that kind of annoyance, always start your _CoqProject with a line listing options:

-Q . MyProject

To note: the options you can put on the first line of your _CoqProject are the ones listed when calling coqtop -help.


问:
Angular2: Component declared in shared module not usable in App module
I have two shared modules Core and MasterData.

I am facing issue to use MasterData module's components in my applcation though i can use Core Module's Components. Following is my code.

Core Module (core.module.ts)

```<code>import { NgModule, ModuleWithProviders, ComponentFactoryResolver } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import {
    IgHierarchicalGridComponent,
    IgPivotGridComponent,
    IgGridComponent
} from 'igniteui-angular2';

import { CacheModule } from 'angular2-cache';
import { AUTH_PROVIDERS } from 'angular2-jwt';

import { CoreComponents, EntryCoreComponents } from './components';
import { CoreService } from './services';

import { ClientInfoServiceProvider } from './client-info';

import { AuthGuard } from './guards/auth.guard';

const IgniteuiComponents = [
    IgHierarchicalGridComponent,
    IgPivotGridComponent,
    IgGridComponent
];

@NgModule({
    declarations: [
        ...CoreComponents,
        ...IgniteuiComponents
    ],
    providers: [
        ...CoreService,
        AUTH_PROVIDERS,
        AuthGuard,
        ClientInfoServiceProvider
    ],
    imports: [
        CommonModule,
        FormsModule,
        RouterModule,
        HttpModule,
        CacheModule,
    ],
    entryComponents: [
        ...EntryCoreComponents
    ],
    exports: [
        HttpModule,
        CacheModule,
        RouterModule,
        FormsModule,
        ...CoreComponents,
        ...IgniteuiComponents
    ]
})
export class CoreModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: QmsCoreModule,
            providers: [
                ...CoreService,
                AUTH_PROVIDERS,
                AuthGuard,
                ClientInfoServiceProvider
            ]
        };
    }
}
</code>```

Master Data Module (which is inheriting Core because I use infragistics library in core and masterdata components) (masterdata.module.ts)

```<code>import { NgModule, ModuleWithProviders, ComponentFactoryResolver } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { QmsCoreModule } from 'qms/core/qms-core.module';

import { MasterdataComponents } from './components';
import { MasterdataServices } from './services';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        RouterModule,
        HttpModule,
        QmsCoreModule.forRoot()
    ],
    declarations: [
        ...MasterdataComponents
    ],
    providers: [
        ...MasterdataServices
    ],
    exports: [
        FormsModule,
        RouterModule,
        HttpModule,
        QmsCoreModule,
        ...MasterdataComponents
    ]
})
export class QmsMasterdataModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: QmsMasterdataModule,
            providers: [
                ...MasterdataServices
            ]
        };
    }
}
</code>```

Master data Module has currently only one component name TeamGrid. (Component Selector is ‘team-grid’)

Main Application AppModule (app.module.ts)

```<code>import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Provider } from '@angular/core';
import { QmsMasterdataModule } from 'qms/masterdata/qms-masterdata.module';
import { SwacProxyInterface } from 'qms/core/swac';

import { AppRoutingModule } from './app-routing.module';
import { HomeModule } from './home/home.module';
import { ProjectModule } from './project/project.module';

import { AppComponent } from './app.component';

import { SharedServices } from './shared/services';

export const AppModule = (proxyInterface: SwacProxyInterface, provider: Provider[]) => {

  @NgModule({
    declarations: [
      AppComponent
    ],
    imports: [
      BrowserModule,
      AppRoutingModule,
      HomeModule,
      ProjectModule,
      QmsMasterdataModule.forRoot()
    ],
    providers: [
      SharedServices,
      ...provider
    ],
    bootstrap: [AppComponent]
  })

  class AppModule {
  }

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

Error message is:

'team-grid' is not a known element:
  1. If 'team-grid' is an Angular component, then verify that it is part of this module.
  2. If 'team-grid' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
  ("

```<code>    [ERROR ->]<team-grid></team-grid>
</code>```

Can someone help me to find the correct solution for this?

答: Above Implementation is correct but only mistake is that each modules (Home.module / Project.module) under App.module should also import masterdata.module or core.module as per required compoenents.</p>

Body:
I have two shared modules Core and MasterData.

I am facing issue to use MasterData module's components in my applcation though i can use Core Module's Components. Following is my code.

Core Module (core.module.ts)

import { NgModule, ModuleWithProviders, ComponentFactoryResolver } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import {
    IgHierarchicalGridComponent,
    IgPivotGridComponent,
    IgGridComponent
} from 'igniteui-angular2';

import { CacheModule } from 'angular2-cache';
import { AUTH_PROVIDERS } from 'angular2-jwt';

import { CoreComponents, EntryCoreComponents } from './components';
import { CoreService } from './services';

import { ClientInfoServiceProvider } from './client-info';

import { AuthGuard } from './guards/auth.guard';

const IgniteuiComponents = [
    IgHierarchicalGridComponent,
    IgPivotGridComponent,
    IgGridComponent
];

@NgModule({
    declarations: [
        ...CoreComponents,
        ...IgniteuiComponents
    ],
    providers: [
        ...CoreService,
        AUTH_PROVIDERS,
        AuthGuard,
        ClientInfoServiceProvider
    ],
    imports: [
        CommonModule,
        FormsModule,
        RouterModule,
        HttpModule,
        CacheModule,
    ],
    entryComponents: [
        ...EntryCoreComponents
    ],
    exports: [
        HttpModule,
        CacheModule,
        RouterModule,
        FormsModule,
        ...CoreComponents,
        ...IgniteuiComponents
    ]
})
export class CoreModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: QmsCoreModule,
            providers: [
                ...CoreService,
                AUTH_PROVIDERS,
                AuthGuard,
                ClientInfoServiceProvider
            ]
        };
    }
}

Master Data Module (which is inheriting Core because I use infragistics library in core and masterdata components) (masterdata.module.ts)

import { NgModule, ModuleWithProviders, ComponentFactoryResolver } from '@angular/core';
import { CommonModule } from '@angular/common';
import { RouterModule } from '@angular/router';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { QmsCoreModule } from 'qms/core/qms-core.module';

import { MasterdataComponents } from './components';
import { MasterdataServices } from './services';

@NgModule({
    imports: [
        CommonModule,
        FormsModule,
        RouterModule,
        HttpModule,
        QmsCoreModule.forRoot()
    ],
    declarations: [
        ...MasterdataComponents
    ],
    providers: [
        ...MasterdataServices
    ],
    exports: [
        FormsModule,
        RouterModule,
        HttpModule,
        QmsCoreModule,
        ...MasterdataComponents
    ]
})
export class QmsMasterdataModule {
    static forRoot(): ModuleWithProviders {
        return {
            ngModule: QmsMasterdataModule,
            providers: [
                ...MasterdataServices
            ]
        };
    }
}

Master data Module has currently only one component name TeamGrid. (Component Selector is ‘team-grid’)

Main Application AppModule (app.module.ts)

import { BrowserModule } from '@angular/platform-browser';
import { NgModule, Provider } from '@angular/core';
import { QmsMasterdataModule } from 'qms/masterdata/qms-masterdata.module';
import { SwacProxyInterface } from 'qms/core/swac';

import { AppRoutingModule } from './app-routing.module';
import { HomeModule } from './home/home.module';
import { ProjectModule } from './project/project.module';

import { AppComponent } from './app.component';

import { SharedServices } from './shared/services';

export const AppModule = (proxyInterface: SwacProxyInterface, provider: Provider[]) => {

  @NgModule({
    declarations: [
      AppComponent
    ],
    imports: [
      BrowserModule,
      AppRoutingModule,
      HomeModule,
      ProjectModule,
      QmsMasterdataModule.forRoot()
    ],
    providers: [
      SharedServices,
      ...provider
    ],
    bootstrap: [AppComponent]
  })

  class AppModule {
  }

  return AppModule;
};

Error message is:

'team-grid' is not a known element:
  1. If 'team-grid' is an Angular component, then verify that it is part of this module.
  2. If 'team-grid' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
  ("

    [ERROR ->]<team-grid></team-grid>

Can someone help me to find the correct solution for this?


问:
Hide or show div based on children's content
After trial and error with many solutions found on SO for hiding and displaying content using jquery based on textarea content I have ended up with a piece of script that nearly does what I want. I'm doing this in MVC 5, though I don't think that any consequence for this dilemma.

I have an edit page which has many optional text areas that can either be empty or have some text, these come from a database. What I wish to do is to hide them by default if they contain no text. They are grouped and they are toggleable with a click of the description text above them.

This is how I have them grouped, displaying one area:

```<code>    <div class="togglerDesc">
    <p class="pointerToggler"><strong>XXX description</strong></p>
        <div class="hiddenContainer">
            <div class="optionalArea">
                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p1, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p1, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p1, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p2, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p2, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p2, "", new { @class = "text-danger" })
                    </div>
                </div>

                <div class="form-group">
                    @Html.LabelFor(model => model.Q1p3, htmlAttributes: new { @class = "control-label col-md-1" })
                    <div class="col-md-10">
                        @Html.TextAreaFor(model => model.Q1p3, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p3, "", new { @class = "text-danger" })
                    </div>
                </div>
            </div>
        </div>
    </div>
</code>```

And the script I have is:

```<code>$(document).ready(function () {
        if (!$.trim($(".optionalArea textarea").val()).length < 1) {
            $(".optionalArea textarea").parents(".hiddenContainer").show();
        }
});
</code>```

Now this works just fine if the immediate text area, Q1p1 in my example has text in it. However if it is empty it does not show the div even if the two other textareas have text in them. It does seem my problem here is that the script is not taking all of the divs into account and only checks the first one. How could I change it so it takes all of the text areas within .optionalArea into account?

答:
You're gonna need .each because .val only takes the value from the first one

So something like this:

```<code>$(document).ready(function () {
    $(".optionalArea textarea").each(function(){ // loops through all elements selected
        if (!$.trim($(this).val()).length < 1) {
             $(this).parents(".hiddenContainer").show();
             return false; // this breaks the loop as soon as 1 textarea has value
        }
    });
});
</code>```

Body:
After trial and error with many solutions found on SO for hiding and displaying content using jquery based on textarea content I have ended up with a piece of script that nearly does what I want. I'm doing this in MVC 5, though I don't think that any consequence for this dilemma.

I have an edit page which has many optional text areas that can either be empty or have some text, these come from a database. What I wish to do is to hide them by default if they contain no text. They are grouped and they are toggleable with a click of the description text above them.

This is how I have them grouped, displaying one area:

XXX description

                    @Html.LabelFor(model => model.Q1p1, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p1, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p1, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Q1p2, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p2, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p2, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Q1p3, htmlAttributes: new { @class = "control-label col-md-1" })

                        @Html.TextAreaFor(model => model.Q1p3, new { @class = "form-control", @rows = "2", @style = "width:90%;max-width:100%;" })
                        @Html.ValidationMessageFor(model => model.Q1p3, "", new { @class = "text-danger" })

And the script I have is:

$(document).ready(function () {
        if (!$.trim($(".optionalArea textarea").val()).length < 1) {
            $(".optionalArea textarea").parents(".hiddenContainer").show();
        }
});

Now this works just fine if the immediate text area, Q1p1 in my example has text in it. However if it is empty it does not show the div even if the two other textareas have text in them. It does seem my problem here is that the script is not taking all of the divs into account and only checks the first one. How could I change it so it takes all of the text areas within .optionalArea into account?

Body:
You're gonna need .each because .val only takes the value from the first one

So something like this:

$(document).ready(function () {
    $(".optionalArea textarea").each(function(){ // loops through all elements selected
        if (!$.trim($(this).val()).length < 1) {
             $(this).parents(".hiddenContainer").show();
             return false; // this breaks the loop as soon as 1 textarea has value
        }
    });
});


问:
c++ save and load game with pointers in structs
I know I can use:

```<code>MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
</code>```

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

答: Try game.serialize(out);. In your serialize member function call serialize of your pointer members.

ContentLicense: CC BY-SA 2.5

Body:
I know I can use:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?


问:
Emulate shell command line in C
I want to emulate the following shell command line in C, with execl():

```<code>find . -type f -ls | cut -d " " -f 3- | sort -n -k 6 >file.txt ; less <file.txt
</code>```

I wrote each of them as:

```<code>execl("/usr/bin/find", "find", ".", "-type", "f", "-ls", (char *)NULL);
execl("/usr/bin/cut", "cut", "-d", "" "", "-f", "3-", (char *)NULL);
execl("/usr/bin/sort", "sort", "-n", "-k", "6", ">file.txt", (char *)NULL);
execl("/usr/bin/less", "less", "<file.txt", (char *)NULL);
</code>```

I also implemented the pipelines but I am getting an error:

```<code>cut: cut: -: Input/Output error -: Input/output error
</code>```

Any idea what it means?
Thanks

答:
All redirections, be them pipes (|) or redirection to files (<, <<, >, >>, etc.) are only processed by the shell. When you pass them in an execx call, they are simply passed as an additional argument to the new program.

And anyway, execl replaces the original program by the new one, so anything after execl in never executed unless execl returned an error. The correct way is to setup pipes for the inter process communications, fork to get the number of processes, redirect standard io to the pipes, and only then exec the new programs.

Title: Emulate shell command line in C

Body:
I want to emulate the following shell command line in C, with execl():

find . -type f -ls | cut -d " " -f 3- | sort -n -k 6 >file.txt ; less <file.txt

I wrote each of them as:

execl("/usr/bin/find", "find", ".", "-type", "f", "-ls", (char *)NULL);
execl("/usr/bin/cut", "cut", "-d", "" "", "-f", "3-", (char *)NULL);
execl("/usr/bin/sort", "sort", "-n", "-k", "6", ">file.txt", (char *)NULL);
execl("/usr/bin/less", "less", "<file.txt", (char *)NULL);

I also implemented the pipelines but I am getting an error:

cut: cut: -: Input/Output error -: Input/output error

Any idea what it means?
Thanks


问:
How to limit the number of characters accepted by textInput in Shiny app
I would like my Shiny app (in R) to limit the number of characters a user can input in response to a textInput command.

I can request the user to limit to 50 characters and can have the app send him a message if he does not, but it would be better if he were prevented from overrunning the limit in the first place.

Suggestions appreciated.

答:
You can't add custom attribute to textInput, you could probably be able to write custom function to generate input, but it will be easier to do this in javascript:</p>

```<code>shinyjs::runjs("$('#inputName').attr('maxlength', 50)")
</code>```

Body:
You can't add custom attribute to textInput, you could probably be able to write custom function to generate input, but it will be easier to do this in javascript:

shinyjs::runjs("$('#inputName').attr('maxlength', 50)")


问:
Access google container registry without the gcloud client
I have a CoreOS docker host that I want to start running containers on, but when trying to use the docker command to fetch the image from the google container private registry (https://cloud.google.com/tools/container-registry/), I get a 403. I did some searching, but I'm not sure how to attach authentication (or where to generate the user+pass bundle to use with the docker login command).

Has anybody had any luck pulling from the google private containers? I can't install the gcloud command because coreos doesn't come with python, which is a requirement

```<code>docker run -p 80:80 gcr.io/prj_name/image_name
Unable to find image 'gcr.io/prj_name/image_name:latest' locally
Pulling repository gcr.io/prj_name/image_name
FATA[0000] HTTP code: 403
</code>```

Update: after getting answers from @mattmoor and @Jesse:

The machine that I'm pulling from does have devaccess

```<code>curl -H 'Metadata-Flavor: Google' http://metadata.google.internal./computeMetadata/v1/instance/service-accounts/default/scopes
https://www.googleapis.com/auth/bigquery
https://www.googleapis.com/auth/cloud-platform
https://www.googleapis.com/auth/compute
https://www.googleapis.com/auth/datastore
----> https://www.googleapis.com/auth/devstorage.read_only
https://www.googleapis.com/auth/logging.admin
https://www.googleapis.com/auth/sqlservice.admin
https://www.googleapis.com/auth/taskqueue
https://www.googleapis.com/auth/userinfo.email
</code>```

Additionally, I tried using the _token login method

```<code>jenkins@riskjenkins:/home/andre$ ACCESS_TOKEN=$(curl -H 'Metadata-Flavor: Google' 'http://metadata.google.internal./computeMetadata/v1/instance/service-accounts/default/token' | cut -d'"' -f 4)
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   142  100   142    0     0  14686      0 --:--:-- --:--:-- --:--:-- 15777
jenkins@riskjenkins:/home/andre$ echo $ACCESS_TOKEN
**************(redacted, but looks valid)
jenkins@riskjenkins:/home/andre$ docker login -e not@val.id -u _token -p $ACCESS_TOKEN http://gcr.io
Login Succeeded
jenkins@riskjenkins:/home/andre$ docker run gcr.io/prj_name/image_name
Unable to find image 'gcr.io/prj_name/image_name:latest' locally
Pulling repository gcr.io/prj_name/image_name
FATA[0000] HTTP code: 403
</code>```

答:
There are two official ways:

$ docker login -e 1234@5678.com -u oauth2accesstoken -p "$(gcloud auth print-access-token)" https://gcr.io

$ docker login -e 1234@5678.com -u _json_key -p "$JSON_KEY" https://gcr.io

Note: The e-mail is not used, so you can put whatever you want in it.

Change gcr.io to whatever is your domain shown in your Google Container Registry (e.g. eu.gcr.io).

Option (1) only gives a temporary token, so you probably want option (2). To get that $JSON_KEY:

Go to API Manager > Credentials

Click "Create credentials" > Service account key:

Service account: New service account

Name: Anything you want, like Docker Registry (read-only)

Role: Storage (scroll down) > Storage Object Viewer

Key type: JSON

Download as keyfile.json

JSON_KEY=$(cat keyfile.json | tr '\n' ' ')

Now you can use it.

Once logged in you can just run docker pull. You can also copy the updated ~/.dockercfg to preserve the settings.

Body:
I have a CoreOS docker host that I want to start running containers on, but when trying to use the docker command to fetch the image from the google container private registry (https://cloud.google.com/tools/container-registry/), I get a 403. I did some searching, but I'm not sure how to attach authentication (or where to generate the user+pass bundle to use with the docker login command).

Has anybody had any luck pulling from the google private containers? I can't install the gcloud command because coreos doesn't come with python, which is a requirement

docker run -p 80:80 gcr.io/prj_name/image_name
Unable to find image 'gcr.io/prj_name/image_name:latest' locally
Pulling repository gcr.io/prj_name/image_name
FATA[0000] HTTP code: 403

Update: after getting answers from @mattmoor and @Jesse:

The machine that I'm pulling from does have devaccess

curl -H 'Metadata-Flavor: Google' http://metadata.google.internal./computeMetadata/v1/instance/service-accounts/default/scopes
https://www.googleapis.com/auth/bigquery
https://www.googleapis.com/auth/cloud-platform
https://www.googleapis.com/auth/compute
https://www.googleapis.com/auth/datastore
----> https://www.googleapis.com/auth/devstorage.read_only
https://www.googleapis.com/auth/logging.admin
https://www.googleapis.com/auth/sqlservice.admin
https://www.googleapis.com/auth/taskqueue
https://www.googleapis.com/auth/userinfo.email

Additionally, I tried using the _token login method

jenkins@riskjenkins:/home/andre$ ACCESS_TOKEN=$(curl -H 'Metadata-Flavor: Google' 'http://metadata.google.internal./computeMetadata/v1/instance/service-accounts/default/token' | cut -d'"' -f 4)
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100   142  100   142    0     0  14686      0 --:--:-- --:--:-- --:--:-- 15777
jenkins@riskjenkins:/home/andre$ echo $ACCESS_TOKEN
**************(redacted, but looks valid)
jenkins@riskjenkins:/home/andre$ docker login -e not@val.id -u _token -p $ACCESS_TOKEN http://gcr.io
Login Succeeded
jenkins@riskjenkins:/home/andre$ docker run gcr.io/prj_name/image_name
Unable to find image 'gcr.io/prj_name/image_name:latest' locally
Pulling repository gcr.io/prj_name/image_name
FATA[0000] HTTP code: 403


问:
Retrieve property value from include'd / import'ed project
I am trying to use ant's include or import tasks to use a common build file. I am stuck at retrieving properties from included file.

These are my non-working samples, trying to retrieve "child-property"

Using ant import

parent file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="parent" basedir=".">
    <import file="child.xml" />
    <target name="parent-target">
        <antcall target="child-target" />
        <echo message="(From Parent) ${child-property}" />
    </target>
</project>
</code>```

child file

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="child" basedir=".">
    <target name="child-target">
        <property name="child-property" value="i am child value" />
        <echo message="(From Child) ${child-property}" />
    </target>
</project>
</code>```

output

```<code>parent-target:

child-target:
     [echo] (From Child) i am child value
     [echo] (From Parent) ${child-property}
</code>```

Using ant include

parent file

```<code><project name="parent" basedir=".">
    <include file="child.xml" />
    <target name="parent-target">
        <antcall target="child.child-target" />
        <echo message="(From Parent) ${child-property}" />
        <echo message="(From Parent2) ${child.child-property}" />
    </target>
</project>
</code>```

child file

same as above

output

```<code>parent-target:

child.child-target:
     [echo] (From Child) i am child value
     [echo] (From Parent) ${child-property}
     [echo] (From Parent2) ${child.child-property}
</code>```

How can I access "child-property" from parent?

答:
It is a different approach but you may use macrodef.

parent.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="parent" basedir=".">
<import file="child.xml"/>
<target name="parent-target">
    <child-macro myid="test"/>
    <echo message="(From Parent) ${child-property}" />
</target>
</code>```

child.xml

```<code><?xml version="1.0" encoding="UTF-8"?>
<project name="child" basedir=".">
<macrodef name="child-macro">
    <attribute name="myid" default=""/>
    <sequential>
        <property name="child-property" value="i am child value" />
        <echo message="(From Child) ${child-property}" />
        <echo message="Received params: myId=@{myid}"/>
    </sequential>
</macrodef>
</project>
</code>```

output

```<code>parent-target:
 [echo] (From Child) i am child value
 [echo] Received params: myId=test
 [echo] (From Parent) i am child value
</code>```

Body:
I am trying to use ant's include or import tasks to use a common build file. I am stuck at retrieving properties from included file.

These are my non-working samples, trying to retrieve "child-property"

Using ant import

parent file

<?xml version="1.0" encoding="UTF-8"?>
<project name="parent" basedir=".">
    <import file="child.xml" />
    <target name="parent-target">
        <antcall target="child-target" />
        <echo message="(From Parent) ${child-property}" />
    </target>
</project>

child file

<?xml version="1.0" encoding="UTF-8"?>
<project name="child" basedir=".">
    <target name="child-target">
        <property name="child-property" value="i am child value" />
        <echo message="(From Child) ${child-property}" />
    </target>
</project>

output

parent-target:

child-target:
     [echo] (From Child) i am child value
     [echo] (From Parent) ${child-property}

Using ant include

parent file

<project name="parent" basedir=".">
    <include file="child.xml" />
    <target name="parent-target">
        <antcall target="child.child-target" />
        <echo message="(From Parent) ${child-property}" />
        <echo message="(From Parent2) ${child.child-property}" />
    </target>
</project>

child file

same as above

output

parent-target:

child.child-target:
     [echo] (From Child) i am child value
     [echo] (From Parent) ${child-property}
     [echo] (From Parent2) ${child.child-property}

How can I access "child-property" from parent?

Body:
It is a different approach but you may use macrodef.

parent.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="parent" basedir=".">
<import file="child.xml"/>
<target name="parent-target">
    <child-macro myid="test"/>
    <echo message="(From Parent) ${child-property}" />
</target>

child.xml

<?xml version="1.0" encoding="UTF-8"?>
<project name="child" basedir=".">
<macrodef name="child-macro">
    <attribute name="myid" default=""/>
    <sequential>
        <property name="child-property" value="i am child value" />
        <echo message="(From Child) ${child-property}" />
        <echo message="Received params: myId=@{myid}"/>
    </sequential>
</macrodef>
</project>

output

parent-target:
 [echo] (From Child) i am child value
 [echo] Received params: myId=test
 [echo] (From Parent) i am child value


问:
Java: Method that returns either String or int
A part of a small program I am coding:

```<code>String maxs = "";
int maxi = 0;
</code>```

At this part I defined two variables as int and String.

```<code>public Class(String max){
   try {
           this.maxi = Integer.parseInt(max);
       }catch (Exception e){
           this.maxs = max;
       }
}
</code>```

I think this way I will get to define one of both variables, if the String does not parse to int it will be saved as normal String.

Now I need to check what I need to return:

```<code>private TypeOfReturn getMax(){
    if(this.maxi == 0){
        // return maxs (return String)
    } else if (this.maxs.equals("")) {
        // return maxi (return int)
    } else return null;
}
</code>```

The quastion is, how do I fill the missing parts of the method getMax()?

Is it even possiable in Java?

答:
Make your TypeOfReturn as String object type and convert the maxi as String  and return that String in your else if condition.

Note:  you cannot return both the  int and String in the Same method.

Body:
A part of a small program I am coding:

String maxs = "";
int maxi = 0;

At this part I defined two variables as int and String.

public Class(String max){
   try {
           this.maxi = Integer.parseInt(max);
       }catch (Exception e){
           this.maxs = max;
       }
}

I think this way I will get to define one of both variables, if the String does not parse to int it will be saved as normal String.

Now I need to check what I need to return:

private TypeOfReturn getMax(){
    if(this.maxi == 0){
        // return maxs (return String)
    } else if (this.maxs.equals("")) {
        // return maxi (return int)
    } else return null;
}

The quastion is, how do I fill the missing parts of the method getMax()?

Is it even possiable in Java?


问:
Javascript setTimeout function call with event argument?
What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

```<code>function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}
</code>```

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

答:
You could use a curry function, there is one for jQuery here.

Generally, you would have this:

```<code>function foo(a, b)
{
    alert(a + b);
}

var bar = curry(foo, 1);

bar(2); // alerts 3, as if you had called foo(1, 2)
</code>```

so you could do:

```<code>setTimeout(curry(checkPos, e), 500);
</code>```

Since curry returns a function with it's first argument bound to e, you can pass it straight into setTimeout.

Body:
What is the best way to pull in the event object when using setTimeout? I'm using jQuery to handle normalizing the event model in all browsers, but I'm not sure how to get the 'e' object in to the checkPos function.

My current code:

function MouseDownEvent(e) {
    *snip*
    timeoutID = setTimeout(checkPos(e), 500);
}
function checkPos(e) {
    //function uses e on a timeout of 500ms
    timeoutID = setTimeout( checkPos(e) }, 500);
}

Currently that code works once because the function is called in the mousedown event, but never updates the e object as the user moves the mouse. The FF javascript error console also declares that it is 'a useless setTimeout call (missing quotes around argument?)', but following that advice causes it to completely fail.

How can I pull in the 'e' event argument from a setTimeout call?

Edit: Added in the code that reruns the checkPos function every 500ms

Body:
You could use a curry function, there is one for jQuery here.

Generally, you would have this:

function foo(a, b)
{
    alert(a + b);
}

var bar = curry(foo, 1);

bar(2); // alerts 3, as if you had called foo(1, 2)

so you could do:

setTimeout(curry(checkPos, e), 500);

Since curry returns a function with it's first argument bound to e, you can pass it straight into setTimeout.


问:
App crashes randomly on viewWillDisappear()
I'm new to Swift, and I find some strange crashes in my app.

The Fabric reports said crashes occurred in viewWillDisappear().

I have two ViewControllers.User tap button in A viewcontroller then they move to B viewcontroller to input something, they user go back, and A get information from B.

I use a delegate to complete this task.

B:

```<code>class LessonNameTagTableViewController: UITableViewController {

...

var delegate:PassingData?

override func viewWillDisappear(_ animated: Bool) {

    lessonName = (tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.viewWithTag(1) as! UITextField ).text!

    delegate?.changeLessonNameTag(name: lessonName, tag: tagColor)
    super.viewWillDisappear(animated)

}
...
}
</code>```

A:

```<code>class LessonEditTableViewController: UITableViewController,PassingData {
var lesson :Lesson?
...
func changeLessonNameTag(name:String,tag:UIColor){
    self.lesson!.lessonName = name
    self.lesson!.lessonTagColor = tag
    tableView.reloadData()

}
...
}
</code>```

The crash happened randomly, I've tested it on my device, and nothing happened.But others said they could repeat this crashes.

I wonder whether I'm using delegate right or it's caused by other reasons.

答:
You probably have a problem in you viewWillDisappear, there's many optionals there that can cause you trouble when you force-unwrap.

It's better to be crash safe:

```<code>override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if let lessonName = (tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.viewWithTag(1) as? UITextField)?.text {
        delegate?.changeLessonNameTag(name: lessonName, tag: tagColor)
    }
}
</code>```

Body:
I'm new to Swift, and I find some strange crashes in my app.

The Fabric reports said crashes occurred in viewWillDisappear().

I have two ViewControllers.User tap button in A viewcontroller then they move to B viewcontroller to input something, they user go back, and A get information from B.

I use a delegate to complete this task.

B:

class LessonNameTagTableViewController: UITableViewController {

...

var delegate:PassingData?

override func viewWillDisappear(_ animated: Bool) {

    lessonName = (tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.viewWithTag(1) as! UITextField ).text!

    delegate?.changeLessonNameTag(name: lessonName, tag: tagColor)
    super.viewWillDisappear(animated)

}
...
}

A:

class LessonEditTableViewController: UITableViewController,PassingData {
var lesson :Lesson?
...
func changeLessonNameTag(name:String,tag:UIColor){
    self.lesson!.lessonName = name
    self.lesson!.lessonTagColor = tag
    tableView.reloadData()

}
...
}

The crash happened randomly, I've tested it on my device, and nothing happened.But others said they could repeat this crashes.

I wonder whether I'm using delegate right or it's caused by other reasons.

Body:
You probably have a problem in you viewWillDisappear, there's many optionals there that can cause you trouble when you force-unwrap.

It's better to be crash safe:

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)

    if let lessonName = (tableView.cellForRow(at: IndexPath(row: 0, section: 0))?.viewWithTag(1) as? UITextField)?.text {
        delegate?.changeLessonNameTag(name: lessonName, tag: tagColor)
    }
}