问:
.htaccess - Force https, force to subfolder, force www, don't break site
I have been having a very difficult time editing my .htaccess file to do these three things together.  I have been able to get each part separately but I just do not understand how the logic flow works to get them all to work.

This is the best I have been able to pull together using the demo at bluehost support
http://helpdesk.bluehost.com/index.php/kb/article/000347

I appreciate any help resolving this issue.

```<code># Use PHP5 Single php.ini as default
AddHandler application/x-httpd-php5s .php
# Bluehost.com
# .htaccess main domain to subdirectory redirect
# Copy and paste the following code into the .htaccess file
# in the public_html folder of your hosting account
# make the changes to the file according to the instructions.
# Do not change this line.
RewriteEngine on
# Change yourdomain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?sampleurl.com$
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/folder/
# Don't change this line.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /folder/$1
# Change yourdomain.com to be your main domain again.
# Change 'subdirectory' to be the directory you will use for your main domain
# followed by / then the main file for your folder, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?sampleurl.com$
RewriteRule ^(/)?$ folder/index.php

RewriteCond %{HTTP_HOST} ^sampleurl\.com$ [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://www.sampleurl.com/$1 [L]

# For security reasons, Option all cannot be overridden.
# Options All -Indexes
# Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes
</code>```

Update:

Well after a long time using the following I have run into issues.

```<code>IndexIgnore *
RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule (.*) https://www.example.com/site/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/site/
RewriteRule (.*) https://www.example.com/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 443
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule (.*) https://www.example.com/site/$1 [L,R]
</code>```

New Issues.

Bluehost has an application that quickly installs and updates open source applications like wordpress, joomla, phpbb etc.  Well apparently my new super .htaccess file completely breaks their system.  The only way I can run updates and installs is to move the .htaccess to .htaccess.bak until the upgrade or install is complete.  Then move it back.

I can't create any .htaccess on other sites that I host in other directories.  e.g. I have a master account that I store in /www/site/ that this script forces requests into.  Unfortunately my other sites stored in /www/site2/ and /www/site3/ don't work well.  First I have to create a blank .htaccess to prevent it from pulling the .htaccess above found in /www/.  For some reason if I try to do anything like force www.site2.com I get 500 error's saying I am forcing too many redirects.

I have a theory that my solution above needs to be a little more specific, to make sure it only effects request sent to example.com.  (I think the line with anything not containing /site/ is a little to broad).

I appreciate any support resolving this.  Would save me a bit of headaches!

Update II:

I do not believe I have access to apache config.  Only option I see in cpanel is apache handlers (not really sure what that section does).

I will submit a ticket to see what location the simplescripts server runs from.  I believe it runs from "https://www.simplescripts.com".  What edit would you recommend I add to ignore this domain?

My host bluehost starts you with a primary account and then subdomains.  The primary account's location is set at user\www.  Unfortunatly this gets messy when you try to host multiple domains.  That is why I use .htaccess to force requests that hit that directory into the \site\ directory.  Thus trapping the primary site into the \site\ directory.

I think the relocation issue I was having with one of my subdomains was due to wordpress trying to force a domain without www and then me writing an .htaccess file forcing www.  That caused the infinite loop, not my .htaccess file this thread is about.  If I can resolve the simplescripts issue I am gmoney ;)

答:
I'd think something like this would work

```<code>RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/folder/
RewriteRule (.*) https://www.example.com/folder/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/folder/
RewriteRule (.*) https://www.example.com/$1 [L,R]
</code>```

but I confess I haven't tested. You can add in all the don't redirect if the file exists, etc., if you want.

In case you haven't seen it, here is the mod_rewrite documentation.

edit:

In response to updated question:

The first thing I notice is that it appears you may have enough control over your setup to put the rewrites in the Apache config files (in the VirtualHost sections) instead of in htaccess files, that'll immediately solve your problem with your other sites.

The first problem, it sounds like you'll need to add RewriteCond to exclude whichever URLs the Bluehost software uses. Either that, or access the Bluehost software under a different VirtualHost (once you've put the rewrite stuff inside the VirtualHost blocks).

If you can't edit your Apache config, then the easiest fix for the other sites it to not make them a subdirectory (on the filesystem) of your main site. That's rather weird, anyway. Move your main site to a sub-directory of /www as well if need be.

Personally, I put all sites in /srv/www/com.site-name.www on my servers (that is, reverse order, with the top-level-domain first, it makes related stuff group together when sorted alphabetically. E.g., when you have www.example.com and static.example.com)

Body:
I have been having a very difficult time editing my .htaccess file to do these three things together.  I have been able to get each part separately but I just do not understand how the logic flow works to get them all to work.

This is the best I have been able to pull together using the demo at bluehost support
http://helpdesk.bluehost.com/index.php/kb/article/000347

I appreciate any help resolving this issue.

# Use PHP5 Single php.ini as default
AddHandler application/x-httpd-php5s .php
# Bluehost.com
# .htaccess main domain to subdirectory redirect
# Copy and paste the following code into the .htaccess file
# in the public_html folder of your hosting account
# make the changes to the file according to the instructions.
# Do not change this line.
RewriteEngine on
# Change yourdomain.com to be your main domain.
RewriteCond %{HTTP_HOST} ^(www.)?sampleurl.com$
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteCond %{REQUEST_URI} !^/folder/
# Don't change this line.
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
# Change 'subdirectory' to be the directory you will use for your main domain.
RewriteRule ^(.*)$ /folder/$1
# Change yourdomain.com to be your main domain again.
# Change 'subdirectory' to be the directory you will use for your main domain
# followed by / then the main file for your folder, index.php, index.html, etc.
RewriteCond %{HTTP_HOST} ^(www.)?sampleurl.com$
RewriteRule ^(/)?$ folder/index.php

RewriteCond %{HTTP_HOST} ^sampleurl\.com$ [OR]
RewriteCond %{REQUEST_FILENAME} -d [OR]
RewriteCond %{SERVER_PORT} 80
RewriteRule (.*) https://www.sampleurl.com/$1 [L]

# For security reasons, Option all cannot be overridden.
# Options All -Indexes
# Options ExecCGI Includes IncludesNOEXEC SymLinksIfOwnerMatch -Indexes

Update:

Well after a long time using the following I have run into issues.

IndexIgnore *
RewriteEngine On

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule (.*) https://www.example.com/site/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/site/
RewriteRule (.*) https://www.example.com/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 443
RewriteCond %{REQUEST_URI} !^/site/
RewriteRule (.*) https://www.example.com/site/$1 [L,R]

New Issues.

Bluehost has an application that quickly installs and updates open source applications like wordpress, joomla, phpbb etc.  Well apparently my new super .htaccess file completely breaks their system.  The only way I can run updates and installs is to move the .htaccess to .htaccess.bak until the upgrade or install is complete.  Then move it back.

I can't create any .htaccess on other sites that I host in other directories.  e.g. I have a master account that I store in /www/site/ that this script forces requests into.  Unfortunately my other sites stored in /www/site2/ and /www/site3/ don't work well.  First I have to create a blank .htaccess to prevent it from pulling the .htaccess above found in /www/.  For some reason if I try to do anything like force www.site2.com I get 500 error's saying I am forcing too many redirects.

I have a theory that my solution above needs to be a little more specific, to make sure it only effects request sent to example.com.  (I think the line with anything not containing /site/ is a little to broad).

I appreciate any support resolving this.  Would save me a bit of headaches!

Update II:

I do not believe I have access to apache config.  Only option I see in cpanel is apache handlers (not really sure what that section does).

I will submit a ticket to see what location the simplescripts server runs from.  I believe it runs from "https://www.simplescripts.com".  What edit would you recommend I add to ignore this domain?

My host bluehost starts you with a primary account and then subdomains.  The primary account's location is set at user\www.  Unfortunatly this gets messy when you try to host multiple domains.  That is why I use .htaccess to force requests that hit that directory into the \site\ directory.  Thus trapping the primary site into the \site\ directory.

I think the relocation issue I was having with one of my subdomains was due to wordpress trying to force a domain without www and then me writing an .htaccess file forcing www.  That caused the infinite loop, not my .htaccess file this thread is about.  If I can resolve the simplescripts issue I am gmoney ;)

Body:
I'd think something like this would work

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} !^/folder/
RewriteRule (.*) https://www.example.com/folder/$1 [L,R]

RewriteCond %{HTTP_HOST} ^example\.com$ [OR]
RewriteCond %{SERVER_PORT} 80
RewriteCond %{REQUEST_URI} ^/folder/
RewriteRule (.*) https://www.example.com/$1 [L,R]

but I confess I haven't tested. You can add in all the don't redirect if the file exists, etc., if you want.

In case you haven't seen it, here is the mod_rewrite documentation.

edit:

In response to updated question:

The first thing I notice is that it appears you may have enough control over your setup to put the rewrites in the Apache config files (in the VirtualHost sections) instead of in htaccess files, that'll immediately solve your problem with your other sites.

The first problem, it sounds like you'll need to add RewriteCond to exclude whichever URLs the Bluehost software uses. Either that, or access the Bluehost software under a different VirtualHost (once you've put the rewrite stuff inside the VirtualHost blocks).

If you can't edit your Apache config, then the easiest fix for the other sites it to not make them a subdirectory (on the filesystem) of your main site. That's rather weird, anyway. Move your main site to a sub-directory of /www as well if need be.

Personally, I put all sites in /srv/www/com.site-name.www on my servers (that is, reverse order, with the top-level-domain first, it makes related stuff group together when sorted alphabetically. E.g., when you have www.example.com and static.example.com)


来源: stackexchange

问:
Correct way to check if value exists and is an array with items
So one way to do it would be..

```<code>if(isset($arrayVar)) {
    if(is_array($arrayVar)) {
        if(count($arrayVar) > 0) {
            // Success
            print_r($arrayVar);
        }
    }
}
</code>```

Are there any better ways?

答:
You can check like this,</p>

