问:
How to make a background of a button transparent with visible border in Android?
This is the coding of the button. I want to make only borders visible and background of the button should be invisible.But with this code everything is becoming invisible.

```<code><Button
    android:id="@+id/button3"
    android:layout_width="200dp"
    android:layout_height="60dp"
    android:text="Sign In"
    android:textAllCaps="false"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"
    android:textColor="@color/white"
   android:background="@android:color/transparent"
</code>```

I want my button to look like this.

答:
Create One button_border.xml file in your drawable folder and paste this code

```<code><?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<stroke
    android:width="3dp"
    android:color="#FFFFFF" />
</code>```

 add button to your xml layout and set background as

```<code><Button
        android:id="@+id/button3"
        android:layout_width="200dp"
        android:layout_height="60dp"
        style="?android:attr/buttonStyleSmall"
        android:text="Sign In"
        android:textAllCaps="false"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:layout_marginLeft="50dp"
        android:textColor="@color/white"
        android:background="@drawable/button_border"/>
</code>```

Body:
This is the coding of the button. I want to make only borders visible and background of the button should be invisible.But with this code everything is becoming invisible.

<Button
    android:id="@+id/button3"
    android:layout_width="200dp"
    android:layout_height="60dp"
    android:text="Sign In"
    android:textAllCaps="false"
    android:layout_gravity="center"
    android:layout_marginTop="50dp"
    android:textColor="@color/white"
   android:background="@android:color/transparent"

I want my button to look like this.

Body:
Create One button_border.xml file in your drawable folder and paste this code

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle" >

<stroke
    android:width="3dp"
    android:color="#FFFFFF" />

 add button to your xml layout and set background as

<Button
        android:id="@+id/button3"
        android:layout_width="200dp"
        android:layout_height="60dp"
        style="?android:attr/buttonStyleSmall"
        android:text="Sign In"
        android:textAllCaps="false"
        android:layout_gravity="center"
        android:layout_marginTop="50dp"
        android:layout_marginLeft="50dp"
        android:textColor="@color/white"
        android:background="@drawable/button_border"/>


来源: stackexchange

问:
how to get value of particular element when clicked on button which is having same class
here is my html

```<code><h3>IRCTC Checked Template</h3>
<div>
<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>
</div>

<h3>ID Created Template</h3>
<div>
<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass"  id="btn" name="b">Send</button>
</div>
</code>```

on click on the button which is having same class i want to get respective textarea value
here my javascript

```<code>$(".btnclass").click(function(){
alert($('.txt').val());
});
</code>```

but the respective .txt class is not getting selected . for two buttons am getting same .txt class value.
i want to get respective text class on cling on the button .

答:
I'd suggest using $(this).parent().find('.txt'). This will always select the .txt element inside the same parent as the pressed button.

$(".w3-btn").click(function(){
alert($(this).parent().find('.txt').val());
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>
</div>

<h3>ID Created Template</h3>
<div>
<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass"  id="btn" name="b">Send</button>
</div></code>```

ContentLicense: CC BY-SA 3.0

Body:
here is my html

IRCTC Checked Template

<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>

ID Created Template

<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass"  id="btn" name="b">Send</button>

on click on the button which is having same class i want to get respective textarea value
here my javascript

$(".btnclass").click(function(){
alert($('.txt').val());
});

but the respective .txt class is not getting selected . for two buttons am getting same .txt class value.
i want to get respective text class on cling on the button .

Body:
I'd suggest using $(this).parent().find('.txt'). This will always select the .txt element inside the same parent as the pressed button.

$(".w3-btn").click(function(){
alert($(this).parent().find('.txt').val());
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here...IRCTC Checked Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
 btnclass" id="btn" name="b">Send</button>
</div>

<h3>ID Created Template</h3>
<div>
<textarea rows="4" cols="50" name="comment" class="txt" form="usrform">
Enter text here... ID Created Template</textarea>
<button class="w3-btn w3-blue w3-border-black  w3-card-24 w3-hover-green
btnclass"  id="btn" name="b">Send</button>
</div>


问:
Fatal error: Call to undefined function oci_connect() in wamp server 3.0 with oracle 10g running on windows 10
I have a 64 bit Windows 10 PC, on which i want to install wamp server which is to be connected with oracle 10g. I have installed oracle 10g, oracle client for 10g. Also, i have downloaded the php_oci8.dll and copied it to ext/ directory of wamp. I also made the changes in the php.ini file i.e. added extension=php_oci8.dll. I have tried installing wamp server3.0 32 bit as well as 64 bit, yet i am not able to connect my php application with my database as it keeps on giving error message : "Fatal error: Call to undefined function oci_connect() in line number 23". But i am able to connect to my database with sqldeveloper.

Any help....

答:
Use the Oracle 32-bit driver rather than the 64-bit.
Configure PHP to work with the oracle client.

http://php.net/manual/en/oci8.installation.php


问:
Replacing DIV content based on variable sent from another HTML file
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

```<code><!-- ORIGINAL DIV -->
<div id="Email">

</div>

<!-- DIV replacement function -->

<script type="text/javascript">
function ReplaceContentInContainer(id,content) {
var container = document.getElementById(id);
container.innerHTML = content;
}
</script>

<!-- Email 1 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 1 content</div>';

ReplaceContentInContainer('Email1',content);
}
</script>

<!-- Email 2 Content -->
<script ="text/javascript">
var content = '<div class="test">Email 2 content</div>';

ReplaceContentInContainer('Email2',content);
}
</script>
</code>```

Any ideas what I've done wrong that is causing it not to work?

答:
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.

As for grabbing the content parameter from the query string:

```<code>var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to get this JavaScript working:

I have an HTML email which links to this page which contains a variable in the link (index.html?content=email1). The JavaScript should replace the DIV content depending on what the variable for 'content' is.

Any ideas what I've done wrong that is causing it not to work?

Body:
David's on the money as to why your DOM script isn't working: there's only an 'Email' id out there, but you're referencing 'Email1' and 'Email2'.

As for grabbing the content parameter from the query string:

var content = (location.search.split(/&*content=/)[1] || '').split(/&/)[0];


答:
```<code>$(".btnclass").click(function(){
   alert($(this).prev().val());
});
</code>```

Title: how to get value of particular element when clicked on button which is having same class


问:
To list all files in Amazon s3 bucket using python
I need to list all files in Amazon S3 bucket. So I wrote the following code:

```<code>from boto.s3.connection import S3Connection

AWS_KEY = 'MY_KEY'
AWS_SECRET = 'MY_SECRET'
aws_connection = S3Connection(AWS_KEY, AWS_SECRET)
bucket = aws_connection.get_bucket('bucketname')

for file_key in bucket.list():
    print file_key.name
</code>```

But whenever I run this code, the following error comes:

ModuleNotFoundError: No module named 'boto.s3'; 'boto' is not a
  package [Finished in 0.1s]

Can anyone help me with this?

答:
you can do following steps:

start the virtualenv

pip install boto

and then try to run your program

Body:
I need to list all files in Amazon S3 bucket. So I wrote the following code:

from boto.s3.connection import S3Connection

AWS_KEY = 'MY_KEY'
AWS_SECRET = 'MY_SECRET'
aws_connection = S3Connection(AWS_KEY, AWS_SECRET)
bucket = aws_connection.get_bucket('bucketname')

for file_key in bucket.list():
    print file_key.name

But whenever I run this code, the following error comes:

ModuleNotFoundError: No module named 'boto.s3'; 'boto' is not a
  package [Finished in 0.1s]

Can anyone help me with this?


问:
How to use NOT IN clause in filter condition in spark
I want to filter a column of an RDD source  :

```<code>val source = sql("SELECT * from sample.source").rdd.map(_.mkString(","))
val destination = sql("select * from sample.destination").rdd.map(_.mkString(","))

val source_primary_key = source.map(rec => (rec.split(",")(0)))
val destination_primary_key = destination.map(rec => (rec.split(",")(0)))

val src = source_primary_key.subtractByKey(destination_primary_key)
</code>```

I want to use IN clause in filter condition to filter out only the values present in src from source, something like below(EDITED):

```<code>val source = spark.read.csv(inputPath + "/source").rdd.map(_.mkString(","))
val destination = spark.read.csv(inputPath + "/destination").rdd.map(_.mkString(","))

val source_primary_key = source.map(rec => (rec.split(",")(0)))
val destination_primary_key = destination.map(rec => (rec.split(",")(0)))

val extra_in_source = source_primary_key.filter(rec._1 != destination_primary_key._1)
</code>```

equivalent SQL code is

```<code>SELECT * FROM SOURCE WHERE ID IN (select ID from src)
</code>```

Thank you

答:
Since your code isn't reproducible, here is a small example using spark-sql on how to select * from t where id in (...) :

```<code>// create a DataFrame for a range 'id' from 1 to 9.
scala> val df = spark.range(1,10).toDF
df: org.apache.spark.sql.DataFrame = [id: bigint]

// values to exclude
scala> val f = Seq(5,6,7)
f: Seq[Int] = List(5, 6, 7)

// select * from df where id is not in the values to exclude
scala> df.filter(!col("id").isin(f  : _*)).show
+---+
| id|
+---+
|  1|
|  2|
|  3|
|  4|
|  8|
|  9|
+---+

// select * from df where id is in the values to exclude
scala> df.filter(col("id").isin(f  : _*)).show
</code>```

Here is the RDD version of the not isin :

```<code>scala> val rdd = sc.parallelize(1 to 10)
rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[2] at parallelize at <console>:24

scala> val f = Seq(5,6,7)
f: Seq[Int] = List(5, 6, 7)

scala> val rdd2 = rdd.filter(x => !f.contains(x))
rdd2: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[3] at filter at <console>:28
</code>```

Nevertheless, I still believe this is an overkill since you are already using spark-sql.

It seems in your case that you are actually dealing with DataFrames, thus the solutions mentioned above don't work.

You can use the left anti join approach :

