问:
Sass not working using prefix
Currently having a small issue.

Currently have a SCSS file which contains a series of styling preferences as shown below:

```<code>.login-scene {
    display: table;
    width: 100%;
    height: 100vh;
}

.login-language {
    padding-top: 12px;
}

.login-button {
    margin-top: 30px;
}

span.login-header {
    font-size: 25px;
    padding: 30px;
    display: block;
    color: white;
}
</code>```

I then try to declare a prefix, and try to do the following:

```<code>$prefix: "login";

.prefix {
  &-scene {
      display: table;
      width: 100%;
      height: 100vh;
  }

  &-language {
      padding-top: 12px;
  }

  &-button {
      margin-top: 30px;
  }
}
</code>```

Im getting no errors in my application, but the styling isnt being applied once I have used a prefix. Any ideas?

答:
answer is as follows. </p>

```<code>$prefix: "login";

.#{$prefix} {
  &-scene {
      display: table;
      width: 100%;
      height: 100vh;
  }

  &-language {
      padding-top: 12px;
  }

  &-button {
      margin-top: 30px;
  }

}
</code>```

Title: Sass not working using prefix

Body:
Currently having a small issue.

Currently have a SCSS file which contains a series of styling preferences as shown below:

.login-scene {
    display: table;
    width: 100%;
    height: 100vh;
}

.login-language {
    padding-top: 12px;
}

.login-button {
    margin-top: 30px;
}

span.login-header {
    font-size: 25px;
    padding: 30px;
    display: block;
    color: white;
}

I then try to declare a prefix, and try to do the following:

$prefix: "login";

.prefix {
  &-scene {
      display: table;
      width: 100%;
      height: 100vh;
  }

  &-language {
      padding-top: 12px;
  }

  &-button {
      margin-top: 30px;
  }
}

Im getting no errors in my application, but the styling isnt being applied once I have used a prefix. Any ideas?

Body:
answer is as follows.

$prefix: "login";

.#{$prefix} {
  &-scene {
      display: table;
      width: 100%;
      height: 100vh;
  }

  &-language {
      padding-top: 12px;
  }

  &-button {
      margin-top: 30px;
  }

}


来源: stackexchange

问:
Ignore a certain layer when using OnPointerDown()
In my 2D top-down game, I have a Script I attach to NPCs to control when the player clicks them, starting a dialogue.

However, the way I've decided to design this is that I have an extra collider on my player called InteractiveArea, and you can only interact with NPCs inside that area. On Start I add:

```<code> Physics2D.IgnoreLayerCollision(LayerMask.NameToLayer("InteractiveArea"), LayerMask.NameToLayer("Player"));
</code>```

to make sure it doesn't collide with my player.

So, the problem I'm facing is that my MousePointer picks up the InteractiveArea collider, and not the NPCs, so if the NPC is inside the InteractiveArea my method won't work:

```<code>public void OnPointerDown(PointerEventData eventData)
{
    if (npcManager.currentlyInteractable) //set to true when inside InteractiveArea
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            npcManager.Clicked();
        }
    }
}
</code>```

Is there any way I can make the InteractiveArea ignore my MousePointer, like I do with my player on Start? Or maybe my entire system with using an InteractiveArea is poor design and I should do something else to control this? Just seemed a very neat and simple solution.

答:
You have already found a hack for this, which is not the best way to do this. So I decided to answer this anyway:

You don't need to use collider to define the interactive area for player and the whole implementation of npcManager.currentlyInteractable.

There are different ways to do this without using collider:

1. Check the Distance

A distance between player and NPC can be checked before interacting like this:

```<code>public void OnPointerDown(PointerEventData eventData)
{
    if (eventData.button == PointerEventData.InputButton.Right)
    {
        float dist = Vector3.Distance(player.transform.position, transform.position)

        if (distance < 2) // player is close enough
        {
            npcManager.Clicked();
        }
    }
}
</code>```

2. Check for Collider Bounds in Radius

Physics2D.OverlapCircleAll can be used to detect if player collider is overlapping a circle of certain radius:

```<code>public void OnPointerDown(PointerEventData eventData)
{
    if (eventData.button == PointerEventData.InputButton.Right)
    {
        Vector2 center = new Vector2(transform.position.x, transform.position.z) // use y component depending on how you setup top-down view
        float raduis = 2f;

        Collider2D[] collidersInCircle = Physics2D.OverlapCircleAll(center, raduis);

        foreach (var collider in collidersInCircle)
        {
            if(collider.CompareTag("Player")) // player must have appropriate tag
            {
                npcManager.Clicked();
                break;
            }
        }
    }
}
</code>```

Hope this helps :)

ContentLicense: CC BY-SA 3.0

Body:
In my 2D top-down game, I have a Script I attach to NPCs to control when the player clicks them, starting a dialogue.

However, the way I've decided to design this is that I have an extra collider on my player called InteractiveArea, and you can only interact with NPCs inside that area. On Start I add:

 Physics2D.IgnoreLayerCollision(LayerMask.NameToLayer("InteractiveArea"), LayerMask.NameToLayer("Player"));

to make sure it doesn't collide with my player.

So, the problem I'm facing is that my MousePointer picks up the InteractiveArea collider, and not the NPCs, so if the NPC is inside the InteractiveArea my method won't work:

public void OnPointerDown(PointerEventData eventData)
{
    if (npcManager.currentlyInteractable) //set to true when inside InteractiveArea
    {
        if (eventData.button == PointerEventData.InputButton.Right)
        {
            npcManager.Clicked();
        }
    }
}

Is there any way I can make the InteractiveArea ignore my MousePointer, like I do with my player on Start? Or maybe my entire system with using an InteractiveArea is poor design and I should do something else to control this? Just seemed a very neat and simple solution.

Body:
You have already found a hack for this, which is not the best way to do this. So I decided to answer this anyway:

You don't need to use collider to define the interactive area for player and the whole implementation of npcManager.currentlyInteractable.

There are different ways to do this without using collider:

1. Check the Distance

A distance between player and NPC can be checked before interacting like this:

public void OnPointerDown(PointerEventData eventData)
{
    if (eventData.button == PointerEventData.InputButton.Right)
    {
        float dist = Vector3.Distance(player.transform.position, transform.position)

        if (distance < 2) // player is close enough
        {
            npcManager.Clicked();
        }
    }
}

2. Check for Collider Bounds in Radius

Physics2D.OverlapCircleAll can be used to detect if player collider is overlapping a circle of certain radius:

public void OnPointerDown(PointerEventData eventData)
{
    if (eventData.button == PointerEventData.InputButton.Right)
    {
        Vector2 center = new Vector2(transform.position.x, transform.position.z) // use y component depending on how you setup top-down view
        float raduis = 2f;

        Collider2D[] collidersInCircle = Physics2D.OverlapCircleAll(center, raduis);

        foreach (var collider in collidersInCircle)
        {
            if(collider.CompareTag("Player")) // player must have appropriate tag
            {
                npcManager.Clicked();
                break;
            }
        }
    }
}

Hope this helps :)


问:
Declaring XML Tags in Ruby
I am using Ruby to pull information from an excel sheet and with this information produce an xml file. I need to produce this in Ruby:

What I want:

```<code><Betrag waehrung="EUR">150000</Betrag>
</code>```

What I have:

```<code><Betrag waehrung ="EUR"/>
</code>```

I am currently trying xml.Betrag "Waehrung": "Eur"
 the Betrag has a row Identifier of "#{row[13]}" which is where it can be found on the excel sheet I am using. I have tried: xml.Betrag "Waehrung": ("Eur"), ("#{row[13]}") with no success, could you please advise?

答:
```<code>require 'nokogiri'
builder = Nokogiri::XML::Builder.new do |xml|
  xml.Betrag(waehrung: 'EUR') do  |e|
    e << '150000'
  end
end
puts builder.to_xml

=>
<?xml version="1.0"?>
<Betrag waehrung="EUR">150000</Betrag>
</code>```

Title: Declaring XML Tags in Ruby

Body:
I am using Ruby to pull information from an excel sheet and with this information produce an xml file. I need to produce this in Ruby:

What I want:

<Betrag waehrung="EUR">150000</Betrag>

What I have:

<Betrag waehrung ="EUR"/>

I am currently trying xml.Betrag "Waehrung": "Eur"
 the Betrag has a row Identifier of "#{row[13]}" which is where it can be found on the excel sheet I am using. I have tried: xml.Betrag "Waehrung": ("Eur"), ("#{row[13]}") with no success, could you please advise?


问:
Docker-php-ext-install mcrypt missing folder
I try to install mcrypt in my docker image based on php:7.2-apache. Therefore I use the RUN-Command from the documentation and also answerd here but I receive this error:

```<code>error: /usr/src/php/ext/mcrypt does not exist

usage: /usr/local/bin/docker-php-ext-install [-jN] ext-name [ext-name ...]

   ie: /usr/local/bin/docker-php-ext-install gd mysqli
   /usr/local/bin/docker-php-ext-install pdo pdo_mysql
   /usr/local/bin/docker-php-ext-install -j5 gd mbstring mysqli pdo pdo_mysql shmop

if custom ./configure arguments are necessary, see docker-php-ext-configure

Possible values for ext-name:
bcmath bz2 calendar ctype curl dba dom enchant exif fileinfo filter ftp  gd gettext gmp hash iconv imap interbase intl json ldap mbstring mysqli oci8  odbc opcache pcntl pdo pdo_dblib pdo_firebird pdo_mysql pdo_oci pdo_odbc pdo_pgsql pdo_sqlite pgsql phar posix pspell readline recode reflection session shmop simplexml snmp soap sockets sodium spl standard sysvmsg sysvsem sysvshm tidy tokenizer wddx xml xmlreader xmlrpc xmlwriter xsl zend_test zip

Some of the above modules are already compiled into PHP; please check
the output of "php -i" to see which modules are already loaded.
ERROR: Service 'web' failed to build: The command '/bin/sh -c apt-get update && apt-get install -y          libfreetype6-dev          libjpeg62-turbo-dev          libmcrypt-dev          libpng-dev     && docker-php-ext-install -j$(nproc) iconv mcrypt gd mbstring zip' returned a non-zero code: 1
</code>```