```<code>if(is_array($arrayVar) && sizeof($arrayVar) > 0)
{
   echo 'Array value exists';
}
else
{
   echo 'array empty or it is not array';
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
So one way to do it would be..

if(isset($arrayVar)) {
    if(is_array($arrayVar)) {
        if(count($arrayVar) > 0) {
            // Success
            print_r($arrayVar);
        }
    }
}

Are there any better ways?

Body:
You can check like this,

if(is_array($arrayVar) && sizeof($arrayVar) > 0)
{
   echo 'Array value exists';
}
else
{
   echo 'array empty or it is not array';
}


问:
Write text behind image keeping everything responsive
This is what I'm trying to achieve through HTML/CSS on my website:

I want to add a div of text behind an image which I have been able to achieve on a laptop screen but I am struggling to keep it from overlapping with the text to the image's right when I resize the screen. How can I keep this structure responsive?

答: Why not break the text into a new row on mobile and have it below the image?</p>


问:
Problems with calculated fields
I'm having problems with calculated fields. I'd like to create something like this:

```<code>[Column("birthyear")]
private int? _BirthYear;
public int? BirthYear {
   get {
      return _BirthYear;
   }
   set {
      _BirthYear = value;
      RaisePropertyChanged();
   }
}
public int? Age {
   get {
      if (BirthYear != null) return DateTime.Now.Year - (int)BirthYear;
         return 0;
   }
   set {
      BirthYear = DateTime.Now.Year - value;
      RaisePropertyChanged();
   }
}
</code>```

But when I run the application I get the following error:

Unknown column 'Extent.Age' in 'field list'.

How can I properly implement this functionality?

答:
it look like issue was in reading it from database.

Can you try the below one.

```<code>[NotMapped]
public int? Age {
....
....
</code>```

Title: Problems with calculated fields

Body:
I'm having problems with calculated fields. I'd like to create something like this:

[Column("birthyear")]
private int? _BirthYear;
public int? BirthYear {
   get {
      return _BirthYear;
   }
   set {
      _BirthYear = value;
      RaisePropertyChanged();
   }
}
public int? Age {
   get {
      if (BirthYear != null) return DateTime.Now.Year - (int)BirthYear;
         return 0;
   }
   set {
      BirthYear = DateTime.Now.Year - value;
      RaisePropertyChanged();
   }
}

But when I run the application I get the following error:

Unknown column 'Extent.Age' in 'field list'.

How can I properly implement this functionality?

Body:
it look like issue was in reading it from database.

Can you try the below one.

[NotMapped]
public int? Age {
....
....


问:
How to install apesmit python package?
I tried to install apesmit from PyPi ( pip install apesmit ). But I'm getting error Could not find a version that satisfies the requirement apesmit (from versions: )
No matching distribution found for apesmit
Could you help me to do this?

答: Because the author hasn't uploaded any packages yet and there is nothing to download. The list of packages at https://pypi.python.org/pypi/apesmit or https://pypi.python.org/simple/apesmit/ is empty.</p>

Title: How to install apesmit python package?


问:
load/import fails in mysql due to date format
I am importing data from a .csv file into the table in MySQL, in file there is multiple date columns in the format of 04-05-2017 , which MySQL doesn't accepts.

It fails saying

ERROR 1292 (22007): Incorrect date value: '04-05-2017' for column 'START_DATE' at row 1

Please note that my

|START_DATE             | date          |

is a date column.

Thanks

答:
Try it like this:

```<code>LOAD DATA INFILE 'file.csv'
INTO TABLE t1
FIELDS TERMINATED BY ','
(column1, @var1, column3, ...)
SET column2 = STR_TO_DATE(@var1,'%d-%m-%Y')
</code>```

Replace the column with a variable. Then in the SET command you convert your string to a proper date.

read more about load data infile here

and here is more information about str_to_date()

and finally more information about using variables, if you need to have those

Body:
Try it like this:

LOAD DATA INFILE 'file.csv'
INTO TABLE t1
FIELDS TERMINATED BY ','
(column1, @var1, column3, ...)
SET column2 = STR_TO_DATE(@var1,'%d-%m-%Y')

Replace the column with a variable. Then in the SET command you convert your string to a proper date.

read more about load data infile here

and here is more information about str_to_date()

and finally more information about using variables, if you need to have those


问:
Left join in Linq to Entities
I am trying to do a left join using Linq, and failing. I have tried to follow a few examples, and ended up with this (failinmg) linq query:

```<code>   var defaultCategories = (from cats in Db.categories
                                 join defaults in Db.payee_default_category on cats.category_id equals
                                     defaults.category_id
                                     into merged
                                 from results in merged.DefaultIfEmpty()
                                 select new {cats.category_id, cats.description}).ToList();
</code>```

So, I need to get ALL items in my Categories table, join to a payee_default_category on Categories.category_id = Payee_Default_Category.Category_id, and return the Category_id, the Category.Description, and a boolean of if there is a record in the payee_default_category table.

However, (overlooking the fact that I am not showing if there is a matching record...) at runtime, I get an error:

"LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable1[Data.payee_default_category] DefaultIfEmpty[payee_default_category](System.Collections.Generic.IEnumerable1[Data.payee_default_category])' method, and this method cannot be translated into a store expression."

答:
First of all, the DefaultIfEmpty method is not supported in version 1 of Entity Framework, but it is supported in version 4. You may want to upgrade.

Secondly, since you're only looking for a boolean to determine whether there are any defaults, you aren't doing a real outer join so much as an "exists," and you should be able to achieve it like this:

```<code>var defaultCategories =
   (from cats in Db.categories
    let defaults = Db.payee_default_category.Where(
        d => d.category_id == cats.category_id)
    select new {cats.category_id, cats.description, hasDefaults = defaults.Any()})
    .ToList();
</code>```

Also, your Entity Framework context would ideally be set up with table mappings, which would make your query even simpler:

```<code>var defaultCategories =
    (from c in Db.categories
     select new {c.category_id, c.description,
         hasDefaults = c.payee_default_categories.Any()})
    .ToList();
</code>```

ContentLicense: CC BY-SA 2.5

Title: Left join in Linq to Entities

Body:
I am trying to do a left join using Linq, and failing. I have tried to follow a few examples, and ended up with this (failinmg) linq query:

   var defaultCategories = (from cats in Db.categories
                                 join defaults in Db.payee_default_category on cats.category_id equals
                                     defaults.category_id
                                     into merged
                                 from results in merged.DefaultIfEmpty()
                                 select new {cats.category_id, cats.description}).ToList();

So, I need to get ALL items in my Categories table, join to a payee_default_category on Categories.category_id = Payee_Default_Category.Category_id, and return the Category_id, the Category.Description, and a boolean of if there is a record in the payee_default_category table.

However, (overlooking the fact that I am not showing if there is a matching record...) at runtime, I get an error:

"LINQ to Entities does not recognize the method 'System.Collections.Generic.IEnumerable1[Data.payee_default_category] DefaultIfEmpty[payee_default_category](System.Collections.Generic.IEnumerable1[Data.payee_default_category])' method, and this method cannot be translated into a store expression."

Body:
First of all, the DefaultIfEmpty method is not supported in version 1 of Entity Framework, but it is supported in version 4. You may want to upgrade.

Secondly, since you're only looking for a boolean to determine whether there are any defaults, you aren't doing a real outer join so much as an "exists," and you should be able to achieve it like this:

var defaultCategories =
   (from cats in Db.categories
    let defaults = Db.payee_default_category.Where(
        d => d.category_id == cats.category_id)
    select new {cats.category_id, cats.description, hasDefaults = defaults.Any()})
    .ToList();

Also, your Entity Framework context would ideally be set up with table mappings, which would make your query even simpler:

var defaultCategories =
    (from c in Db.categories
     select new {c.category_id, c.description,
         hasDefaults = c.payee_default_categories.Any()})
    .ToList();


问:
Git commit messages if I split a single task into 2 commits
For example, if I haven’t finished a task at the end of a day but want to commit and push my work. The next day I’ll finish the task and commit the finished task again. What should the 2 commit messages look like?

For example Apply new Changes (Part1) and Apply new Changes (Part2) looks not like a good commit message to me.

答:
Unfinished work should not be pushed. A commit should be atomic1, containing one (and only one) complete task unless it can be split into reasonable subtasks.

If you want to push your unfinished work for the backup purpose, use a branch that is OK to rebase the next day when you amend your previous commit.

1 Atomic in the meaning of using VCS, there is another meaning describing how VCS shall work internally.


问:
Mutex for two threads in C++
I've created two threads that use a variable declared in main via pthread_create's last argument. I want thread2  to use modify the value of that variable after thread1 is done with a set of particular instructions. I know how we can use mutex in one thread but how about two or more threads?
Refer to the following code:</p>

```<code>#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 6
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *even(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( !(i % 2) )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Even Thread: " << sum << endl;
    pthread_mutex_lock(&mutex);
    *((int*)arg) = sum;
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond);
}
void *odd(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( i % 2 )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Odd Thread: " << sum << endl;
    pthread_cond_wait(&cond, &mutex);
    *((int*)arg) = *((int*)arg) + sum;
}

int main()
{
    int mainSum = 0;
    pthread_t tidO, tidE;
    pthread_create(&tidO, NULL, odd, (void *)&mainSum);
    pthread_create(&tidE, NULL, even, (void *)&mainSum);
    pthread_join(tidO, NULL);
    pthread_join(tidE, NULL);
    cout << "Sum of first " << NUM << " Natural Numbers: " << mainSum << endl;
    return 0;
}
</code>```

答:
Your use case needs a condition variable combined with a mutex.

http://en.cppreference.com/w/cpp/thread/condition_variable

Title: Mutex for two threads in C++

Body:
I've created two threads that use a variable declared in main via pthread_create's last argument. I want thread2  to use modify the value of that variable after thread1 is done with a set of particular instructions. I know how we can use mutex in one thread but how about two or more threads?
Refer to the following code:

#include<iostream>
#include<unistd.h>
#include<stdlib.h>
#include<pthread.h>
#define NUM 6
using namespace std;
pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
void *even(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( !(i % 2) )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Even Thread: " << sum << endl;
    pthread_mutex_lock(&mutex);
    *((int*)arg) = sum;
    pthread_mutex_unlock(&mutex);
    pthread_cond_signal(&cond);
}
void *odd(void *arg)
{
    int sum = 0;
    int count = 0;
    for (int i = 1; count < NUM/2; i++)
    {
        if( i % 2 )
        {
            count++;
            sum += i;
        }
    }
    cout << "In Odd Thread: " << sum << endl;
    pthread_cond_wait(&cond, &mutex);
    *((int*)arg) = *((int*)arg) + sum;
}

int main()
{
    int mainSum = 0;
    pthread_t tidO, tidE;
    pthread_create(&tidO, NULL, odd, (void *)&mainSum);
    pthread_create(&tidE, NULL, even, (void *)&mainSum);
    pthread_join(tidO, NULL);
    pthread_join(tidE, NULL);
    cout << "Sum of first " << NUM << " Natural Numbers: " << mainSum << endl;
    return 0;
}


问:
How to make a python list from a .csv list?
I want to know how to make a .csv list into a python list which I can do plotting and calculating:

I used:

```<code>    fpath = r'C:112017\temp\tT.csv'
    with open(fpath,'r') as csvfile:
         reader = csv.reader(csvfile, delimiter=',')
         for row in reader:
             print(list(reader))
