问:
How To send attachments with email in php
I have email content with data=> name, email, phone , description and attachment.
I am able send the email with all the data to email. But what I want is , Actually I want to send attachments to the email content. But in my code I just sending the links to the email content. But If I click on that links it is not downloading. I need to send attachments to the email and also when I click on that it should download. How to resolve this. Plese somebody help me.

Below is code,

```<code>$name = $this->request->post['name'];
$email = $this->request->post['email'];
$description = $this->request->post['description'];
$phone = $this->request->post['phone'];
$upload_base_dir="image/service-images/";
$upload_time_dir=time(); // setup directory name
$upload_dir = $upload_base_dir.$upload_time_dir;

if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0775, true);  //create directory if not exist
}
foreach($_FILES['attachment']['error'] as $k=>$v)
{
$uploadfile = $_FILES['attachment']['name'][$k];
move_uploaded_file($_FILES['attachment']['tmp_name'][$k],$upload_dir."/".$uploadfile);
$subject = 'Service Request';

$email_header ='<html style="color: rgb(34, 34, 34); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: -webkit-auto; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); max-width: 575px; line-height: 18px; font-size: 12px; font-family: Arial, Helvetica, sans-serif;"><head><meta name="viewport" content="width=device-width" /><meta http-equiv="content-type" content="text/html; charset=UTF-8"></head><body bgcolor="#FFFFFF" text="#000000"  style="color: rgb(34, 34, 34); font-style: normal; font-variant: normal; font-weight: normal; letter-spacing: normal; orphans: 2; text-align: -webkit-auto; text-indent: 0px; text-transform: none; white-space: normal; widows: 2; word-spacing: 0px; -webkit-text-size-adjust: auto; -webkit-text-stroke-width: 0px; background-color: rgb(255, 255, 255); max-width: 575px; line-height: 18px; font-size: 12px; font-family: Arial, Helvetica, sans-serif;"><table style="font-family:Helvetica,Arial,sans-serif;background:#EFEDED;" cellpadding="0" cellspacing="0" bgcolor="#EFEDED" border="0" width="100%"><tbody><tr><td align="center"><table width="96%" cellpadding="0" cellspacing="0"border="0"><tbody><tr><td style="border-top:5px solid #1e96d3; background:#fff;margin:0; padding:20px; border-spacing:0px;">';

$email_footer = '</td></tr><tr><td style="margin:0; padding:15px 0;"><table style="font-family:Arial, Helvetica,sans-serif;font-size:11px;color:#999999;" cellpadding="0" cellspacing="0" border="0" width="100%"><tbody> <tr>
<td style="font-family:Arial, Helvetica,sans-serif; margin:0; font-size:11px; padding:8px 0 0 0;">This email was intended for Inf. </td></tr><tr>
<td style="font-family:Arial, Helvetica,sans-serif; margin:0; font-size:11px; padding:8px 0 0 0;"></td></tr></tbody></table></td></tr></tbody></table></td>
</tr></tbody></table></body></html>';

$body = $email_header.'<table width="100%" cellpadding="0" cellspacing="0"><tr>
<td style="margin:0; padding:0px 0px 15px 0px; border-spacing:0px;">
<p style="font-size:14px; color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-weight: bold; line-height: 1.5em; margin: 0px; padding: 0.4em; text-align: left;">'.$subject.'</p></td></tr><tr><td style="margin:0; padding:0px 0px 15px 0px; border-spacing:0px;"><p style="color:#000; font-size:13px; margin:0; font-family:Arial, Helvetica,sans-serif;"><strong>Dear Sir/Madam,</strong><br></p></td></tr><tr><td style="margin:0; padding:0 0 5px 0;"><p style="font-size:13px; background-color: rgb(234, 234, 234); color: rgb(0, 0, 0); font-family: Arial, Helvetica, sans-serif; font-weight: bold; line-height: 1.5em; margin: 0px; padding: 0.4em; text-align: left;">Details:</p></td></tr><tr><td style="margin:0; padding:0px 0px 15px 0px; border-spacing:0px;"><table style="font-family:Helvetica,Arial,sans-serif; font-size:12px; font-weight:bold; margin-top:10px; width:100%"><tbody>
<tr><td style="padding:4px 0;">Name</td>
<td>:</td><td style="font-weight:normal;">'.$name.'</td></tr>
<tr><td style="padding:4px 0;">Email Address</td>
<td>:</td><td style="font-weight:normal;">'.$email.'</td></tr>
<tr><td style="padding:4px 0;">Phone</td><td>:</td><td style="font-weight:normal;">'.$phone.'</td></tr>
<tr><td style="padding:4px 0;">Description</td><td>:</td><td style="font-weight:normal;">'.$description.'</td></tr>
<tr><td style="padding:4px 0;">Attachments</td><td>:</td><td style="font-weight:normal;">';
foreach($_FILES['attachment']['error'] as $k=>$v)
{
$uploadfile = $_FILES['attachment']['name'][$k];

move_uploaded_file($_FILES['attachment']['tmp_name'][$k],$upload_dir."/".$uploadfile);
$images[] = $_FILES['attachment']['name'][$k];
$count=0;
foreach($images as $image){
$count++;
}
if($_SERVER['HTTP_HOST'] == "localhost"){
$body .= '<a href='.'localhost'."/inf/".$upload_dir."/".$image.' download>Attachment'.$count.'</a>    ';
}
if($_SERVER['HTTP_HOST'] == "192.168.1.156"){
$body .= '<a href='.'192.168.1.156'."/inf/".$upload_dir."/".$image.' download>Attachment'.$count.'</a>    ';
}
if($_SERVER['HTTP_HOST'] == "floretmedia.net"){
$body .= '<a href='."http://floretmedia.net/temp"."/inf/".$upload_dir."/".$image' download>'.$image.'</a>    ';
}
if($_SERVER['HTTP_HOST'] == "www.arbour.in" || $_SERVER['HTTP_HOST'] == "arbour.in"){
$body .= '<a href='.'http://www.arbour.in'."/".$upload_dir."/".$image.' download>Attachment'.$count.'</a>    ';
}
}
$body .= '</td></tr></tbody></table></td></tr></table>'.$email_footer.'';

//echo $body;die;

$mail = new Mail($this->config->get('config_mail'));
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($email);
$mail->setSender($name);
$mail->setSubject($subject);
$mail->setHtml($body);
$mail->send();
</code>```

答:
you can attach the file to the body like this</p>

```<code>$body .= '</td></tr></tbody></table></td></tr></table>'.$email_footer.'';

$filename = 'myfile';
$path = 'your path goes here';
$file = $path . "/" . $filename;

$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));

$body .= $content . "\r\n";

// send the mail

$mail = new Mail($this->config->get('config_mail'));
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($email);
$mail->setSender($name);
$mail->setSubject($subject);
$mail->setHtml($body);
$mail->send();
</code>```

Body:
I have email content with data=> name, email, phone , description and attachment.
I am able send the email with all the data to email. But what I want is , Actually I want to send attachments to the email content. But in my code I just sending the links to the email content. But If I click on that links it is not downloading. I need to send attachments to the email and also when I click on that it should download. How to resolve this. Plese somebody help me.

Below is code,

$name = $this->request->post['name'];
$email = $this->request->post['email'];
$description = $this->request->post['description'];
$phone = $this->request->post['phone'];
$upload_base_dir="image/service-images/";
$upload_time_dir=time(); // setup directory name
$upload_dir = $upload_base_dir.$upload_time_dir;