```<code>scala> val source = spark.read.format("csv").load("source.file")
source: org.apache.spark.sql.DataFrame = [_c0: string, _c1: string ... 9 more fields]

scala> val destination = spark.read.format("csv").load("destination.file")
destination: org.apache.spark.sql.DataFrame = [_c0: string, _c1: string ... 9 more fields]

scala> source.show
+---+------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
|_c0|               _c1|     _c2|       _c3|            _c4|_c5|_c6|       _c7|  _c8|      _c9|        _c10|
+---+------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
|  1|        Ravi kumar|   Ravi |     kumar|           MSO |  1|  M|17-01-1994| 74.5| 24000.78|    Alabama |
|  2|Shekhar shudhanshu| Shekhar|shudhanshu|      Manulife |  2|  M|18-01-1994|76.34|   250000|     Alaska |
|  3|Preethi Narasingam| Preethi|Narasingam|        Retail |  3|  F|19-01-1994|77.45|270000.01|    Arizona |
|  4|     Abhishek Nair|Abhishek|      Nair|       Banking |  4|  M|20-01-1994|78.65|   345000|   Arkansas |
|  5|        Ram Sharma|     Ram|    Sharma|Infrastructure |  5|  M|21-01-1994|79.12|    45000| California |
|  6|   Chandani Kumari|Chandani|    Kumari|          BNFS |  6|  F|22-01-1994|80.13| 43000.02|   Colorado |
|  7|      Balaji Kumar|  Balaji|     Kumar|           MSO |  1|  M|23-01-1994|81.33|  1234678|Connecticut |
|  8|  Naveen Shekrappa|  Naveen| Shekrappa|      Manulife |  2|  M|24-01-1994|  100|   789414|   Delaware |
|  9|     Milind Chavan|  Milind|    Chavan|        Retail |  3|  M|25-01-1994|83.66|   245555|    Florida |
| 10|      Raghu Rajeev|   Raghu|    Rajeev|       Banking |  4|  M|26-01-1994|87.65|   235468|     Georgia|
+---+------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+

scala> destination.show
+---+-------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
|_c0|                _c1|     _c2|       _c3|            _c4|_c5|_c6|       _c7|  _c8|      _c9|        _c10|
+---+-------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
|  1|         Ravi kumar|   Revi |     kumar|           MSO |  1|  M|17-01-1994| 74.5| 24000.78|    Alabama |
|  1|        Ravi1 kumar|   Revi |     kumar|           MSO |  1|  M|17-01-1994| 74.5| 24000.78|    Alabama |
|  1|        Ravi2 kumar|   Revi |     kumar|           MSO |  1|  M|17-01-1994| 74.5| 24000.78|    Alabama |
|  2| Shekhar shudhanshu| Shekhar|shudhanshu|      Manulife |  2|  M|18-01-1994|76.34|   250000|     Alaska |
|  3|Preethi Narasingam1| Preethi|Narasingam|        Retail |  3|  F|19-01-1994|77.45|270000.01|    Arizona |
|  4|     Abhishek Nair1|Abhishek|      Nair|       Banking |  4|  M|20-01-1994|78.65|   345000|   Arkansas |
|  5|         Ram Sharma|     Ram|    Sharma|Infrastructure |  5|  M|21-01-1994|79.12|    45000| California |
|  6|    Chandani Kumari|Chandani|    Kumari|          BNFS |  6|  F|22-01-1994|80.13| 43000.02|   Colorado |
|  7|       Balaji Kumar|  Balaji|     Kumar|           MSO |  1|  M|23-01-1994|81.33|  1234678|Connecticut |
|  8|   Naveen Shekrappa|  Naveen| Shekrappa|      Manulife |  2|  M|24-01-1994|  100|   789414|   Delaware |
|  9|      Milind Chavan|  Milind|    Chavan|        Retail |  3|  M|25-01-1994|83.66|   245555|    Florida |
| 10|       Raghu Rajeev|   Raghu|    Rajeev|       Banking |  4|  M|26-01-1994|87.65|   235468|     Georgia|
+---+-------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
</code>```

You'll just need to do the following :

```<code>scala> val res1 = source.join(destination, Seq("_c0"), "leftanti")

scala> val res2 = destination.join(source, Seq("_c0"), "leftanti")
</code>```

It's the same logic I mentioned in my answer here.

Body:
I want to filter a column of an RDD source  :

val source = sql("SELECT * from sample.source").rdd.map(_.mkString(","))
val destination = sql("select * from sample.destination").rdd.map(_.mkString(","))

val source_primary_key = source.map(rec => (rec.split(",")(0)))
val destination_primary_key = destination.map(rec => (rec.split(",")(0)))

val src = source_primary_key.subtractByKey(destination_primary_key)

I want to use IN clause in filter condition to filter out only the values present in src from source, something like below(EDITED):

val source = spark.read.csv(inputPath + "/source").rdd.map(_.mkString(","))
val destination = spark.read.csv(inputPath + "/destination").rdd.map(_.mkString(","))

val source_primary_key = source.map(rec => (rec.split(",")(0)))
val destination_primary_key = destination.map(rec => (rec.split(",")(0)))

val extra_in_source = source_primary_key.filter(rec._1 != destination_primary_key._1)

equivalent SQL code is

SELECT * FROM SOURCE WHERE ID IN (select ID from src)

Thank you

Body:
Since your code isn't reproducible, here is a small example using spark-sql on how to select * from t where id in (...) :

// create a DataFrame for a range 'id' from 1 to 9.
scala> val df = spark.range(1,10).toDF
df: org.apache.spark.sql.DataFrame = [id: bigint]

// values to exclude
scala> val f = Seq(5,6,7)
f: Seq[Int] = List(5, 6, 7)

// select * from df where id is not in the values to exclude
scala> df.filter(!col("id").isin(f  : _*)).show
+---+
| id|
+---+
|  1|
|  2|
|  3|
|  4|
|  8|
|  9|
+---+

// select * from df where id is in the values to exclude
scala> df.filter(col("id").isin(f  : _*)).show

Here is the RDD version of the not isin :

scala> val rdd = sc.parallelize(1 to 10)
rdd: org.apache.spark.rdd.RDD[Int] = ParallelCollectionRDD[2] at parallelize at <console>:24

scala> val f = Seq(5,6,7)
f: Seq[Int] = List(5, 6, 7)

scala> val rdd2 = rdd.filter(x => !f.contains(x))
rdd2: org.apache.spark.rdd.RDD[Int] = MapPartitionsRDD[3] at filter at <console>:28

Nevertheless, I still believe this is an overkill since you are already using spark-sql.

It seems in your case that you are actually dealing with DataFrames, thus the solutions mentioned above don't work.

You can use the left anti join approach :

scala> val source = spark.read.format("csv").load("source.file")
source: org.apache.spark.sql.DataFrame = [_c0: string, _c1: string ... 9 more fields]

scala> val destination = spark.read.format("csv").load("destination.file")
destination: org.apache.spark.sql.DataFrame = [_c0: string, _c1: string ... 9 more fields]

scala> source.show
+---+------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
|_c0|               _c1|     _c2|       _c3|            _c4|_c5|_c6|       _c7|  _c8|      _c9|        _c10|
+---+------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
|  1|        Ravi kumar|   Ravi |     kumar|           MSO |  1|  M|17-01-1994| 74.5| 24000.78|    Alabama |
|  2|Shekhar shudhanshu| Shekhar|shudhanshu|      Manulife |  2|  M|18-01-1994|76.34|   250000|     Alaska |
|  3|Preethi Narasingam| Preethi|Narasingam|        Retail |  3|  F|19-01-1994|77.45|270000.01|    Arizona |
|  4|     Abhishek Nair|Abhishek|      Nair|       Banking |  4|  M|20-01-1994|78.65|   345000|   Arkansas |
|  5|        Ram Sharma|     Ram|    Sharma|Infrastructure |  5|  M|21-01-1994|79.12|    45000| California |
|  6|   Chandani Kumari|Chandani|    Kumari|          BNFS |  6|  F|22-01-1994|80.13| 43000.02|   Colorado |
|  7|      Balaji Kumar|  Balaji|     Kumar|           MSO |  1|  M|23-01-1994|81.33|  1234678|Connecticut |
|  8|  Naveen Shekrappa|  Naveen| Shekrappa|      Manulife |  2|  M|24-01-1994|  100|   789414|   Delaware |
|  9|     Milind Chavan|  Milind|    Chavan|        Retail |  3|  M|25-01-1994|83.66|   245555|    Florida |
| 10|      Raghu Rajeev|   Raghu|    Rajeev|       Banking |  4|  M|26-01-1994|87.65|   235468|     Georgia|
+---+------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+

scala> destination.show
+---+-------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
|_c0|                _c1|     _c2|       _c3|            _c4|_c5|_c6|       _c7|  _c8|      _c9|        _c10|
+---+-------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+
|  1|         Ravi kumar|   Revi |     kumar|           MSO |  1|  M|17-01-1994| 74.5| 24000.78|    Alabama |
|  1|        Ravi1 kumar|   Revi |     kumar|           MSO |  1|  M|17-01-1994| 74.5| 24000.78|    Alabama |
|  1|        Ravi2 kumar|   Revi |     kumar|           MSO |  1|  M|17-01-1994| 74.5| 24000.78|    Alabama |
|  2| Shekhar shudhanshu| Shekhar|shudhanshu|      Manulife |  2|  M|18-01-1994|76.34|   250000|     Alaska |
|  3|Preethi Narasingam1| Preethi|Narasingam|        Retail |  3|  F|19-01-1994|77.45|270000.01|    Arizona |
|  4|     Abhishek Nair1|Abhishek|      Nair|       Banking |  4|  M|20-01-1994|78.65|   345000|   Arkansas |
|  5|         Ram Sharma|     Ram|    Sharma|Infrastructure |  5|  M|21-01-1994|79.12|    45000| California |
|  6|    Chandani Kumari|Chandani|    Kumari|          BNFS |  6|  F|22-01-1994|80.13| 43000.02|   Colorado |
|  7|       Balaji Kumar|  Balaji|     Kumar|           MSO |  1|  M|23-01-1994|81.33|  1234678|Connecticut |
|  8|   Naveen Shekrappa|  Naveen| Shekrappa|      Manulife |  2|  M|24-01-1994|  100|   789414|   Delaware |
|  9|      Milind Chavan|  Milind|    Chavan|        Retail |  3|  M|25-01-1994|83.66|   245555|    Florida |
| 10|       Raghu Rajeev|   Raghu|    Rajeev|       Banking |  4|  M|26-01-1994|87.65|   235468|     Georgia|
+---+-------------------+--------+----------+---------------+---+---+----------+-----+---------+------------+

You'll just need to do the following :

scala> val res1 = source.join(destination, Seq("_c0"), "leftanti")

scala> val res2 = destination.join(source, Seq("_c0"), "leftanti")

It's the same logic I mentioned in my answer here.


问:
Node.js append a row to xlsx file
I'm just trying to figure out how to append a single row to an xlsx file. For example, append array = [1 2 3 4 5] to the first empty row using columns 1,2,3,4,5. Ideally I'd start with an empty .xlsx file, and repeatedly rerun this program, which appends a new row to the file each time it is ran.