</code>```

it gives me lists like this (which I dont' want):

```<code>    [['2014-12-30', '18.34244791666665'], ['2014-12-31', '18.540224913494818'], ['2015-01-01', '18.15729166666666'],......
</code>```

If I use

```<code>    print(row)
</code>```

it gives me lists like this (looks better but I still can not use it for calculating):

```<code>    ...
    ['2016-07-27', '20.434809022479584']
    ['2016-07-28', '21.395138886239796']
    ['2016-07-29', '20.81571181284057']
    ['2016-07-30', '20.565711801250778']
    ...
</code>```

How can I use panda to make a list? Or is there any easier way to achieve this? Is that possible to use something like:

```<code>    date = row[0]
    temp = row[1]
    lis = pd.DataFrame(date,temp)
</code>```

I guess there are some basic mistakes, but I can't fix it by myself.
Thank you for your time to help.

答:
I guess you are trying to get the columns as list i.e. a list of dates and temperatures.</p>

```<code>fpath = r'C:112017\temp\tT.csv'
with open(fpath,'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    data = list(reader)

date, temp = list(map(list, zip(*data)))
# for python 2 use map(list,zip(*data))
# converting temp to float
temp = list(map(float,temp))
</code>```

Body:
I want to know how to make a .csv list into a python list which I can do plotting and calculating:

I used:

    fpath = r'C:112017\temp\tT.csv'
    with open(fpath,'r') as csvfile:
         reader = csv.reader(csvfile, delimiter=',')
         for row in reader:
             print(list(reader))

it gives me lists like this (which I dont' want):

    [['2014-12-30', '18.34244791666665'], ['2014-12-31', '18.540224913494818'], ['2015-01-01', '18.15729166666666'],......

If I use

    print(row)

it gives me lists like this (looks better but I still can not use it for calculating):

    ...
    ['2016-07-27', '20.434809022479584']
    ['2016-07-28', '21.395138886239796']
    ['2016-07-29', '20.81571181284057']
    ['2016-07-30', '20.565711801250778']
    ...

How can I use panda to make a list? Or is there any easier way to achieve this? Is that possible to use something like:

    date = row[0]
    temp = row[1]
    lis = pd.DataFrame(date,temp)

I guess there are some basic mistakes, but I can't fix it by myself.
Thank you for your time to help.

Body:
I guess you are trying to get the columns as list i.e. a list of dates and temperatures.

fpath = r'C:112017\temp\tT.csv'
with open(fpath,'r') as csvfile:
    reader = csv.reader(csvfile, delimiter=',')
    data = list(reader)

date, temp = list(map(list, zip(*data)))
# for python 2 use map(list,zip(*data))
# converting temp to float
temp = list(map(float,temp))


问:
Why does this JS not work?
I'm trying to calculate the size of 3 elements and if they're greater than the window height, apply another class to a 4 element.

This is what I have so far:

```<code>var limit = $(".logo").height() + $(".nav-items").height() + $(".nav-footer").height();
var win = $(window).height();
    $(document).ready(function(checkHeight) {
        if (limit > win) {
            var element = document.getElementById("sidebar-column");
            element.classList.toggle("red");
    }
});
</code>```

Update:

I would like to apply the check to an existing function - I am VERY NEW to all this, thank you for your patients.

```<code>function aboutUssubNav() {
    var element = document.getElementById("about-us");
    element.classList.toggle("open");
    var element = document.getElementById("about-us-button");
    element.classList.toggle("open");
    // Check Height of Sidebar Elements to position Sidebar Footer
    var limit = $(".logo").height() + $(".nav-items").height() + $(".nav-footer").height();
    var win = $(window).height();
    if (limit > win) {
         var element = document.getElementById("sidebar-column");
         element.classList.toggle("red");
    }
}
</code>```

答:
It is because you are the limit value on document.ready event which is unlikely to get fired again during the life cycle of your page.

Simply remove the document.ready and make it

```<code>var limit = $(".logo").height() + $(".nav-items").height() + $(".nav-footer").height();
var win = $(window).height();
if (limit > win) {
     var element = document.getElementById("sidebar-column");
     element.classList.toggle("red");
}
</code>```

Title: Why does this JS not work?

Body:
I'm trying to calculate the size of 3 elements and if they're greater than the window height, apply another class to a 4 element.

This is what I have so far:

var limit = $(".logo").height() + $(".nav-items").height() + $(".nav-footer").height();
var win = $(window).height();
    $(document).ready(function(checkHeight) {
        if (limit > win) {
            var element = document.getElementById("sidebar-column");
            element.classList.toggle("red");
    }
});

Update:

I would like to apply the check to an existing function - I am VERY NEW to all this, thank you for your patients.

function aboutUssubNav() {
    var element = document.getElementById("about-us");
    element.classList.toggle("open");
    var element = document.getElementById("about-us-button");
    element.classList.toggle("open");
    // Check Height of Sidebar Elements to position Sidebar Footer
    var limit = $(".logo").height() + $(".nav-items").height() + $(".nav-footer").height();
    var win = $(window).height();
    if (limit > win) {
         var element = document.getElementById("sidebar-column");
         element.classList.toggle("red");
    }
}

Body:
It is because you are the limit value on document.ready event which is unlikely to get fired again during the life cycle of your page.

Simply remove the document.ready and make it

var limit = $(".logo").height() + $(".nav-items").height() + $(".nav-footer").height();
var win = $(window).height();
if (limit > win) {
     var element = document.getElementById("sidebar-column");
     element.classList.toggle("red");
}


问:
SetWindowsHookEx WH_MOUSE freeze on breakpoint in Win7
helos,

on WinXP my application has been sucessfully using a global mousehook to retrieve mouseposition and clicks even if it does not have the focus. the hook is in a separate .dll and is being initialized like this (in delphi):

```<code>SetWindowsHookEx(WH_MOUSE, @MouseHookCB, HInstance , 0);
</code>```

now on Win7 this basically also works during runtime but i can no longer debug my application nicely (which i can under XP). as soon as i hit a breakpoint, Win7 freezes completely. i cannot switch to another process (even taskmanager fails to open). if i am lucky i can stop my process in the IDE. most of the times though i have to restart/logoff to regain access.

i know the problem is related to the mouse-hook as it is not present if i don't use the hook.
this is even if my hookprocedure does nothing but the following:

```<code>CallNextHookEx(MouseHook, Code, wParam, lParam);
</code>```

ie. simply the presence of the hook causes the troubles.

having the globalhooks.dll write something into the EventLog i see that it is still active even while i am on a breakpoint.

i tried to use a lowlevelmouse hook via WH_MOUSE_LL which basically works but gives me strange mouse-move delays while installing the hook and sometimes while resizing a window. also there is a freeze for some seconds when hitting a breakpoint but at least the system recovers after ~5 seconds... therefore this option is even worse as it also affects runtime.

any idea why the WH_MOUSE hook freezes my app during debugging in the first place?

答:
if you're debugging an APP you shouldn't use HInstance.
You're injecting the .exe itself into the global process, when debugging you are halting all mouse processing which could explain your issue.

SetWindowsHookEx documentation states to pass 0 when hoocking into own process and handle to a DLL when hoocking into a remote or global process.

Also make sure MouseHookCB() is resturning the value of CallNextHookEx.

Body:
helos,

on WinXP my application has been sucessfully using a global mousehook to retrieve mouseposition and clicks even if it does not have the focus. the hook is in a separate .dll and is being initialized like this (in delphi):

SetWindowsHookEx(WH_MOUSE, @MouseHookCB, HInstance , 0);

now on Win7 this basically also works during runtime but i can no longer debug my application nicely (which i can under XP). as soon as i hit a breakpoint, Win7 freezes completely. i cannot switch to another process (even taskmanager fails to open). if i am lucky i can stop my process in the IDE. most of the times though i have to restart/logoff to regain access.

i know the problem is related to the mouse-hook as it is not present if i don't use the hook.
this is even if my hookprocedure does nothing but the following:

CallNextHookEx(MouseHook, Code, wParam, lParam);

ie. simply the presence of the hook causes the troubles.

having the globalhooks.dll write something into the EventLog i see that it is still active even while i am on a breakpoint.

i tried to use a lowlevelmouse hook via WH_MOUSE_LL which basically works but gives me strange mouse-move delays while installing the hook and sometimes while resizing a window. also there is a freeze for some seconds when hitting a breakpoint but at least the system recovers after ~5 seconds... therefore this option is even worse as it also affects runtime.

any idea why the WH_MOUSE hook freezes my app during debugging in the first place?


问:
TRACKER : error TRK0005: Failed to locate: "CL.exe". The system cannot find the file specified
I'm trying to execute the following command in a Node.js project on Windows 8:

npm install web3@1.0.0-beta.24

But I'm gettig an error that I have node idea how to deal with.

TRACKER : error TRK0005: Failed to locate: "CL.exe". The system cannot
  find the file specified. [C:\Projects\myproject\node_modules\scrypt\build\copied_files.vcxproj]

Here is the entire output:

scrypt@6.0.3 preinstall C:\Projects\myproject\node_modules\scrypt
    node node-scrypt-preinstall.js

scrypt@6.0.3 install C:\Projects\myproject\node_modules\scrypt
    node-gyp rebuild

C:\Projects\myproject\node_modules\scrypt>if not defined
  npm_config_node_gyp (node "C:\Program
  Files\nodejs\node_modules\npm\bin\node-gyp-bin\....\node_modules\node-gyp\bin\node-g
  yp.js" rebuild )  else (node "" rebuild ) Warning: Missing input
  files: C:\Projects\myproject\node_modules\scrypt\build..\scrypt\win\include\config.h
  Building the projects in this solution one at a time. To enable
  parallel build, please add the "/m" switch. C:\Program Files
  (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppBuild.targets(366,5):
  warning MSB8003: Could not find WindowsSDKDir variable from the
  registry.  TargetFrameworkVersion  or PlatformToolset may be set to an
  invalid version number. [C:\Projects\myproject\node_modules\scrypt\build\copied_files.vcxproj]   Copying
  scrypt/win/include/config.h to scrypt/scrypt-1.2.0/config.h   The
  system cannot find the file specified. TRACKER : error TRK0005: Failed
  to locate: "CL.exe". The system cannot find the file specified.
  [C:\Projects\myproject\node_modules\scrypt\build\copied_files.vcxproj]

C:\Program Files
  (x86)\MSBuild\Microsoft.Cpp\v4.0\V140\Microsoft.CppBuild.targets(366,5):
  warning MSB8003: Could not find WindowsSDKDir variable from the
  registry.  TargetFrameworkVersion  or PlatformToolset may be set to an
  invalid version number. [C:\Projects\myproject\node_modules\scrypt\build\scrypt_wrapper.vcxproj] TRACKER :
  error TRK0005: Failed to locate: "CL.exe". The system cannot find the
  file specified. [C:\Projects\myproject\node_modules\scrypt\build\scrypt_wrapper.vcxproj]

gyp ERR! build error gyp ERR! stack Error: C:\Program Files
  (x86)\MSBuild\14.0\bin\msbuild.exe failed with exit code: 1 gyp ERR!
  stack     at ChildProcess.onExit (C:\Program
  Files\nodejs\node_modules\npm\node_modules\node-gyp\lib\build.js:258:23)
  gyp ERR! stack     at emitTwo (events.js:126:13) gyp ERR! stack     at
  ChildProcess.emit (events.js:214:7) gyp ERR! stack     at
  Process.ChildProcess._handle.onexit (internal/child_process.js:198:12)
  gyp ERR! System Windows_NT 6.2.9200 gyp ERR! command "C:\Program
  Files\nodejs\node.exe" "C:\Program
  Files\nodejs\node_modules\npm\node_modules\node-gyp\bin\node-gyp.js"
  "rebuild" gyp ERR! cwd C:\Projects\myproject\node_modules\scrypt gyp ERR! node -v v8.9.1 gyp ERR! node-gyp
  -v v3.6.2 gyp ERR! not ok npm WARN inbanner@1.6.0 No repository field.

npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! scrypt@6.0.3
  install: node-gyp rebuild npm ERR! Exit status 1 npm ERR! npm ERR!
  Failed at the scrypt@6.0.3 install script. npm ERR! This is probably
  not a problem with npm. There is likely additional logging output
  above.

npm ERR! A complete log of this run can be found in: npm ERR!

  C:\Users\user\AppData\Roaming\npm-cache_logs\2017-11-13T01_31_12_133Z-debug.log

Help!

答:
This packages seems to be requiring native compiling. You need to install Visual Studio C++ Build Tools for the same. You can download the same from below link

http://landinghub.visualstudio.com/visual-cpp-build-tools

Also after that you need to make sure that CL.exe is available in your path. It would be on a path like C:\Program Files\Microsoft Visual Studio 10.0\VC\ce\bin. This would change based on the version of build tools you have installed.

You will need to make sure to update your Windows PATH environment variable if the setup doesn't do that for you.

Also if npm still fails, you can always try using yarn

```<code>yarn add web3@1.0.0-beta.24
</code>```

Body:
This packages seems to be requiring native compiling. You need to install Visual Studio C++ Build Tools for the same. You can download the same from below link

http://landinghub.visualstudio.com/visual-cpp-build-tools

Also after that you need to make sure that CL.exe is available in your path. It would be on a path like C:\Program Files\Microsoft Visual Studio 10.0\VC\ce\bin. This would change based on the version of build tools you have installed.

You will need to make sure to update your Windows PATH environment variable if the setup doesn't do that for you.

Also if npm still fails, you can always try using yarn

yarn add web3@1.0.0-beta.24


问:
read from a formatted test file using fscanf() in c
Here is the text file

```<code>Username:user1  Password:pass1
Username:user2  Password:pass2
</code>```

I want to read the username and password from the text. the problem is there is not way to change the format of the text. i tried to read but as there is not space between colon(:), it gives whole username:user1 as string but i want only user1. i referred to this question but it did not help as there is no space between colon.

I tried :

```<code> while ((fscanf(fp,"Username:%s Password:%s",username,password))!=EOF)
</code>```

but it gives many undefined characters after user1 and loop never ends.

答:
I would use this algorithm:

Read while char read isn't ':'

Start storing all next chars on username var while the char read is !=' '

Remove the last space on the username string

Repeat step 1.

Same as step 2 but now we store the read data on password value while the read char is != ''\n'

Repeat while ! end of file

Body:
Here is the text file

Username:user1  Password:pass1
Username:user2  Password:pass2

I want to read the username and password from the text. the problem is there is not way to change the format of the text. i tried to read but as there is not space between colon(:), it gives whole username:user1 as string but i want only user1. i referred to this question but it did not help as there is no space between colon.

I tried :

 while ((fscanf(fp,"Username:%s Password:%s",username,password))!=EOF)

but it gives many undefined characters after user1 and loop never ends.


问:
How to get return value each state changed in another componentin React
In a React Component Passed a value, if Component Change state, How to return a new value from this component.
If ScrollDetecter state changed how to return value this component?

```<code><ScrollDetector/>

export default class ScrollDetector extends React.Component {
 //Most impotant function only metioned
handleScroll() {
const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight,  html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight) {

  this.setState({
    message:'bottom reached'
  });
} else {
  this.setState({
    message:'not at bottom'
  });
}
}
}
</code>```

How to a particular value to parent component return if bottom reached message state.?

答:
You want to change a parent component on event in child component(ScrollDetector)?

If so pass the callback function, that will update parent component, as a prop.

Let's say you want to change the state of parent component based on scroll. You would have something like this.

```<code><ScrollDetector checkIfBottomReached={this.checkIfBottomReached} />
</code>```

while the implementation of function would be

```<code>isBottomReached() {
    this.setState({ isBottomReached: true });
}
</code>```

or simply pass it shorthanded

```<code><ScrollDetector checkIfBottomReached={() => this.setState({ isBottomReached: true })} />
</code>```

and inside ScrollDetector component you would call this function when you reach the bottom, just by calling this.props.checkIfBottomReached()

Body:
In a React Component Passed a value, if Component Change state, How to return a new value from this component.
If ScrollDetecter state changed how to return value this component?

<ScrollDetector/>

export default class ScrollDetector extends React.Component {
 //Most impotant function only metioned
handleScroll() {
const windowHeight = "innerHeight" in window ? window.innerHeight : document.documentElement.offsetHeight;
const body = document.body;
const html = document.documentElement;
const docHeight = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight,  html.scrollHeight, html.offsetHeight);
const windowBottom = windowHeight + window.pageYOffset;
if (windowBottom >= docHeight) {

  this.setState({
    message:'bottom reached'
  });
} else {
  this.setState({
    message:'not at bottom'
  });
}
}
}

How to a particular value to parent component return if bottom reached message state.?

Body:
You want to change a parent component on event in child component(ScrollDetector)?

If so pass the callback function, that will update parent component, as a prop.

Let's say you want to change the state of parent component based on scroll. You would have something like this.

<ScrollDetector checkIfBottomReached={this.checkIfBottomReached} />

while the implementation of function would be

isBottomReached() {
    this.setState({ isBottomReached: true });
}

or simply pass it shorthanded

<ScrollDetector checkIfBottomReached={() => this.setState({ isBottomReached: true })} />

and inside ScrollDetector component you would call this function when you reach the bottom, just by calling this.props.checkIfBottomReached()


问:
lazily building up an enumerable with breaks in between
I have a collection of objects IEnumerable<object> obs.
I have another collection of objects IEnumerable<object> data.

For each ob in obs I need to find the first item in data that has the same value in a certain property as ob. For example I could be looking for the first item in data that has the same ToString() value as ob. When the first item where the property values match is found, I do something with the found data item and then I check the next ob in obs. If none is found, I throw an error.

Here is a naive approach:

```<code>foreach (object ob in obs)
{
    foreach (object dataOb in data)
        if (ob.ToString() == dataOb.ToString())
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}
</code>```

The disadvantage is that I calculate dataOb.ToString() every time, which is unnecessary.
I could cache it:

```<code>IDictionary<object, string> dataToDataStr = new Dictionary<object, string>();
foreach (object dataObj in data) // collect all ToString values in advance
    dataToDataStr.Add(dataObj, dataObj.ToString());

foreach (object ob in obs)
{
    foreach (object dataOb in dataToDataStr.Keys)
        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}
</code>```

The disadvantage is that I calculate all ToString() values even though it might not be necessary. I might find all matching data objects in the first half of the data collection.

How can I build up the dataToDataStr dictionary (or any other enumerable data structure that lets me retrieve both the object and its only-once-calculated ToString value) lazily?

Here is code (mixed with pseudocode) of what I have in mind:

```<code>IDictionary<object, string> dataToDataStr = new Dictionary<object, string>();
object lastProcessedDataOb = null;

foreach (object ob in obs)
{
    foreach (object dataOb in dataToDataStr.Keys)
        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }

    foreach (object dataOb in data STARTING AFTER lastProcessedDataOb)
    // if lastProcessedDataOb == null, start with the first entry of data
    {
        dataToDataStr.Add(dataOb, dataOb.ToString();
        lastProcessedDataOb = dataOb;

        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}
</code>```

I know it is easy if data was a LinkedList or any collection with indexed access (then I could store a linked list node or an index as lastProcessedDataOb), but it isn't - it is an IEnumerable. Maybe yield return can be used here?

答:
Totally forgot that LINQ uses lazy evaluation...
This should work (I use the new value tuple notation of C# 7):</p>

```<code>IEnumerable<(object, string)> objStrPairs = data.Select(o => (o, o.ToString()));
foreach (object ob in obs)
{
    foreach ((object, string) dataPair in objStrPairs)
        if (ob.ToString() == objStrPairs.Item2)
        {
            ... // do something with objStrPairs.Item1
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}
</code>```

Body:
I have a collection of objects IEnumerable<object> obs.
I have another collection of objects IEnumerable<object> data.

For each ob in obs I need to find the first item in data that has the same value in a certain property as ob. For example I could be looking for the first item in data that has the same ToString() value as ob. When the first item where the property values match is found, I do something with the found data item and then I check the next ob in obs. If none is found, I throw an error.

Here is a naive approach:

foreach (object ob in obs)
{
    foreach (object dataOb in data)
        if (ob.ToString() == dataOb.ToString())
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}

The disadvantage is that I calculate dataOb.ToString() every time, which is unnecessary.
I could cache it:

IDictionary<object, string> dataToDataStr = new Dictionary<object, string>();
foreach (object dataObj in data) // collect all ToString values in advance
    dataToDataStr.Add(dataObj, dataObj.ToString());

foreach (object ob in obs)
{
    foreach (object dataOb in dataToDataStr.Keys)
        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}

The disadvantage is that I calculate all ToString() values even though it might not be necessary. I might find all matching data objects in the first half of the data collection.

How can I build up the dataToDataStr dictionary (or any other enumerable data structure that lets me retrieve both the object and its only-once-calculated ToString value) lazily?

Here is code (mixed with pseudocode) of what I have in mind:

IDictionary<object, string> dataToDataStr = new Dictionary<object, string>();
object lastProcessedDataOb = null;

foreach (object ob in obs)
{
    foreach (object dataOb in dataToDataStr.Keys)
        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }

    foreach (object dataOb in data STARTING AFTER lastProcessedDataOb)
    // if lastProcessedDataOb == null, start with the first entry of data
    {
        dataToDataStr.Add(dataOb, dataOb.ToString();
        lastProcessedDataOb = dataOb;

        if (ob.ToString() == dataToDataStr[dataOb])
        {
            ... // do something with dataOb
            goto ContinueOuter;
        }
    }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}

I know it is easy if data was a LinkedList or any collection with indexed access (then I could store a linked list node or an index as lastProcessedDataOb), but it isn't - it is an IEnumerable. Maybe yield return can be used here?

Body:
Totally forgot that LINQ uses lazy evaluation...
This should work (I use the new value tuple notation of C# 7):

IEnumerable<(object, string)> objStrPairs = data.Select(o => (o, o.ToString()));
foreach (object ob in obs)
{
    foreach ((object, string) dataPair in objStrPairs)
        if (ob.ToString() == objStrPairs.Item2)
        {
            ... // do something with objStrPairs.Item1
            goto ContinueOuter;
        }
    throw new Exception("No matching data found.");

    ContinueOuter: ;
}


问:
difference beetwen path.join(__dirname , 'views') and path.join(__dirname + 'views') in node.js
im stuck with node.js again.

i try the first path.join in my code for setup view engine its not working, the index won't showing up, then i change to path.join(__dirname , 'views'); and its working well, the index showing, i dont know how

can someone explain how this work ?

```<code>path.join(__dirname + 'views');

path.join(__dirname, 'views');
</code>```

this is my script

```<code>app.set('views', path.join(__dirname, 'views')); //its work
app.set('views', path.join(__dirname + 'views')); // if i change like this, its not work
</code>```

答:
path.join is a function. Using the + operator means you send only one argument which is a concatenation of __dirname and 'views'.
The function should return a path which is constructed from the arguments passed. In you case just one, so it won't be a valid path.</p>

Body:
im stuck with node.js again.

i try the first path.join in my code for setup view engine its not working, the index won't showing up, then i change to path.join(__dirname , 'views'); and its working well, the index showing, i dont know how

can someone explain how this work ?

path.join(__dirname + 'views');

path.join(__dirname, 'views');

this is my script

app.set('views', path.join(__dirname, 'views')); //its work
app.set('views', path.join(__dirname + 'views')); // if i change like this, its not work


问:
removing all option of dropdown box in javascript
How can i dynamically remove all options of a drop down box in javascript?</p>

答:
The fastest solution I was able to find is the following code (taken from this article):</p>

```<code>// Fast javascript function to clear all the options in an HTML select element
// Provide the id of the select element
// References to the old <select> object will become invalidated!
// This function returns a reference to the new select object.
function ClearOptionsFast(id)
{
    var selectObj = document.getElementById(id);
    var selectParentNode = selectObj.parentNode;
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelectObj, selectObj);
    return newSelectObj;
}
</code>```

Body:
The fastest solution I was able to find is the following code (taken from this article):

// Fast javascript function to clear all the options in an HTML select element
// Provide the id of the select element
// References to the old <select> object will become invalidated!
// This function returns a reference to the new select object.
function ClearOptionsFast(id)
{
    var selectObj = document.getElementById(id);
    var selectParentNode = selectObj.parentNode;
    var newSelectObj = selectObj.cloneNode(false); // Make a shallow copy
    selectParentNode.replaceChild(newSelectObj, selectObj);
    return newSelectObj;
}


问:
Count from two tables and display the counts in the same table in MYSQL
I have two tables with a primary key and a column(name color)

```<code>Table1
|Color|
|red  |
|green|
|blue |

Table2
|Color|
|red  |
|red  |
|green|
</code>```

I tried

```<code>SELECT  (
        SELECT COUNT(*)
        FROM   table1
        ) AS count1,
        (
        SELECT COUNT(*)
        FROM   table2
    ) AS count2
</code>```

but this gives

```<code>count1|count2|
 3    |3     |
</code>```

How can i get an output grouped with the color like,

```<code>|Color|count1| count2
|red  | 1    |2
|green| 1    |1
|blue |1     |0
</code>```

答:
```<code>SELECT
      color
    , MAX(CASE WHEN tabl = 'T1' THEN count_of END) count1
    , MAX(CASE WHEN tabl = 'T2' THEN count_of END) count2
FROM (
      SELECT 'T1' tabl, Color, COUNT(*) count_of FROM table1 GROUP BY Color
      UNION ALL
      SELECT 'T2' tabl , Color , COUNT(*)        FROM table2 GROUP BY color
     ) d
GROUP BY color
</code>```

Body:
I have two tables with a primary key and a column(name color)

Table1
|Color|
|red  |
|green|
|blue |

Table2
|Color|
|red  |
|red  |
|green|

I tried

SELECT  (
        SELECT COUNT(*)
        FROM   table1
        ) AS count1,
        (
        SELECT COUNT(*)
        FROM   table2
    ) AS count2

but this gives

count1|count2|
 3    |3     |

How can i get an output grouped with the color like,

|Color|count1| count2
|red  | 1    |2
|green| 1    |1
|blue |1     |0


问:
What languages allow cross-platform native executables to be created?
I'm frustrated to discover that Java lacks an acceptable solution for creating programs that will run via double-click.  Other than .NET for Windows, what modern and high-level programming languages can I write code in that can be compiled for various platforms and run as a native/binary in each (Windows, Linux, OSX (optional))

Assuming I wanted to write code in python, for instance, is there a cohesive way that I could distribute my software which wouldn't require users to do anything special to get it to run?  I want to write and distribute software for computer-illiterate and Java has turned out to be a real pain in this respect.

CLARIFICATION: When i say cross-platform I mean that there are ways I can compile my source code using different compilers for each target system.  I don't need a compile-once solution... I just want a simple experience for users of the software even if I need to compile it and work out code issues for each target platform.

答:
Rust should be in this list.

Install the Rust toolchain from https://www.rust-lang.org/en-US/

cargo new "my_first_rust_progam" --bin

cd my_first_rust_progam

cargo run

No really that's it. No pre-installation requisites for runtimes or frameworks for end users. It's really that simple. You just wrote and compiled a tiny "hello world" source to a native binary and executed it too.

There's nice Documentation at https://doc.rust-lang.org/ to get you started. Learn Rust today!


问:
XML serialization library interoperability between Java and Python
I have been searching for an xml serialization library that can serialize and deserialize an (Java/Python) object into xml and back. I am using XStream right now for Java. If XStream had a python version to deserialize from xml generated by Xstream that would have done it for me. Thrift or such other libraries is not going to work unless they allow the data format to be xml. I am looking for suggestion for any library that can do it. - Thanks</p>

答:
The problem is (like sort of suggested by other answers) that XStream is a Java object serialization framework, and not general data mapping/binding framework. This is by design (see XStream FAQ): upside is that it can nicely serialize and deserialize all kinds of Java objects out-of-box. Downside is that resulting XML structure is fairly rigid, and while you can rename things there isn't much other configurability.

But XStream is not the only Java XML handling library. I would suggest checking out either JAXB reference implementation or JibX as possibly better alternatives, so that you have more control over XML to process. This may be necessary to achieve good interoperability.


问:
Disable text on top of my spinner
This is my spinner init code:

```<code>private void InitSpinner()
{
    spnAvatar = FindViewById<Spinner>(Resource.Id.btn_avatarProfile);

    var adapter = ArrayAdapter.CreateFromResource(
            this, Resource.Array.planets_array, Android.Resource.Layout.SimpleSpinnerItem);

    adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
    spnAvatar.Adapter = adapter;

    spnAvatar.ItemSelected += delegate
    {
        Toast.MakeText(this, "Spinner Info Changed", ToastLength.Long).Show();
    };
}
</code>```

For some reason, my spinner always displays the text of the chosen item from the drop down menu on top of the background resource that my spinner is using. This is the result:

It streches my profile phote and looks stupid.
How do I disable that?

答:
Instead of a spinner, I went with this:

```<code>    private void AlertForFacebook()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.SetPositiveButton("Change Picture", (senderAlert, args) =>
        {

        });

        alert.SetNeutralButton("Show Picture", (senderAlert, args) =>
        {

        });

        Dialog dialog = alert.Create();
        dialog.Show();
    }
</code>```

Looks a lot better in HOLO LIGHT theme :)

Title: Disable text on top of my spinner

Body:
This is my spinner init code:

private void InitSpinner()
{
    spnAvatar = FindViewById<Spinner>(Resource.Id.btn_avatarProfile);

    var adapter = ArrayAdapter.CreateFromResource(
            this, Resource.Array.planets_array, Android.Resource.Layout.SimpleSpinnerItem);

    adapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);
    spnAvatar.Adapter = adapter;

    spnAvatar.ItemSelected += delegate
    {
        Toast.MakeText(this, "Spinner Info Changed", ToastLength.Long).Show();
    };
}

For some reason, my spinner always displays the text of the chosen item from the drop down menu on top of the background resource that my spinner is using. This is the result:

It streches my profile phote and looks stupid.
How do I disable that?

Body:
Instead of a spinner, I went with this:

    private void AlertForFacebook()
    {
        AlertDialog.Builder alert = new AlertDialog.Builder(this);
        alert.SetPositiveButton("Change Picture", (senderAlert, args) =>
        {

        });

        alert.SetNeutralButton("Show Picture", (senderAlert, args) =>
        {

        });

        Dialog dialog = alert.Create();
        dialog.Show();
    }

Looks a lot better in HOLO LIGHT theme :)


问:
AIML 2.0 - multiple <set> in <pattern>
My problem is that I'm trying to use multiple <set> in <pattern> tag but my core (in this case, Pandorabots) is not recognizing what I wrote. I thought the problem was the multiple set tag in the pattern tag. With just one, it works.

So here's the slice of aiml:

```<code><category>
    <pattern>^ <set>components</set> ^ <set>desc_broken</set></pattern>
    <template>Test answer</template>
</category>
</code>```

And the relative sets:

components.set

```<code>[
    ["ENGINE"],
    ["FILTERS"],
    ["CARBURETORS"]
]
</code>```

desc_broken.set

```<code>[
    ["BROKEN"]
]
</code>```

My goal is to match strings like "My engine is broken" or, more general: "something CAR PART something ADJECTIVE something"

答:
I tried using below code by creating "colors.txt" and "modify.txt" files under "sets" folder.

colors.txt has

green

red

And modify.txt has

modify

change

```<code><category>
     <pattern># <SET>colors</SET> <SET>modify</SET> #</pattern>
     <template>Working on <star index = "2" /> color <star index = "3" /></template>
</category>
</code>```

When i give input as green modify

output as Working on green color modify

Title: AIML 2.0 - multiple <set> in <pattern>

Body:
My problem is that I'm trying to use multiple <set> in <pattern> tag but my core (in this case, Pandorabots) is not recognizing what I wrote. I thought the problem was the multiple set tag in the pattern tag. With just one, it works.

So here's the slice of aiml:

<category>
    <pattern>^ <set>components</set> ^ <set>desc_broken</set></pattern>
    <template>Test answer</template>
</category>

And the relative sets:

components.set

[
    ["ENGINE"],
    ["FILTERS"],
    ["CARBURETORS"]
]

desc_broken.set

[
    ["BROKEN"]
]

My goal is to match strings like "My engine is broken" or, more general: "something CAR PART something ADJECTIVE something"

Body:
I tried using below code by creating "colors.txt" and "modify.txt" files under "sets" folder.

colors.txt has

green

red

And modify.txt has

modify

change

<category>
     <pattern># <SET>colors</SET> <SET>modify</SET> #</pattern>
     <template>Working on <star index = "2" /> color <star index = "3" /></template>
</category>

When i give input as green modify

output as Working on green color modify


问:
R multiple integrals
I have a four integrals like this:

To calculate this function, my R code is as follows:

```<code>tol <- 1e-05
t.cutoff = 1e-15

integrand <- function(kappa, sigma, eta, tau) sqrt((tau-eta)/(sigma-kappa))*exp(-(sigma-kappa))

integrate1 <- function(sigma, eta, tau) integrate(integrand, tol * sigma, (1 - tol) * sigma, sigma = sigma, eta = eta, tau = tau)$value
integrate1.vec <- function(sigma, eta, tau) mapply(integrate1, sigma, eta, tau)

integrate2 <- function(eta, tau) integrate(integrate1.vec, tol * eta, (1 - tol) * eta, eta = eta, tau = tau)$value
integrate2.vec <- function(eta, tau) mapply(integrate2, eta, tau)

integrate3 <- function(tau) integrate(integrate2.vec, tol * tau, (1 - tol) * tau, tau = tau)$value
integrate3.vec <- function(tau) mapply(integrate3, tau)

c_t <- function(t) ifelse(t > t.cutoff, integrate(integrate3.vec, tol * t, (1 - tol) * t)$value, 0)

c_t(1)
</code>```

I think my above code is low efficient; I wonder if there is any improvement or available package for this kind of integrals. Thanks in advance!

答:
This domain of integration can be obtained by applying cumsum to a simplex. Thus you can use the SimplicialCubature package.

```<code>library(SimplicialCubature)
integrand <- function(y){
  x <- cumsum(y)
  sqrt((x[4]-x[3])/(x[2]-x[1]))*exp(-(x[2]-x[1]))
}
t <- 1
S <- t*CanonicalSimplex(4)
adaptIntegrateSimplex(integrand, S, maxEvals = 100000L, absError = 1e-4)
</code>```

Result:

```<code>> adaptIntegrateSimplex(integrand, S, maxEvals = 100000L, absError = 1e-4)
$integral
[1] 0.05961484

$estAbsError
[1] 9.991182e-05
</code>```

I've checked with Mathematica and it gives 0.0596353.

We get closer to this result by reducing absError, but this requires to increase maxEvals:

```<code>> adaptIntegrateSimplex(integrand, S, maxEvals = 1000000L, absError = 1e-5)
$integral
[1] 0.05963446

$estAbsError
[1] 9.993167e-06
</code>```

Title: R multiple integrals

Body:
I have a four integrals like this:

To calculate this function, my R code is as follows:

tol <- 1e-05
t.cutoff = 1e-15

integrand <- function(kappa, sigma, eta, tau) sqrt((tau-eta)/(sigma-kappa))*exp(-(sigma-kappa))

integrate1 <- function(sigma, eta, tau) integrate(integrand, tol * sigma, (1 - tol) * sigma, sigma = sigma, eta = eta, tau = tau)$value
integrate1.vec <- function(sigma, eta, tau) mapply(integrate1, sigma, eta, tau)

integrate2 <- function(eta, tau) integrate(integrate1.vec, tol * eta, (1 - tol) * eta, eta = eta, tau = tau)$value
integrate2.vec <- function(eta, tau) mapply(integrate2, eta, tau)

integrate3 <- function(tau) integrate(integrate2.vec, tol * tau, (1 - tol) * tau, tau = tau)$value
integrate3.vec <- function(tau) mapply(integrate3, tau)

c_t <- function(t) ifelse(t > t.cutoff, integrate(integrate3.vec, tol * t, (1 - tol) * t)$value, 0)

c_t(1)

I think my above code is low efficient; I wonder if there is any improvement or available package for this kind of integrals. Thanks in advance!

Body:
This domain of integration can be obtained by applying cumsum to a simplex. Thus you can use the SimplicialCubature package.

library(SimplicialCubature)
integrand <- function(y){
  x <- cumsum(y)
  sqrt((x[4]-x[3])/(x[2]-x[1]))*exp(-(x[2]-x[1]))
}
t <- 1
S <- t*CanonicalSimplex(4)
adaptIntegrateSimplex(integrand, S, maxEvals = 100000L, absError = 1e-4)

Result:

> adaptIntegrateSimplex(integrand, S, maxEvals = 100000L, absError = 1e-4)
$integral
[1] 0.05961484

$estAbsError
[1] 9.991182e-05

I've checked with Mathematica and it gives 0.0596353.

We get closer to this result by reducing absError, but this requires to increase maxEvals:

> adaptIntegrateSimplex(integrand, S, maxEvals = 1000000L, absError = 1e-5)
$integral
[1] 0.05963446

$estAbsError
[1] 9.993167e-06


问:
using the value of an argument to access an object property
This is the simple currency converter script which gets the currency rate from JS library - it's based on the last value in JSON chaining (PLN, EUR etc. ) ->

```<code>    var priceAmount = amount;
    var currencyRateUSDPLN = Currency.rates.PLN;
</code>```

I know that I can't pass the function argument straight to Currency.rates.PLN, what is the shortest way to achieve this functionality ?

```<code>function convertCurrency (amount, to) {
    var priceAmount = amount;
    // here I want to pass 'to' argument (EUR, PLN for example)
    var currencyRateUSDPLN = Currency.rates.to;
    var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
    console.log(pricePLN + ' PLN');
}
</code>```

The Currency object contains -> link

答:
The way to do this is to interpolate the to value via square brackets ([]). So:

```<code>Currency.rates[to]
</code>```

Alternatively, instead of passing strings in to the function and interpolating them, you could just pass the currency rate reference directly:

```<code>function convertCurrency (amount, to) {
    console.log(( amount / to ).toFixed(2) + ' PLN');
}

convertCurrency(34.56, Currency.rates.PLN)
</code>```

Body:
This is the simple currency converter script which gets the currency rate from JS library - it's based on the last value in JSON chaining (PLN, EUR etc. ) ->

    var priceAmount = amount;
    var currencyRateUSDPLN = Currency.rates.PLN;

I know that I can't pass the function argument straight to Currency.rates.PLN, what is the shortest way to achieve this functionality ?

function convertCurrency (amount, to) {
    var priceAmount = amount;
    // here I want to pass 'to' argument (EUR, PLN for example)
    var currencyRateUSDPLN = Currency.rates.to;
    var pricePLN = ( priceAmount / currencyRateUSDPLN ).toFixed(2);
    console.log(pricePLN + ' PLN');
}

The Currency object contains -> link

Body:
The way to do this is to interpolate the to value via square brackets ([]). So:

Currency.rates[to]

Alternatively, instead of passing strings in to the function and interpolating them, you could just pass the currency rate reference directly:

function convertCurrency (amount, to) {
    console.log(( amount / to ).toFixed(2) + ' PLN');
}

convertCurrency(34.56, Currency.rates.PLN)


问:
the application crashed when i used custom adapter with using json

java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0  in
  spinner

```<code>   public void GetAllData() {
        JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    ArrayList<CityList>mylist=new ArrayList<CityList>();
                    JSONArray array=response.getJSONArray("data");
                    for(int index=0;index<array.length();index++)
                    {
                        JSONObject object=array.getJSONObject(index);
                        mylist.add(new CityList(object.getInt("id"),object.getString("name")));
                    }
                    CityAdapter cityAdapter=new CityAdapter(MainActivity.this,R.layout.custome_spinner,R.id.humanmed,mylist);
                    ServiceName.setAdapter(cityAdapter);
                } catch (JSONException e) {
                    Toast.makeText(MainActivity.this, "bad", Toast.LENGTH_SHORT).show();        }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "sad", Toast.LENGTH_SHORT).show();
            }
        });