if (!file_exists($upload_dir)) {
mkdir($upload_dir, 0775, true);  //create directory if not exist
}
foreach($_FILES['attachment']['error'] as $k=>$v)
{
$uploadfile = $_FILES['attachment']['name'][$k];
move_uploaded_file($_FILES['attachment']['tmp_name'][$k],$upload_dir."/".$uploadfile);
$subject = 'Service Request';

$email_header ='<meta name="viewport" content="width=device-width" /><meta http-equiv="content-type" content="text/html; charset=UTF-8">

';

$email_footer = '

This email was intended for Inf.

';

$body = $email_header.'

'.$subject.'

Dear Sir/Madam,

Details:

Name
:	'.$name.'

Email Address
:	'.$email.'

Phone	:	'.$phone.'

Description	:	'.$description.'

Attachments	:	';
foreach($_FILES['attachment']['error'] as $k=>$v)
{
$uploadfile = $_FILES['attachment']['name'][$k];

move_uploaded_file($_FILES['attachment']['tmp_name'][$k],$upload_dir."/".$uploadfile);
$images[] = $_FILES['attachment']['name'][$k];
$count=0;
foreach($images as $image){
$count++;
}
if($_SERVER['HTTP_HOST'] == "localhost"){
$body .= 'Attachment'.$count.'    ';
}
if($_SERVER['HTTP_HOST'] == "192.168.1.156"){
$body .= 'Attachment'.$count.'    ';
}
if($_SERVER['HTTP_HOST'] == "floretmedia.net"){
$body .= ''.$image.'    ';
}
if($_SERVER['HTTP_HOST'] == "www.arbour.in" || $_SERVER['HTTP_HOST'] == "arbour.in"){
$body .= 'Attachment'.$count.'    ';
}
}
$body .= '

'.$email_footer.'';

//echo $body;die;

$mail = new Mail($this->config->get('config_mail'));
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($email);
$mail->setSender($name);
$mail->setSubject($subject);
$mail->setHtml($body);
$mail->send();

Body:
you can attach the file to the body like this

$body .= '</td></tr></tbody></table></td></tr></table>'.$email_footer.'';

$filename = 'myfile';
$path = 'your path goes here';
$file = $path . "/" . $filename;

$content = file_get_contents($file);
$content = chunk_split(base64_encode($content));

$body .= $content . "\r\n";

// send the mail

$mail = new Mail($this->config->get('config_mail'));
$mail->setTo($this->config->get('config_email'));
$mail->setFrom($email);
$mail->setSender($name);
$mail->setSubject($subject);
$mail->setHtml($body);
$mail->send();


来源: stackexchange

问:
Update Query takes only one row as value - Access 2000?
I am unable to understand why my Update Query takes only the value in the last row and puts it in all other, in the same column.

Here are pictures:

So, I need to calculate percent(PBrojProdPoTip), given BrojProdPoTip and VkBrojProdPoTip which is the sum.

```<code>PBrojProdPoTip = BrojProdPoTip * 100 / VkBrojProdPoTip
</code>```

If you try the last value, 244 out of 18248 gives 01.34%

```<code>P = 244 * 100 / 18248 = 1.34%
</code>```

What do I do wrong? Why it takes only one value?

答:
You have a Cartesian (multiplying) query.

It probably updates using all of the values of VkBrojProdPoTip. However, each one overwrites the previous one, thus you only see the last update.

ContentLicense: CC BY-SA 3.0

Body:
I am unable to understand why my Update Query takes only the value in the last row and puts it in all other, in the same column.

Here are pictures:

So, I need to calculate percent(PBrojProdPoTip), given BrojProdPoTip and VkBrojProdPoTip which is the sum.

PBrojProdPoTip = BrojProdPoTip * 100 / VkBrojProdPoTip

If you try the last value, 244 out of 18248 gives 01.34%

P = 244 * 100 / 18248 = 1.34%

What do I do wrong? Why it takes only one value?


问:
Behaviour of threads with combination of synchronized methods in a class

Case 1

I have 2 synchronized methods as shown below:

```<code>class A {
    public void synchronized methodA() {}
    public void synchronized methodB() {}
}
</code>```

A: I have threads T1 and T2. Can the threads simultaneously executemethodA and methodB (respectively) belonging to the same instance of class A?

My analysis: The answer is no because only one method will be executed by thread T1 and thread T2 will be blocked until T1 finishes execution.

B: I have threads T1 and T2. Can the threads simultaneously execute methodA and methodB (respectively) belonging to different instances of class A?

My analysis: The answer is yes because T1 and T2 can execute methodA and methodB belonging to different instances of class A and they will not be blocked.

Is my understanding correct as per my analysis for case 1?

Update: Case 2

I have 2 synchronized methods, one is non static and the other is static.

```<code>class A {
    public void synchronized methodA() {}
    public void static synchronized methodB() {}
}
</code>```

A: I have threads T1 and T2.  Can the threads simultaneously execute methodA and  methodB (respectively) belonging to the same instance of class A?

My analysis: The answer is no because only one method will be executed by T1 and T2 will be blocked until T1 finishes execution.

B: I have threads T1 and T2. Can the threads simultaneously execute methodA and methodB (respectively) belonging to different instances of class A?

My analysis: The answer is yes because T1 and T2 can execute methodA and methodB belonging to different instances and they will not be blocked.

Is my understanding correct as per my analysis for case 2?

答:
Case A: No

Case B: Yes

Your analysis is correct.  A synchronized keyword on an instance method is functionally equivalent to this:

```<code>public void someMethod() {
   synchronized(this) {
      //code
   }
}
</code>```

Since this is different in the two contexts, they are not mutually exclusive.  Note that even the same method could be called at the same time for two different instances.

Edit

For case 2, you are incorrect on 2A; it doesn't even make sense.  A static synchronized method does not "belong" to an instance of the class; if it did it wouldn't be static!  It doesn't synchronize on any instance of the class (it has no reference to an instance to synchronize on!) so it instead synchronizes on the class object of A.  A static synchronized method in class A is equivalent to this:

```<code>public static void methodB() {
   synchronized (A.class) {
      //code
   }
}
</code>```

Your instance method will synchronize on the instance as I've shown above, so the two threads can run in parallel.

In case B then, obviously they also can run in parallel but you're still missing the fundamental concept that a static method is not associated with any instance.

ContentLicense: CC BY-SA 2.5

Body:
Case 1

I have 2 synchronized methods as shown below:

class A {
    public void synchronized methodA() {}
    public void synchronized methodB() {}
}

A: I have threads T1 and T2. Can the threads simultaneously executemethodA and methodB (respectively) belonging to the same instance of class A?

My analysis: The answer is no because only one method will be executed by thread T1 and thread T2 will be blocked until T1 finishes execution.

B: I have threads T1 and T2. Can the threads simultaneously execute methodA and methodB (respectively) belonging to different instances of class A?

My analysis: The answer is yes because T1 and T2 can execute methodA and methodB belonging to different instances of class A and they will not be blocked.

Is my understanding correct as per my analysis for case 1?

Update: Case 2

I have 2 synchronized methods, one is non static and the other is static.

class A {
    public void synchronized methodA() {}
    public void static synchronized methodB() {}
}

A: I have threads T1 and T2.  Can the threads simultaneously execute methodA and  methodB (respectively) belonging to the same instance of class A?

My analysis: The answer is no because only one method will be executed by T1 and T2 will be blocked until T1 finishes execution.

B: I have threads T1 and T2. Can the threads simultaneously execute methodA and methodB (respectively) belonging to different instances of class A?

My analysis: The answer is yes because T1 and T2 can execute methodA and methodB belonging to different instances and they will not be blocked.

Is my understanding correct as per my analysis for case 2?

Body:
Case A: No

Case B: Yes

Your analysis is correct.  A synchronized keyword on an instance method is functionally equivalent to this:

public void someMethod() {
   synchronized(this) {
      //code
   }
}

Since this is different in the two contexts, they are not mutually exclusive.  Note that even the same method could be called at the same time for two different instances.

Edit

For case 2, you are incorrect on 2A; it doesn't even make sense.  A static synchronized method does not "belong" to an instance of the class; if it did it wouldn't be static!  It doesn't synchronize on any instance of the class (it has no reference to an instance to synchronize on!) so it instead synchronizes on the class object of A.  A static synchronized method in class A is equivalent to this:

public static void methodB() {
   synchronized (A.class) {
      //code
   }
}

Your instance method will synchronize on the instance as I've shown above, so the two threads can run in parallel.

In case B then, obviously they also can run in parallel but you're still missing the fundamental concept that a static method is not associated with any instance.


问:
Casting an object to List<T> to be able to use extension methods
I have generated an extension method to display a IList<T> in a meaningful manner:

```<code>public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}
</code>```

To use this extension I can do this:

```<code>IList<someClass> myList = CreateList();
myList.ToDisplay();
</code>```

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

```<code>public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}
</code>```

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

答:
If you look into the List T definition on MSDN, you can observe that it actually inherits a non-generic IList interface.

So you can use this to check if your object is implementing this interface. Any List will implement IList.

This implies one thing, remove the generic parameter from your ToDisplay method.

Also, you can use the is keyword to check that your object is in the inheritance tree (ref here).

Note, to use it, you must add using System.Collections;

```<code>public static class IListExtension
{
  public static string ToDisplay(this IList source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}

public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element is Ilist)
    return (element as IList).ToDisplay();

  return element.ToString();
}
</code>```

Body:
I have generated an extension method to display a IList<T> in a meaningful manner:

public static class IListExtension
{
  public static string ToDisplay<T>(this IList<T> source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}

To use this extension I can do this:

IList<someClass> myList = CreateList();
myList.ToDisplay();

My problem is now, that I have a method that gets an object, which also can be a list. So, if the object is no list, I want to use the ToString() method, if it IS a list, I want to use my extension.

public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element as IList<T> != null)
    return (element as IList<T>).ToDisplay();

  return element.ToString();
}

Obviously, the code above does not work, because I cannot cast to the generic IList<T>. If I use an existing class, like IList<string> it works for lists of strings like I want it to, but of course I don't want to create a statement for each possible IList<[name of class]>. Is there a way to use the extension method or any other means to get a custom string from a list of any type?

Body:
If you look into the List T definition on MSDN, you can observe that it actually inherits a non-generic IList interface.

So you can use this to check if your object is implementing this interface. Any List will implement IList.

This implies one thing, remove the generic parameter from your ToDisplay method.

Also, you can use the is keyword to check that your object is in the inheritance tree (ref here).

Note, to use it, you must add using System.Collections;

public static class IListExtension
{
  public static string ToDisplay(this IList source, string seperator = ",")
  {
    string display = string.Empty;
    // create the display string from the elements of this list
    return display;
  }
}

public string CreateDisplayString(object element)
{
  if (element == null)
    return string.Empty;

  if (element is Ilist)
    return (element as IList).ToDisplay();

  return element.ToString();
}


答: Long, long time since I've used an Access Query Design to do this, but I am sure your problem is that you have created no relationships between the three tables. As a result all the fields in the target table are updated with all the answers from your calculation.  In practice they end up all getting the last value calculated.  Instead you need to create links between the tables, which you can do by drag and drop.</p>

Title: Update Query takes only one row as value - Access 2000?


问:
How to split a string into two parts then join them in reverse order as a new string?
This is an example:

```<code>$str="this is string 1 / 4w";
$str=preg_replace(?); var_dump($str);
</code>```

I want to capture 1 / 4w in this string and move this portion to the begin of string.

Result: 1/4W this is string

Just give me the variable that contains the capture.

The last portion 1 /  4W may be different.

e.g.  1 / 4w can be 1/ 16W , 1 /2W , 1W , or 2w

The character W may be an upper case or a lower case.