My Dockerfile:

```<code>FROM php:7.2-apache

RUN apt-get update && apt-get install -y \
     libfreetype6-dev \
     libjpeg62-turbo-dev \
     libmcrypt-dev \
     libpng-dev \
&& docker-php-ext-install -j$(nproc) iconv mcrypt gd mbstring zip
#    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
#    && docker-php-ext-install -j$(nproc) gd

COPY ./etc/000-default.conf /etc/apache2/sites-available/

EXPOSE 80
</code>```

Has anybody an idea how to solve or how to get the needed files in the requested folder?

Thanks!

答:
mcrypt extension is not provided with the PHP source since 7.2 , but are instead available through PECL. To install a PECL extension in docker, use pecl install to download and compile it, then use docker-php-ext-enable to enable it:

pecl install mcrypt-1.0.5
docker-php-ext-enable mcrypt
```
<p>Before the <code>pecl install</code> you may need to install/update the package <code>libmcrypt-dev</code></p>
<pre class="lang-bash prettyprint-override"><code>apt-get update && apt-get install -y libmcrypt-dev
</code>```

Body:
I try to install mcrypt in my docker image based on php:7.2-apache. Therefore I use the RUN-Command from the documentation and also answerd here but I receive this error:

error: /usr/src/php/ext/mcrypt does not exist

usage: /usr/local/bin/docker-php-ext-install [-jN] ext-name [ext-name ...]

   ie: /usr/local/bin/docker-php-ext-install gd mysqli
   /usr/local/bin/docker-php-ext-install pdo pdo_mysql
   /usr/local/bin/docker-php-ext-install -j5 gd mbstring mysqli pdo pdo_mysql shmop

if custom ./configure arguments are necessary, see docker-php-ext-configure

Possible values for ext-name:
bcmath bz2 calendar ctype curl dba dom enchant exif fileinfo filter ftp  gd gettext gmp hash iconv imap interbase intl json ldap mbstring mysqli oci8  odbc opcache pcntl pdo pdo_dblib pdo_firebird pdo_mysql pdo_oci pdo_odbc pdo_pgsql pdo_sqlite pgsql phar posix pspell readline recode reflection session shmop simplexml snmp soap sockets sodium spl standard sysvmsg sysvsem sysvshm tidy tokenizer wddx xml xmlreader xmlrpc xmlwriter xsl zend_test zip

Some of the above modules are already compiled into PHP; please check
the output of "php -i" to see which modules are already loaded.
ERROR: Service 'web' failed to build: The command '/bin/sh -c apt-get update && apt-get install -y          libfreetype6-dev          libjpeg62-turbo-dev          libmcrypt-dev          libpng-dev     && docker-php-ext-install -j$(nproc) iconv mcrypt gd mbstring zip' returned a non-zero code: 1

My Dockerfile:

FROM php:7.2-apache

RUN apt-get update && apt-get install -y \
     libfreetype6-dev \
     libjpeg62-turbo-dev \
     libmcrypt-dev \
     libpng-dev \
&& docker-php-ext-install -j$(nproc) iconv mcrypt gd mbstring zip
#    && docker-php-ext-configure gd --with-freetype-dir=/usr/include/ --with-jpeg-dir=/usr/include/ \
#    && docker-php-ext-install -j$(nproc) gd

COPY ./etc/000-default.conf /etc/apache2/sites-available/

EXPOSE 80

Has anybody an idea how to solve or how to get the needed files in the requested folder?

Thanks!

Body:
mcrypt extension is not provided with the PHP source since 7.2 , but are instead available through PECL. To install a PECL extension in docker, use pecl install to download and compile it, then use docker-php-ext-enable to enable it:

pecl install mcrypt-1.0.5
docker-php-ext-enable mcrypt

Before the pecl install you may need to install/update the package libmcrypt-dev

apt-get update && apt-get install -y libmcrypt-dev

ContentLicense: CC BY-SA 4.0


问:
How to protect AWS API gateway URL from unauthorized access?
I want to host my static website in AWS  S3. But it contains "contact us" page which is for sending emails. When the user clicks the submit button it sends the request to AWS API gateway, API gateway triggers the lambda function; the lambda function sends the mail to Admin.

But it has some problem . when we host the website at server we can use captcha to prevent the submit request automation and fraudulent activities . in this case the anybody can misuse (sending more request by passing a query string in the URL ) my API gateway URL who know it.

So my question is how to know that the submit request is requested from my website only and is there any way to use instead of Captcha?.

答: You can use Referer header on http. It is set by browser. </p>


问:
How to read text file form particular directory in ios app?
I want to read text file in my ios app. test1 folder contains one.txt file. When I remove this "inDirectory:"test1""  my code works correctly. But I want to mention the folder name. How to do that ?

```<code>if let path = Bundle.main.path(forResource: "one", ofType: "txt" ,

 inDirectory:"test1" )

    {
        text2 = try! String(contentsOfFile: path, encoding:String.Encoding.utf8)
    }
    else
    {
        print("file not found")
    }
</code>```

答:
If you add files and folders with settings: Create group

Then you shouldn't setup folder in this case (system create ipa file and put all file together in one place).
When you add files with references it create folder inside ipa. Don't forget to check this files in the target list.

Body:
I want to read text file in my ios app. test1 folder contains one.txt file. When I remove this "inDirectory:"test1""  my code works correctly. But I want to mention the folder name. How to do that ?

if let path = Bundle.main.path(forResource: "one", ofType: "txt" ,

 inDirectory:"test1" )

    {
        text2 = try! String(contentsOfFile: path, encoding:String.Encoding.utf8)
    }
    else
    {
        print("file not found")
    }


问:
How to optimize SQL query with two where clauses?
My query is something like this

```<code>SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND (tbl2.date = '$date' OR ('$date' BETWEEN tbl1.planA AND tbl1.planB ))
</code>```

When I run this query, it is considerably slower than for example this query

```<code>SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND ('$date' BETWEEN tbl1.planA AND tbl1.planB )
</code>```

or

```<code>SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND tbl2.date = '$date'
</code>```

In localhost, the first query takes about 0.7 second, the second query about 0.012 second and the third one 0.008 second.

My question is how do you optimize this? If currently I have 1000 rows in my tables and it takes 0.7 second to display the first query, it will take 7 seconds if I have 10.000 rows right? That's a massive slow down compared to second query (0.12 second) and third (0.08).

I've tried adding indexes, but the result is no different.

Thanks

Edit : This application will only work locally, so no need to worry about the speed over the web.

Sorry, I didn't include the EXPLAIN because my real query are much more complicated (about 5 joins). But the joins (I think) don't really matter, cos I've tried omitting them and still get approximately the same result as above.

The date belongs to tbl1, planA and planB belongs to tbl2. I've tried adding indexes to tbl1.date, tbl2.planA and tbl2.planB but the result is insignificant.

By schema do you mean MyISAM or InnoDB? It's MyISAM.

Okay, I'll just post my query straight away. Hopefully it's not that confusing.

```<code>SELECT *
FROM tb_joborder jo
LEFT JOIN tb_project p ON jo.project_id = p.project_id
LEFT JOIN tb_customer c ON p.customer_id = c.customer_id
LEFT JOIN tb_dispatch d ON jo.joborder_id = d.joborder_id
LEFT JOIN tb_joborderitem ji ON jo.joborder_id = ji.joborder_id
LEFT JOIN tb_mix m ON ji.mix_id = m.mix_id
WHERE dispatch_date = '2011-01-11'
OR '2011-01-11'
BETWEEN planA
AND planB
GROUP BY jo.joborder_id
ORDER BY customer_name ASC
</code>```

And the describe output

```<code>id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  jo  ALL     NULL    NULL    NULL    NULL    453     Using temporary; Using filesort
1   SIMPLE  p   eq_ref  PRIMARY     PRIMARY     4   db_dexada.jo.project_id     1
1   SIMPLE  c   eq_ref  PRIMARY     PRIMARY     4   db_dexada.p.customer_id     1
1   SIMPLE  d   ALL     NULL    NULL    NULL    NULL    2048    Using where
1   SIMPLE  ji  ALL     NULL    NULL    NULL    NULL    455
1   SIMPLE  m   eq_ref  PRIMARY     PRIMARY     4   db_dexada.ji.mix_id     1
</code>```

答:
Even if most slow queries are usually due to the query itself or index setup of the used tables, you can try to find out where your bottleneck is with using the MySQL Query Profiler, too. It has been implemented into MySQL since Version 5.0.37.

Before you start your query, activate the profiler with this statement:

```<code> mysql> set profiling=1;
</code>```

Now execute your long query.

With

```<code>mysql> show profiles;
</code>```

you can now find out what internal number (query number) your long query has.

If you now execute the following query, you'll get alot of details about what took how long:

```<code>mysql> show profile for query (insert query number here);
(example output)
+--------------------+------------+
| Status             | Duration   |
+--------------------+------------+
| (initialization)   | 0.00005000 |
| Opening tables     | 0.00006000 |
| System lock        | 0.00000500 |
| Table lock         | 0.00001200 |
| init               | 0.00002500 |
| optimizing         | 0.00001000 |
| statistics         | 0.00009200 |
| preparing          | 0.00003700 |
| executing          | 0.00000400 |
| Sending data       | 0.00066600 |
| end                | 0.00000700 |
| query end          | 0.00000400 |
| freeing items      | 0.00001800 |
| closing tables     | 0.00000400 |
| logging slow query | 0.00000500 |
+--------------------+------------+
</code>```

This is a more general, administrative approach, but can help narrow down or even find out the cause for slow queries very nice.