</code>```

答:
Instead of this:

```<code>ArrayList<CityList>mylist=new ArrayList<CityList>();
</code>```

use:

```<code>ArrayList<City>mylist=new ArrayList<City>();
</code>```

Instead of this:

```<code>mylist.add(new CityList(object.getInt("id"),object.getString("name")));
</code>```

use:

```<code>City city = new City();
city.setId(object.getInt("id"));
city.setName = (object.getString("name"));

mylist.add(city);
</code>```

You also have to make a class city as:

```<code>public class City {

private int id;

private String name;

public int getId() {
    return id;
}

public void setId(Int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}
</code>```

}

And create class CityList as:

```<code>public class CityList {

private List<City> cities;

public List<City> getCities() {
    return cities;
}

public void setCities(List<City> cities) {
    this.cities = cities;
}
</code>```

}

Body:
java.lang.IndexOutOfBoundsException: Invalid index 0, size is 0  in
  spinner

   public void GetAllData() {
        JsonObjectRequest request=new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                try {
                    ArrayList<CityList>mylist=new ArrayList<CityList>();
                    JSONArray array=response.getJSONArray("data");
                    for(int index=0;index<array.length();index++)
                    {
                        JSONObject object=array.getJSONObject(index);
                        mylist.add(new CityList(object.getInt("id"),object.getString("name")));
                    }
                    CityAdapter cityAdapter=new CityAdapter(MainActivity.this,R.layout.custome_spinner,R.id.humanmed,mylist);
                    ServiceName.setAdapter(cityAdapter);
                } catch (JSONException e) {
                    Toast.makeText(MainActivity.this, "bad", Toast.LENGTH_SHORT).show();        }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(MainActivity.this, "sad", Toast.LENGTH_SHORT).show();
            }
        });

Body:
Instead of this:

ArrayList<CityList>mylist=new ArrayList<CityList>();

use:

ArrayList<City>mylist=new ArrayList<City>();

Instead of this:

mylist.add(new CityList(object.getInt("id"),object.getString("name")));

use:

City city = new City();
city.setId(object.getInt("id"));
city.setName = (object.getString("name"));

mylist.add(city);

You also have to make a class city as:

public class City {

private int id;

private String name;

public int getId() {
    return id;
}

public void setId(Int id) {
    this.id = id;
}

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

}

And create class CityList as:

public class CityList {

private List<City> cities;

public List<City> getCities() {
    return cities;
}

public void setCities(List<City> cities) {
    this.cities = cities;
}

}


问:
Trying to find list of supported CSS for TCPDF
I am trying to find the list of supported CSS for TCPDF - supposedly there's a list in here: getHtmlDomArray(), but I cannot find this function in any of the files.

Has it been updated recently? I'm trying to add margins on every div.

答:
Generally, TCPDF supports following attributes

color

background-color

font-size

font-weight

font-family

text-align

text-transform

width

height

border

Does not supported margin, padding, etc attributes of CSS. If you want to use CSS attributes then you have define in . Example is given below.

```<code>// define some HTML content with style
$html = <<<EOF
<!-- EXAMPLE OF CSS STYLE -->
<style>
    h1 {
        color: navy;
        font-family: times;
        font-size: 24pt;
        text-decoration: underline;
    }
    p.first {
        color: #003300;
        font-family: helvetica;
        font-size: 12pt;
    }
    p.first span {
        color: #006600;
        font-style: italic;
    }
    p#second {
        color: rgb(00,63,127);
        font-family: times;
        font-size: 12pt;
        text-align: justify;
    }
    p#second > span {
        background-color: #FFFFAA;
    }
    table.first {
        color: #003300;
        font-family: helvetica;
        font-size: 8pt;
        border-left: 3px solid red;
        border-right: 3px solid #FF00FF;
        border-top: 3px solid green;
        border-bottom: 3px solid blue;
        background-color: #ccffcc;
    }
    td {
        border: 2px solid blue;
        background-color: #ffffee;
    }
    td.second {
        border: 2px dashed green;
    }
    div.test {
        color: #CC0000;
        background-color: #FFFF66;
        font-family: helvetica;
        font-size: 10pt;
        border-style: solid solid solid solid;
        border-width: 2px 2px 2px 2px;
        border-color: green #FF00FF blue red;
        text-align: center;
    }
    .lowercase {
        text-transform: lowercase;
    }
    .uppercase {
        text-transform: uppercase;
    }
    .capitalize {
        text-transform: capitalize;
    }