I'm attempting to use exceljs, but any test writes I try to do to a file say corrupted when I attempt to open them.

edited code (still not working):

```<code>var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('rssi');
file = 'testfile.xlsx'
var array = [1,2,3,4,5]
sheet.addRow(array)
workbook.xlsx.writeFile(file)
.then(function() {
    console.log('Array added and file saved.')
});
</code>```

Output is zero bytes and cannot be opened by Microsoft Excel. Says, "The file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."

答:
Add row to spreadsheet:-

I also stuck with the same functionality issue, so I used 'spread_sheet' module.

It worked for me

Title: Node.js append a row to xlsx file

Body:
I'm just trying to figure out how to append a single row to an xlsx file. For example, append array = [1 2 3 4 5] to the first empty row using columns 1,2,3,4,5. Ideally I'd start with an empty .xlsx file, and repeatedly rerun this program, which appends a new row to the file each time it is ran.

I'm attempting to use exceljs, but any test writes I try to do to a file say corrupted when I attempt to open them.

edited code (still not working):

var Excel = require('exceljs');
var workbook = new Excel.Workbook();
var sheet = workbook.addWorksheet('rssi');
file = 'testfile.xlsx'
var array = [1,2,3,4,5]
sheet.addRow(array)
workbook.xlsx.writeFile(file)
.then(function() {
    console.log('Array added and file saved.')
});

Output is zero bytes and cannot be opened by Microsoft Excel. Says, "The file format or file extension is not valid. Verify that the file has not been corrupted and that the file extension matches the format of the file."


问:
Android app not recognising volume key presses when showing android.widget.MediaController
I cannot get an Android app (running on Android 6.0) to respond to volume key presses when the android.widget.MediaController is showing.

The media controller is shown by a fragment when a button in the fragment is tapped.

The activity that has loaded the fragment has the following code in onCreate:

```<code>AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
</code>```

When the media controller is not showing, the volume key presses do adjust the volume and this volume adjustment does impact on the volume with which the sound is played by the media controller.

However, when the media controller is shown visible in the app, then the volume keys are ignored.  I have overridden the onKeyDown method of the activity to detect when the key presses are recognised, and they are only recognised when the media controller is not visible.

```<code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        Log.i(TAG, "Increased volume");
        getAudioManager().adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        Log.i(TAG, "Decreased volume");
        getAudioManager().adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        return true;
    default:
        return false;
    }
}
</code>```

Users will tend to want to adjust volumes when the sound is being heard and this is exactly when they cannot adjust volumes, the way things are working. How can the media controller behaviour be changed so that it recognises the volume key presses?

答:
Had this issue yesterday and stumbled upon your question. I know it's rather old and you've probably found a way around it but I thought I should post an answer in case someone else finds their way here.

Your initial idea helped a lot but instead of overriding the handler for KeyEvents for my activity I did so for the MediaController.

What I did was override public boolean dispatchKeyEvent(KeyEvent event) and initialise my MediaController object like this:

```<code>        mediaControls = new MediaController(this) {

            @Override
            public boolean dispatchKeyEvent(KeyEvent event) {
                int action = event.getAction();
                int keyCode = event.getKeyCode();
                switch (keyCode) {
                    case KeyEvent.KEYCODE_VOLUME_UP:
                        if (action == KeyEvent.ACTION_DOWN) {
                            audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
                        }
                        break;
                    case KeyEvent.KEYCODE_VOLUME_DOWN:
                        if (action == KeyEvent.ACTION_DOWN) {
                            audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
                        }
                        break;
                    default:
                        return super.dispatchKeyEvent(event);
                }
                return true;
            }
        };
</code>```

audioManager is a private member in my Activity and is created the same way as in the question above.

Hope this will help someone.

Have a productive day!

Body:
I cannot get an Android app (running on Android 6.0) to respond to volume key presses when the android.widget.MediaController is showing.

The media controller is shown by a fragment when a button in the fragment is tapped.

The activity that has loaded the fragment has the following code in onCreate:

AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);

When the media controller is not showing, the volume key presses do adjust the volume and this volume adjustment does impact on the volume with which the sound is played by the media controller.

However, when the media controller is shown visible in the app, then the volume keys are ignored.  I have overridden the onKeyDown method of the activity to detect when the key presses are recognised, and they are only recognised when the media controller is not visible.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    switch (keyCode) {
    case KeyEvent.KEYCODE_VOLUME_UP:
        Log.i(TAG, "Increased volume");
        getAudioManager().adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
        return true;
    case KeyEvent.KEYCODE_VOLUME_DOWN:
        Log.i(TAG, "Decreased volume");
        getAudioManager().adjustStreamVolume(AudioManager.STREAM_MUSIC,
                AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
        return true;
    default:
        return false;
    }
}

Users will tend to want to adjust volumes when the sound is being heard and this is exactly when they cannot adjust volumes, the way things are working. How can the media controller behaviour be changed so that it recognises the volume key presses?

Body:
Had this issue yesterday and stumbled upon your question. I know it's rather old and you've probably found a way around it but I thought I should post an answer in case someone else finds their way here.

Your initial idea helped a lot but instead of overriding the handler for KeyEvents for my activity I did so for the MediaController.

What I did was override public boolean dispatchKeyEvent(KeyEvent event) and initialise my MediaController object like this:

        mediaControls = new MediaController(this) {

            @Override
            public boolean dispatchKeyEvent(KeyEvent event) {
                int action = event.getAction();
                int keyCode = event.getKeyCode();
                switch (keyCode) {
                    case KeyEvent.KEYCODE_VOLUME_UP:
                        if (action == KeyEvent.ACTION_DOWN) {
                            audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
                        }
                        break;
                    case KeyEvent.KEYCODE_VOLUME_DOWN:
                        if (action == KeyEvent.ACTION_DOWN) {
                            audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
                        }
                        break;
                    default:
                        return super.dispatchKeyEvent(event);
                }
                return true;
            }
        };

audioManager is a private member in my Activity and is created the same way as in the question above.

Hope this will help someone.

Have a productive day!


问:
Raspberry pi2 Python adafruit_CharLCD SystemError: error return without exception set
I am trying to get an LCD screen to display some text while following a tutorial the only differences between the tutorial code and mine is the text message.

I have also checked my wiring and tested the pins on the pi for functionality.
I do not understand why i'm getting this error.

my code:

```<code>    from time import sleep
    import Adafruit_CharLCD as LCD

    lcd = LCD.Adafruit_CharLCD(rs=23, en=19, d4=13, d5=6, d6=5, d7=11, cols=16, lines=2)
    lcd.clear()

    lcd.message('hi\n guy')
    sleep(3)
</code>```

my error

```<code>Traceback (most recent call last):
  File "lcd3.py", line 4, in <module>
    lcd = LCD.Adafruit_CharLCD(rs=23, en=19, d4=13, d5=6, d6=5, d7=11, cols=16, lines=2)
  File "/home/pi/Adafruit_CharLCD.py", line 143, in __init__
    gpio.setup(pin, GPIO.OUT)
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_GPIO/GPIO.py", line 278, in setup
    pull_up_down=self._pud_mapping[pull_up_down])
SystemError: error return without exception set
</code>```

答:
I get the same problem. I try to reinstall the raspberry pi update software. in a terminal execute:

```<code>sudo apt-get autoremove && sudo apt-get -f install && sudo apt-get update && sudo apt-get upgrade -y
</code>```

(Remove unneeded packages, fix broken installs, update package lists, upgrade installed packages).

Also reinstall Library RPi.GPIO and Adafruit_BBIO library On a Debian-based Linux like Raspbian. in a terminal execute:

```<code>sudo apt-get install build-essential python-pip python-dev python-smbus git
git clone https://github.com/adafruit/Adafruit_Python_GPIO.git
cd Adafruit_Python_GPIO
sudo python setup.py install
</code>```

And rerun the python script, its work for me.

Body:
I am trying to get an LCD screen to display some text while following a tutorial the only differences between the tutorial code and mine is the text message.

I have also checked my wiring and tested the pins on the pi for functionality.
I do not understand why i'm getting this error.

my code:

    from time import sleep
    import Adafruit_CharLCD as LCD

    lcd = LCD.Adafruit_CharLCD(rs=23, en=19, d4=13, d5=6, d6=5, d7=11, cols=16, lines=2)
    lcd.clear()

    lcd.message('hi\n guy')
    sleep(3)

my error

Traceback (most recent call last):
  File "lcd3.py", line 4, in <module>
    lcd = LCD.Adafruit_CharLCD(rs=23, en=19, d4=13, d5=6, d6=5, d7=11, cols=16, lines=2)
  File "/home/pi/Adafruit_CharLCD.py", line 143, in __init__
    gpio.setup(pin, GPIO.OUT)
  File "/usr/local/lib/python2.7/dist-packages/Adafruit_GPIO/GPIO.py", line 278, in setup
    pull_up_down=self._pud_mapping[pull_up_down])
SystemError: error return without exception set

Body:
I get the same problem. I try to reinstall the raspberry pi update software. in a terminal execute:

sudo apt-get autoremove && sudo apt-get -f install && sudo apt-get update && sudo apt-get upgrade -y

(Remove unneeded packages, fix broken installs, update package lists, upgrade installed packages).

Also reinstall Library RPi.GPIO and Adafruit_BBIO library On a Debian-based Linux like Raspbian. in a terminal execute:

sudo apt-get install build-essential python-pip python-dev python-smbus git
git clone https://github.com/adafruit/Adafruit_Python_GPIO.git
cd Adafruit_Python_GPIO
sudo python setup.py install

And rerun the python script, its work for me.


问:
Automatic class decoration (or validation) upon derivation

I have a base class from which I derive multiple subclasses.

Each subclass defines class constants, and I wish to enforce certain limitations on them.
For example:

```<code>class Base(object):
    # define these in your sub-class, and make sure (NOM % DENOM == 0)
    NOMINATOR = None
    DENOMINATOR = None

class Subclass_good(Base):
    NOMINATOR = 6
    DENOMINATOR = 3

class Subclass_bad(Base):
    NOMINATOR = 7
    DENOMINATOR = 5
</code>```

I want to be able to enforce the rule (NOM % DENOM == 0).

I currently do this with a class decorator:

```<code>def nom_denom_validator(cls):
    assert(cls.NOMINATOR % cls.DENOMINATOR == 0)
    return cls

# and decorate each subclass, e.g.:
@nom_denom_validator
class Subclass_another(Base):
    NOMINATOR = 9
    DENOMINATOR = 12
</code>```