答:
Without seeing some different sample inputs, it seems as though there are no numbers in the first substring.  For this reason, I use a negated character class to capture the first substring, leave out the delimiting space, and then capture the rest of the string as the second substring.  This makes my pattern very efficient (6x faster than Toto's and with no linger white-space characters).

Pattern Demo

Code:

```<code>$str="this is string 1 / 4w";
$str=preg_replace('/([^\d]+) (.*)/',"$2 $1",$str);
var_export($str);
</code>```

Output:

```<code>'1 / 4w this is string'
</code>```

Body:
This is an example:

$str="this is string 1 / 4w";
$str=preg_replace(?); var_dump($str);

I want to capture 1 / 4w in this string and move this portion to the begin of string.

Result: 1/4W this is string

Just give me the variable that contains the capture.

The last portion 1 /  4W may be different.

e.g.  1 / 4w can be 1/ 16W , 1 /2W , 1W , or 2w

The character W may be an upper case or a lower case.

Body:
Without seeing some different sample inputs, it seems as though there are no numbers in the first substring.  For this reason, I use a negated character class to capture the first substring, leave out the delimiting space, and then capture the rest of the string as the second substring.  This makes my pattern very efficient (6x faster than Toto's and with no linger white-space characters).

Pattern Demo

Code:

$str="this is string 1 / 4w";
$str=preg_replace('/([^\d]+) (.*)/',"$2 $1",$str);
var_export($str);

Output:

'1 / 4w this is string'


问:
Path to django on google app engine
I completely don't understand this error. I use django-nonrel, upload it to my application by manage.py. And sometimes I have this:

```<code><type 'exceptions.AttributeError'>: 'Settings' object has no attribute 'DATABASE_ROUTERS'
Traceback (most recent call last):
File "/base/data/home/apps/appid/3.347077242893060339/execute.py", line 2, in <module>
  from djapp import queue_controller
File "/base/data/home/apps/appid/3.347077242893060339/djapp/queue_controller.py", line 5, in <module>
  from djapp.models import Operation
File "/base/data/home/apps/appid/3.347077242893060339/djapp/models.py", line 3, in <module>
  from django.db import models
File "/base/data/home/apps/appid/3.347077242893060339/django/db/__init__.py", line 66, in <module>
  router = ConnectionRouter(settings.DATABASE_ROUTERS)
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/conf/__init__.py", line 32, in __getattr__
  return getattr(self._target, name)
</code>```

or

```<code><type 'exceptions.ImportError'>: No module named files.uploadhandler
Traceback (most recent call last):
File "/base/data/home/apps/appid/3.347067228745038183/djangoappengine/main/main.py", line 28, in <module>
  from django.core.handlers.wsgi import WSGIHandler
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/handlers/wsgi.py", line 1, in <module>
  from django.core.handlers.base import BaseHandler
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/handlers/base.py", line 3, in <module>
  from django import http
File "/base/data/home/apps/appid/3.347067228745038183/django/http/__init__.py", line 28, in <module>
  from django.http.multipartparser import MultiPartParser
File "/base/data/home/apps/appid/3.347067228745038183/django/http/multipartparser.py", line 14, in <module>
  from django.core.files.uploadhandler import StopUpload, SkipFile, StopFutureHandlers
</code>```

What is wrong with the path? Why does this happen? At first the path is "/base/data/home/apps/app-id/3.347046818251769742/django/", then it is "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/".

And how to avoid this error?

I have checked sys.path, uploaded new django several times, removed all unnecessary files, I am lost :(

```<code>sys.path = ['/base/data/home/apps/appid/3.347077364008022180',
'/base/data/home/apps/appid/3.347077364008022180/djangoappengine/lib',
'/base/python_runtime/python_dist/lib/python25.zip',
'/base/python_runtime/python_dist/lib/python2.5/',
'/base/python_runtime/python_dist/lib/python2.5/plat-linux2',
'/base/python_runtime/python_dist/lib/python2.5/lib-tk',
'/base/python_runtime/python_dist/lib/python2.5/lib-dynload',
'/base/python_runtime/python_lib/versions/1',
'/base/data/home/apps/appid/3.347077364008022180/']
</code>```

答:
I guess that db/__init__.py does something like from django.conf import Settings, and for whatever reason, it's sometimes being given the system's version of Django rather than your own.

You could try changing it to use a relative import, like from ..conf import Settings, which should mean it uses the version in the same package as itself. That works from Python 2.5, which is what Appengine uses.

Title: Path to django on google app engine

Body:
I completely don't understand this error. I use django-nonrel, upload it to my application by manage.py. And sometimes I have this:

<type 'exceptions.AttributeError'>: 'Settings' object has no attribute 'DATABASE_ROUTERS'
Traceback (most recent call last):
File "/base/data/home/apps/appid/3.347077242893060339/execute.py", line 2, in <module>
  from djapp import queue_controller
File "/base/data/home/apps/appid/3.347077242893060339/djapp/queue_controller.py", line 5, in <module>
  from djapp.models import Operation
File "/base/data/home/apps/appid/3.347077242893060339/djapp/models.py", line 3, in <module>
  from django.db import models
File "/base/data/home/apps/appid/3.347077242893060339/django/db/__init__.py", line 66, in <module>
  router = ConnectionRouter(settings.DATABASE_ROUTERS)
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/conf/__init__.py", line 32, in __getattr__
  return getattr(self._target, name)

or

<type 'exceptions.ImportError'>: No module named files.uploadhandler
Traceback (most recent call last):
File "/base/data/home/apps/appid/3.347067228745038183/djangoappengine/main/main.py", line 28, in <module>
  from django.core.handlers.wsgi import WSGIHandler
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/handlers/wsgi.py", line 1, in <module>
  from django.core.handlers.base import BaseHandler
File "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/handlers/base.py", line 3, in <module>
  from django import http
File "/base/data/home/apps/appid/3.347067228745038183/django/http/__init__.py", line 28, in <module>
  from django.http.multipartparser import MultiPartParser
File "/base/data/home/apps/appid/3.347067228745038183/django/http/multipartparser.py", line 14, in <module>
  from django.core.files.uploadhandler import StopUpload, SkipFile, StopFutureHandlers

What is wrong with the path? Why does this happen? At first the path is "/base/data/home/apps/app-id/3.347046818251769742/django/", then it is "/base/python_runtime/python_lib/versions/third_party/django-0.96/django/".

And how to avoid this error?

I have checked sys.path, uploaded new django several times, removed all unnecessary files, I am lost :(

sys.path = ['/base/data/home/apps/appid/3.347077364008022180',
'/base/data/home/apps/appid/3.347077364008022180/djangoappengine/lib',
'/base/python_runtime/python_dist/lib/python25.zip',
'/base/python_runtime/python_dist/lib/python2.5/',
'/base/python_runtime/python_dist/lib/python2.5/plat-linux2',
'/base/python_runtime/python_dist/lib/python2.5/lib-tk',
'/base/python_runtime/python_dist/lib/python2.5/lib-dynload',
'/base/python_runtime/python_lib/versions/1',
'/base/data/home/apps/appid/3.347077364008022180/']


问:
django template / File name too long error/ when getting models objects
I am getting an error which lokks like this:

```<code>IOError at /url/
[Errno 36] File name too long: "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/templates/

    <user_prefs: user_prefs object>,<user_prefs: user_prefs object>,<user_prefs: user_prefs object> etc..
</code>```

my views.py look like this

```<code>def show_interests(request):
    current_user = request.user.id
    output = user_prefs()
    output.save()
    outputs = user_prefs.objects.all().filter(userID=current_user)
    return render('showme.html',{'outputs':outputs})
</code>```

and my template( i use a very basic html form just to test things as for now.)

```<code><!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8">
    <title>Hi, it's a test</title>
    {% for outputs in output %}
    {{ outputs.Cuisine }}
    {{ outputs.Cuisine1 }}
    {{ outputs.LunchPref }}
    {{ outputs.DinnerPref }}
    {{ outputs.Friday }}
    {{ outputs.Sunday }}
    {% endfor %}
<body>

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

Never ever seen an error like this, and my other models that i have work just fine.

答:
```<code>return render(request, 'showme.html',{'outputs':outputs})
</code>```

you missed the request parameter in the render and its mandatory

and also change this in your template

```<code>{% for output in outputs %}
    {{ output.Cuisine }}
    {{ output.Cuisine1 }}
    {{ output.LunchPref }}
    {{ output.DinnerPref }}
    {{ output.Friday }}
    {{ output.Sunday }}
{% endfor %}
</code>```

Body:
I am getting an error which lokks like this:

IOError at /url/
[Errno 36] File name too long: "/app/.heroku/python/lib/python2.7/site-packages/django/contrib/admin/templates/

    <user_prefs: user_prefs object>,<user_prefs: user_prefs object>,<user_prefs: user_prefs object> etc..

my views.py look like this

def show_interests(request):
    current_user = request.user.id
    output = user_prefs()
    output.save()
    outputs = user_prefs.objects.all().filter(userID=current_user)
    return render('showme.html',{'outputs':outputs})

and my template( i use a very basic html form just to test things as for now.)

<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Hi, it's a test</title>
    {% for outputs in output %}
    {{ outputs.Cuisine }}
    {{ outputs.Cuisine1 }}
    {{ outputs.LunchPref }}
    {{ outputs.DinnerPref }}
    {{ outputs.Friday }}
    {{ outputs.Sunday }}
    {% endfor %}

Never ever seen an error like this, and my other models that i have work just fine.

Body:
return render(request, 'showme.html',{'outputs':outputs})

you missed the request parameter in the render and its mandatory

and also change this in your template

{% for output in outputs %}
    {{ output.Cuisine }}
    {{ output.Cuisine1 }}
    {{ output.LunchPref }}
    {{ output.DinnerPref }}
    {{ output.Friday }}
    {{ output.Sunday }}
{% endfor %}


问:
Comparing unordered_map vs unordered_set
First of all, what is the main difference between them?

The only thing i've found is that unordered_set has no operator [].
How should i access an element in unordered_set, since there is no []?

Which container is using random access to memory(or both)?

And which one of them faster in any sense or using less memory?

答:
you can use iterators to access elements.    </p>

```<code>unordered_set <string> u{
            "Dog",
            "Cat",
            "Rat",
            "Parrot",
            "bee"
};

for(auto& s:u){
     cout << s << ' ';
}

unordered_set<string>::const_iterator point = u.find("bee");
</code>```

Body:
you can use iterators to access elements.

unordered_set <string> u{
            "Dog",
            "Cat",
            "Rat",
            "Parrot",
            "bee"
};

for(auto& s:u){
     cout << s << ' ';
}

unordered_set<string>::const_iterator point = u.find("bee");


问:
isset is not working on submit
This is a 5-star rating form and I am trying to make it work.

```<code><div class="stars">
  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>
    <label class="star star-5" for="star-5"></label>
    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>
    <label class="star star-4" for="star-4"></label>
    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>
    <label class="star star-3" for="star-3"></label>
    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>
    <label class="star star-2" for="star-2"></label>
    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>
    <label class="star star-1" for="star-1"></label>
    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>
</div>
</code>```

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

```<code><?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>
</code>```

答:
You have to set method and action attributes in the form tag.

```<code> <form method='post' action='page.php'>
</code>```

Title: isset is not working on submit

Body:
This is a 5-star rating form and I am trying to make it work.

  <form>
    <input class="star star-5" id="star-5" type="radio" name="star" value="5"/>

    <input class="star star-4" id="star-4" type="radio" name="star" value="4"/>

    <input class="star star-3" id="star-3" type="radio" name="star" value="3"/>

    <input class="star star-2" id="star-2" type="radio" name="star" value="2"/>

    <input class="star star-1" id="star-1" type="radio" name="star" value="1"/>

    <button class="button" type="submit" name="submit" value="submit">Submit</button>

  </form>

When I press the submit button nothing happens. The code does not move into the if statement, though it should since submit is not longer null.

<?php
if(isset($_POST['submit'])){
    $rating = $_POST['star'];
    echo "hello";
    echo $rating;
}
?>

Body:
You have to set method and action attributes in the form tag.

 <form method='post' action='page.php'>


问:
Get n-th element from all dictionary values - Python
Is there any out of the box syntax/func that would return n-th value of all dictionary keys. For example n=2 for the following dic

```<code>dic = {'a': [1, 2, 3, 4],
       'b': [5, 6, 7, 8],
       'c': [9, 10, 11, 12]}
</code>```

would return:

```<code>newdic = {'a': 3,
          'b': 7,
          'c': 11}
</code>```

For now I defined the following function which works fine, but I find it kind of ugly.

```<code>def nth_value(n, **kwargs):
    dic = {}
    for key, value in kwargs.items():
        dic[key] = value[n]
    return dic
</code>```

P.S. I know for sure that all lists are of same length.

Body:
Is there any out of the box syntax/func that would return n-th value of all dictionary keys. For example n=2 for the following dic

dic = {'a': [1, 2, 3, 4],
       'b': [5, 6, 7, 8],
       'c': [9, 10, 11, 12]}

would return:

newdic = {'a': 3,
          'b': 7,
          'c': 11}

For now I defined the following function which works fine, but I find it kind of ugly.

def nth_value(n, **kwargs):
    dic = {}
    for key, value in kwargs.items():
        dic[key] = value[n]
    return dic

P.S. I know for sure that all lists are of same length.

Body:
Try this:

>>> n = 2
>>> {k:v[n] for k,v in dic.items()}
{'c': 11, 'b': 7, 'a': 3}


问:
Grafana -- Zabbix Data Source cannot connect
I've got my system all set up with Zabbix and love it for my detailed monitoring.
I need to put a pretty wrapper on it for displaying on our status screen and have been trying to use Grafana but cannot seem to get the Zabbix Data Source correctly connected.
I've hunted all around for more detailed documentation -- is there any?

OR Does anyone who has done this have some hints about what I can try?

Thanks in advance -- James

答:
you need to install "Zabbix plugin for Grafana"

https://grafana.com/plugins/alexanderzobnin-zabbix-app

Use the grafana-cli tool to install Zabbix from the command line:

```<code>grafana-cli plugins install alexanderzobnin-zabbix-app
</code>```

Body:
you need to install "Zabbix plugin for Grafana"

https://grafana.com/plugins/alexanderzobnin-zabbix-app

Use the grafana-cli tool to install Zabbix from the command line:

grafana-cli plugins install alexanderzobnin-zabbix-app


问:
Is this the correct way to handle a response in Xamarin Forms?
```<code>var response = await App.PhrasespageCS.DisplayAlert("Reset score",
     "You have more than 50 points. Are you sure you want to reset it to 0?",
     "Yes", "No");

if (response == true)
{
    App.DB.ResetPointsForSelectedPhrase(App.cfs);
}
</code>```

I am not clear on the use of await here and would appreciate advice.  Also could this be combined into one statement?

答: As described in the example you should use await. Check this also. The code for your purpose is given above in the answer.</p>

Body:
var response = await App.PhrasespageCS.DisplayAlert("Reset score",
     "You have more than 50 points. Are you sure you want to reset it to 0?",
     "Yes", "No");

if (response == true)
{
    App.DB.ResetPointsForSelectedPhrase(App.cfs);
}

I am not clear on the use of await here and would appreciate advice.  Also could this be combined into one statement?


问:
Azure Storage Emulator 403 Forbidden
Via Nuget, I upgraded WindowsAzure.Storage to 8.1.1.

I then downloaded the AzureStorageEmulator 5.1.0.0 client.

My connection string:

```<code>UseDevelopmentStorage=true;
</code>```

I've made no code changes since previously when it was apparently working fine.  I know get the exception:

```<code>Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (403) Forbidden. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 677
   --- End of inner exception stack trace ---
   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 604
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.CreateIfNotExists(BlobContainerPublicAccessType accessType, BlobRequestOptions requestOptions, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobContainer.cs:line 233
   at C3.Code.Controls.Application.Storage.Blob.Blob.GetContainer(String containerName) in C:\Dropbox\Dropbox (Scirra Ltd)\Tom\C3 Website\C3Alpha2\Code\Controls\Application\Storage\Blob\Blob.cs:line 112
Request Information
RequestID:621bc19f-eb6a-4a98-b19e-f5b01ac22c26
RequestDate:Thu, 27 Apr 2017 16:17:34 GMT
StatusMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
ErrorCode:AuthenticationFailed
ErrorMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:621bc19f-eb6a-4a98-b19e-f5b01ac22c26
Time:2017-04-27T16:17:34.5166522Z
</code>```

When I call

```<code>var blobClient = GetClient();
var container = blobClient.GetContainerReference(containerName);
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);
</code>```

I saw that system time can impact this, so I checked:

```<code>Server DateTime.UtcNow = 27/04/2017 16:17:34
Exception RequestDate = Thu, 27 Apr 2017 16:17:34 GMT
</code>```

Any ideas why I'm seeing this error after updating the client and the nuget package?

Edit: GetClient() Code:

```<code>private static CloudBlobClient GetClient()
{
    var account = CloudStorageAccount.Parse(Settings.Deployment.AzureConnectionString);
    return account.CreateCloudBlobClient();
}
</code>```

Edit: BaseUri

Base URI is:
    http://127.0.0.1:10000/devstoreaccount1

Visit this I get:

```<code><Error>
<Code>InvalidQueryParameterValue</Code>
<Message>
Value for one of the query parameters specified in the request URI is invalid. RequestId:9cc906b0-eec6-44b2-bb3d-f77020af4a4c Time:2017-04-27T16:43:16.8538679Z
</Message>
<QueryParameterName>comp</QueryParameterName>
<QueryParameterValue/>
<Reason/>
</Error>
</code>```

During storage emulator init, it shows it's installed it to:

(localdb)\MSSQLLocalDB as AzureStorageEmulatorDb51

Visiting: http://127.0.0.1:10000/azurestorageemulatordb51

Shows:

```<code><Error>
<Code>OutOfRangeInput</Code>
<Message>
One of the request inputs is out of range. RequestId:dab5e6c1-bc4a-4c65-a4d9-6d44634cb36a Time:2017-04-27T16:47:20.3093597Z
</Message>
</Error>
</code>```

答:
I've had the same problem, could not find any solution to fix that. It really seems to be connected to ApplicationInsights - direct call to the local emulator from a clean console application works fine, calling the emulator from a web project with ApplicationInsights returns 403.

You can use another storage emulator or use a real Azure Blob Storage.

Title: Azure Storage Emulator 403 Forbidden

Body:
Via Nuget, I upgraded WindowsAzure.Storage to 8.1.1.

I then downloaded the AzureStorageEmulator 5.1.0.0 client.

My connection string:

UseDevelopmentStorage=true;

I've made no code changes since previously when it was apparently working fine.  I know get the exception:

Microsoft.WindowsAzure.Storage.StorageException: The remote server returned an error: (403) Forbidden. ---> System.Net.WebException: The remote server returned an error: (403) Forbidden.
   at System.Net.HttpWebRequest.GetResponse()
   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 677
   --- End of inner exception stack trace ---
   at Microsoft.WindowsAzure.Storage.Core.Executor.Executor.ExecuteSync[T](RESTCommand`1 cmd, IRetryPolicy policy, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Core\Executor\Executor.cs:line 604
   at Microsoft.WindowsAzure.Storage.Blob.CloudBlobContainer.CreateIfNotExists(BlobContainerPublicAccessType accessType, BlobRequestOptions requestOptions, OperationContext operationContext) in c:\Program Files (x86)\Jenkins\workspace\release_dotnet_master\Lib\ClassLibraryCommon\Blob\CloudBlobContainer.cs:line 233
   at C3.Code.Controls.Application.Storage.Blob.Blob.GetContainer(String containerName) in C:\Dropbox\Dropbox (Scirra Ltd)\Tom\C3 Website\C3Alpha2\Code\Controls\Application\Storage\Blob\Blob.cs:line 112
Request Information
RequestID:621bc19f-eb6a-4a98-b19e-f5b01ac22c26
RequestDate:Thu, 27 Apr 2017 16:17:34 GMT
StatusMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
ErrorCode:AuthenticationFailed
ErrorMessage:Server failed to authenticate the request. Make sure the value of Authorization header is formed correctly including the signature.
RequestId:621bc19f-eb6a-4a98-b19e-f5b01ac22c26
Time:2017-04-27T16:17:34.5166522Z

When I call

var blobClient = GetClient();
var container = blobClient.GetContainerReference(containerName);
container.CreateIfNotExists(BlobContainerPublicAccessType.Blob);

I saw that system time can impact this, so I checked:

Server DateTime.UtcNow = 27/04/2017 16:17:34
Exception RequestDate = Thu, 27 Apr 2017 16:17:34 GMT

Any ideas why I'm seeing this error after updating the client and the nuget package?

Edit: GetClient() Code:

private static CloudBlobClient GetClient()
{
    var account = CloudStorageAccount.Parse(Settings.Deployment.AzureConnectionString);
    return account.CreateCloudBlobClient();
}

Edit: BaseUri

Base URI is:
    http://127.0.0.1:10000/devstoreaccount1

Visit this I get:

<Error>
InvalidQueryParameterValue
<Message>
Value for one of the query parameters specified in the request URI is invalid. RequestId:9cc906b0-eec6-44b2-bb3d-f77020af4a4c Time:2017-04-27T16:43:16.8538679Z
</Message>
<QueryParameterName>comp</QueryParameterName>
<QueryParameterValue/>
<Reason/>
</Error>

During storage emulator init, it shows it's installed it to:

(localdb)\MSSQLLocalDB as AzureStorageEmulatorDb51

Visiting: http://127.0.0.1:10000/azurestorageemulatordb51

Shows:

<Error>
OutOfRangeInput
<Message>
One of the request inputs is out of range. RequestId:dab5e6c1-bc4a-4c65-a4d9-6d44634cb36a Time:2017-04-27T16:47:20.3093597Z
</Message>
</Error>


问:
How can I count unread message in firebase chat messages in javascript
I developed a chat using firebase.

Not want to count all message that has unread status and display it to my list of users.

Here is my database.

As you can see in the image, I have status:"unread"

Here is what I did in javascript.

```<code><script>
    var ref = new Firebase("https://mosbeau-cd349.firebaseio.com/Users/<?php echo $ae; ?>/");

    ref.on("value", function(snapshot) {
        var names="";
        var un=0;
        for (x in snapshot.val()) {
            var xRef = new Firebase("https://mosbeau-cd349.firebaseio.com/Users/<?php echo $ae; ?>/"+x+"/");
            var messagesRef = new Firebase("https://mosbeau-cd349.firebaseio.com/Chats/"+x+" <?php echo $ae; ?>");
            xRef.once("value", function(xsnapshot) {
                var data = xsnapshot.val();
                var name = data["cuname"];
                //console.log(name);

                messagesRef.on("value", function(ysnapshot) {
                    for (y in ysnapshot.val()) {
                        var yRef = new Firebase("https://mosbeau-cd349.firebaseio.com/Chats/"+x+" <?php echo $ae; ?>/"+y+"/");
                        yRef.once("value", function(zsnapshot) {
                            var ydata = zsnapshot.val();
                            var status = ydata["status"];
                            alert(status);
                            if(status=="unread"){
                                un++;
                            }
                        });
                    }
                });

                names += "<li style='padding:10px;border-bottom:1px solid#f2f2f2;'><a href='adminchat.php?id="+x+"&ae=<?php echo $ae; ?>&aeid=<?php echo $aeid; ?>&custo="+name+"'>"+name+" "+un+"</a></li>";
            });
        }
        document.getElementById('results').innerHTML=names;
    });

    </script>
</code>```

I can't get the total of unread message.

Please help me.

答:
Use a query, a very common thing in Firebase:

```<code>...
//console.log(name);

// NEW
messagesRef.orderByChild("status").equalTo("unread").on("value", function(ysnapshot) {
    var unread = ysnapshot.numChildren();
});

names += "<li style='padding:10px;border-bottom:1px solid#f2f2f2;'><a href='adminchat.php?id="+x+"&ae=<?php echo $ae; ?>&aeid=<?php echo $aeid; ?>&custo="+name+"'>"+name+" "+un+"</a></li>";
...
</code>```

Assuming "https://mosbeau-cd349.firebaseio.com/Chats/"+x+" <?php echo $ae; ?>/" resolves to something like: "https://mosbeau-cd349.firebaseio.com/Chats/10736 ONLINESHOP/"

So all you're doing is getting this node, 10736 ONLINESHOP, and retrieving by its children having a child status with value unread.

Body:
I developed a chat using firebase.

Not want to count all message that has unread status and display it to my list of users.

Here is my database.

As you can see in the image, I have status:"unread"

Here is what I did in javascript.

I can't get the total of unread message.

Please help me.

Body:
Use a query, a very common thing in Firebase:

...
//console.log(name);

// NEW
messagesRef.orderByChild("status").equalTo("unread").on("value", function(ysnapshot) {
    var unread = ysnapshot.numChildren();
});

names += "<li style='padding:10px;border-bottom:1px solid#f2f2f2;'><a href='adminchat.php?id="+x+"&ae=<?php echo $ae; ?>&aeid=<?php echo $aeid; ?>&custo="+name+"'>"+name+" "+un+"</a></li>";
...

Assuming "https://mosbeau-cd349.firebaseio.com/Chats/"+x+" <?php echo $ae; ?>/" resolves to something like: "https://mosbeau-cd349.firebaseio.com/Chats/10736 ONLINESHOP/"

So all you're doing is getting this node, 10736 ONLINESHOP, and retrieving by its children having a child status with value unread.


问:
How to avoid the Outlook security warning for email automation?
I'm trying to send an Outlook email from Excel 2010 using VBA.

Most answers on Stack Overflow don't seem to have a method of using VBA to avoid the Outlook security warning, nor for Outlook/Excel 2010.

Do any free methods exist? The Redemption method won't be a viable option, unless it is easy to install on 10 machines in a large company.

How I send emails:

Dim emailAddr As String
Dim OutApp As Object
Dim OutMail As Object

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)
With OutMail
    .To = "xxxx@xxxx.edu"
    .Subject = "Demande"
    .HtmlBody = CombinedValueHtml
    .Send
End With

Set OutMail = Nothing
Set OutApp = Nothing

Exit Sub
```

答:
If you don't send the message immediately but just display it and let the user do modifications (if any) and let them press the send button theirselves, this would work:

i.e. use

```<code>.Display
</code>```

instead of

```<code>.Send
</code>```

ContentLicense: CC BY-SA 4.0

Body:
If you don't send the message immediately but just display it and let the user do modifications (if any) and let them press the send button theirselves, this would work:

i.e. use

.Display

instead of

.Send


问:
Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."
When upgraded to django 1.9 from 1.8 I got this error. I checked answers for similar questions, but I didn't think this is an issue with any 3rd party packages or apps.

```<code>Traceback (most recent call last):
File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 176, in fetch_command
commands = get_commands()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 100, in wrapper
result = user_function(*args, **kwds)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 71, in get_commands
for app_config in reversed(list(apps.get_app_configs())):
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/apps/registry.py", line 137, in get_app_configs
self.check_apps_ready()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.
</code>```

I'd modified the Installed apps for 'django.contrib.auth'.

答: If your setting.py files fill are correct，you can try to arrive manage.py files proceed call danjgo.setup() in main method . Then run manage.py ,finally again run project ,the issue could disappear.</p>

Body:
When upgraded to django 1.9 from 1.8 I got this error. I checked answers for similar questions, but I didn't think this is an issue with any 3rd party packages or apps.

Traceback (most recent call last):
File "manage.py", line 10, in <module> execute_from_command_line(sys.argv)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
utility.execute()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 342, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 176, in fetch_command
commands = get_commands()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/utils/lru_cache.py", line 100, in wrapper
result = user_function(*args, **kwds)
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 71, in get_commands
for app_config in reversed(list(apps.get_app_configs())):
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/apps/registry.py", line 137, in get_app_configs
self.check_apps_ready()
File "/home/kishore/.virtualenvs/andone/local/lib/python2.7/site-packages/django/apps/registry.py", line 124, in check_apps_ready
raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

I'd modified the Installed apps for 'django.contrib.auth'.


问:
How to get verbose output for undefined reference error using -v in clang (Android-Studio)
Whenever you get a linker error in Android Studio it suggests you to use -v to see invocation, but where to put the -v command to get the "verbose output" (according to llvm clang command guide)?

Already tried:

```<code>externalNativeBuild {
            cmake {
                cppFlags "-frtti -fexceptions -v"
            }
        }
</code>```

which is not changing anything in the output as far as i noticed and

--stacktrace --debug

in

```<code>Settings > Compiler > Command-line Options
</code>```

Which is showing way more output but not what I am looking for!

Thank you very much for your help in advance!

EDIT

Since i am compiling C files i obviously had to use cFlags. Now the gradle file looks as follows (thx to @Alex Cohn):

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "<my_id>"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cFlags "-v"
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    testCompile 'junit:junit:4.12'
}
</code>```

EDIT 2

Adding following pre-processor command in a few C-classes i did not notice they were missing it, i was able to get rid of my linker error about the missing reference:

```<code>#ifdef __cplusplus
extern "C"
{
#endif

// your includes and your code here

#ifdef __cplusplus
}
#endif
</code>```

答:
cppFlags "-frtti -fexceptions -v" works as well as cppFlags "-frtti", "-fexceptions",  "-v" for clang++ tasks, that is, to get verbose output for .cpp or .cxx files compilation.

cFlags "-v" works to produce verbose output for .c files compilation.

To produce verbose output for link step, edit your CMakeLists.txt file, add -v to the relevant target_link_libraries statement, e.g.

```<code>target_link_libraries(myjnilib android log -v)
</code>```

All above may not be enough to understand and fix undefined reference error.

Body:
Whenever you get a linker error in Android Studio it suggests you to use -v to see invocation, but where to put the -v command to get the "verbose output" (according to llvm clang command guide)?

Already tried:

externalNativeBuild {
            cmake {
                cppFlags "-frtti -fexceptions -v"
            }
        }

which is not changing anything in the output as far as i noticed and

--stacktrace --debug

in

Settings > Compiler > Command-line Options

Which is showing way more output but not what I am looking for!

Thank you very much for your help in advance!

EDIT

Since i am compiling C files i obviously had to use cFlags. Now the gradle file looks as follows (thx to @Alex Cohn):

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "<my_id>"
        minSdkVersion 16
        targetSdkVersion 25
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
        externalNativeBuild {
            cmake {
                cFlags "-v"
            }
        }
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    externalNativeBuild {
        cmake {
            path "CMakeLists.txt"
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
        exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.1'
    testCompile 'junit:junit:4.12'
}

EDIT 2

Adding following pre-processor command in a few C-classes i did not notice they were missing it, i was able to get rid of my linker error about the missing reference:

#ifdef __cplusplus
extern "C"
{
#endif

// your includes and your code here

#ifdef __cplusplus
}
#endif

Body:
cppFlags "-frtti -fexceptions -v" works as well as cppFlags "-frtti", "-fexceptions",  "-v" for clang++ tasks, that is, to get verbose output for .cpp or .cxx files compilation.

cFlags "-v" works to produce verbose output for .c files compilation.

To produce verbose output for link step, edit your CMakeLists.txt file, add -v to the relevant target_link_libraries statement, e.g.

target_link_libraries(myjnilib android log -v)

All above may not be enough to understand and fix undefined reference error.


问:
Heroku : This version of the API has been Sunset. is displayed when heroku pg:psql
When I try to use heroku pg:psql, the following error is displayed.

!    This version of the API has been Sunset.
 !    Please see https://devcenter.heroku.com/changelog-items/1147 for more information.

How can I access postgresql on Heroku?
heroku pg:psql command worked a few week ago.

I develop my Rails app on the Cloud 9.

答:
I had the same issue with my ruby on rails project since last Friday.

However, i was able to resolve this error message by update my heroku toolbelt on my mac os.

*Hint, if your heroku file was installed in project gem. you will need to delete that file.

Use command which heroku to identify where is the heroku file. if it is inside the .rvm folder that means your project is still using outdated heroku file. and simply remove it and then ran an new install heroku cli should fix this error.

Let me know if this works for you.


问:
SWP_NOSIZE doesn't have desired effect
I have a window that has its ScaleMode set to "Pixel"

When I'm calling the API function "SetWindowPos", I'm passing "SWP_NOSIZE" as an argument:

```<code>SetWindowPos Me.hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE Or SWP_NOMOVE Or SWP_NOACTIVATE
</code>```

However, after the API call, the width of my window is 3240 instead of the intended width of 216.

I think this has to do with the fact that 216 * Screen.TwipsPerPixelX is 3240.

So I would tend to think that the API call changes the window's ScaleMode.

Does anybody how to avoid it?

Thank you!

答:
The problem seems to be that the API function changes the VB6's windows scale mode to twips, no matter what it was before.
I've therefore changed the form to twips instead of pixels, and I changed everything around it (for example by removing "Screen.TwipsPerPixel") accordingly.</p>

Title: SWP_NOSIZE doesn't have desired effect

Body:
I have a window that has its ScaleMode set to "Pixel"

When I'm calling the API function "SetWindowPos", I'm passing "SWP_NOSIZE" as an argument:

SetWindowPos Me.hWnd, HWND_TOPMOST, 0, 0, 0, 0, SWP_NOSIZE Or SWP_NOMOVE Or SWP_NOACTIVATE

However, after the API call, the width of my window is 3240 instead of the intended width of 216.

I think this has to do with the fact that 216 * Screen.TwipsPerPixelX is 3240.

So I would tend to think that the API call changes the window's ScaleMode.

Does anybody how to avoid it?

Thank you!


问:
How to copy a directory from local machine to remote machine
I am using ssh to connect to a remote machine.

Is there a way i can copy an entire directory from a local machine to the remote machine?

I found this link to do it the other way round i.e copying from remote machine to local machine.

答:
This is worked for me </p>

```<code>rsync -avz -e 'ssh' /path/to/local/dir user@remotehost:/path/to/remote/dir
</code>```

Body:
This is worked for me

rsync -avz -e 'ssh' /path/to/local/dir user@remotehost:/path/to/remote/dir


问:
Lambda Expression example not working in java 8
I am trying to learn Lambda Expression in java 8. I do have installed eclipse plugin and java 8 SDK but when I am trying to execute following code eclipse is showing error.

```<code>(String s) -> {
            s="hello";
            System.out.println(s); }
</code>```

its showing "The left-hand side of an assignment must be a variable" error.

please help.

答:
The lambda expressions always expects a reference to be assigned.

Java 7 Code:

Valid:

```<code>new Hahaha() {
    @Override
    public void howtolaugh(int number, String sound) {
        System.out.println("say "+sound + number + " number of times");
    }
};
</code>```

Java 8:

Invalid:

```<code>(int i, String sound) -> System.out.println("say "+sound + i + " number of times");
</code>```

Though these two serve the same purpose, the first one is an inner class. Inner classes have a default reference to the enclosing class. When they are decompiled, a different class file is generated for them in the format <Enclosing_Class_Name>$<a_number>.class or <Enclosing_Class_Name>$<a_number>.class. Ex: TestClass$1.class.

This is not the case in lambda expressions. They do not have an implicit reference to the enclosing class neither do they have a different class generated. They need an explicit reference either as a method parameter name, or a reference object on the left hand side or a return reference.

Body:
I am trying to learn Lambda Expression in java 8. I do have installed eclipse plugin and java 8 SDK but when I am trying to execute following code eclipse is showing error.

(String s) -> {
            s="hello";
            System.out.println(s); }

its showing "The left-hand side of an assignment must be a variable" error.

please help.

Body:
The lambda expressions always expects a reference to be assigned.

Java 7 Code:

Valid:

new Hahaha() {
    @Override
    public void howtolaugh(int number, String sound) {
        System.out.println("say "+sound + number + " number of times");
    }
};

Java 8:

Invalid:

(int i, String sound) -> System.out.println("say "+sound + i + " number of times");

Though these two serve the same purpose, the first one is an inner class. Inner classes have a default reference to the enclosing class. When they are decompiled, a different class file is generated for them in the format <Enclosing_Class_Name>$<a_number>.class or <Enclosing_Class_Name>$<a_number>.class. Ex: TestClass$1.class.

This is not the case in lambda expressions. They do not have an implicit reference to the enclosing class neither do they have a different class generated. They need an explicit reference either as a method parameter name, or a reference object on the left hand side or a return reference.


问:
Excel to DataGridView
Additional information: The Microsoft Office Access database engine could not find the object 'C:\Users\username\Documents\sampleData.xls'.  Make sure the object exists and that you spell its name and the path name correctly.

The Error is highlighted at

```<code>theDataAdapter.Fill(spreadSheetData);
</code>```

Here's the sample data I used (tried in .csv , .xls , .xlsx )

```<code>Name    Age     Status      Children
Johnny  34      Married     3
Joey    21      Single      1
Michael 16      Dating      0
Smith   42      Divorced    4
</code>```

Here's the code associated:

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;

namespace uploadExcelFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            var frmDialog = new System.Windows.Forms.OpenFileDialog();
            if (frmDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                string strFileName = frmDialog.FileName;
                System.IO.FileInfo spreadSheetFile = new System.IO.FileInfo(strFileName);

                scheduleGridView.DataSource = spreadSheetFile.ToString();
                System.Diagnostics.Debug.WriteLine(frmDialog.FileName);
                System.Diagnostics.Debug.WriteLine(frmDialog.SafeFileName);

                String name = frmDialog.SafeFileName;

                String constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);

                OleDbConnection myConnection = new OleDbConnection(constr);

                OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + frmDialog.FileName + "]", myConnection);

                myConnection.Open();

                OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(onlineConnection);
                DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                theDataAdapter.Fill(spreadSheetData);
                scheduleGridView.DataSource = spreadSheetData;
            }
        }
    }
}
</code>```

scheduleGridView is the DataGridViews name, & btnImport is the name for the import Button.

I've installed 2007 Office System Driver: Data Connectivity Components; which gave me the AccessDatabaseEngine.exe, but from there I've been stuck here without understanding how to get around this. It should go without saying that the filepath is correct in its entirety. There is no odd characters in the path name either (spaces, underlines, etc)

Mini Update :: (another dead end it seems like)

Although the initial error says, "could not find the object 'C:\Users\username\Documents\sampleData.xls'"

In the Debugger the exception is read as
When I look at details the exception as "C:\Users\username\Documents\sampleData.xls"

So I thought the error was that it wasn't taking the path as a literal, but this article C# verbatim string literal not working. Very Strange backslash always double
Shows very clearly that that is not my issue.

答:
I am guessing you may be mistaken by what is returned from the following line of code…

```<code>DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
</code>```

The DataTable returned from this line will have nine (9) columns (TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE, TABLE_GUID, DESCRIPTION, TABLE_PROPID, DATE_CREATED and DATE_MODIFIED). This ONE (1) DataTable returned simply “Describes” the worksheet(s) and named range(s) in the entire selected Excel workbook. Each row in this DataTable represent either a worksheet OR a named range. To distinguish worksheets from named ranges, the “TABLE_NAME” column in this DataTable has the name of the worksheet or range AND ends each “Worksheet” Name with a dollar sign ($). If the “TABLE_NAME” value in a row does NOT end in dollar sign, then it is a range and not a worksheet.

Therefore, when the line

```<code>OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(onlineConnection);
</code>```

Blows up and says it cannot file the “filename” error… is somewhat expected because this line is looking for a “worksheet” name, not a filename. On the line creating the select command…

```<code>OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + frmDialog.FileName + "]", myConnection);
</code>```

This is incorrect; you have already selected the filename and open the file with

```<code>String constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);
OleDbConnection myConnection = new OleDbConnection(constr);
myConnection.Open();
</code>```

The correct OleDbCommand line should be…

```<code>OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", myConnection);
</code>```

The problem here is that the current code is not getting the worksheet names. Therefore, we cannot “select” the worksheet from the workbook then fill the adapter with the worksheet.

The other issue is setting the DataGridView’s DataSource to spreadSheetData… when you get the worksheet(s) from an Excel “Workbook”, you must assume there will be more than one sheet. Therefore a DataSet will work as a container to hold all the worksheets in the workbook. Each DataTable in the DataSet would be a single worksheet and it can be surmised that the DataGridView can only display ONE (1) of these tables at a time. Given this, below are the changes described along with an added button to display the “Next” worksheet in the DataGridView since there may be more than one worksheet in the workbook. Hope this makes sense.

```<code>int sheetIndex = 0;
DataSet ds = new DataSet();