</style>

<h1 class="title">Example of <i style="color:#990000">XHTML + CSS</i></h1>

<p class="first">Example of paragraph with class selector. <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.</span></p>

<p id="second">Example of paragraph with ID selector. <span>Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.</span></p>

<div class="test">example of DIV with border and fill.
<br />Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<br /><span class="lowercase">text-transform <b>LOWERCASE</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<br /><span class="uppercase">text-transform <b>uppercase</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<br /><span class="capitalize">text-transform <b>cAPITALIZE</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>

<br />

<table class="first" cellpadding="4" cellspacing="6">
 <tr>
  <td width="30" align="center"><b>No.</b></td>
  <td width="140" align="center" bgcolor="#FFFF00"><b>XXXX</b></td>
  <td width="140" align="center"><b>XXXX</b></td>
  <td width="80" align="center"> <b>XXXX</b></td>
  <td width="80" align="center"><b>XXXX</b></td>
  <td width="45" align="center"><b>XXXX</b></td>
 </tr>
 <tr>
  <td width="30" align="center">1.</td>
  <td width="140" rowspan="6" class="second">XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="140">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="30" align="center" rowspan="3">2.</td>
  <td width="140" rowspan="3">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="80">XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="80" rowspan="2" >XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="30" align="center">3.</td>
  <td width="140">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr bgcolor="#FFFF80">
  <td width="30" align="center">4.</td>
  <td width="140" bgcolor="#00CC00" color="#FFFF00">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