But I don't like the fact that I need to decorate each subclass (I have plenty). I'm interested whether this can be done by some manipulation on the Base class directly.

Any advice?

答:
Ok, funny. I was thinking about it for a while, but only after posting the question - specifically when choosing tags, and adding "metaclass" there - did I realize I may have an answer myself.

So, submitted for review and future knowledge, here goes:

```<code>class Base_Metaclass(type):
    def __new__(meta, classname, bases, class_dict):
        new_type = type.__new__(meta, classname, bases, class_dict)
        if not (new_type.NOMINATOR % new_type.DENOMINATOR) == 0:
            raise Exception("Invalid subclass created - validation failed")
        return new_type

# have Base and all its descendants be enforced:
class Base(object):
    __metaclass__ = Base_Metaclass
    # I must pass the validation myself, no None's anymore...
    NOMINATOR = 1
    DENOMINATOR = 1
</code>```

And now all children should be auto-enforced.

Body:
I have a base class from which I derive multiple subclasses.

Each subclass defines class constants, and I wish to enforce certain limitations on them.
For example:

class Base(object):
    # define these in your sub-class, and make sure (NOM % DENOM == 0)
    NOMINATOR = None
    DENOMINATOR = None

class Subclass_good(Base):
    NOMINATOR = 6
    DENOMINATOR = 3

class Subclass_bad(Base):
    NOMINATOR = 7
    DENOMINATOR = 5

I want to be able to enforce the rule (NOM % DENOM == 0).

I currently do this with a class decorator:

def nom_denom_validator(cls):
    assert(cls.NOMINATOR % cls.DENOMINATOR == 0)
    return cls

# and decorate each subclass, e.g.:
@nom_denom_validator
class Subclass_another(Base):
    NOMINATOR = 9
    DENOMINATOR = 12

But I don't like the fact that I need to decorate each subclass (I have plenty). I'm interested whether this can be done by some manipulation on the Base class directly.

Any advice?

Body:
Ok, funny. I was thinking about it for a while, but only after posting the question - specifically when choosing tags, and adding "metaclass" there - did I realize I may have an answer myself.

So, submitted for review and future knowledge, here goes:

class Base_Metaclass(type):
    def __new__(meta, classname, bases, class_dict):
        new_type = type.__new__(meta, classname, bases, class_dict)
        if not (new_type.NOMINATOR % new_type.DENOMINATOR) == 0:
            raise Exception("Invalid subclass created - validation failed")
        return new_type

# have Base and all its descendants be enforced:
class Base(object):
    __metaclass__ = Base_Metaclass
    # I must pass the validation myself, no None's anymore...
    NOMINATOR = 1
    DENOMINATOR = 1

And now all children should be auto-enforced.


问:
Getting return type of Task (not Task<T>)
I use ASP.NET Identity 2.2.1.

I implement the interface IIdentityMessageService like this:

```<code>public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        string body = ONMailStyles.getOpening();
        body += message.Body;
        Mail mailService = new Mail(message.Destination, message.Subject, body);
        string succes = mailService.send();
        return Task.FromResult(succes);
    }
}
</code>```

Below is (a part) of my Mail class:

```<code>public class Mail
{
    public MailMessage message { get; set; }
    public string send(string host, int port, string username, string wachtwoord, int timeout)
    {
        SmtpClient ss = new SmtpClient(host, port);
        ss.EnableSsl = true;
        ss.Timeout = timeout;
        ss.DeliveryMethod = SmtpDeliveryMethod.Network;
        ss.UseDefaultCredentials = false;
        ss.Credentials = new System.Net.NetworkCredential(username, wachtwoord);
        try
        {
            ss.Send(message);
            message.Dispose();
            return "succes";
        }
        catch (Exception ex)
        {
            return "no succes: " + ex.ToString();
        }
    }
}
</code>```

In one of my controller's I have the following line:

```<code>var emailResult = UserManager.SendEmailAsync(user.Id, "Activeer uw lichtmeting account.", htmlMessage);
</code>```

I get a result back of type Task. If I had await a like this I expected to get the string result of succes:

```<code>var emailResult = await UserManager.SendEmailAsync(user.Id, "Activeer uw lichtmeting account.", htmlMessage);
</code>```

But I get the following compile error: "cannot assign void to an implicitly-typed variable". I just want to get the result of success in my controller. How do I accomplish that?

答:
You don't have an await in your SendAsync method - is it actually calling anything asynchronously? Also if you want it to return a string you should make it return Task<string>, not Task. I'd try something along these lines.

```<code>public class EmailService : IIdentityMessageService
{
    public async Task<string> SendAsync(IdentityMessage message)
    {
        string body = ONMailStyles.getOpening();
        body += message.Body;
        var mailService = new Mail(message.Destination, message.Subject, body);
        string success = await mailService.send();
        return success;
    }
}
</code>```

Body:
I use ASP.NET Identity 2.2.1.

I implement the interface IIdentityMessageService like this:

public class EmailService : IIdentityMessageService
{
    public Task SendAsync(IdentityMessage message)
    {
        string body = ONMailStyles.getOpening();
        body += message.Body;
        Mail mailService = new Mail(message.Destination, message.Subject, body);
        string succes = mailService.send();
        return Task.FromResult(succes);
    }
}

Below is (a part) of my Mail class:

public class Mail
{
    public MailMessage message { get; set; }
    public string send(string host, int port, string username, string wachtwoord, int timeout)
    {
        SmtpClient ss = new SmtpClient(host, port);
        ss.EnableSsl = true;
        ss.Timeout = timeout;
        ss.DeliveryMethod = SmtpDeliveryMethod.Network;
        ss.UseDefaultCredentials = false;
        ss.Credentials = new System.Net.NetworkCredential(username, wachtwoord);
        try
        {
            ss.Send(message);
            message.Dispose();
            return "succes";
        }
        catch (Exception ex)
        {
            return "no succes: " + ex.ToString();
        }
    }
}

In one of my controller's I have the following line:

var emailResult = UserManager.SendEmailAsync(user.Id, "Activeer uw lichtmeting account.", htmlMessage);

I get a result back of type Task. If I had await a like this I expected to get the string result of succes:

var emailResult = await UserManager.SendEmailAsync(user.Id, "Activeer uw lichtmeting account.", htmlMessage);

But I get the following compile error: "cannot assign void to an implicitly-typed variable". I just want to get the result of success in my controller. How do I accomplish that?

Body:
You don't have an await in your SendAsync method - is it actually calling anything asynchronously? Also if you want it to return a string you should make it return Task<string>, not Task. I'd try something along these lines.

public class EmailService : IIdentityMessageService
{
    public async Task<string> SendAsync(IdentityMessage message)
    {
        string body = ONMailStyles.getOpening();
        body += message.Body;
        var mailService = new Mail(message.Destination, message.Subject, body);
        string success = await mailService.send();
        return success;
    }
}


问:
Language filter in SonarQube component_tree url
The api api/measures/component_tree gives the list of components based on the provided input filters. Is there any parameter to provide the language so that the returned list only contains components of that language?

答:
No, currently you cannot filter on language.

You could do it like this:

Find all potentially relevant components with api/measures/component_tree

Use api/components/show to get the language of each of those

Only take components, that are included in 1. and have your desired language in 2.


问:
NSRegularExpression pattern for mobile no validation
Please someone help me to make pattern for mobile number validation using NSRegularExpression  in ObejctiveC.
Here is the rule:</p>

```<code>  1. Number should start with 01
  2. 3rd digit between 5 and 9
  3. Total length should be 11
</code>```

答:
The best way to perform validation would be to use a Regex. There is a wrapper in iOS called NSRegularExpression. Unfortunately, I can't give you some 'magic bullet' code as your Regex will likely need to be different to mine. (Given that mine is looking for a UK mobile number, yours might not be).

This code validates a string against the United Kingdom mobile number standard.

```<code>NSString *str = @"07578565203"
NSError *err;
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"(07\d{8,9})$" options:nil error:&err];
NSTextCheckingResult *result [regex firstMatchInString:str options:nil range:NSMakeRange(0, str.length)];
if (result == 1) {
    // number is valid
} else {
    // number is invalid, check err to see why
}
</code>```

Note the initWithPattern of the NSRegularExpression. You must pass the pattern that works for your phone number. You can generate one here. This site is also good for teaching you about RegEx.

If you get stuck, let me know the rules of a phone number where you live and I will write a Regex.

EDIT: A suitable RegEx for Bangladesh, as per OP's comment, would be (01[5-9]\d{8})$.

Body:
Please someone help me to make pattern for mobile number validation using NSRegularExpression  in ObejctiveC.
Here is the rule:

  1. Number should start with 01
  2. 3rd digit between 5 and 9
  3. Total length should be 11

Body:
The best way to perform validation would be to use a Regex. There is a wrapper in iOS called NSRegularExpression. Unfortunately, I can't give you some 'magic bullet' code as your Regex will likely need to be different to mine. (Given that mine is looking for a UK mobile number, yours might not be).

This code validates a string against the United Kingdom mobile number standard.

NSString *str = @"07578565203"
NSError *err;
NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"(07\d{8,9})$" options:nil error:&err];
NSTextCheckingResult *result [regex firstMatchInString:str options:nil range:NSMakeRange(0, str.length)];
if (result == 1) {
    // number is valid
} else {
    // number is invalid, check err to see why
}

Note the initWithPattern of the NSRegularExpression. You must pass the pattern that works for your phone number. You can generate one here. This site is also good for teaching you about RegEx.

If you get stuck, let me know the rules of a phone number where you live and I will write a Regex.

EDIT: A suitable RegEx for Bangladesh, as per OP's comment, would be (01[5-9]\d{8})$.

ContentLicense: CC BY-SA 4.0


问:
Filter, calculate and restructure data in Access SQL
I have just began my trip to database languages and encountered the following problem. I have created a table that look like this

tbl1

```<code>Year    Account   AccValue
2014    Sales     1000
2014    Cost      -400
2014    Tax       -200
2015    Sales     1200
2015    Cost      -900
</code>```

What I want to do is to create a query that calculates financial indicators like Gross Profit (Sales-Cost), Net profit (Sales-Cost-Tax), Gross Margin ([Sales-Cost]/Sales) year-wise, which means eventually I hope to access to a query like this:

```<code>Year    FAccount       FAccValue
2014    Gross profit   600
2014    Net profit     400
2014    Gross margin   60%
2015    Gross profit   300
2015    Net profit     300
2015    Gross margin   25%
</code>```

I referred to some rudimentary SQL materials I have at hand, but they just covered how to filter and calculate based on data from different columns, such as how to calculate sales from given columns of price and quantity, so basically the calculation output has an equal number of rows as the input.