public Form1() {
  InitializeComponent();
}

private void btnImport_Click(object sender, EventArgs e) {
  var frmDialog = new System.Windows.Forms.OpenFileDialog();
  if (frmDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    String constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);
    OleDbConnection myConnection = new OleDbConnection(constr);
    myConnection.Open();
    DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    string sheetName = "";
    DataTable dt;
    OleDbCommand onlineConnection;
    OleDbDataAdapter theDataAdapter;
    // fill the "DataSet" each table in the set is a worksheet in the Excel file
    foreach (DataRow dr in spreadSheetData.Rows) {
      sheetName = dr["TABLE_NAME"].ToString();
      sheetName = sheetName.Replace("'", "");
      if (sheetName.EndsWith("$")) {
        onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", myConnection);
        theDataAdapter = new OleDbDataAdapter(onlineConnection);
        dt = new DataTable();
        dt.TableName = sheetName;
        theDataAdapter.Fill(dt);
        ds.Tables.Add(dt);
      }
    }
    myConnection.Close();
    scheduleGridView.DataSource = ds.Tables[0];
    setLabel();
  }
}

private void setLabel() {
  label1.Text = "Showing worksheet " + sheetIndex + " Named: " + ds.Tables[sheetIndex].TableName + " out of a total of " + ds.Tables.Count + " worksheets";
}