A good tutorial on how to use the MySQL Query Profiler can be found here in the MySQL articles.

ContentLicense: CC BY-SA 2.5

Body:
My query is something like this

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND (tbl2.date = '$date' OR ('$date' BETWEEN tbl1.planA AND tbl1.planB ))

When I run this query, it is considerably slower than for example this query

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND ('$date' BETWEEN tbl1.planA AND tbl1.planB )

or

SELECT * FROM tbl1
JOIN tbl2 ON something = something
WHERE 1 AND tbl2.date = '$date'

In localhost, the first query takes about 0.7 second, the second query about 0.012 second and the third one 0.008 second.

My question is how do you optimize this? If currently I have 1000 rows in my tables and it takes 0.7 second to display the first query, it will take 7 seconds if I have 10.000 rows right? That's a massive slow down compared to second query (0.12 second) and third (0.08).

I've tried adding indexes, but the result is no different.

Thanks

Edit : This application will only work locally, so no need to worry about the speed over the web.

Sorry, I didn't include the EXPLAIN because my real query are much more complicated (about 5 joins). But the joins (I think) don't really matter, cos I've tried omitting them and still get approximately the same result as above.

The date belongs to tbl1, planA and planB belongs to tbl2. I've tried adding indexes to tbl1.date, tbl2.planA and tbl2.planB but the result is insignificant.

By schema do you mean MyISAM or InnoDB? It's MyISAM.

Okay, I'll just post my query straight away. Hopefully it's not that confusing.

SELECT *
FROM tb_joborder jo
LEFT JOIN tb_project p ON jo.project_id = p.project_id
LEFT JOIN tb_customer c ON p.customer_id = c.customer_id
LEFT JOIN tb_dispatch d ON jo.joborder_id = d.joborder_id
LEFT JOIN tb_joborderitem ji ON jo.joborder_id = ji.joborder_id
LEFT JOIN tb_mix m ON ji.mix_id = m.mix_id
WHERE dispatch_date = '2011-01-11'
OR '2011-01-11'
BETWEEN planA
AND planB
GROUP BY jo.joborder_id
ORDER BY customer_name ASC

And the describe output

id  select_type     table   type    possible_keys   key     key_len     ref     rows    Extra
1   SIMPLE  jo  ALL     NULL    NULL    NULL    NULL    453     Using temporary; Using filesort
1   SIMPLE  p   eq_ref  PRIMARY     PRIMARY     4   db_dexada.jo.project_id     1
1   SIMPLE  c   eq_ref  PRIMARY     PRIMARY     4   db_dexada.p.customer_id     1
1   SIMPLE  d   ALL     NULL    NULL    NULL    NULL    2048    Using where
1   SIMPLE  ji  ALL     NULL    NULL    NULL    NULL    455
1   SIMPLE  m   eq_ref  PRIMARY     PRIMARY     4   db_dexada.ji.mix_id     1

Body:
Even if most slow queries are usually due to the query itself or index setup of the used tables, you can try to find out where your bottleneck is with using the MySQL Query Profiler, too. It has been implemented into MySQL since Version 5.0.37.

Before you start your query, activate the profiler with this statement:

 mysql> set profiling=1;

Now execute your long query.

With

mysql> show profiles;

you can now find out what internal number (query number) your long query has.

If you now execute the following query, you'll get alot of details about what took how long:

mysql> show profile for query (insert query number here);
(example output)
+--------------------+------------+
| Status             | Duration   |
+--------------------+------------+
| (initialization)   | 0.00005000 |
| Opening tables     | 0.00006000 |
| System lock        | 0.00000500 |
| Table lock         | 0.00001200 |
| init               | 0.00002500 |
| optimizing         | 0.00001000 |
| statistics         | 0.00009200 |
| preparing          | 0.00003700 |
| executing          | 0.00000400 |
| Sending data       | 0.00066600 |
| end                | 0.00000700 |
| query end          | 0.00000400 |
| freeing items      | 0.00001800 |
| closing tables     | 0.00000400 |
| logging slow query | 0.00000500 |
+--------------------+------------+

This is a more general, administrative approach, but can help narrow down or even find out the cause for slow queries very nice.

A good tutorial on how to use the MySQL Query Profiler can be found here in the MySQL articles.


问:
Nesting tag name into class style in SCSS
I want to nest selector for  tag inside a class .class-name, in order to apply those styles only for elements who has both the  tag and the class .class-name using SCSS. What I want to do can be performed the following way:

.class-name {
  font-size: 40px;
 }

 a.class-name {
   color: #ff6666;
 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="class-name">Hello</div>
World!</code>```

I've tried two different ways in SCSS using & parent selector

```<code># successfully transpiled but no change
.class-name {
  font-size: 40px;
  &a {
    color: #ff6666;
  }
}

# Got an error trying to transpile
.class-name {
  font-size: 40px;
  a& {
    color: #ff6666;
  }
}
</code>```

I do not want to nest the other way around (.class-name inside a).

答:
Its not nesting, its two different elements, try as below to achieve as you want

```<code>.class-name {
  font-size: 40px;
}

a.class-name {
  color: #ff6666;
}
</code>```

Or in nested way

```<code>a{
   &.class-name{
    color: #ff6666;
   }
}
</code>```

It not possible to target parent class from child

Get more details from this Answer

Body:
I want to nest selector for  tag inside a class .class-name, in order to apply those styles only for elements who has both the  tag and the class .class-name using SCSS. What I want to do can be performed the following way:

.class-name {
  font-size: 40px;
 }

 a.class-name {
   color: #ff6666;
 }

Hello

World!

I've tried two different ways in SCSS using & parent selector

# successfully transpiled but no change
.class-name {
  font-size: 40px;
  &a {
    color: #ff6666;
  }
}

# Got an error trying to transpile
.class-name {
  font-size: 40px;
  a& {
    color: #ff6666;
  }
}

I do not want to nest the other way around (.class-name inside a).

Body:
Its not nesting, its two different elements, try as below to achieve as you want

.class-name {
  font-size: 40px;
}

a.class-name {
  color: #ff6666;
}

Or in nested way

a{
   &.class-name{
    color: #ff6666;
   }
}

It not possible to target parent class from child

Get more details from this Answer


问:
CSS not loading properly magento2
CSS not loading properly in magento2. Getting below error:</p>

```<code>NameError: variable @button__shadow-active is undefined

in _buttons.less
</code>```

答:
CSS not loading properly due to static deploy not push the file to pub/static directory.

You have to follow the below steps.

rm -rf var/*

rm -rf pub/static/*

php bin/magento setup:static-content:deploy

chmod -R 7777 var pub/static

Title: CSS not loading properly magento2

Body:
CSS not loading properly in magento2. Getting below error:

NameError: variable @button__shadow-active is undefined

in _buttons.less


问:
Using nginx with redis to read a key value pair
I'm new with working on nginx and redis,Unable to connect a redis from nginx to read a redis key value

i see most of the documents for redis refer to old modules which are no more active on nginx

please help with a simple example for this

答:
I am using openresty with redis to read a key value pair.
Here is my conf

```<code>server {
    listen       80;
    server_name  localhost;

  #GET http://localhost/get?key=key
  location /get {
      default_type "text/plain";
        content_by_lua_block {
        local redis_info = {
            host = "127.0.0.1",
            port = 6379,
            db = 0
        }
        local redis = require "resty.redis"
        local red = redis:new()
        red:set_timeout(1000)

        local ok, err = red:connect(redis_info.host, redis_info.port)
        if not ok then
            ngx.say("failed to connect: ", err)
            return
        end
        ok, err = red:select(redis_info.db)

        local value = red:get(ngx.var.arg_key)
        ngx.say(value)
    }
  }

  #SET http://localhost/set?key=key&val=value
  location /set {
      default_type "text/plain";
      set_unescape_uri $key $arg_key;
      set_unescape_uri $val $arg_val;
      redis2_query set $key $val;
      redis2_pass 127.0.0.1:6379;
  }
}
</code>```

You can do the same thing with nginx, please look at the document here.

Body:
I am using openresty with redis to read a key value pair.
Here is my conf

server {
    listen       80;
    server_name  localhost;

  #GET http://localhost/get?key=key
  location /get {
      default_type "text/plain";
        content_by_lua_block {
        local redis_info = {
            host = "127.0.0.1",
            port = 6379,
            db = 0
        }
        local redis = require "resty.redis"
        local red = redis:new()
        red:set_timeout(1000)

        local ok, err = red:connect(redis_info.host, redis_info.port)
        if not ok then
            ngx.say("failed to connect: ", err)
            return
        end
        ok, err = red:select(redis_info.db)

        local value = red:get(ngx.var.arg_key)
        ngx.say(value)
    }
  }

  #SET http://localhost/set?key=key&val=value
  location /set {
      default_type "text/plain";
      set_unescape_uri $key $arg_key;
      set_unescape_uri $val $arg_val;
      redis2_query set $key $val;
      redis2_pass 127.0.0.1:6379;
  }
}

You can do the same thing with nginx, please look at the document here.


问:
C# asp.net build SQL Query dynamically from viewstate
On my C# asp.net webform I have a search page that has roughly 20 elements that "could" be used as part of the search.  There will be more added later.

What I have done is extend the textbox and dropdown listbox to include a few variables:

fieldname: Tablename.columnname
dbtype: DbType.Int32
Joinparam: LEFT Join on otherTable ON x.y = a.b

These are all stored in the viewstate and loaded back in.  The reason I do this is so that I can iterate through all the controls and pull out all the controls that are of my type.  I can then validate them to make sure they have input and are of the right type.  If so I can then pass them off to the database access layer and let the code dynamically generate the SQL statement.

I do not let anything but SELECT statements happen from this.  The fields selected and returned can not be changed and I use the dbparameter to try and avoid sql injection.

My worry is that I put the table and field names that will be used in the search criteria and the JOINS required all in the viewstate.  Is this a real bad idea?

I could obscurify this by just having some int index's into tables that hold this info in the DB but this would still need to be put into the viewstate and just mean they would have an extra layer to figure out.

The reason I went for this approach was that I did not want to have to put tons of IF statements in the DB layer to build the statement there.  It would be ugly as hell and a pain to maintain.

Thanks for any and all advice about this.

Jon

EDIT

Thanks all for the advice.  Thankfully this app is an internal thing only so the damage would be limited.  But I will never use this technique again and will work on the search template idea instead.

Cheers :)

答: I think it's a real design mistake to encode parts of your data access layer in your view logic.  Putting aside the security concerns, this is going to be really hard to maintain and understand for anyone coming after you.  I think a factory class to produce your specific queries from the various selected inputs is probably going to be easier to work with in the long run.  Or perhaps, you could populate a "search template" from the inputs and have the search template function as the factory for producing the query, much like the way the UserPrincipal interacts with a PrincipalSearcher in the System.DirectoryServices.AccountManagement namespace.</p>

OwnerDisplayName: Jon

LastEditorDisplayName: Jon

OwnerDisplayName: tvanfosson


问:
Search multidimensional jsonb data in laravel postgres

I have multiple jsonb data fields in my postgres database. Like my Contacts table has name, addresses, phones and emails as jsonb data fields. Most of the jsonb data fields are multidimensional. Like emails field have different json data for different email types. Following is the sample emails data i have in my database.

```<code>[
    {"tag": "Home", "value": "foo@bar.com"},
    {"tag": "Other", "value": "john@doe.net"},
    {"tag": "Work", "value": "john@foo.com"},
    {"tag": "Home", "value": "foo@gmail.com"}
]
</code>```

I want to execute a search on emails field's value data. Like i want to fetch all the contacts with email john@doe.net in emails field.

I have tried to fetch the contacts with normal where query like

```<code>$contacts = Contact::where('emails->value', 'ilike', "%$query%")->get();
</code>```

But it does not return anything and that is obvious because emails field is multidimensional. Although on a single dimensional json data this query works fine.

What is the proper way of searching such data fields in laravel eloquent ?. It will be better if it can be done without using whereRaw with jsonb_exists function.

答:
I got it working and posting the answer here if in case anyone needs help in future.

Basically we can do a simple where query with @> operator. And the value can be json encoded with the searched email. Following is the query to search for particular email without using whereRaw method.

```<code>$contacts = Contact::where("emails", '@>', '[' . json_encode(['value' => $query]) . ']')->get();
</code>```

Hope it helps some one else in future :)

Body:
I have multiple jsonb data fields in my postgres database. Like my Contacts table has name, addresses, phones and emails as jsonb data fields. Most of the jsonb data fields are multidimensional. Like emails field have different json data for different email types. Following is the sample emails data i have in my database.

[
    {"tag": "Home", "value": "foo@bar.com"},
    {"tag": "Other", "value": "john@doe.net"},
    {"tag": "Work", "value": "john@foo.com"},
    {"tag": "Home", "value": "foo@gmail.com"}
]

I want to execute a search on emails field's value data. Like i want to fetch all the contacts with email john@doe.net in emails field.

I have tried to fetch the contacts with normal where query like

$contacts = Contact::where('emails->value', 'ilike', "%$query%")->get();

But it does not return anything and that is obvious because emails field is multidimensional. Although on a single dimensional json data this query works fine.

What is the proper way of searching such data fields in laravel eloquent ?. It will be better if it can be done without using whereRaw with jsonb_exists function.

Body:
I got it working and posting the answer here if in case anyone needs help in future.

Basically we can do a simple where query with @> operator. And the value can be json encoded with the searched email. Following is the query to search for particular email without using whereRaw method.

$contacts = Contact::where("emails", '@>', '[' . json_encode(['value' => $query]) . ']')->get();

Hope it helps some one else in future :)


问:
angular 5 material 2 - auto complete getting data from external api
I'm using angular 5 and material 2.

In ts file, I have this proeperty:

```<code>      filteredOptions: Observable<any[]>;
</code>```

This property is going to have an array of values to show in the autocomplete field.

```<code>      [{
        id:'1', name: 'teste 1'},
        {id:'2', name: 'teste 2'},
        {id:'3', name: 'teste 3'
      }]
</code>```

This array of values come from the database and it is going to be shown after the user type something.

html file:

```<code>          ##            <form class="example-form">
          ##              <mat-form-field class="example-full-width">
          ##                <input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto">
          ##                <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
          ##                  <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
          ##                    {{ option.name }}
          ##                  </mat-option>
          ##                </mat-autocomplete>
          ##              </mat-form-field>
          ##            </form>
</code>```

ts file example:

```<code>    this.filteredOptions = Observable<any[]>;

    ngOnInit() {
      this.filteredOptions = this.myControl.valueChanges
        .pipe(
          startWith({}),
          map(getArrayOfValue(val))
        );
      }

      // it is going to call an api to get the array of values to be shown in the field
      getArrayOfValue(val): Observable<any[]> {
        const url = this.ROOT_URL + 'veiculo/' + val;
        return this.http.get<any[]>(url);
      }
</code>```

This code give me an error

ERROR in src/app/oficina/cadastro/veiculo/veiculo.component.ts(55,5):
  error TS2322: Type 'Observable>' is not assignable
  to type 'Observable'.   Type 'Observable' is not
  assignable to type 'any[]'.
      Property 'includes' is missing in type 'Observable'

答:
I see some issues, for example you should map(val => this.getArrayOfValue(val)). But I would also suggest some additional changes. Think about adding debounceTime, distinctUntilChanged and switchMap. Set a debounce time of your choosing. This, not to completely overload the api. As well as switchMap is useful to make the request switches to the last value user has typed. Also you should consider using a service for your api requests, that is usually how we handle things. So I suggest moving the http-request to the service and call that from the component.

TS:

  // inject your created service which makes the http-request
  constructor(private service: Service) {

  this.filteredOptions = this.myControl.valueChanges
        .pipe(
          startWith(''),
          debounceTime(400),
          distinctUntilChanged(),
          switchMap(val => {
            return this.filter(val || '')
          })
        );
  }

  // filter and return the values
 filter(val: string): Observable<any[]> {
    // call the service which makes the http-request
    return this.service.getData()
     .pipe(
       map(response => response.filter(option => {
         return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
       }))
     )
   }
}
```

<p>Service would then call the http-request. If you do not overload the API, we could store the data in a variable after first fetch, and instead return an observable of that variable, but that is just optional.</p>

<pre class="lang-ts prettyprint-override"><code>opts = [];

getData() {
  return this.opts.length ?
    of(this.opts) :
    this.http.get<any>('https://jsonplaceholder.typicode.com/users').pipe(tap(data => this.opts = data))
}
</code>```

Also you seem to use value for your option in template. If you want to capture the whole object, use [value].

Here's a DEMO for you to play around with :)

Body:
I'm using angular 5 and material 2.

In ts file, I have this proeperty:

      filteredOptions: Observable<any[]>;

This property is going to have an array of values to show in the autocomplete field.

      [{
        id:'1', name: 'teste 1'},
        {id:'2', name: 'teste 2'},
        {id:'3', name: 'teste 3'
      }]

This array of values come from the database and it is going to be shown after the user type something.

html file:

          ##            <form class="example-form">
          ##              <mat-form-field class="example-full-width">
          ##                <input type="text" placeholder="Assignee" aria-label="Assignee" matInput [formControl]="myControl" [matAutocomplete]="auto">
          ##                <mat-autocomplete #auto="matAutocomplete" [displayWith]="displayFn">
          ##                  <mat-option *ngFor="let option of filteredOptions | async" [value]="option">
          ##                    {{ option.name }}
          ##                  </mat-option>
          ##                </mat-autocomplete>
          ##              </mat-form-field>
          ##            </form>

ts file example:

    this.filteredOptions = Observable<any[]>;

    ngOnInit() {
      this.filteredOptions = this.myControl.valueChanges
        .pipe(
          startWith({}),
          map(getArrayOfValue(val))
        );
      }

      // it is going to call an api to get the array of values to be shown in the field
      getArrayOfValue(val): Observable<any[]> {
        const url = this.ROOT_URL + 'veiculo/' + val;
        return this.http.get<any[]>(url);
      }

This code give me an error

ERROR in src/app/oficina/cadastro/veiculo/veiculo.component.ts(55,5):
  error TS2322: Type 'Observable>' is not assignable
  to type 'Observable'.   Type 'Observable' is not
  assignable to type 'any[]'.
      Property 'includes' is missing in type 'Observable'

Body:
I see some issues, for example you should map(val => this.getArrayOfValue(val)). But I would also suggest some additional changes. Think about adding debounceTime, distinctUntilChanged and switchMap. Set a debounce time of your choosing. This, not to completely overload the api. As well as switchMap is useful to make the request switches to the last value user has typed. Also you should consider using a service for your api requests, that is usually how we handle things. So I suggest moving the http-request to the service and call that from the component.

TS:

  // inject your created service which makes the http-request
  constructor(private service: Service) {

  this.filteredOptions = this.myControl.valueChanges
        .pipe(
          startWith(''),
          debounceTime(400),
          distinctUntilChanged(),
          switchMap(val => {
            return this.filter(val || '')
          })
        );
  }

  // filter and return the values
 filter(val: string): Observable<any[]> {
    // call the service which makes the http-request
    return this.service.getData()
     .pipe(
       map(response => response.filter(option => {
         return option.name.toLowerCase().indexOf(val.toLowerCase()) === 0
       }))
     )
   }
}

Service would then call the http-request. If you do not overload the API, we could store the data in a variable after first fetch, and instead return an observable of that variable, but that is just optional.

opts = [];

getData() {
  return this.opts.length ?
    of(this.opts) :
    this.http.get<any>('https://jsonplaceholder.typicode.com/users').pipe(tap(data => this.opts = data))
}

Also you seem to use value for your option in template. If you want to capture the whole object, use [value].

Here's a DEMO for you to play around with :)


问:
What should be return value of a jar called from Makefile in case of failure?
I have created a jar that has a main class and main method. So, I can execute the jar like java -jar jarname.jar.
Now, I am executing this jar from a Makefile. So, if the jar fails to do its purpose, Makefile should stop there and not continue. For this purpose, in the main method in jar, I'm returning 0 if success, and 1 if it fails. It is working perfectly as I expect. But my question is, is this the right way to do? Or is there a better way to do this? I think this is sufficient info, but in case you need extra info, I'm glad to provide.

答: Yes - the convention (which Make understands) is that success is an exit status of 0, failure is any other exit status.</p>


问:
Utilizing Bluetooth for generic data transfer in .NET
We are developing an Windows application that will need to talk to a remote battery-powered device.  The app is being developed using C#/.NET for Windows 7 machines.  WiFi is an option on the remote device but Bluetooth would be better for power conservation.  The connection would be used for transfer of generic serial data as well as audio.

Reviewing previous questions, I see here, for example, that 32feet and WCL appear to be popular libraries to use with .NET.  However, 32feet seems to be no longer under development.  WCL seems to have stopped Bluetooth development at .NET 4.6. Perhaps not a concern if 4.6.1 and 4.6.2 not require Blueooth updates?

Interested in getting some answers on the following:

1) Why do these libraries exist?  Why is there not native support for Bluetooth in .NET?

2) Why are the options so limited? Why is there no more development interest in 32feet? Is there a reluctance Bluetooth in .NET for some reason?  Has some other path opened up?

3) What are the concerns we might run into in implementing an app that would Bluetooth for generic data transfer as it relates to the various radios and stacks that are available?

In general, I am getting the impression that the approach is not taken much and I'm wondering why that is, if that is indeed the case, or I am wrong.  What approach would you take?

答:
I have the same questions and the same impression.

I think that the reply for the first question is in the Supported Hardware and Software wiki of 32feet:

The library is supported both in a version for desktop Windows, and a
  version for NETCF v2.0. On both platforms various companies have
  provided software protocol stack software to use Bluetooth hardware.
  For instance, on desktop Windows there are well known stacks from
  Microsoft, Widcomm (now Broadcom(Broadcom)), BlueSoleil and Toshiba.
  On CE platforms there are also stacks from Microsoft and
  Broadcom(Broadcom)/Widcomm.

and

Note that most Bluetooth dongles use a standard connection protocol
  and thus they appear very similar. This means that most Bluetooth
  software stacks (Microsoft, Broadcom/Widcomm, BlueZ, Bluetopia etc)
  can use any dongle. It it not the case for instance that Broadcom
  dongles can only be used by the Broadcom/Widcomm stack. There are some
  dongles that are non-standard however; I have one from Trust like that
  and it can thus only be used with the stack supplied with it.

I hope that the no-interest to development of 32feet is because microsoft is developping a native support.


问:
Downloaded by ajax excel file is corrupted
I have a Spring Boot web application, which generate Microsoft Excel file with extention .xlsx.

If I try to download file from browser calling the localhost:8080/report/stats it a returns correct file and I always can open it one successfully.

But, when I download a file from web page by click on button I get a bad file and I can't open it one.

I have the following part on JS:

```<code>$.ajax({
    url: 'report/stats',
    type: "GET",
    success: function (data) {
        var link = document.createElement('a');
        link.download = 'report.xlsx';
        link.href = 'data:,' + data;
        link.click();
    }
});
</code>```

Controller:

```<code>@GetMapping("stats")
public ResponseEntity downloadStatsReport() throws IOException {
    return fileResponse(excelReportService.create(new StatFilter()));
}

private ResponseEntity fileResponse(File report) throws IOException {
    InputStreamResource resource = new InputStreamResource(new FileInputStream(report));
    return ResponseEntity.ok()
            .contentLength(report.length())
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + report.getName())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}
</code>```

Why downloading from browser works well and not works from JS?

Open file error:

YES has been clicked:

NO has need clicked:

答:
I was able to download a valid file using the following code</p>

```<code>function download(fileName) {
    window.location.href = "/download?description=test&logId=123";
}
</code>```

Body:
I have a Spring Boot web application, which generate Microsoft Excel file with extention .xlsx.

If I try to download file from browser calling the localhost:8080/report/stats it a returns correct file and I always can open it one successfully.

But, when I download a file from web page by click on button I get a bad file and I can't open it one.

I have the following part on JS:

$.ajax({
    url: 'report/stats',
    type: "GET",
    success: function (data) {
        var link = document.createElement('a');
        link.download = 'report.xlsx';
        link.href = 'data:,' + data;
        link.click();
    }
});

Controller:

@GetMapping("stats")
public ResponseEntity downloadStatsReport() throws IOException {
    return fileResponse(excelReportService.create(new StatFilter()));
}

private ResponseEntity fileResponse(File report) throws IOException {
    InputStreamResource resource = new InputStreamResource(new FileInputStream(report));
    return ResponseEntity.ok()
            .contentLength(report.length())
            .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + report.getName())
            .contentType(MediaType.APPLICATION_OCTET_STREAM)
            .body(resource);
}

Why downloading from browser works well and not works from JS?

Open file error:

YES has been clicked:

NO has need clicked:

Body:
I was able to download a valid file using the following code

function download(fileName) {
    window.location.href = "/download?description=test&logId=123";
}


问:
Android How to adjust layout in Full Screen Mode when softkeyboard is visible
I have researched a lot to adjust the layout when softkeyboard is active and I have successfully implemented it but the problem comes when I use android:theme="@android:style/Theme.NoTitleBar.Fullscreen" this in my activity tag in manifest file.

For this I have used android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" with different options but no luck.

After that I implemented FullScreen programmatically and tried various layout to work with FullScreen but all in vain.

I referred these links and have looked many posts here related to this issue:

http://android-developers.blogspot.com/2009/04/updating-applications-for-on-screen.html

http://davidwparker.com/2011/08/30/android-how-to-float-a-row-above-keyboard/

Here is xml code:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/masterContainerView"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#ffffff">

    <ScrollView android:id="@+id/parentScrollView"
        android:layout_width="fill_parent" android:layout_height="wrap_content">

        <LinearLayout android:layout_width="fill_parent"
            android:layout_height="fill_parent" android:orientation="vertical">

            <TextView android:id="@+id/setup_txt" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="Setup - Step 1 of 3"
                android:textColor="@color/top_header_txt_color" android:textSize="20dp"
                android:padding="8dp" android:gravity="center_horizontal" />

            <TextView android:id="@+id/txt_header" android:layout_width="fill_parent"
                android:layout_height="40dp" android:text="AutoReply:"
                android:textColor="@color/top_header_txt_color" android:textSize="14dp"
                android:textStyle="bold" android:padding="10dp"
                android:layout_below="@+id/setup_txt" />

            <EditText android:id="@+id/edit_message"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:text="Some text here." android:textSize="16dp"
                android:textColor="@color/setting_editmsg_color" android:padding="10dp"
                android:minLines="5" android:maxLines="6" android:layout_below="@+id/txt_header"
                android:gravity="top" android:scrollbars="vertical"
                android:maxLength="132" />

            <ImageView android:id="@+id/image_bottom"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:layout_below="@+id/edit_message" />

        </LinearLayout>
    </ScrollView>

    <RelativeLayout android:id="@+id/scoringContainerView"
        android:layout_width="fill_parent" android:layout_height="50px"
        android:orientation="vertical" android:layout_alignParentBottom="true"
        android:background="#535254">

        <Button android:id="@+id/btn_save" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_alignParentRight="true"
            android:layout_marginTop="7dp" android:layout_marginRight="15dp"
            android:layout_below="@+id/edit_message"
            android:text = "Save" />

        <Button android:id="@+id/btn_cancel" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_marginTop="7dp"
            android:layout_marginRight="10dp" android:layout_below="@+id/edit_message"
            android:layout_toLeftOf="@+id/btn_save" android:text = "Cancel" />

    </RelativeLayout>
</RelativeLayout>
</code>```