</table>
EOF;

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// add a page
$pdf->AddPage();
</code>```

I hope, this would be helpful to you.

Body:
Generally, TCPDF supports following attributes

color

background-color

font-size

font-weight

font-family

text-align

text-transform

width

height

border

Does not supported margin, padding, etc attributes of CSS. If you want to use CSS attributes then you have define in . Example is given below.

// define some HTML content with style
$html = <<<EOF
<!-- EXAMPLE OF CSS STYLE -->
<style>
    h1 {
        color: navy;
        font-family: times;
        font-size: 24pt;
        text-decoration: underline;
    }
    p.first {
        color: #003300;
        font-family: helvetica;
        font-size: 12pt;
    }
    p.first span {
        color: #006600;
        font-style: italic;
    }
    p#second {
        color: rgb(00,63,127);
        font-family: times;
        font-size: 12pt;
        text-align: justify;
    }
    p#second > span {
        background-color: #FFFFAA;
    }
    table.first {
        color: #003300;
        font-family: helvetica;
        font-size: 8pt;
        border-left: 3px solid red;
        border-right: 3px solid #FF00FF;
        border-top: 3px solid green;
        border-bottom: 3px solid blue;
        background-color: #ccffcc;
    }
    td {
        border: 2px solid blue;
        background-color: #ffffee;
    }
    td.second {
        border: 2px dashed green;
    }
    div.test {
        color: #CC0000;
        background-color: #FFFF66;
        font-family: helvetica;
        font-size: 10pt;
        border-style: solid solid solid solid;
        border-width: 2px 2px 2px 2px;
        border-color: green #FF00FF blue red;
        text-align: center;
    }
    .lowercase {
        text-transform: lowercase;
    }
    .uppercase {
        text-transform: uppercase;
    }
    .capitalize {
        text-transform: capitalize;
    }
</style>

<h1 class="title">Example of <i style="color:#990000">XHTML + CSS</i></h1>

<p class="first">Example of paragraph with class selector. <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.</span></p>

<p id="second">Example of paragraph with ID selector. <span>Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.</span></p>

<div class="test">example of DIV with border and fill.
<br />Lorem ipsum dolor sit amet, consectetur adipiscing elit.
<br /><span class="lowercase">text-transform <b>LOWERCASE</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<br /><span class="uppercase">text-transform <b>uppercase</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
<br /><span class="capitalize">text-transform <b>cAPITALIZE</b> Lorem ipsum dolor sit amet, consectetur adipiscing elit.</span>
</div>

<br />

<table class="first" cellpadding="4" cellspacing="6">
 <tr>
  <td width="30" align="center"><b>No.</b></td>
  <td width="140" align="center" bgcolor="#FFFF00"><b>XXXX</b></td>
  <td width="140" align="center"><b>XXXX</b></td>
  <td width="80" align="center"> <b>XXXX</b></td>
  <td width="80" align="center"><b>XXXX</b></td>
  <td width="45" align="center"><b>XXXX</b></td>
 </tr>
 <tr>
  <td width="30" align="center">1.</td>
  <td width="140" rowspan="6" class="second">XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="140">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="30" align="center" rowspan="3">2.</td>
  <td width="140" rowspan="3">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="80">XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="80" rowspan="2" >XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr>
  <td width="30" align="center">3.</td>
  <td width="140">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
 <tr bgcolor="#FFFF80">
  <td width="30" align="center">4.</td>
  <td width="140" bgcolor="#00CC00" color="#FFFF00">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td width="80">XXXX<br />XXXX</td>
  <td align="center" width="45">XXXX<br />XXXX</td>
 </tr>
</table>
EOF;

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');

// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

// add a page
$pdf->AddPage();

I hope, this would be helpful to you.


问:
How to use jquery in a function
So I want to hide an input in a function. Here's what I already have:

function doGetWord() {
  var word = F.gword.value;
  var wLength = word.length;
  for (var i = 0; i < wLength; i++) {
    document.getElementById("dword").innerHTML += "_ "
  }

  $(document).ready(function() {
    $("input.cclick").click(function() {
      $("input.cword").hide();
    });
  });
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form name="F">
  <input type="text" name="gword" class="cword">
  <!--<input type="text" name="t" class="in2">-->
  <input type="button" name="b" value="do" onclick="doGetWord()" class="cclick">
  <div id="dword"></div>
</form></code>```