In this case, I need to select rows of data for calculation based on particular columns ("Year" and "Account"), and store results with specific columns.

It does occur to me that maybe I should store results in separate queries like "tbl_grossprofit", "tbl_grossmargin" etc. and create another query to summarize them, but I am not sure which one is "conventional" in this case.

Sorry if this is a basic question, help is greatly appreciated!

--EDIT--

I have been trying to figure how to use sub queries in Access but I cannot figure out a way to use them in this case. So a workaround I did is to create separate queries on sales and profit directly from the raw data with GROUP BY and WHERE like this:

qry_Sales

```<code>Year    Sales
2014    1000
2015    1200
</code>```

qry_Profit

```<code>Year    Gross Profit
2014    400
2015    300
</code>```

Then I created another query on gross profit margin by

```<code>SELECT qry_Profit.[Gross profit]/qry_Sales.[Sales] AS [Gross margin], qry_Profit.[Year]
FROM qry_Profit,qry_Sales
GROUP BY [Year]
</code>```

This did end up with my desired outcome, but if I am to follow this idea, it would mean creating tens of queries. I am sure there is a better way. Could you give me some more advice?

Besides, honestly I wish to store the account names (such as "Gross profit", "Net profit") in rows (like shown in the original post) so I can display them easier in Excel. Thank you.

EDIT 2
I combined some great ideas here and this question and eventually came out with a workaround like

```<code>SELECT [Year],
(SELECT Sum(AccValue) FROM tbl AS Cal WHERE Cal.[Year]=tbl.[Year] AND Account=Sales) AS Sales,
(SELECT Sum(AccValue) FROM tbl AS Cal WHERE Cal.[Year]=tbl.[Year] AND Account=Cost) AS Cost,
Sales-Cost AS [Gross profit]
[Gross profit]/Sales AS [Gross Margin]
FROM tbl1
GROUP BY [Year]
--The Sum function is unnecessary here, but in the real case Sales data is divided into many rows.
</code>```

I haven't finished the entire query, but it seems that I have made one big step forward.

答:
This will hopefully get you started.

First create the example table and fill it with your data:

```<code>CREATE Table tbl1 (Year int, account nvarchar(25), AccValue int)

INSERT INTO tbl1
VALUES (2014, 'Sales', 1000), (2014, 'Cost', -400), (2014, 'Tax', -200), (2015, 'Sales', 1200), (2015, 'Cost', -900)
;
</code>```

Then, define CTEs to grab Cost, Tax and Sales per year. We join the three CTEs on Year, and can then perform calculations on them. I use a LEFT JOIN to take into account Tax can be unknown (as in 2015).

```<code>WITH Sales AS (
        SELECT [Year], AccValue FROM tbl1 WHERE Account = 'Sales'
    ), Cost AS (
        SELECT [Year], AccValue FROM tbl1 WHERE Account = 'Cost'
    ), Tax AS (
        SELECT [Year], AccValue FROM tbl1 WHERE Account = 'Tax'
    )
    SELECT
        a.[Year]
        , SUM(a.AccValue + b.accValue) AS GrossProfit
        , SUM(a.AccValue + b.accValue - ISNULL(c.AccValue, 0)) AS GrossProfit
    FROM

        Sales a
        LEFT JOIN Cost b ON a.[Year] = b.[Year]
        LEFT JOIN Tax c ON a.[Year] = c.[Year]
    GROUP BY a.[Year]
</code>```

Output:

```<code>Year    GrossProfit GrossProfit
2014    600         800
2015    300         300
</code>```

For Access, instead of using CTEs, you should be able to store the individual sub-queries as queries in Access, and then build the final query that way.

Body:
I have just began my trip to database languages and encountered the following problem. I have created a table that look like this

tbl1

Year    Account   AccValue
2014    Sales     1000
2014    Cost      -400
2014    Tax       -200
2015    Sales     1200
2015    Cost      -900

What I want to do is to create a query that calculates financial indicators like Gross Profit (Sales-Cost), Net profit (Sales-Cost-Tax), Gross Margin ([Sales-Cost]/Sales) year-wise, which means eventually I hope to access to a query like this:

Year    FAccount       FAccValue
2014    Gross profit   600
2014    Net profit     400
2014    Gross margin   60%
2015    Gross profit   300
2015    Net profit     300
2015    Gross margin   25%

I referred to some rudimentary SQL materials I have at hand, but they just covered how to filter and calculate based on data from different columns, such as how to calculate sales from given columns of price and quantity, so basically the calculation output has an equal number of rows as the input.

In this case, I need to select rows of data for calculation based on particular columns ("Year" and "Account"), and store results with specific columns.

It does occur to me that maybe I should store results in separate queries like "tbl_grossprofit", "tbl_grossmargin" etc. and create another query to summarize them, but I am not sure which one is "conventional" in this case.

Sorry if this is a basic question, help is greatly appreciated!

--EDIT--

I have been trying to figure how to use sub queries in Access but I cannot figure out a way to use them in this case. So a workaround I did is to create separate queries on sales and profit directly from the raw data with GROUP BY and WHERE like this:

qry_Sales

Year    Sales
2014    1000
2015    1200

qry_Profit

Year    Gross Profit
2014    400
2015    300

Then I created another query on gross profit margin by

SELECT qry_Profit.[Gross profit]/qry_Sales.[Sales] AS [Gross margin], qry_Profit.[Year]
FROM qry_Profit,qry_Sales
GROUP BY [Year]

This did end up with my desired outcome, but if I am to follow this idea, it would mean creating tens of queries. I am sure there is a better way. Could you give me some more advice?

Besides, honestly I wish to store the account names (such as "Gross profit", "Net profit") in rows (like shown in the original post) so I can display them easier in Excel. Thank you.

EDIT 2
I combined some great ideas here and this question and eventually came out with a workaround like

SELECT [Year],
(SELECT Sum(AccValue) FROM tbl AS Cal WHERE Cal.[Year]=tbl.[Year] AND Account=Sales) AS Sales,
(SELECT Sum(AccValue) FROM tbl AS Cal WHERE Cal.[Year]=tbl.[Year] AND Account=Cost) AS Cost,
Sales-Cost AS [Gross profit]
[Gross profit]/Sales AS [Gross Margin]
FROM tbl1
GROUP BY [Year]
--The Sum function is unnecessary here, but in the real case Sales data is divided into many rows.

I haven't finished the entire query, but it seems that I have made one big step forward.

Body:
This will hopefully get you started.

First create the example table and fill it with your data:

CREATE Table tbl1 (Year int, account nvarchar(25), AccValue int)

INSERT INTO tbl1
VALUES (2014, 'Sales', 1000), (2014, 'Cost', -400), (2014, 'Tax', -200), (2015, 'Sales', 1200), (2015, 'Cost', -900)
;

Then, define CTEs to grab Cost, Tax and Sales per year. We join the three CTEs on Year, and can then perform calculations on them. I use a LEFT JOIN to take into account Tax can be unknown (as in 2015).

WITH Sales AS (
        SELECT [Year], AccValue FROM tbl1 WHERE Account = 'Sales'
    ), Cost AS (
        SELECT [Year], AccValue FROM tbl1 WHERE Account = 'Cost'
    ), Tax AS (
        SELECT [Year], AccValue FROM tbl1 WHERE Account = 'Tax'
    )
    SELECT
        a.[Year]
        , SUM(a.AccValue + b.accValue) AS GrossProfit
        , SUM(a.AccValue + b.accValue - ISNULL(c.AccValue, 0)) AS GrossProfit
    FROM

        Sales a
        LEFT JOIN Cost b ON a.[Year] = b.[Year]
        LEFT JOIN Tax c ON a.[Year] = c.[Year]
    GROUP BY a.[Year]

Output:

Year    GrossProfit GrossProfit
2014    600         800
2015    300         300

For Access, instead of using CTEs, you should be able to store the individual sub-queries as queries in Access, and then build the final query that way.


问:
populate dropdown list from a list of objects
In an attempt of building a 3-tier architecture c# asp.net application, I've started building a class that is database which is used for the connecting to the database, another class that is City which has a method for each column in the table cities, and a Cities class in which I have the GetCities method that creates a list of City objects and then use the DataSource wizard to set the control to use the data from GetCities().
All I get is blanks in the dropdown list. Any idea why?

```<code>        public List<City> GetCities()
    {
        List<City> cities = new List<City>();
        Database db = new Database();
        SqlConnection conn = db.GetConnection();
        String sql = "SELECT * FROM CITIES";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            City c = new City(reader.GetInt32(0), reader.GetString(1).ToString());
            cities.Add(c);
        }

        db.CloseConnection();
        return cities;
    }
</code>```

thanks

答:
Did you set the DataTextField, DataValueField properties, and call DataBind?

At this point I would try to get the concept working as simply as possible, and then start adding things back in until you locate the problem.  Start with a brand new page, add a DropDownList but don't touch the data source or change any properties, go directly into the codebehind and add this in Page_Load:

```<code>DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataSource = new[] {
    new { ID = 1, Name = "Alice" },
    new { ID = 2, Name = "Mike" },
    new { ID = 3, Name = "John" }
};
DropDownList1.DataBind();
</code>```

Does it work?  It does for me.  Then try to change DataValueField, DataTextField, and DataSource to work with your customer list.  Is it broken now?  Then you know the problem is in the customer list somewhere, not with the way you're binding the data.

Body:
In an attempt of building a 3-tier architecture c# asp.net application, I've started building a class that is database which is used for the connecting to the database, another class that is City which has a method for each column in the table cities, and a Cities class in which I have the GetCities method that creates a list of City objects and then use the DataSource wizard to set the control to use the data from GetCities().
All I get is blanks in the dropdown list. Any idea why?

        public List<City> GetCities()
    {
        List<City> cities = new List<City>();
        Database db = new Database();
        SqlConnection conn = db.GetConnection();
        String sql = "SELECT * FROM CITIES";
        SqlCommand cmd = new SqlCommand(sql, conn);
        SqlDataReader reader = cmd.ExecuteReader();

        while (reader.Read())
        {
            City c = new City(reader.GetInt32(0), reader.GetString(1).ToString());
            cities.Add(c);
        }

        db.CloseConnection();
        return cities;
    }

thanks

Body:
Did you set the DataTextField, DataValueField properties, and call DataBind?

At this point I would try to get the concept working as simply as possible, and then start adding things back in until you locate the problem.  Start with a brand new page, add a DropDownList but don't touch the data source or change any properties, go directly into the codebehind and add this in Page_Load:

DropDownList1.DataValueField = "ID";
DropDownList1.DataTextField = "Name";
DropDownList1.DataSource = new[] {
    new { ID = 1, Name = "Alice" },
    new { ID = 2, Name = "Mike" },
    new { ID = 3, Name = "John" }
};
DropDownList1.DataBind();

Does it work?  It does for me.  Then try to change DataValueField, DataTextField, and DataSource to work with your customer list.  Is it broken now?  Then you know the problem is in the customer list somewhere, not with the way you're binding the data.


问:
Raspberry Pi camera. Out of resources
Trying to launch my camera with motion sensor.
Works fine like this:

```<code>import RPi.GPIO as GPIO
import time
import picamera
import datetime
import os

def getFileName():
    return datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")

pin = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
prevState = False
currState = False
camera = picamera.PiCamera()
while True:
    time.sleep(0.1)
    prevState = currState
    currState = GPIO.input(pin)
    if currState != prevState:
        newState = "HIGH" if currState else "LOW"
        print ("GPIO pin %s is %s" % (pin, newState))
        if currState:
            fileName = getFileName()
            print ("Starting Recording...")
            camera.start_preview()
            camera.start_recording(fileName)
            time.sleep(10)
            print (fileName)
        else:
            camera.stop_preview()
            time.sleep(1)
            camera.stop_recording()
            print ("Stopped Recording")

    else:
        print("No motions")
</code>```

But then i try to def my function for Tornado server:

```<code>def secure_on(prevState, currState):
    pin = 4
    #GPIO.setmode(GPIO.BCM)
    #GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    #camera = picamera.PiCamera()
    time.sleep(0.1)
    prevState = currState
    #currState = GPIO.input(pin)
    if currState != prevState:
        newState = "HIGH" if currState else "LOW"
        return {'info': "GPIO pin %s is %s" % (pin, newState)}
        if currState:
            fileName = getFileName()
            print ("Starting Recording...")
            #camera.start_preview()
            #camera.start_recording(fileName)
            time.sleep(10)
            return {'info': fileName}
        else:
            #camera.stop_preview()
            time.sleep(1)
            #camera.stop_recording()
            return {'info': "Stopped Recording"}
    else:
        return {'info': "No motions"}
</code>```

Tornado:

```<code>class SecureOnHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        result = RosPi.secure_on(prevSec, currSec)

        self.write({"info": result['info']})
</code>```

After that i get an error

"Camera component couldn't be enabled: Out of resources (other than memory)
  ERROR:tornado.access:500 GET /secure_on

What could be causing the error?
Thanks in advance!

答:
I know this is an old question but I just wanted to post my solution to the Out of resources error in case it can save someone time and effort.

The problem for me was that I was initializing the camera module is two Python files at the same time (a script with a while loop that took a picture when motion was detected and another script that took a picture on demand).

As per the documentation: https://picamera.readthedocs.io/en/release-1.13/faq.html#camera-locks-up-with-multiprocessing you must ensure that only a single process creates an instance of PiCamera at one time.

My solution was simply to move initializing the camera module inside a function and call .close() after taking the picture to free up the process ready to be used by the next script that calls it.

Title: Raspberry Pi camera. Out of resources

Body:
Trying to launch my camera with motion sensor.
Works fine like this:

import RPi.GPIO as GPIO
import time
import picamera
import datetime
import os

def getFileName():
    return datetime.datetime.now().strftime("%Y-%m-%d_%H.%M.%S.h264")

pin = 4
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
prevState = False
currState = False
camera = picamera.PiCamera()
while True:
    time.sleep(0.1)
    prevState = currState
    currState = GPIO.input(pin)
    if currState != prevState:
        newState = "HIGH" if currState else "LOW"
        print ("GPIO pin %s is %s" % (pin, newState))
        if currState:
            fileName = getFileName()
            print ("Starting Recording...")
            camera.start_preview()
            camera.start_recording(fileName)
            time.sleep(10)
            print (fileName)
        else:
            camera.stop_preview()
            time.sleep(1)
            camera.stop_recording()
            print ("Stopped Recording")

    else:
        print("No motions")

But then i try to def my function for Tornado server:

def secure_on(prevState, currState):
    pin = 4
    #GPIO.setmode(GPIO.BCM)
    #GPIO.setup(pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
    #camera = picamera.PiCamera()
    time.sleep(0.1)
    prevState = currState
    #currState = GPIO.input(pin)
    if currState != prevState:
        newState = "HIGH" if currState else "LOW"
        return {'info': "GPIO pin %s is %s" % (pin, newState)}
        if currState:
            fileName = getFileName()
            print ("Starting Recording...")
            #camera.start_preview()
            #camera.start_recording(fileName)
            time.sleep(10)
            return {'info': fileName}
        else:
            #camera.stop_preview()
            time.sleep(1)
            #camera.stop_recording()
            return {'info': "Stopped Recording"}
    else:
        return {'info': "No motions"}

Tornado:

class SecureOnHandler(tornado.web.RequestHandler):
    @gen.coroutine
    def get(self):
        result = RosPi.secure_on(prevSec, currSec)

        self.write({"info": result['info']})

After that i get an error

"Camera component couldn't be enabled: Out of resources (other than memory)
  ERROR:tornado.access:500 GET /secure_on

What could be causing the error?
Thanks in advance!


问:
Handle muliple push notifications click in Android
I'm using FCM notification in my android application. When the application is on background, the notification click navigates to the MainActivity. This only happens when there is only one notification, When there are multiple notifications, only the last notification is able to start the application.
Notification click is not happening once the app comes to foreground. If I close the app and click the next notification from notification bar, then the app opens again.

I think there a problem with the notification action in the notification payload.

```<code>   <application
    android:name=".MyApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:launchMode="singleTop"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    tools:replace="android:allowBackup">

    <!-- tools:replace="android:theme" -->
    <!-- Launch Flow -->
    <activity
        android:name=".ui.activity.MainActivity"
        android:screenOrientation="portrait"
        android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="myAction" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <!-- [START firebase_service] -->
    <service android:name=".service.MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>
    <!-- [END firebase_service] -->

    <!-- [START firebase_iid_service] -->
    <service android:name=".service.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>
    <!-- [END firebase_iid_service] -->

</application>
</code>```

This is my notification json.

```<code>{

"notification":{
    "title":"Jogn Doe",
    "body":"Jogn commented on your post",
    "sound":"mySound",
    "tag":"88211407420864",
    "click_action":"myAction"
},
"data":{
    "notificationCount":2,
    "creatorName":"John Doe",
    "creatorImage":"https://image.com/sample.png",
    "notificationId":"88335540289536",
    "universityId":"8821098664448"
},
    "to":"fYu_ybp3Wu8:APA91bHxOact-9gcqf7rAqNSPSkvU7N5h4t4m0XgCAHBdu"
}
</code>```

I do this in onCreate method..

```<code>Intent intent = new Intent(LauncherActivity.this, PostFeedActivity.class);
    if (getIntent().getAction().equalsIgnoreCase("myAction")) {
        Bundle extras = getIntent().getExtras();
        String universityId = extras.getString(getString(R.string.notification_university));

        String notificationId = extras.getString(getString(R.string.notification_id));
        String notificationCreatorName = extras.getString(getString(R.string.notification_creator_name));
        String notificationCreatorImage = extras.getString(getString(R.string.notification_creator_image));
        int notificationCount = extras.getInt(getString(R.string.notification_count), 0);
        if (!TextUtils.isEmpty(notificationId)) {
            intent.setAction(getString(R.string.action_notification_from_push));

            intent.putExtra(getString(R.string.notification_count),
                    notificationCount);
            intent.putExtra(getString(R.string.notification_id),
                    notificationId);
            intent.putExtra(getString(R.string.notification_creator_name),
                    notificationCreatorName);
            intent.putExtra(getString(R.string.notification_creator_image),
                    notificationCreatorImage);

            //fetch notification data by calling API and start activity
            requestNotification(notificationId, intent);
            //

        } else {
            startActivity(intent);
            finish();
        }
</code>```

答:
If all your notifications have the same tag they are grouped by android and then you only have the latest notification available.
I can not see from your code, whether your tag is a unique value (so you show them side-by-side in the notification bar of the device).

As soon as you have a notification object and not only data, android takes partially control of the notification, means:

If your app is not running or in background, the notification is shown on notification bar

If your app is in foreground active, no notification is shown, instead, the callback onMessageReceived callback is invoked directly in your FirebaseMessagingService (this is the callback that is also invoked if you receive a data-only message from FCM)

See also here FCM notification merge

Hope this helps,
cheers

Body:
I'm using FCM notification in my android application. When the application is on background, the notification click navigates to the MainActivity. This only happens when there is only one notification, When there are multiple notifications, only the last notification is able to start the application.
Notification click is not happening once the app comes to foreground. If I close the app and click the next notification from notification bar, then the app opens again.

I think there a problem with the notification action in the notification payload.

   <application
    android:name=".MyApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:launchMode="singleTop"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    tools:replace="android:allowBackup">

    <activity
        android:name=".ui.activity.MainActivity"
        android:screenOrientation="portrait"
        android:theme="@style/SplashTheme">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>

        <intent-filter>
            <action android:name="myAction" />
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

    <service android:name=".service.MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service android:name=".service.MyFirebaseInstanceIDService">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

</application>

This is my notification json.

{

"notification":{
    "title":"Jogn Doe",
    "body":"Jogn commented on your post",
    "sound":"mySound",
    "tag":"88211407420864",
    "click_action":"myAction"
},
"data":{
    "notificationCount":2,
    "creatorName":"John Doe",
    "creatorImage":"https://image.com/sample.png",
    "notificationId":"88335540289536",
    "universityId":"8821098664448"
},
    "to":"fYu_ybp3Wu8:APA91bHxOact-9gcqf7rAqNSPSkvU7N5h4t4m0XgCAHBdu"
}

I do this in onCreate method..