I want the bottom 2 buttons should go upward when the softkeyboard comes in picture.

答:
I tried many solutions include Joseph Johnson's and Johan Stuyts's. But as a result I got a white space between content and keyboard on some devices (like Lenovo s820) in all cases.
So I made some changes to their codes and finally got working solution.

My idea based on adding margin to top of content when keyboard is showing.

```<code>contentContainer.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds);
    int usableHeightNow = contentAreaOfWindowBounds.height();

    if (usableHeightNow != usableHeightPrevious) {

        int difference = usableHeightNow - usableHeightPrevious;

        if (difference < 0 && difference < -150) {
            keyboardShowed = true;
            rootViewLayout.topMargin -= difference + 30;
            rootViewLayout.bottomMargin += 30;
        }
        else if (difference < 0 && difference > -150){
            rootViewLayout.topMargin -= difference + 30;
        }
        else if (difference > 0 && difference > 150) {
            keyboardShowed = false;
            rootViewLayout.topMargin = 0;
            rootViewLayout.bottomMargin = 0;
        }

        rootView.requestLayout();

        Log.e("Bug Workaround", "Difference: " + difference);

        usableHeightPrevious = usableHeightNow;
}
</code>```

As you can see, I add 30 px to difference because there is a small white space between top of the screen and content zone with margin. And I dont know whence it appears so I decided just make margins smaller and now it works exactly how I needed.

Body:
I have researched a lot to adjust the layout when softkeyboard is active and I have successfully implemented it but the problem comes when I use android:theme="@android:style/Theme.NoTitleBar.Fullscreen" this in my activity tag in manifest file.

For this I have used android:windowSoftInputMode="adjustPan|adjustResize|stateHidden" with different options but no luck.

After that I implemented FullScreen programmatically and tried various layout to work with FullScreen but all in vain.