private void btnNextSheet_Click(object sender, EventArgs e) {
  if (sheetIndex == ds.Tables.Count - 1)
    sheetIndex = 0;
  else
    sheetIndex++;
  scheduleGridView.DataSource = ds.Tables[sheetIndex];
  setLabel();
}
</code>```

Title: Excel to DataGridView

Body:
Additional information: The Microsoft Office Access database engine could not find the object 'C:\Users\username\Documents\sampleData.xls'.  Make sure the object exists and that you spell its name and the path name correctly.

The Error is highlighted at

theDataAdapter.Fill(spreadSheetData);

Here's the sample data I used (tried in .csv , .xls , .xlsx )

Name    Age     Status      Children
Johnny  34      Married     3
Joey    21      Single      1
Michael 16      Dating      0
Smith   42      Divorced    4

Here's the code associated:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Data.OleDb;

namespace uploadExcelFile
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            var frmDialog = new System.Windows.Forms.OpenFileDialog();
            if (frmDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {

                string strFileName = frmDialog.FileName;
                System.IO.FileInfo spreadSheetFile = new System.IO.FileInfo(strFileName);

                scheduleGridView.DataSource = spreadSheetFile.ToString();
                System.Diagnostics.Debug.WriteLine(frmDialog.FileName);
                System.Diagnostics.Debug.WriteLine(frmDialog.SafeFileName);

                String name = frmDialog.SafeFileName;

                String constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);

                OleDbConnection myConnection = new OleDbConnection(constr);

                OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + frmDialog.FileName + "]", myConnection);

                myConnection.Open();

                OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(onlineConnection);
                DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
                theDataAdapter.Fill(spreadSheetData);
                scheduleGridView.DataSource = spreadSheetData;
            }
        }
    }
}

scheduleGridView is the DataGridViews name, & btnImport is the name for the import Button.

I've installed 2007 Office System Driver: Data Connectivity Components; which gave me the AccessDatabaseEngine.exe, but from there I've been stuck here without understanding how to get around this. It should go without saying that the filepath is correct in its entirety. There is no odd characters in the path name either (spaces, underlines, etc)

Mini Update :: (another dead end it seems like)

Although the initial error says, "could not find the object 'C:\Users\username\Documents\sampleData.xls'"

In the Debugger the exception is read as
When I look at details the exception as "C:\Users\username\Documents\sampleData.xls"

So I thought the error was that it wasn't taking the path as a literal, but this article C# verbatim string literal not working. Very Strange backslash always double
Shows very clearly that that is not my issue.

Body:
I am guessing you may be mistaken by what is returned from the following line of code…

DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

The DataTable returned from this line will have nine (9) columns (TABLE_CATALOG, TABLE_SCHEMA, TABLE_NAME, TABLE_TYPE, TABLE_GUID, DESCRIPTION, TABLE_PROPID, DATE_CREATED and DATE_MODIFIED). This ONE (1) DataTable returned simply “Describes” the worksheet(s) and named range(s) in the entire selected Excel workbook. Each row in this DataTable represent either a worksheet OR a named range. To distinguish worksheets from named ranges, the “TABLE_NAME” column in this DataTable has the name of the worksheet or range AND ends each “Worksheet” Name with a dollar sign ($). If the “TABLE_NAME” value in a row does NOT end in dollar sign, then it is a range and not a worksheet.

Therefore, when the line

OleDbDataAdapter theDataAdapter = new OleDbDataAdapter(onlineConnection);

Blows up and says it cannot file the “filename” error… is somewhat expected because this line is looking for a “worksheet” name, not a filename. On the line creating the select command…

OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + frmDialog.FileName + "]", myConnection);

This is incorrect; you have already selected the filename and open the file with

String constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);
OleDbConnection myConnection = new OleDbConnection(constr);
myConnection.Open();

The correct OleDbCommand line should be…

OleDbCommand onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", myConnection);

The problem here is that the current code is not getting the worksheet names. Therefore, we cannot “select” the worksheet from the workbook then fill the adapter with the worksheet.

The other issue is setting the DataGridView’s DataSource to spreadSheetData… when you get the worksheet(s) from an Excel “Workbook”, you must assume there will be more than one sheet. Therefore a DataSet will work as a container to hold all the worksheets in the workbook. Each DataTable in the DataSet would be a single worksheet and it can be surmised that the DataGridView can only display ONE (1) of these tables at a time. Given this, below are the changes described along with an added button to display the “Next” worksheet in the DataGridView since there may be more than one worksheet in the workbook. Hope this makes sense.

int sheetIndex = 0;
DataSet ds = new DataSet();

public Form1() {
  InitializeComponent();
}

private void btnImport_Click(object sender, EventArgs e) {
  var frmDialog = new System.Windows.Forms.OpenFileDialog();
  if (frmDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) {
    String constr = String.Format(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", frmDialog.FileName);
    OleDbConnection myConnection = new OleDbConnection(constr);
    myConnection.Open();
    DataTable spreadSheetData = myConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
    string sheetName = "";
    DataTable dt;
    OleDbCommand onlineConnection;
    OleDbDataAdapter theDataAdapter;
    // fill the "DataSet" each table in the set is a worksheet in the Excel file
    foreach (DataRow dr in spreadSheetData.Rows) {
      sheetName = dr["TABLE_NAME"].ToString();
      sheetName = sheetName.Replace("'", "");
      if (sheetName.EndsWith("$")) {
        onlineConnection = new OleDbCommand("SELECT * FROM [" + sheetName + "]", myConnection);
        theDataAdapter = new OleDbDataAdapter(onlineConnection);
        dt = new DataTable();
        dt.TableName = sheetName;
        theDataAdapter.Fill(dt);
        ds.Tables.Add(dt);
      }
    }
    myConnection.Close();
    scheduleGridView.DataSource = ds.Tables[0];
    setLabel();
  }
}

private void setLabel() {
  label1.Text = "Showing worksheet " + sheetIndex + " Named: " + ds.Tables[sheetIndex].TableName + " out of a total of " + ds.Tables.Count + " worksheets";
}

private void btnNextSheet_Click(object sender, EventArgs e) {
  if (sheetIndex == ds.Tables.Count - 1)
    sheetIndex = 0;
  else
    sheetIndex++;
  scheduleGridView.DataSource = ds.Tables[sheetIndex];
  setLabel();
}


问:
How to check if a big decimal number can be divided by 2^x or 5^x
I have a big decimal number N (up to 100.000 digits) and I need to check if N can be divided by 2^X or 5^X ( 0 < X < 5 ).

```<code>bignumber % (2^x) == 0
</code>```

Can I get a tip? I don't have any idea.

答:
If 0 < x < 5 => Very easy :)

X is an integer, definitively. => X = 1,2,3,4

You just check for each case.
For example X = 4  => 5^4 = 625

You must check whether Bignumber % 625 == 0

You known that 10000 % 625 == 0
=> Just check the last 4 if these 4 number is divided by 625 => the big number is divided by 625.

OK for you?

Body:
I have a big decimal number N (up to 100.000 digits) and I need to check if N can be divided by 2^X or 5^X ( 0 < X < 5 ).

bignumber % (2^x) == 0

Can I get a tip? I don't have any idea.


问:
ES6 imports using module names without path
I would like to be able to import my modules using just name without path.

For example, say I want to use:

```<code>import ViewportChecker from 'viewport-checker';
</code>```

instead of

```<code>import ViewportChecker from '../ViewportChecker';
</code>```

But I want to keep the file where it is and not create a new npm module of it. Would it be possible to define it as module for exmaple in package.json?

答: You can use webpack's alias feature : https://webpack.js.org/configuration/resolve/#resolve-alias</p>

Body:
I would like to be able to import my modules using just name without path.

For example, say I want to use:

import ViewportChecker from 'viewport-checker';

instead of

import ViewportChecker from '../ViewportChecker';

But I want to keep the file where it is and not create a new npm module of it. Would it be possible to define it as module for exmaple in package.json?


问:
Fetch data from mysql database
How to pass array into where, if this array has dynamic values ?</p>

```<code>foreach($value as  $v)
{
        echo $v->acc_pkey." ";
        $account = ledger::where('ledger_group', '=', 18)->orwhere('ledger_group', '=', $v->acc_pkey)->get();
}
</code>```

答:
We don't have to put '=' in a where,

```<code> $whereData = [
      'ledger_group' => $v->acc_pkey,
    ];
    foreach($value as  $v) {
        echo $v->acc_pkey." ";

        $account = ledger::where('ledger_group',18)
                         ->orwhere($whereData)
                         ->get();
    }