Intent intent = new Intent(LauncherActivity.this, PostFeedActivity.class);
    if (getIntent().getAction().equalsIgnoreCase("myAction")) {
        Bundle extras = getIntent().getExtras();
        String universityId = extras.getString(getString(R.string.notification_university));

        String notificationId = extras.getString(getString(R.string.notification_id));
        String notificationCreatorName = extras.getString(getString(R.string.notification_creator_name));
        String notificationCreatorImage = extras.getString(getString(R.string.notification_creator_image));
        int notificationCount = extras.getInt(getString(R.string.notification_count), 0);
        if (!TextUtils.isEmpty(notificationId)) {
            intent.setAction(getString(R.string.action_notification_from_push));

            intent.putExtra(getString(R.string.notification_count),
                    notificationCount);
            intent.putExtra(getString(R.string.notification_id),
                    notificationId);
            intent.putExtra(getString(R.string.notification_creator_name),
                    notificationCreatorName);
            intent.putExtra(getString(R.string.notification_creator_image),
                    notificationCreatorImage);

            //fetch notification data by calling API and start activity
            requestNotification(notificationId, intent);
            //

        } else {
            startActivity(intent);
            finish();
        }


问:
IBM Watson Conversation: How to programmatically turn messages to counterexamples?
The IBM Watson Conversation service offers as part of its UI "Improve". It has the ability to see recent messages, their classification and then to reclassify or mark as irrelevant.

In the REST API for that conversation service there functions to list and create counterexamples and examples. I looked at the Python SDK and that API is supported, too. How do I programmatically turn recent user conversation (messages, user input) into examples or counterexamples? What API function do I need to use?

答:
You need to use the logging API referenced in the Workspace API.

The logging uses elastic search if you need to filter it down.

It is not going to give you the breakdown similar to the improve tab though. So you will need to programatically track what you want to capture and add.

I would be very wary though of having any kind of automation updating your training. Proper training should only be done by a subject matter expert. Automating it is likely to pollute the training.

Another thing to avoid is don't add correct answers to the training if Conversation got it correct. It's redundant and also means further testing to see that it doesn't impact your existing model.


问:
swift skscene touch and hold other action than just touching
So I recently made a swift game with sprite kit and now I am stuck.
I have a character selection screen and I want to show a description for the character if you hold on the character, but if you just touch it you choose it and play with it. I already have the code to play/show the description. I just need to know when to call the corresponding functions and how to differentiate if the node is held or just touched.

Thanks in advance

答:
So, here is how you can do it using SKActions... Also, there is another way using SKAction but I can't really show you all the possibilities :) Anyways, here is the code which does what you want:

```<code>import SpriteKit
import GameplayKit

class GameScene: SKScene {

    let kLongPressDelayActionKey = "longPressDelay"
    let kLongPressStartedActionKey = "longPressStarted"
    let kStoppingLongPressActionKey = "stoppingLongPressActionKey"

    let desc = SKSpriteNode(color: .white, size: CGSize(width: 150, height: 150))
    let button = SKSpriteNode(color: .purple, size: CGSize(width: 150, height: 150))
    let other = SKSpriteNode(color: .yellow, size: CGSize(width: 150, height: 150))
    override func didMove(to view: SKView) {

        addChild(desc)
        addChild(button)
        addChild(other)

        button.position.y = -160
        button.name = "button"
        desc.alpha = 0.0
        desc.name = "description"
        other.name = "other"
        other.alpha = 0.0
        other.position.y = -320

    }

    private func singleTap(onNode:SKNode){

        other.alpha = other.alpha == 0.0 ? 1.0 : 0.0
    }

    private func startLongPress(withDuration duration:TimeInterval){

        //How long does it take before long press is fired
        //If user moves his finger of the screen within this delay, the single tap will be fired
        let delay = SKAction.wait(forDuration: duration)

        let completion = SKAction.run({
        [unowned self] in

             self.desc.removeAction(forKey: self.kLongPressDelayActionKey)
             self.desc.run(SKAction.fadeIn(withDuration: 0.5), withKey: self.kLongPressStartedActionKey)
        })

        self.desc.run(SKAction.sequence([delay,completion]), withKey: kLongPressDelayActionKey)

    }

    private func stopLongPress(){

        //Fire single tap and stop long press
        if desc.action(forKey: kLongPressDelayActionKey) != nil{

            desc.removeAction(forKey: kLongPressDelayActionKey)
            self.singleTap(onNode: self.other)
        //or just stop the long press
        }else{

            desc.removeAction(forKey: kLongPressStartedActionKey)

            //Start fade out action if it isn't already started
            if desc.action(forKey: kStoppingLongPressActionKey) == nil {
                desc.run(SKAction.fadeOut(withDuration: 0.2), withKey: kStoppingLongPressActionKey)
            }
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        //To stop the long press if we slide a finger of the button
        if let touch = touches.first {

            let location = touch.location(in: self)

            if !button.contains(location) {

              stopLongPress()

            }

        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        if let touch = touches.first {

            let location = touch.location(in: self)

            if button.contains(location) {
                print("Button tapped")

                startLongPress( withDuration: 1)
            }
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

       stopLongPress()
    }
}
</code>```

You can run the code and you will see that if you tap on the purple button, a yellow box will pop up. If you tap it again, it will hide. Also, if you hold your finger on purple box for 1 second, a white box will fade in. When you release the finger, it will fade out. As an addition, I have implemented touchesMoved, so if you slide your finger of the purple button while blue box is out, it will fade out as well.

So in this example, I have fused long press with single tap. Single tap is considered to be everything that is not long press. Eg, if user holds his finger 0.01 sec, or 0.5 sec, or 0.99 sec, it will be considered as single tap and yellow box will pop out. If you hold your finger for >= 1 second, the long press action will be triggered.

Another way would be to use gesture recognizers...And I will probably make an example for that later :)

Body:
So, here is how you can do it using SKActions... Also, there is another way using SKAction but I can't really show you all the possibilities :) Anyways, here is the code which does what you want:

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    let kLongPressDelayActionKey = "longPressDelay"
    let kLongPressStartedActionKey = "longPressStarted"
    let kStoppingLongPressActionKey = "stoppingLongPressActionKey"

    let desc = SKSpriteNode(color: .white, size: CGSize(width: 150, height: 150))
    let button = SKSpriteNode(color: .purple, size: CGSize(width: 150, height: 150))
    let other = SKSpriteNode(color: .yellow, size: CGSize(width: 150, height: 150))
    override func didMove(to view: SKView) {

        addChild(desc)
        addChild(button)
        addChild(other)

        button.position.y = -160
        button.name = "button"
        desc.alpha = 0.0
        desc.name = "description"
        other.name = "other"
        other.alpha = 0.0
        other.position.y = -320

    }

    private func singleTap(onNode:SKNode){

        other.alpha = other.alpha == 0.0 ? 1.0 : 0.0
    }

    private func startLongPress(withDuration duration:TimeInterval){

        //How long does it take before long press is fired
        //If user moves his finger of the screen within this delay, the single tap will be fired
        let delay = SKAction.wait(forDuration: duration)

        let completion = SKAction.run({
        [unowned self] in

             self.desc.removeAction(forKey: self.kLongPressDelayActionKey)
             self.desc.run(SKAction.fadeIn(withDuration: 0.5), withKey: self.kLongPressStartedActionKey)
        })

        self.desc.run(SKAction.sequence([delay,completion]), withKey: kLongPressDelayActionKey)

    }

    private func stopLongPress(){

        //Fire single tap and stop long press
        if desc.action(forKey: kLongPressDelayActionKey) != nil{

            desc.removeAction(forKey: kLongPressDelayActionKey)
            self.singleTap(onNode: self.other)
        //or just stop the long press
        }else{

            desc.removeAction(forKey: kLongPressStartedActionKey)

            //Start fade out action if it isn't already started
            if desc.action(forKey: kStoppingLongPressActionKey) == nil {
                desc.run(SKAction.fadeOut(withDuration: 0.2), withKey: kStoppingLongPressActionKey)
            }
        }
    }

    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {

        //To stop the long press if we slide a finger of the button
        if let touch = touches.first {

            let location = touch.location(in: self)

            if !button.contains(location) {

              stopLongPress()

            }

        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

        if let touch = touches.first {

            let location = touch.location(in: self)

            if button.contains(location) {
                print("Button tapped")

                startLongPress( withDuration: 1)
            }
        }
    }

    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

       stopLongPress()
    }
}

You can run the code and you will see that if you tap on the purple button, a yellow box will pop up. If you tap it again, it will hide. Also, if you hold your finger on purple box for 1 second, a white box will fade in. When you release the finger, it will fade out. As an addition, I have implemented touchesMoved, so if you slide your finger of the purple button while blue box is out, it will fade out as well.

So in this example, I have fused long press with single tap. Single tap is considered to be everything that is not long press. Eg, if user holds his finger 0.01 sec, or 0.5 sec, or 0.99 sec, it will be considered as single tap and yellow box will pop out. If you hold your finger for >= 1 second, the long press action will be triggered.

Another way would be to use gesture recognizers...And I will probably make an example for that later :)


问:
User defined Exception doubt
I have this exception class

```<code>class Value(Exception):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return repr(self.val)

raise Value('4')
</code>```

and the exception comes as

```<code>Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'
</code>```

------------------------------------update------

I found out a typo mistake thanks to mark.... but my problem now is that say I want to display 4 and a string hello along with the error how to do so......

Thanks a lot

答:
```<code>>>> class Value(Exception):
 def __init__(self, val):
  self.val = val
 def __repr__(self):
  return ' ,'.join(str(x) for x in self.val) + ' hello world!'
 def __str__(self):
  return repr(self)
</code>```

of course you can do whatever you want in init.. as using the syntax *val (instead of val in init) to use the class Value as you showed in your example and then simply call

Value(4, 2) or Value(4) etc...

edit:

just return self.msg in repr...

```<code>def __repr__(self):
    return self.val + self.msg #or whatever you want
</code>```

my previous example showed how to accept and print multiple values...if you want just a value and a msg, and display them, you can do this:

```<code>class Value(Exception):
    def __init__(self, val, msg):
        self.val = val
        self.msg = msg
    def __repr__(self):
        return 'Error code: %s  Error message: %s' % (self.val, self.msg)
    def __str__(self):
        return repr(self)
</code>```

Title: User defined Exception doubt

Body:
I have this exception class

class Value(Exception):
    def __init__(self,val):
        self.val = val

    def __str__(self):
        return repr(self.val)

raise Value('4')

and the exception comes as

Traceback (most recent call last):
File "<module1>", line 20, in <module>
Value: '4'

------------------------------------update------

I found out a typo mistake thanks to mark.... but my problem now is that say I want to display 4 and a string hello along with the error how to do so......

Thanks a lot

Body:
>>> class Value(Exception):
 def __init__(self, val):
  self.val = val
 def __repr__(self):
  return ' ,'.join(str(x) for x in self.val) + ' hello world!'
 def __str__(self):
  return repr(self)

of course you can do whatever you want in init.. as using the syntax *val (instead of val in init) to use the class Value as you showed in your example and then simply call

Value(4, 2) or Value(4) etc...

edit:

just return self.msg in repr...