I referred these links and have looked many posts here related to this issue:

http://android-developers.blogspot.com/2009/04/updating-applications-for-on-screen.html

http://davidwparker.com/2011/08/30/android-how-to-float-a-row-above-keyboard/

Here is xml code:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout android:id="@+id/masterContainerView"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical" xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="#ffffff">

    <ScrollView android:id="@+id/parentScrollView"
        android:layout_width="fill_parent" android:layout_height="wrap_content">

        <LinearLayout android:layout_width="fill_parent"
            android:layout_height="fill_parent" android:orientation="vertical">

            <TextView android:id="@+id/setup_txt" android:layout_width="wrap_content"
                android:layout_height="wrap_content" android:text="Setup - Step 1 of 3"
                android:textColor="@color/top_header_txt_color" android:textSize="20dp"
                android:padding="8dp" android:gravity="center_horizontal" />

            <TextView android:id="@+id/txt_header" android:layout_width="fill_parent"
                android:layout_height="40dp" android:text="AutoReply:"
                android:textColor="@color/top_header_txt_color" android:textSize="14dp"
                android:textStyle="bold" android:padding="10dp"
                android:layout_below="@+id/setup_txt" />

            <EditText android:id="@+id/edit_message"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:text="Some text here." android:textSize="16dp"
                android:textColor="@color/setting_editmsg_color" android:padding="10dp"
                android:minLines="5" android:maxLines="6" android:layout_below="@+id/txt_header"
                android:gravity="top" android:scrollbars="vertical"
                android:maxLength="132" />

            <ImageView android:id="@+id/image_bottom"
                android:layout_width="fill_parent" android:layout_height="wrap_content"
                android:layout_below="@+id/edit_message" />

        </LinearLayout>
    </ScrollView>

    <RelativeLayout android:id="@+id/scoringContainerView"
        android:layout_width="fill_parent" android:layout_height="50px"
        android:orientation="vertical" android:layout_alignParentBottom="true"
        android:background="#535254">

        <Button android:id="@+id/btn_save" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_alignParentRight="true"
            android:layout_marginTop="7dp" android:layout_marginRight="15dp"
            android:layout_below="@+id/edit_message"
            android:text = "Save" />

        <Button android:id="@+id/btn_cancel" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_marginTop="7dp"
            android:layout_marginRight="10dp" android:layout_below="@+id/edit_message"
            android:layout_toLeftOf="@+id/btn_save" android:text = "Cancel" />

    </RelativeLayout>
</RelativeLayout>

I want the bottom 2 buttons should go upward when the softkeyboard comes in picture.

Body:
I tried many solutions include Joseph Johnson's and Johan Stuyts's. But as a result I got a white space between content and keyboard on some devices (like Lenovo s820) in all cases.
So I made some changes to their codes and finally got working solution.

My idea based on adding margin to top of content when keyboard is showing.

contentContainer.getWindowVisibleDisplayFrame(contentAreaOfWindowBounds);
    int usableHeightNow = contentAreaOfWindowBounds.height();

    if (usableHeightNow != usableHeightPrevious) {

        int difference = usableHeightNow - usableHeightPrevious;

        if (difference < 0 && difference < -150) {
            keyboardShowed = true;
            rootViewLayout.topMargin -= difference + 30;
            rootViewLayout.bottomMargin += 30;
        }
        else if (difference < 0 && difference > -150){
            rootViewLayout.topMargin -= difference + 30;
        }
        else if (difference > 0 && difference > 150) {
            keyboardShowed = false;
            rootViewLayout.topMargin = 0;
            rootViewLayout.bottomMargin = 0;
        }

        rootView.requestLayout();

        Log.e("Bug Workaround", "Difference: " + difference);

        usableHeightPrevious = usableHeightNow;
}

As you can see, I add 30 px to difference because there is a small white space between top of the screen and content zone with margin. And I dont know whence it appears so I decided just make margins smaller and now it works exactly how I needed.


问:
Is there simple “angularJS” way using ng-repeat directive, to replace characters in object.name string with other character directly?
If the object's property name is Bob_Kenneth_Frank (as actual value) to Bob Kenneth Frank (displayed output)

I unsuccessfully tried different variants of:

html

```<code>ng-repeat="myChange(person.name) in persons"
</code>```

in controller

```<code>function myChange(name){
    return name.replace(/_/g, " ")
}
</code>```

答:
Use a custom filter.

See a working demo.

```<code>angular.module('app').filter('replaceUnderscoreBySpace', function () {
  return function (input) {
      return input.replace(/_/g, ' ');
  };
});
</code>```

View:

```<code><div ng-repeat="x in y">
  {{x | replaceUnderscoreBySpace}}
</div>
</code>```

Explanations on Todd Motto Blog

Body:
If the object's property name is Bob_Kenneth_Frank (as actual value) to Bob Kenneth Frank (displayed output)

I unsuccessfully tried different variants of:

html

ng-repeat="myChange(person.name) in persons"

in controller

function myChange(name){
    return name.replace(/_/g, " ")
}

Body:
Use a custom filter.

See a working demo.

angular.module('app').filter('replaceUnderscoreBySpace', function () {
  return function (input) {
      return input.replace(/_/g, ' ');
  };
});

View:

<div ng-repeat="x in y">
  {{x | replaceUnderscoreBySpace}}
</div>

Explanations on Todd Motto Blog


问:
how to return two array list in JSON and view in data table rows using asp.net MVC?
RoleListand EmpListwe having two arraylist how to return two array list in JSON and how to view in data table rows.

I need to return return Json(EmpList,RoleList, JsonRequestBehavior.AllowGet);

```<code>[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
            string sRptModuleIDs = string.Empty;
            foreach (ViewRoleModules emp in EmpList)
            {
                sRptModuleIDs += emp.ModuleID + ",";
            }
            if (sRptModuleIDs != "")
            {
                sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
            }

            List<ViewRoleModules> RoleList;
            foreach (var rid in sRptModuleIDs.Split(','))
            {
                string RID = rid;
                RoleList = type.GetSiteRoleModulesViews(rid);
            }

            return Json(EmpList, JsonRequestBehavior.AllowGet);

        }
</code>```

Scripts:

```<code><script>
        $(document).ready(function () {

            $("#DomainID").change(function () {

                var id = $(this).val();
                $("#example tbody tr").remove();

                $.ajax({

                    type: 'POST',

                    url: '@Url.Action("ViewModules")',
                    dataType: 'json',
                    data: { id: id },
                    success: function (data) {
                        var items = '';
                        $.each(data, function (i, item) {
                            $("#findValue").show();
                            var rows = "<tr>"
                            + "<td>" + i + "</td>"
                            + "<td>" + item.ModuleName + "</td>"
                            + "<td>" + item.Url + "</td>"
                            + "<td>" + item.RoleName + "</td>"
                            + "</tr>";
                            $('#example tbody').append(rows);
                        });

                    },
                    error: function (ex) {
                        var r = jQuery.parseJSON(response.responseText);
                        alert("Message: " + r.Message);
                        alert("StackTrace: " + r.StackTrace);
                        alert("ExceptionType: " + r.ExceptionType);
                    }
                });
                return false;
            })
        });
    </script>
</code>```

Cshtml:

```<code><table id="example" class="display table table-bordered" cellspacing="0" width="100%;">
                        <thead>
                            <tr>
                                <th>S#</th>
                                <th>Module Name</th>
                                <th>Url</th>
                                <th>Roles</th>
                                @*<th>Action</th>*@
                            </tr>
                        </thead>
                        <tbody>
                        </tbody>
                    </table>
</code>```

in my code return only one array list..

I need to display to array list

```<code>public List<ViewRoleModules> GetRoleModulesViews(int id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@DomainID", id);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    EmpList.Add(

                        new ViewRoleModules
                        {
                            ModuleID = Convert.ToInt32(dr["ModuleID"]),
                            CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                            DomainID = Convert.ToInt32(dr["DomainID"]),
                            ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                            ModuleName = Convert.ToString(dr["ModuleName"]),
                            FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                            Url = Convert.ToString(dr["Url"]),
                            TabOrder = Convert.ToInt32(dr["TabOrder"]),
                            Style = Convert.ToString(dr["Style"]),
                            Status = Convert.ToString(dr["Status"]),
                            IsTab = Convert.ToString(dr["IsTab"]),
                            ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                            CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                            CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                            ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                            ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                        }
                    );
                }

                return EmpList;
            }
        }

        public List<ViewRoleModules> GetSiteRoleModulesViews(string rid)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", Convert.ToInt32(rid));
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])

                        }
                    );
                }

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

答:
you can try the simple way with dictionary.

```<code>     public ActionResult ViewModules(int id)
    {
        Domain_Bind();
        dynamic mymodel = new ExpandoObject();
        userType type = new userType();

         Dictionary<string, object> dList = new Dictionary<string, object>();

        List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
        string sRptModuleIDs = string.Empty;
        foreach (ViewRoleModules emp in EmpList)
        {
            sRptModuleIDs += emp.ModuleID + ",";
        }
        if (sRptModuleIDs != "")
        {
            sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
        }

        List<ViewRoleModules> RoleList;
        foreach (var rid in sRptModuleIDs.Split(','))
        {
            string RID = rid;
            RoleList = type.GetSiteRoleModulesViews(rid);
        }

        dList.Add("EmpList", EmpList);
        dList.Add("RoleList", RoleList);

        return Json(dList, JsonRequestBehavior.AllowGet);

    }