But it doesn't seem to hide it.

Thanks in advance.

答:
Please check the updated code

function doGetWord(){
    var word = F.gword.value;
    var wLength = word.length;
    for(var i = 0; i < wLength; i++){
        document.getElementById("cword").innerHTML += "_ "
    }
}

$("input.cclick").click(function(){
          $("input.cword").hide();
      });  ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form name="F">
        <input type="text" name="gword" class="cword">
        <!--<input type="text" name="t" class="in2">-->
        <input type="button" name="b" value="do" onclick="doGetWord()" class="cclick">
        <div id="dword"></div>
    </form></code>```

Title: How to use jquery in a function

Body:
So I want to hide an input in a function. Here's what I already have:

function doGetWord() {
  var word = F.gword.value;
  var wLength = word.length;
  for (var i = 0; i < wLength; i++) {
    document.getElementById("dword").innerHTML += "_ "
  }

  $(document).ready(function() {
    $("input.cclick").click(function() {
      $("input.cword").hide();
    });
  });
}

<form name="F">
  <input type="text" name="gword" class="cword">

  <input type="button" name="b" value="do" onclick="doGetWord()" class="cclick">

</form>

But it doesn't seem to hide it.

Thanks in advance.

Body:
Please check the updated code

function doGetWord(){
    var word = F.gword.value;
    var wLength = word.length;
    for(var i = 0; i < wLength; i++){
        document.getElementById("cword").innerHTML += "_ "
    }
}

$("input.cclick").click(function(){
          $("input.cword").hide();
      });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script>
<form name="F">
        <input type="text" name="gword" class="cword">
        <!--<input type="text" name="t" class="in2">-->
        <input type="button" name="b" value="do" onclick="doGetWord()" class="cclick">
        <div id="dword"></div>
    </form>


问:
Maven dependency with version
In my current maven project I have dependencies which including to output-version.jar file as dependency.jar without version in name, I would like to change name of this dependency to looks like as dependency-version.jar.

Is it possible?

My output-version.jar contains:

threetenbp.jar

dependency.jar

com

 site

  application

   JavaClass.class

答: you can use maven dependency plugin to achieve this : https://maven.apache.org/plugins/maven-dependency-plugin/usage.html</p>

Title: Maven dependency with version


问:
how to check for localStorage value, before page loads
I have a function named validateLogin in index.html where I set the local-Storage value key userID, and on return true of this function, I load other web-page (home.html) where I used this local-Storage value userID, but now, I need to restrict user and redirect them to signup.html, if local-Storage is empty when home.html is accessed directly without the validateLogin function or localStorage is empty ,
I tried below but its not working, what am I doing wrong?

index.html

```<code><form id="login_form" name="login" action="home.html" method=POST onsubmit="return validateLogin()">
<script>
  var userid;
  function validateLogin() {
    userid = document.getElementById('user_id').value;
    localStorage.setItem("userID",userid);
    var passid = document.getElementById('pass_id').value;
    if ((userid.length < 3) || (passid.length < 6)) {
      document.getElementById('user_error').setAttribute("style", "color:red")
      document.getElementById('user_error').innerHTML = "invalid username/password.";
      return false;
    }
    preventBack();
    return true;
  }