def __repr__(self):
    return self.val + self.msg #or whatever you want

my previous example showed how to accept and print multiple values...if you want just a value and a msg, and display them, you can do this:

class Value(Exception):
    def __init__(self, val, msg):
        self.val = val
        self.msg = msg
    def __repr__(self):
        return 'Error code: %s  Error message: %s' % (self.val, self.msg)
    def __str__(self):
        return repr(self)


问:
[Symfony2]: Cascading element deletion of an entity How to have a life cycle attribute
I'm using symfony 2.7 as CMF .

I have 2 entity user and Mission . mission have a life cycle attribute (createdBy ,updatedBy).

when i try to delete the user i have this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (XXXX.mission, CONSTRAINT FK_19653DBD16FE72E1 FOREIGN KEY (updated_by) REFERENCES fos_user_user (id))

this is my life cycle elément in the entity mission:

```<code>   /**
 * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
 * @ORM\JoinColumn(name="created_by", referencedColumnName="id" , onDelete="CASCADE")
 */
private $createdBy;

/**
 * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
 * @ORM\JoinColumn(name="updated_by", referencedColumnName="id" , onDelete="CASCADE")
 */
private $updatedBy;
</code>```

thx for help.

答:
Put it on your doctrine relation in the user side, something like :

```<code>* @ORM\OneToMany(targetEntity="your\entity\mission", cascade={"delete"})
</code>```

EDIT :

If you can't access the user entity (don't see why you can't ...) you can do something a bit ugly like get the mission attached to the user, delete it then delete the user

Body:
I'm using symfony 2.7 as CMF .

I have 2 entity user and Mission . mission have a life cycle attribute (createdBy ,updatedBy).

when i try to delete the user i have this error:

SQLSTATE[23000]: Integrity constraint violation: 1451 Cannot delete or update a parent row: a foreign key constraint fails (XXXX.mission, CONSTRAINT FK_19653DBD16FE72E1 FOREIGN KEY (updated_by) REFERENCES fos_user_user (id))

this is my life cycle elément in the entity mission:

   /**
 * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
 * @ORM\JoinColumn(name="created_by", referencedColumnName="id" , onDelete="CASCADE")
 */
private $createdBy;

/**
 * @ORM\ManyToOne(targetEntity="Application\Sonata\UserBundle\Entity\User")
 * @ORM\JoinColumn(name="updated_by", referencedColumnName="id" , onDelete="CASCADE")
 */
private $updatedBy;

thx for help.

Body:
Put it on your doctrine relation in the user side, something like :

* @ORM\OneToMany(targetEntity="your\entity\mission", cascade={"delete"})

EDIT :

If you can't access the user entity (don't see why you can't ...) you can do something a bit ugly like get the mission attached to the user, delete it then delete the user


问:
An error: configured the header search paths
I wanted to use cocoapods in an old project, but it gave me an error: library not found for -lPodsxxx.

And the following tips:

*xxx target overrides the HEADER_SEARCH_PATHS build setting defined in `Pods/Target Support Files/Pods/Pods.release.xcconfig'. This can lead to problems with the CocoaPods installation
This can lead to problems with the CocoaPods installation

```<code>- Use the `$(inherited)` flag, or

- Remove the build settings from the target.*
</code>```

I configured it according to the prompt Build Settings -> Header Search Paths $(inherited), and pod update success.

But I compile a new error: 'libxml/tree.h' file not found 。

So I've been reconfigured Build Settings -> Header Search Paths

 ${SDKROOT}/usr/include/libxml2 。
But it also appeared in front of the problems.

I need help.

答:
I have solved this problem.

Build Settings - > Header Search Paths

configure like this:

$(inherited)

${SDKROOT}/usr/include/libxml2

Body:
I wanted to use cocoapods in an old project, but it gave me an error: library not found for -lPodsxxx.

And the following tips:

*xxx target overrides the HEADER_SEARCH_PATHS build setting defined in `Pods/Target Support Files/Pods/Pods.release.xcconfig'. This can lead to problems with the CocoaPods installation
This can lead to problems with the CocoaPods installation

- Use the `$(inherited)` flag, or

- Remove the build settings from the target.*

I configured it according to the prompt Build Settings -> Header Search Paths $(inherited), and pod update success.

But I compile a new error: 'libxml/tree.h' file not found 。

So I've been reconfigured Build Settings -> Header Search Paths

 ${SDKROOT}/usr/include/libxml2 。
But it also appeared in front of the problems.

I need help.


问:
Route Action Method in Laravel 5.4
I am trying to do a before-action check on a route. Therefore I set up a middleware as follows:

```<code><?php

namespace App\Http\Middleware;

use Closure;
use Route;

class PermissionMiddleware
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
   list(, $action) = explode('@', Route::getCurrentRoute()->getActionName());

    return $next($request);
}
}
</code>```

In my controller, I do as follows:

```<code><?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Blog;
use Image;
use File;
use Route;

class BlogController extends Controller
{

public function __construct()
{
    $this->middleware(['auth','permission']);
}

public function create()
{
   .......
   .......
}
</code>```

And my route is as follows:

```<code>Route::get('create/news',"BlogController@create");
</code>```

However, when I navigate to the route, it displays an error as follows:

Giving an exception as follows:

FatalErrorException Call to a member function getActionName() on null
  in PermissionMiddleware.php (line 19)

I have tried to no avail to resolve this.

答:
Read again the error message and you'll find the problem.

The error is:

```<code>FatalErrorException Call to a member function getActionName() on null in PermissionMiddleware.php (line 19)
</code>```

On line 19, I guess you have this:

```<code>list(, $action) = explode('@', Route::getCurrentRoute()->getActionName());
</code>```

That means that error comes from here: "Route::getCurrentRoute()->getActionName()".

Route::getCurrentRoute() returns null. So you call the method "getActionName()" from null.

Please check the method "getCurrentRoute()" in order to fix the problem.
Good luck.

Title: Route Action Method in Laravel 5.4

Body:
I am trying to do a before-action check on a route. Therefore I set up a middleware as follows:

<?php

namespace App\Http\Middleware;

use Closure;
use Route;

class PermissionMiddleware
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
   list(, $action) = explode('@', Route::getCurrentRoute()->getActionName());

    return $next($request);
}
}

In my controller, I do as follows:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Blog;
use Image;
use File;
use Route;

class BlogController extends Controller
{

public function __construct()
{
    $this->middleware(['auth','permission']);
}

public function create()
{
   .......
   .......
}

And my route is as follows:

Route::get('create/news',"BlogController@create");

However, when I navigate to the route, it displays an error as follows:

Giving an exception as follows:

FatalErrorException Call to a member function getActionName() on null
  in PermissionMiddleware.php (line 19)

I have tried to no avail to resolve this.

Body:
Read again the error message and you'll find the problem.

The error is:

FatalErrorException Call to a member function getActionName() on null in PermissionMiddleware.php (line 19)

On line 19, I guess you have this:

list(, $action) = explode('@', Route::getCurrentRoute()->getActionName());

That means that error comes from here: "Route::getCurrentRoute()->getActionName()".

Route::getCurrentRoute() returns null. So you call the method "getActionName()" from null.

Please check the method "getCurrentRoute()" in order to fix the problem.
Good luck.


问:
How to adjust my code to this situation for SAX XML parsing in Android
On advice on someone here on Stackoverflow I changed my method of parsing to the SAXParser.

Thanks to different tutorials I'm able to get it to work, and I have to say that it does work faster (which is very important for my app).

The problem, however, is that my XML file goes deeper than the tutorial's example XML's I've seen.

This a sample of my XML file:

```<code><Message>

  <Service>servicename</Service>

  <Insurances>

    <BreakdownInsurance>

      <Name>Insurance name</Name>

      <InsuranceNR/>

      <LicenseNr/>

    </BreakdownInsurance>

    <CarDamageInsurance>

      <Name>Insurance name 2</Name>

      <InsuranceNR></InsuranceNR>

    </CarDamageInsurance>
  </Insurances>

  <Personal>
    <Name>my name</Name>
  </Personal>
</Message>
</code>```

I can get the personal details like name, but my code doesn't seem to work with the insurances. I think this is because it's one node more.

This is the code I'm using in my Handler class:

```<code>@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    currentElement = true;
    if (localName.equals("Message")) {
        geg = new GegevensXML();
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement = false;

    /********** Autopech **********/
    if (localName.equals("Name")) {
        geg.setAutopechMaatschappij(currentValue);
    }
    else if (localName.equals("InsuranceNR")){
        geg.setAutopechPolis(currentValue);
    }
    else if (localName.equals("LicenseNr")){
        geg.setAutopechKenteken(currentValue);
    }

@Override
public void characters(char ch[], int start, int length) {
    if (currentElement) {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }
</code>```

So how must I adjust it?

答:
Just modify the endElement()...

Add Flags to indicate where current Name is to be saved since you are having Name coming under both <BreakdownInsurance>
 and <Personal>.

Body:
On advice on someone here on Stackoverflow I changed my method of parsing to the SAXParser.

Thanks to different tutorials I'm able to get it to work, and I have to say that it does work faster (which is very important for my app).

The problem, however, is that my XML file goes deeper than the tutorial's example XML's I've seen.

This a sample of my XML file:

<Message>

  <Service>servicename</Service>

  <Insurances>

    <BreakdownInsurance>

      <Name>Insurance name</Name>

      <InsuranceNR/>

      <LicenseNr/>

    </BreakdownInsurance>

    <CarDamageInsurance>

      <Name>Insurance name 2</Name>

      <InsuranceNR></InsuranceNR>

    </CarDamageInsurance>
  </Insurances>

  <Personal>
    <Name>my name</Name>
  </Personal>
</Message>

I can get the personal details like name, but my code doesn't seem to work with the insurances. I think this is because it's one node more.

This is the code I'm using in my Handler class:

@Override
public void startElement(String namespaceURI, String localName, String qName, Attributes atts) throws SAXException {
    currentElement = true;
    if (localName.equals("Message")) {
        geg = new GegevensXML();
    }
}

@Override
public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
    currentElement = false;

    /********** Autopech **********/
    if (localName.equals("Name")) {
        geg.setAutopechMaatschappij(currentValue);
    }
    else if (localName.equals("InsuranceNR")){
        geg.setAutopechPolis(currentValue);
    }
    else if (localName.equals("LicenseNr")){
        geg.setAutopechKenteken(currentValue);
    }

@Override
public void characters(char ch[], int start, int length) {
    if (currentElement) {
        currentValue = new String(ch, start, length);
        currentElement = false;
    }

So how must I adjust it?