</code>```

Title: Fetch data from mysql database

Body:
How to pass array into where, if this array has dynamic values ?

foreach($value as  $v)
{
        echo $v->acc_pkey." ";
        $account = ledger::where('ledger_group', '=', 18)->orwhere('ledger_group', '=', $v->acc_pkey)->get();
}

Body:
We don't have to put '=' in a where,

 $whereData = [
      'ledger_group' => $v->acc_pkey,
    ];
    foreach($value as  $v) {
        echo $v->acc_pkey." ";

        $account = ledger::where('ledger_group',18)
                         ->orwhere($whereData)
                         ->get();
    }


问:
Function does not run in angularjs file
My code is below from an Angular js file,

```<code>ctrl.issuesGridConfig = {
        modelSetName: 'issues',
        serializerChildName: 'issues', //will be prepended with "__" before fields for validation
        actions: {
            addRow: {
                active: function(row) {return !ctrl.readOnly;},
                callback: addIssueRow,
            },
            editRow: {
                active: function(issue){ return issue.provider_issue_code;} ? true : false,
                label:  "View test" : "Edit",
                callback: function(issue){
                    $location.path('/issue/' + issue.provider_issue_code);
                }
            },
            deleteRow: {
                active: function(row) {return !ctrl.readOnly;},
                callback: function(row){
                    _.pull(ctrl.activity.issues, row);
                }
            }
        },
</code>```

My problem is- under the Editrow I am running the function(issue). it is working fine in callback:, but for active: it does not work. I get value of issue.provider_issue_code under callback:, but not under active:. I want to make active = true only if issue.provider_issue_code has some value. Please let me know whats going wrong here.

答:
Wrong code there, active is always true because of your wrong typo, in your code you assign active with a ternary operator: active = condition ? true : false; (the function is the condition there)

```<code>active: function(issue){ return issue.provider_issue_code;} ? true : false,
</code>```

should be

```<code>active: function(issue){ return issue.provider_issue_code ? true : false;} ,
</code>```

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

Title: Function does not run in angularjs file

Body:
My code is below from an Angular js file,

ctrl.issuesGridConfig = {
        modelSetName: 'issues',
        serializerChildName: 'issues', //will be prepended with "__" before fields for validation
        actions: {
            addRow: {
                active: function(row) {return !ctrl.readOnly;},
                callback: addIssueRow,
            },
            editRow: {
                active: function(issue){ return issue.provider_issue_code;} ? true : false,
                label:  "View test" : "Edit",
                callback: function(issue){
                    $location.path('/issue/' + issue.provider_issue_code);
                }
            },
            deleteRow: {
                active: function(row) {return !ctrl.readOnly;},
                callback: function(row){
                    _.pull(ctrl.activity.issues, row);
                }
            }
        },

My problem is- under the Editrow I am running the function(issue). it is working fine in callback:, but for active: it does not work. I get value of issue.provider_issue_code under callback:, but not under active:. I want to make active = true only if issue.provider_issue_code has some value. Please let me know whats going wrong here.

Body:
Wrong code there, active is always true because of your wrong typo, in your code you assign active with a ternary operator: active = condition ? true : false; (the function is the condition there)

active: function(issue){ return issue.provider_issue_code;} ? true : false,

should be

active: function(issue){ return issue.provider_issue_code ? true : false;} ,

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator


Title: Does pytest support unicode in test name?

Body:
Here is my test sample (test_time.py):

#!/usr/bin/python
# -*- coding: utf-8 -*-

import pytest
from datetime import datetime, timedelta

testdata = [
    (datetime(2001, 12, 12), datetime(2001, 12, 11), timedelta(1)),
    (datetime(2001, 12, 11), datetime(2001, 12, 12), timedelta(-1)),
]

@pytest.mark.parametrize("a,b,expected", testdata, ids=[u"中文", u"English"])
def test_timedistance_v1(a, b, expected):
    diff = a - b
    assert diff != expected

Here is the pytest output:

============================================================================== FAILURES ==============================================================================
_________________________________________________________________ test_timedistance_v1[\u4e2d\u6587] _________________________________________________________________

a = datetime.datetime(2001, 12, 12, 0, 0), b = datetime.datetime(2001, 12, 11, 0, 0), expected = datetime.timedelta(1)

    @pytest.mark.parametrize("a,b,expected", testdata, ids=[u"中文", u"English"])
    def test_timedistance_v1(a, b, expected):
        diff = a - b
>       assert diff != expected
E       assert datetime.timedelta(1) != datetime.timedelta(1)

test_time.py:15: AssertionError
___________________________________________________________________ test_timedistance_v1[English] ____________________________________________________________________

a = datetime.datetime(2001, 12, 11, 0, 0), b = datetime.datetime(2001, 12, 12, 0, 0), expected = datetime.timedelta(-1)

    @pytest.mark.parametrize("a,b,expected", testdata, ids=[u"中文", u"English"])
    def test_timedistance_v1(a, b, expected):
        diff = a - b
>       assert diff != expected
E       assert datetime.timedelta(-1) != datetime.timedelta(-1)

test_time.py:15: AssertionError
====================================================================== 2 failed in 0.05 seconds ======================================================================

For the second line in output , the test name is "test_timedistance_v1[\u4e2d\u6587]" , I hope it's "test_timedistance_v1[中文]"， does py.test support it?
(my pytest version is 3.1.2, OS: macOS 10.12.5)

Body:
It does not depend of pytest but of your computer locale.

Here the trace-log of test (LC_ALL="en_US.UTF-8") :

================================ test session starts ================================
platform linux -- Python 3.5.3, pytest-2.9.2, py-1.4.34, pluggy-0.3.1
rootdir: /home/..../tmp, inifile:
collected 2 items

pytest_chin.py FF

===================================== FAILURES ======================================
_____________________________ test_timedistance_v1[中文] ______________________________
...

And with with LC_ALL="fr_FR.iso8859-1" :

================================ test session starts ================================
platform linux -- Python 3.5.3, pytest-2.9.2, py-1.4.34, pluggy-0.3.1
rootdir: /home/gustavi/tmp, inifile:
collected 2 items

pytest_chin.py FF

===================================== FAILURES ======================================
\x1b[1m\x1b[31m_____________________________ test_timedistance_v1[\u4e2d\u6587] ______________________________\x1b[0m
...

Here an usefull link to setup your locale on OS X.


问:
How should a list be represented in XML?
In XML, how should a list be represented?

With an enclosing list entity:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>
</code>```

Or without:

```<code><person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>
</code>```

答:
Think of it in code you'd like to write against it.:

To me...

```<code>spouse.children = person.children...
</code>```

is a lot nicer semantically than...

```<code>for child in person:
    spouse.addChild(person.child)
</code>```

OwnerDisplayName: Mat

Body:
In XML, how should a list be represented?

With an enclosing list entity:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <children>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
        <child .../>
    </children>
</person>

Or without:

<person>
    <firstname>Joe</firstname>
    <lastname>Bloggs</lastname>

    <child .../>
    <child .../>
    <child .../>
    <child .../>
    <child .../>
</person>

Body:
Think of it in code you'd like to write against it.:

To me...

spouse.children = person.children...

is a lot nicer semantically than...

for child in person:
    spouse.addChild(person.child)

OwnerDisplayName: Triptych

LastEditorDisplayName: Triptych


问:
Saving UI state with cookie and jquery
I'm trying to save the state of a collapsible menu, and using the jquery cookie plug in .. I'm having trouble so far though.. any help?

The script that does the collapse/expand

```<code><script type="text/javascript">
    $(document).ready(function() {

    $(".login-holder > ul > .loginTitle").click(function() {
        $(this).parent().find("li").slideToggle("fast");
        if ($(this).parent().find(".toggle").html() == "+") {
            $(this).parent().find(".toggle").html("-");
        } else {
            $(this).parent().find(".toggle").html("+");
        }
    });
   })
</script>
</code>```

The xhtml

```<code><ul class="account-links">
         <div class="loginTitle">User Options<span class="toggle">-</span></div>
         <div class="menuLinks">
         <li>
            <%= Html.ActionLink<EventController>( x => x.List(), "Events Near Me" )%>
         </li>
         <li>
            <%= Html.ActionLink<MyEventsController>( x => x.List(), "My Events" )%>
         </li>
         <li>
            <%= Html.ActionLink<AccountController>( x => x.Edit(), "My Profile" )%>
         </li>
         <li>
            <%= Html.ActionLink<ClubController>( x => x.List(), "Clubs Near Me" )%>
         </li>
         <li>
            <%= Html.ActionLink<MyClubsController>( x => x.List(), "My Clubs" )%>
         </li>
         <li>
            <%= Html.ActionLink<AccountController>( x => x.ChangePassword(), "Change My Password" )%>
         </li>
         <li>
            <%= Html.ActionLink<DependantController>( x => x.List(), "My Dependants" ) %>
         </li>
        </div>
      </ul>
   </div>
  <% if ( ViewModel.Profile.HasOrganizerInfo ) { %>
  <div class="login-holder">
     <ul class="account-links">
        <div class="loginTitle">Organizer Details<span class="toggle">-</span></div>
        <div class=menuLinks>
        <li>
           <%= Html.ActionLink<AccountController>( x => x.Organizer(), "Organizer Details" )%>
        </li>
        <li>
           <%= Html.ActionLink<EventController>( x => x.Edit( default(int?) ), "Post An Event" )%>
        </li>
        <li>
           <%= Html.ActionLink<EventAdminController>( x => x.List(), "Events Created By Me" ) %>
        </li>
        <li>
           <%= Html.ActionLink<ClubController>( x => x.Edit( default( int? ) ), "Create A Club" )%>
        </li>
        <li>
           <%= Html.ActionLink<ClubAdminController>( x => x.List( ), "Clubs Created By Me" )%>
        </li>
        </div>
     </ul>
  </div>
  <% } %>
</code>```

答: One way that I've done this using cookies was to attach an unload handler that set the cookie - it did it by finding the IDs of all the classes that were currently not the default (whether that's visible or hidden is up to you), and then saving them into the cookie. When the page was loaded again, it would check if that cookie existed, and if it did it would use the string of IDs as a selector to apply the toggled from the default class to the items saved earlier.