</script>
</code>```

home.html

```<code><body>
  <!--Navigation bar-->
  <div id="nav-placeholder">
  </div>
  <!--end of Navigation bar-->

<script>
  window.onload = checkUser;
  function checkUser(){
    if(localStorage.getItem("userID") === "") {
      window.location ="signup.html";
    }
    else {
      $("#nav-placeholder").load("nav_auth.html");
    }
  };
  </script>
</body>
</code>```

答:
```<code>if(!localStorage.getItem("userID")){

}
</code>```

Worked for me

Body:
I have a function named validateLogin in index.html where I set the local-Storage value key userID, and on return true of this function, I load other web-page (home.html) where I used this local-Storage value userID, but now, I need to restrict user and redirect them to signup.html, if local-Storage is empty when home.html is accessed directly without the validateLogin function or localStorage is empty ,
I tried below but its not working, what am I doing wrong?

index.html

<form id="login_form" name="login" action="home.html" method=POST onsubmit="return validateLogin()">

home.html

Body:
if(!localStorage.getItem("userID")){

}

Worked for me


问:
Google Admin SDK - watch users with Let's Encrypt secured endpoint
I'm doing PoC of some GSuite custom solution which needs to listen to changes on users resource. I've created a GSuite account, linked it (and verified) with mytestdomain.com. It's also verified in API console. Basically followed instructions from https://developers.google.com/admin-sdk/directory/v1/guides/push
and fulfilled all requirements from there.

Unfortunately when I try to register my web hook I'm getting following error:

```<code>Watch request denied by backend [403]
Errors [
    Message[Watch request denied by backend] Location[ - ] Reason[watchDenied] Domain[push]
]
</code>```

I stuck with it and don't know where too look for more details about that error.
I'm using a certificate generated by Let's encrypt, but tested it with https://www.ssllabs.com/ssltest/ and got rank A. How to check if Google API treats Let's Encrypt as trusted CA?

答:
Problem wasn't anyhow related to Let's Encrypt certificates. They're working just fine with Google's push notifications. I've contacted with Google support and with their help I've established that sending a request with showDeleted parameter set to true was a root cause of above problem.

Support guy claimed that documentation was copied from list method and that parameter cannot be used with watch method and they're going to update docs of watch method in API reference. (However it's still there).

Body:
I'm doing PoC of some GSuite custom solution which needs to listen to changes on users resource. I've created a GSuite account, linked it (and verified) with mytestdomain.com. It's also verified in API console. Basically followed instructions from https://developers.google.com/admin-sdk/directory/v1/guides/push
and fulfilled all requirements from there.

Unfortunately when I try to register my web hook I'm getting following error:

Watch request denied by backend [403]
Errors [
    Message[Watch request denied by backend] Location[ - ] Reason[watchDenied] Domain[push]
]

I stuck with it and don't know where too look for more details about that error.
I'm using a certificate generated by Let's encrypt, but tested it with https://www.ssllabs.com/ssltest/ and got rank A. How to check if Google API treats Let's Encrypt as trusted CA?


问:
removing certain objects from list of objects in c#
i have a list of objects </p>

```<code>    public int id { get; set; }
    public string device_code { get; set; }
    public string device_type { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }
</code>```

<p>while returning the list i want to remove "device_code" and "device_type" from the list and return the list only with "id","authentication_token" and "status".
How can I delete certain objects? </p>

答:
If you have this class:

```<code>class MyClass
{
    public int id { get; set; }
    public string device_code { get; set; }
    public string device_type { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }
}
</code>```

...and you have a list of them...

```<code>List<MyClass> list;
</code>```

You can extract just the properties you want into an anonymous type by using LINQ:

```<code>var justWhatIWant = list.Select( a => new
{
    id = a.id,
    authentication_token = a.authentication_token,
    Status = a.Status
});
</code>```

The anonymous type isn't interface-compatible with anything, but you could use it to, say, create some JSON.

Body:
i have a list of objects

    public int id { get; set; }
    public string device_code { get; set; }
    public string device_type { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }

while returning the list i want to remove "device_code" and "device_type" from the list and return the list only with "id","authentication_token" and "status".
How can I delete certain objects?

Body:
If you have this class:

class MyClass
{
    public int id { get; set; }
    public string device_code { get; set; }
    public string device_type { get; set; }
    public string authentication_token { get; set; }
    public string Status { get; set; }
}

...and you have a list of them...

List<MyClass> list;

You can extract just the properties you want into an anonymous type by using LINQ:

var justWhatIWant = list.Select( a => new
{
    id = a.id,
    authentication_token = a.authentication_token,
    Status = a.Status
});

The anonymous type isn't interface-compatible with anything, but you could use it to, say, create some JSON.


问:
Scala_Spark_DataFrame using Future method
I have to solve a scenario in which I am reading the HiveContext as Future using Scala. But I am unable to print the returned dataframe.

My code:

```<code>val f: Future[DataFrame] = Future{hive.sql("select * from test1.emp")}
</code>```

How to get the DataFrame from the Future[DataFrame] object?

答:
As simple as

val f: Future[DataFrame] = Future{hive.sql("select * from test1.emp")}.foreach(df => df.show())

So basically like in the answers already posted here - Getting data out of a Future in Scala , you can do all you operations on a DataFrame in a map function. df.show() can be replaced with any other command.

Body:
I have to solve a scenario in which I am reading the HiveContext as Future using Scala. But I am unable to print the returned dataframe.

My code:

val f: Future[DataFrame] = Future{hive.sql("select * from test1.emp")}

How to get the DataFrame from the Future[DataFrame] object?