</code>```

With the help of dictionary, you can bind n number of object together.

Body:
RoleListand EmpListwe having two arraylist how to return two array list in JSON and how to view in data table rows.

I need to return return Json(EmpList,RoleList, JsonRequestBehavior.AllowGet);

[HttpPost]
        [MyExceptionHandler]
        public ActionResult ViewModules(int id)
        {
            Domain_Bind();
            dynamic mymodel = new ExpandoObject();
            userType type = new userType();
            List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
            string sRptModuleIDs = string.Empty;
            foreach (ViewRoleModules emp in EmpList)
            {
                sRptModuleIDs += emp.ModuleID + ",";
            }
            if (sRptModuleIDs != "")
            {
                sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
            }

            List<ViewRoleModules> RoleList;
            foreach (var rid in sRptModuleIDs.Split(','))
            {
                string RID = rid;
                RoleList = type.GetSiteRoleModulesViews(rid);
            }

            return Json(EmpList, JsonRequestBehavior.AllowGet);

        }

Scripts:

Cshtml:

                                S#
                                Module Name
                                Url
                                Roles
                                @*Action	*@

in my code return only one array list..

I need to display to array list

public List<ViewRoleModules> GetRoleModulesViews(int id)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> EmpList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_Modules_SelectDomainModules", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@DomainID", id);
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    EmpList.Add(

                        new ViewRoleModules
                        {
                            ModuleID = Convert.ToInt32(dr["ModuleID"]),
                            CompanyTypeID = Convert.ToInt32(dr["CompanyTypeID"]),
                            DomainID = Convert.ToInt32(dr["DomainID"]),
                            ParentModuleID = Convert.ToInt32(dr["ParentModuleID"]),
                            ModuleName = Convert.ToString(dr["ModuleName"]),
                            FolderName = Convert.ToString(dr["FolderName"] == DBNull.Value ? null : dr["FolderName"].ToString()),
                            Url = Convert.ToString(dr["Url"]),
                            TabOrder = Convert.ToInt32(dr["TabOrder"]),
                            Style = Convert.ToString(dr["Style"]),
                            Status = Convert.ToString(dr["Status"]),
                            IsTab = Convert.ToString(dr["IsTab"]),
                            ApprovalProcess = Convert.ToString(dr["ApprovalProcess"]),
                            CreatedBy = Convert.ToInt32(dr["CreatedBy"] == DBNull.Value ? null : dr["CreatedBy"].ToString()),
                            CreatedDate = Convert.ToDateTime(dr["CreatedDate"]),
                            ModifiedBy = Convert.ToInt32(dr["ModifiedBy"] == DBNull.Value ? null : dr["ModifiedBy"].ToString()),
                            ModifiedDate = Convert.ToDateTime(dr["ModifiedDate"] == DBNull.Value ? null : dr["ModifiedDate"].ToString())
                        }
                    );
                }

                return EmpList;
            }
        }

        public List<ViewRoleModules> GetSiteRoleModulesViews(string rid)
        {
            using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["Admin"].ConnectionString))
            {
                List<ViewRoleModules> RoleList = new List<ViewRoleModules>();
                SqlCommand com = new SqlCommand("MEDEIL_SiteRoleModules_SelectOne", conn);
                com.CommandType = CommandType.StoredProcedure;
                com.Parameters.AddWithValue("@ModuleID", Convert.ToInt32(rid));
                SqlDataAdapter da = new SqlDataAdapter(com);
                DataTable dt = new DataTable();

                conn.Open();
                da.Fill(dt);
                conn.Close();
                foreach (DataRow dr in dt.Rows)
                {

                    RoleList.Add(

                        new ViewRoleModules
                        {
                            RoleID = Convert.ToInt32(dr["RoleID"]),
                            RoleName = Convert.ToString(dr["RoleName"])

                        }
                    );
                }

                return RoleList;
            }
        }

Body:
you can try the simple way with dictionary.

     public ActionResult ViewModules(int id)
    {
        Domain_Bind();
        dynamic mymodel = new ExpandoObject();
        userType type = new userType();

         Dictionary<string, object> dList = new Dictionary<string, object>();

        List<ViewRoleModules> EmpList = type.GetRoleModulesViews(id);
        string sRptModuleIDs = string.Empty;
        foreach (ViewRoleModules emp in EmpList)
        {
            sRptModuleIDs += emp.ModuleID + ",";
        }
        if (sRptModuleIDs != "")
        {
            sRptModuleIDs = sRptModuleIDs.Remove(sRptModuleIDs.Length - 1, 1);
        }

        List<ViewRoleModules> RoleList;
        foreach (var rid in sRptModuleIDs.Split(','))
        {
            string RID = rid;
            RoleList = type.GetSiteRoleModulesViews(rid);
        }

        dList.Add("EmpList", EmpList);
        dList.Add("RoleList", RoleList);

        return Json(dList, JsonRequestBehavior.AllowGet);

    }

With the help of dictionary, you can bind n number of object together.


问:
JavaScript event CSS background image loaded
Is there any way to detect that a CSS background image has been loaded? By using normal  tags this would be easy but I need to use a CSS background because I'm placing divs over the image.

The reason why I need to detect that this image has been loaded is that I don't want to start preload additional images before the background image is shown.

答:
Had the same problem. After thinking it for a while, I made an  below the
 that had the background and positioned it as the background using css. Then attached the onLoad on it :)

Body: Had the same problem. After thinking it for a while, I made an <img> below the <div> that had the background and positioned it as the background using css. Then attached the onLoad on it :)


问:
Tensorflow Unsupported feed type
Hoping someone can help me out with this TensorFlow (1.3) error when attempting to do a WideAndDeep model. At the limits of my sanity.

Error:
tensorflow.python.framework.errors_impl.InternalError: Unsupported feed type

Full Stack:

```<code>2017-11-09 00:42:06.024911: I tensorflow/core/common_runtime/gpu/gpu_device.cc:965] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 11.10GiB
2017-11-09 00:42:06.024939: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1055] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Traceback (most recent call last):
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1321, in _do_call
return fn(*args)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1300, in _run_fn
status, run_metadata)
File "/home/centos/anaconda3/lib/python3.6/contextlib.py", line 89, in __exit__
next(self.gen)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 467, in raise_exception_on_not_ok_status
c_api.TF_GetCode(status.status))
tensorflow.python.framework.errors_impl.InternalError: Unsupported feed type

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "BareBonesWideDeep.py", line 152, in <module>
train_and_eval('', 'wide_n_deep', 50,'', '')
File "BareBonesWideDeep.py", line 129, in train_and_eval
m.train(input_fn=input_fn(train_file_name, num_epochs=None, shuffle=True), steps=train_steps)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 255, in train
loss = self._train_model(input_fn=input_fn, hooks=hooks)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 717, in _train_model
_, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss])
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/monitored_session.py", line 537, in __exit__
self._close_internal(exception_type)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/monitored_session.py", line 574, in _close_internal
self._sess.close()
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/monitored_session.py", line 820, in close
self._sess.close()
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/monitored_session.py", line 941, in close
ignore_live_threads=True)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/coordinator.py", line 389, in join
six.reraise(*self._exc_info_to_raise)
File "/home/centos/anaconda3/lib/python3.6/site-packages/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py", line 94, in _run
sess.run(enqueue_op, feed_dict=feed_dict)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 889, in run
run_metadata_ptr)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1118, in _run
feed_dict_tensor, options, run_metadata)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1315, in _do_run
options, run_metadata)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1334, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InternalError: Unsupported feed type
</code>```

The only thing I've seen from searching is this code where it looks like
it is from Tensorflow and is doing data mapping from python to TF internal and throws "Unsupported feed type".
https://github.com/petewarden/tensorflow_makefile/blob/master/tensorflow/python/client/tf_session_helper.cc

Printing my feature data types results in:

```<code>f_1     float64
f_2     float64
f_3     float64
f_4     float64
f_5     float64
f_6     float64
f_7     float64
f_8     float64
f_9     float64
f_10    float64
f_11    float64
f_12     object
f_13    float64
</code>```

The last of my code in the stack trace is m.train where it invokes the input_fcn:

```<code>print("Training.....")
print('num_epochs train_and_eval:' + str(train_steps))
m.train(input_fn=input_fn(train_file_name, num_epochs=None,
shuffle=True), steps=train_steps)

def input_fn(data_file, num_epochs, shuffle):
    """Input builder function."""
    df_data = pd.read_csv('data.csv')
    df_data.fillna(0, inplace = True)
    df_data = df_data[df_data['y_actual_bucket']>=-4]
    df_data.f_12 = df_data.f_12.astype(str)
    df_data['f_12'] = 'a'
    print("CSV file data dimensions:",df_data.shape)
    print('num_epochs input_fn:' + str(num_epochs))
    labels = df_data["y_actual_bucket"]#.apply(lambda x: ">50K" in x).astype(int)
    labels = labels+4
    df_data = df_data.iloc[:,5:]
    train_test_cutoff = int(df_data.shape[0]*.7)
    if data_file == 'fake1':
      df_data = df_data.iloc[:train_test_cutoff,:]
      labels = labels.iloc[:train_test_cutoff]
      print("Training data shape:", df_data.shape)
    else:
      df_data = df_data.iloc[train_test_cutoff:,:]
      labels = labels.iloc[train_test_cutoff:]
      print("test data shape:", df_data.shape)
    print(df_data.dtypes)
    return tf.estimator.inputs.pandas_input_fn(
        x=df_data,
        y=labels,
        batch_size=100,
        num_epochs=num_epochs,
        shuffle=shuffle,
        num_threads=1)