Title: Saving UI state with cookie and jquery

Body:
I'm trying to save the state of a collapsible menu, and using the jquery cookie plug in .. I'm having trouble so far though.. any help?

The script that does the collapse/expand

The xhtml

User Options-

            <%= Html.ActionLink<EventController>( x => x.List(), "Events Near Me" )%>

            <%= Html.ActionLink<MyEventsController>( x => x.List(), "My Events" )%>

            <%= Html.ActionLink<AccountController>( x => x.Edit(), "My Profile" )%>

            <%= Html.ActionLink<ClubController>( x => x.List(), "Clubs Near Me" )%>

            <%= Html.ActionLink<MyClubsController>( x => x.List(), "My Clubs" )%>

            <%= Html.ActionLink<AccountController>( x => x.ChangePassword(), "Change My Password" )%>

            <%= Html.ActionLink<DependantController>( x => x.List(), "My Dependants" ) %>

  <% if ( ViewModel.Profile.HasOrganizerInfo ) { %>

Organizer Details-

           <%= Html.ActionLink<AccountController>( x => x.Organizer(), "Organizer Details" )%>

           <%= Html.ActionLink<EventController>( x => x.Edit( default(int?) ), "Post An Event" )%>

           <%= Html.ActionLink<EventAdminController>( x => x.List(), "Events Created By Me" ) %>

           <%= Html.ActionLink<ClubController>( x => x.Edit( default( int? ) ), "Create A Club" )%>

           <%= Html.ActionLink<ClubAdminController>( x => x.List( ), "Clubs Created By Me" )%>

  <% } %>