</code>```

答:
This is a very irritating and unhelpful error message. I solved it by coercing my features and labels to float32:

df2 = df1.apply(lambda x: x.astype('float32'))

I believe this error arises because tf.feature_column.numeric_column() defaults to float32.

Title: Tensorflow Unsupported feed type

Body:
Hoping someone can help me out with this TensorFlow (1.3) error when attempting to do a WideAndDeep model. At the limits of my sanity.

Error:
tensorflow.python.framework.errors_impl.InternalError: Unsupported feed type

Full Stack:

2017-11-09 00:42:06.024911: I tensorflow/core/common_runtime/gpu/gpu_device.cc:965] Found device 0 with properties:
name: Tesla K80 major: 3 minor: 7 memoryClockRate(GHz): 0.8235
pciBusID: 0000:00:1e.0
totalMemory: 11.17GiB freeMemory: 11.10GiB
2017-11-09 00:42:06.024939: I tensorflow/core/common_runtime/gpu/gpu_device.cc:1055] Creating TensorFlow device (/device:GPU:0) -> (device: 0, name: Tesla K80, pci bus id: 0000:00:1e.0, compute capability: 3.7)
Traceback (most recent call last):
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1321, in _do_call
return fn(*args)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1300, in _run_fn
status, run_metadata)
File "/home/centos/anaconda3/lib/python3.6/contextlib.py", line 89, in __exit__
next(self.gen)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/framework/errors_impl.py", line 467, in raise_exception_on_not_ok_status
c_api.TF_GetCode(status.status))
tensorflow.python.framework.errors_impl.InternalError: Unsupported feed type

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "BareBonesWideDeep.py", line 152, in <module>
train_and_eval('', 'wide_n_deep', 50,'', '')
File "BareBonesWideDeep.py", line 129, in train_and_eval
m.train(input_fn=input_fn(train_file_name, num_epochs=None, shuffle=True), steps=train_steps)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 255, in train
loss = self._train_model(input_fn=input_fn, hooks=hooks)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/estimator/estimator.py", line 717, in _train_model
_, loss = mon_sess.run([estimator_spec.train_op, estimator_spec.loss])
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/monitored_session.py", line 537, in __exit__
self._close_internal(exception_type)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/monitored_session.py", line 574, in _close_internal
self._sess.close()
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/monitored_session.py", line 820, in close
self._sess.close()
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/monitored_session.py", line 941, in close
ignore_live_threads=True)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/training/coordinator.py", line 389, in join
six.reraise(*self._exc_info_to_raise)
File "/home/centos/anaconda3/lib/python3.6/site-packages/six.py", line 685, in reraise
raise value.with_traceback(tb)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/estimator/inputs/queues/feeding_queue_runner.py", line 94, in _run
sess.run(enqueue_op, feed_dict=feed_dict)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 889, in run
run_metadata_ptr)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1118, in _run
feed_dict_tensor, options, run_metadata)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1315, in _do_run
options, run_metadata)
File "/home/centos/anaconda3/lib/python3.6/site-packages/tensorflow/python/client/session.py", line 1334, in _do_call
raise type(e)(node_def, op, message)
tensorflow.python.framework.errors_impl.InternalError: Unsupported feed type

The only thing I've seen from searching is this code where it looks like
it is from Tensorflow and is doing data mapping from python to TF internal and throws "Unsupported feed type".
https://github.com/petewarden/tensorflow_makefile/blob/master/tensorflow/python/client/tf_session_helper.cc

Printing my feature data types results in:

f_1     float64
f_2     float64
f_3     float64
f_4     float64
f_5     float64
f_6     float64
f_7     float64
f_8     float64
f_9     float64
f_10    float64
f_11    float64
f_12     object
f_13    float64

The last of my code in the stack trace is m.train where it invokes the input_fcn:

print("Training.....")
print('num_epochs train_and_eval:' + str(train_steps))
m.train(input_fn=input_fn(train_file_name, num_epochs=None,
shuffle=True), steps=train_steps)

def input_fn(data_file, num_epochs, shuffle):
    """Input builder function."""
    df_data = pd.read_csv('data.csv')
    df_data.fillna(0, inplace = True)
    df_data = df_data[df_data['y_actual_bucket']>=-4]
    df_data.f_12 = df_data.f_12.astype(str)
    df_data['f_12'] = 'a'
    print("CSV file data dimensions:",df_data.shape)
    print('num_epochs input_fn:' + str(num_epochs))
    labels = df_data["y_actual_bucket"]#.apply(lambda x: ">50K" in x).astype(int)
    labels = labels+4
    df_data = df_data.iloc[:,5:]
    train_test_cutoff = int(df_data.shape[0]*.7)
    if data_file == 'fake1':
      df_data = df_data.iloc[:train_test_cutoff,:]
      labels = labels.iloc[:train_test_cutoff]
      print("Training data shape:", df_data.shape)
    else:
      df_data = df_data.iloc[train_test_cutoff:,:]
      labels = labels.iloc[train_test_cutoff:]
      print("test data shape:", df_data.shape)
    print(df_data.dtypes)
    return tf.estimator.inputs.pandas_input_fn(
        x=df_data,
        y=labels,
        batch_size=100,
        num_epochs=num_epochs,
        shuffle=shuffle,
        num_threads=1)


问:
Unable add ValueAxis property to Amchart stock graph
I'm trying to add title to the first graph in a multiple stock graphs list.
But it doesn't show up.
Here is the code:

```<code>stockGraphs: [{
            id: "g1",
            valueField: "value",
            comparable: true,
            bullet: "round",
            valueAxis: [
            {
             title: "t1"
            }]
}]
</code>```

Here is a demo

答:
As indicated in the documentation, the valueAxis property takes an id or a reference to the valueAxis object. You're trying to assign an array, which is way off.

You need to add an id to the valueAxes array inside your panel in your demo, then set the valueAxis property to the id as a string:

```<code>  valueAxes: [
    {
      id: "t1",
      title: "t1",
      maximum: 3000
    },{
      id: "t2",
      title: "t1",
      position: "right",
      maximum: 3000
    }
  ],
  stockGraphs: [
    {
      id: "g1",
      valueField: "value",
      comparable: true,
      bullet: "round",
      valueAxis: "t1"
    },{
      id: "g2",
      valueField: "value2dataset1",
      comparable: true,
      bullet: "round",
      valueAxis: "t2"
    }
  ],
</code>```

Demo

I added a second value axis as assigning a value axis to a graph only helps if you need to display multiple value axes in a panel as all graphs will use the first value axis by default if it is not assigned.

Body:
I'm trying to add title to the first graph in a multiple stock graphs list.
But it doesn't show up.
Here is the code:

stockGraphs: [{
            id: "g1",
            valueField: "value",
            comparable: true,
            bullet: "round",
            valueAxis: [
            {
             title: "t1"
            }]
}]

Here is a demo

Body:
As indicated in the documentation, the valueAxis property takes an id or a reference to the valueAxis object. You're trying to assign an array, which is way off.

You need to add an id to the valueAxes array inside your panel in your demo, then set the valueAxis property to the id as a string:

  valueAxes: [
    {
      id: "t1",
      title: "t1",
      maximum: 3000
    },{
      id: "t2",
      title: "t1",
      position: "right",
      maximum: 3000
    }
  ],
  stockGraphs: [
    {
      id: "g1",
      valueField: "value",
      comparable: true,
      bullet: "round",
      valueAxis: "t1"
    },{
      id: "g2",
      valueField: "value2dataset1",
      comparable: true,
      bullet: "round",
      valueAxis: "t2"
    }
  ],

Demo

I added a second value axis as assigning a value axis to a graph only helps if you need to display multiple value axes in a panel as all graphs will use the first value axis by default if it is not assigned.


问:
Multi language support while migrating from db2 to mysql
I have a database in db2 that needs to be migrated to mysql. I am exporting data from db2 to csv and then csv to mysql. The data is in multiple languages like Chinese, French, Latin, Hebrew, etc. Due to character set issues, the data is converted into symbols. How shall I ensure that the import is done correctly without any changes in the data ?</p>

答:
If the Db2 data is encoded in UTF-8, and your target is UTF-8  and especially if your LOCALE is correctly set on the export from Db2 then you won't lose any data.

If your LOCALE is incorrect or if you use the wrong export options from Db2 then there is a risk of data conversion issues. The way to set the locale depends on the operating-system where you run the EXPORT command from Db2 and the command-line options you give the Db2 EXPORt command.


问:
How to delete every row in a range that contains data?
In a big data set I am trying to find each cell in column J that contains any data so "is not blank", then delete that row that  contains data. My code however won't work for it:

```<code>Dim rng3 As Range

Do
    Set rng3 = Columns("J:J")
    If Not rng3 Is Nothing Then
        rng.EntireRow.Delete
    Else
        Exit Do
    End If
Loop
</code>```

I was hoping somebody can help me with this.

答:
Several moments:

You test Range against being Nothing - it will always return True because it actually refers to an object. To test the contents of the cell, use IsEmpty().

If you are deleting rows, then run the loop backwards.

```<code>Sub Test()
    Dim Rng As Range
    Dim I As Integer

'You need only non-empty cells, thus the intersection of needed column and used range of your worksheet
    Set Rng = Intersect(ActiveSheet.UsedRange, Columns("J"))

'Loop the cells backwards, from the last row to the first
    For I = Rng.Rows.Count To 1 Step -1
'If the cell is not empty, the delete that row and continue upwards
        If Not IsEmpty(Rng.Cells(I)) Then
            Rng.Cells(I).EntireRow.Delete
        End If
    Next

End Sub
</code>```

Body:
In a big data set I am trying to find each cell in column J that contains any data so "is not blank", then delete that row that  contains data. My code however won't work for it:

Dim rng3 As Range

Do
    Set rng3 = Columns("J:J")
    If Not rng3 Is Nothing Then
        rng.EntireRow.Delete
    Else
        Exit Do
    End If
Loop

I was hoping somebody can help me with this.

Body:
Several moments:

You test Range against being Nothing - it will always return True because it actually refers to an object. To test the contents of the cell, use IsEmpty().

If you are deleting rows, then run the loop backwards.

Sub Test()
    Dim Rng As Range
    Dim I As Integer

'You need only non-empty cells, thus the intersection of needed column and used range of your worksheet
    Set Rng = Intersect(ActiveSheet.UsedRange, Columns("J"))

'Loop the cells backwards, from the last row to the first
    For I = Rng.Rows.Count To 1 Step -1
'If the cell is not empty, the delete that row and continue upwards
        If Not IsEmpty(Rng.Cells(I)) Then
            Rng.Cells(I).EntireRow.Delete
        End If
    Next

End Sub