问:
Log producer object in Scala
I am new to scala and java altogether and trying to run a sample producer code. All it does is, takes some raw products and referrers stored in csv files and uses rnd to generate some random log. Following is my code:

```<code>object LogProducer extends App {
//WebLog config
val wlc = Settings.WebLogGen

val Products = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/products.csv")).getLines().toArray
val Referrers = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/referrers.csv")).getLines().toArray
val Visitors = (0 to wlc.visitors).map("Visitors-" + _)
val Pages = (0 to wlc.pages).map("Pages-" + _)

val rnd = new Random()
val filePath = wlc.filePath

val fw = new FileWriter(filePath, true)

//adding randomness to time increments for demo
val incrementTimeEvery = rnd.nextInt(wlc.records - 1) + 1

var timestamp = System.currentTimeMillis()
var adjustedTimestamp = timestamp

for (iteration <- 1 to wlc.records) {
  adjustedTimestamp = adjustedTimestamp + ((System.currentTimeMillis() - timestamp) * wlc.timeMultiplier)
timestamp = System.currentTimeMillis()
  val action = iteration % (rnd.nextInt(200) + 1) match {
    case 0 => "purchase"
    case 1 => "add_to_cart"
    case _ => "page_view"
  }

  val referrer = Referrers(rnd.nextInt(Referrers.length - 1))
  val prevPage = referrer match {
    case "Internal" => Pages(rnd.nextInt(Pages.length - 1))
    case _ => ""
  }

val visitor = Visitors(rnd.nextInt(Visitors.length - 1))
val page = Pages(rnd.nextInt(Pages.length - 1))
val product = Products(rnd.nextInt(Products.length - 1))

val line = s"$adjustedTimestamp\t$referrer\t$action\t$prevPage\t$visitor\t$page\t$product\n"
fw.write(line)

if (iteration % incrementTimeEvery == 0) {
  //os.flush()
  println(s"Sent $iteration messages!")
  val sleeping = rnd.nextInt(incrementTimeEvery * 60)
  println(s"Sleeping for $sleeping ms")
  }
 }
}
</code>```

It is pretty straightforward where it is basically generating some variables and adding it to the line.

However I am getting a big exception error stack which i am not able to understand:

```<code>"C:\Program Files\Java\jdk1.8.0_92\bin\java...

Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at scala.io.BufferedSource$BufferedLineIterator.hasNext(BufferedSource.scala:70)
at scala.collection.Iterator.foreach(Iterator.scala:929)
at scala.collection.Iterator.foreach$(Iterator.scala:929)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1417)
at scala.collection.generic.Growable.$plus$plus$eq(Growable.scala:59)
at scala.collection.generic.Growable.$plus$plus$eq$(Growable.scala:50)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48)
at scala.collection.TraversableOnce.to(TraversableOnce.scala:310)
at scala.collection.TraversableOnce.to$(TraversableOnce.scala:308)
at scala.collection.AbstractIterator.to(Iterator.scala:1417)
at scala.collection.TraversableOnce.toBuffer(TraversableOnce.scala:302)
at scala.collection.TraversableOnce.toBuffer$(TraversableOnce.scala:302)
at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1417)
at scala.collection.TraversableOnce.toArray(TraversableOnce.scala:289)
at scala.collection.TraversableOnce.toArray$(TraversableOnce.scala:283)
at scala.collection.AbstractIterator.toArray(Iterator.scala:1417)
at clickstream.LogProducer$.delayedEndpoint$clickstream$LogProducer$1(logProducer.scala:16)
at clickstream.LogProducer$delayedInit$body.apply(logProducer.scala:12)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:389)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at clickstream.LogProducer$.main(logProducer.scala:12)
at clickstream.LogProducer.main(logProducer.scala)

Process finished with exit code 1
</code>```

Can someone please help me identify what the exception mean? Thanks all

答:
So it wasnt hard.. it was my amateurish knowledge. It was a simple IO exception where Intellij wasnt able to get the values from my csv file. When i imported it into resources root directory, it gave me a warning message of wrong encoding.

The error was at this point:

val Products = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/products.csv")).getLines().toArray

thanks for efforts though

Title: Log producer object in Scala

Body:
I am new to scala and java altogether and trying to run a sample producer code. All it does is, takes some raw products and referrers stored in csv files and uses rnd to generate some random log. Following is my code:

object LogProducer extends App {
//WebLog config
val wlc = Settings.WebLogGen

val Products = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/products.csv")).getLines().toArray
val Referrers = scala.io.Source.fromInputStream(getClass.getResourceAsStream("/referrers.csv")).getLines().toArray
val Visitors = (0 to wlc.visitors).map("Visitors-" + _)
val Pages = (0 to wlc.pages).map("Pages-" + _)

val rnd = new Random()
val filePath = wlc.filePath

val fw = new FileWriter(filePath, true)

//adding randomness to time increments for demo
val incrementTimeEvery = rnd.nextInt(wlc.records - 1) + 1

var timestamp = System.currentTimeMillis()
var adjustedTimestamp = timestamp

for (iteration <- 1 to wlc.records) {
  adjustedTimestamp = adjustedTimestamp + ((System.currentTimeMillis() - timestamp) * wlc.timeMultiplier)
timestamp = System.currentTimeMillis()
  val action = iteration % (rnd.nextInt(200) + 1) match {
    case 0 => "purchase"
    case 1 => "add_to_cart"
    case _ => "page_view"
  }

  val referrer = Referrers(rnd.nextInt(Referrers.length - 1))
  val prevPage = referrer match {
    case "Internal" => Pages(rnd.nextInt(Pages.length - 1))
    case _ => ""
  }

val visitor = Visitors(rnd.nextInt(Visitors.length - 1))
val page = Pages(rnd.nextInt(Pages.length - 1))
val product = Products(rnd.nextInt(Products.length - 1))

val line = s"$adjustedTimestamp\t$referrer\t$action\t$prevPage\t$visitor\t$page\t$product\n"
fw.write(line)

if (iteration % incrementTimeEvery == 0) {
  //os.flush()
  println(s"Sent $iteration messages!")
  val sleeping = rnd.nextInt(incrementTimeEvery * 60)
  println(s"Sleeping for $sleeping ms")
  }
 }
}

It is pretty straightforward where it is basically generating some variables and adding it to the line.

However I am getting a big exception error stack which i am not able to understand:

"C:\Program Files\Java\jdk1.8.0_92\bin\java...

Exception in thread "main" java.nio.charset.MalformedInputException: Input length = 1
at java.nio.charset.CoderResult.throwException(CoderResult.java:281)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:339)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputStreamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at scala.io.BufferedSource$BufferedLineIterator.hasNext(BufferedSource.scala:70)
at scala.collection.Iterator.foreach(Iterator.scala:929)
at scala.collection.Iterator.foreach$(Iterator.scala:929)
at scala.collection.AbstractIterator.foreach(Iterator.scala:1417)
at scala.collection.generic.Growable.$plus$plus$eq(Growable.scala:59)
at scala.collection.generic.Growable.$plus$plus$eq$(Growable.scala:50)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:104)
at scala.collection.mutable.ArrayBuffer.$plus$plus$eq(ArrayBuffer.scala:48)
at scala.collection.TraversableOnce.to(TraversableOnce.scala:310)
at scala.collection.TraversableOnce.to$(TraversableOnce.scala:308)
at scala.collection.AbstractIterator.to(Iterator.scala:1417)
at scala.collection.TraversableOnce.toBuffer(TraversableOnce.scala:302)
at scala.collection.TraversableOnce.toBuffer$(TraversableOnce.scala:302)
at scala.collection.AbstractIterator.toBuffer(Iterator.scala:1417)
at scala.collection.TraversableOnce.toArray(TraversableOnce.scala:289)
at scala.collection.TraversableOnce.toArray$(TraversableOnce.scala:283)
at scala.collection.AbstractIterator.toArray(Iterator.scala:1417)
at clickstream.LogProducer$.delayedEndpoint$clickstream$LogProducer$1(logProducer.scala:16)
at clickstream.LogProducer$delayedInit$body.apply(logProducer.scala:12)
at scala.Function0.apply$mcV$sp(Function0.scala:34)
at scala.Function0.apply$mcV$sp$(Function0.scala:34)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12)
at scala.App.$anonfun$main$1$adapted(App.scala:76)
at scala.collection.immutable.List.foreach(List.scala:389)
at scala.App.main(App.scala:76)
at scala.App.main$(App.scala:74)
at clickstream.LogProducer$.main(logProducer.scala:12)
at clickstream.LogProducer.main(logProducer.scala)

Process finished with exit code 1

Can someone please help me identify what the exception mean? Thanks all


来源: stackexchange

问:
How can I create a PDF file in classic ASP?
Is there any way to generate PDF files from classic ASP? I have a bunch of user-entered data that needs to be turned into a PDF that the user can download. How can I do this? OpenOffice allows exporting documents to PDF, so could this somehow be leveraged?</p>

答:
See a full list of PDF components here: http://www.aspin.com/home/components/document/pdf Many of them are free.

It is also possible to use XSLT to output PDF but I am not sure if this is supported by the Microsoft XML Parser. I remember there were something stopping me when I tried to do this 3-4 years ago. Might be worth checking out know depending out the type of data you have as source.

However if these are static files or a one time job consider using a PDF converter on your computer and just upload the files to the server. There are heaps of tools for this, including Adobe Acrobat.

OwnerDisplayName: cdeszaq

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: Espen


问:
Pyserial - RS232 9600,8,N,1 send and receive data
I need to communicate and pass values to a serial connected device using RS232 Protocol. I need to pass commands through the 8 bytes of data and then be able to receive the response afterwards.. Im not sure how to write this in PySerial so if anyone can help out it would be great (9600 Baud, 8 data bits, No parity, and 1 stop bit.)

```<code>import serial
ser = serial.Serial('/dev/ttyUSB0')  # open serial port
print(ser.name)         # check which port was really used
ser.write(b'hello')     # write a string
ser.close()             # close port
</code>```

The Timer Manager Command structure consists of one start byte, one command byte, five bytes of data, and a one byte checksum.  Each message packet is formatted as follows:

```<code>BYTE 0  BYTE 1    BYTE 2    BYTE 3     BYTE 4   BYTE 5    BYTE 6    BYTE 7
200     COMMAND   DATA1     DATA2      DATA3    DATA4     DATA5     CK SUM
</code>```

Im looking to receive the following back from the machine:
If command was successfully received, the Timer Manager will respond with:

```<code>  BYTE 0    BYTE 1  BYTE 2
   6            0       6
</code>```

The actual data that I want to send is this
Data i need to pass to the timer is structured this way:

```<code>   BYTE 0   BYTE 1  BYTE 2  BYTE 3  BYTE 4  BYTE 5  BYTE 6  BYTE 7
      200       31      4      0        0        0       0  235
</code>```

Is this passed via bytearray ?

```<code>      ser.write( bytearray(200,31,4,0,0,0,0,235) );
</code>```

答:
I generally have something like this to do binary IO over a serial port:

```<code>from timeit import default_timer as clk
from serial import Serial, SerialException

class TimeManager(object):
    def __init__(self, port, baudrate=9600):
        self.ser = Serial(port, baudrate=baudrate)
        self.ser.open()
        self.ser.flushInput()
        self.ser.flushOutput()

    def send(self, tx):
        tx = bytearray(tx)
        try:
            self.ser.write(tx)
            self.ser.flush()
        except SerialException as e:
            if e.args == (5, "WriteFile", "Access is denied."):
                # This occurs on win32 when a USB serial port is
                # unplugged and replugged.  It should be fixed by
                # closing and reopening the port, which should happen
                # in the error handling of our caller.
                raise IOError(errno.ENOENT, "Serial port disappeared.",
                              self.ser.portstr)
            else:
                raise

    def receive(self):
        rx = bytearray()
        delay = 10e-3 # s
        timeout = 1 # s
        end_time = clk() + timeout
        while True:
            time_remaining = end_time - clk()
            if time_remaining < 0:
                break
            rx += self.ser.read(self.ser.inWaiting())
            if 0 in rx:
                break
            time.sleep(delay)

        if time_remaining <= 0:
            raise IOError(errno.ETIMEDOUT, "Communication timed out.")

        return rx

tm = TimeManager("/dev/ttyS0")
</code>```

My device sends null terminated messages (the if 0 in rx: line).  You'd have to figure out a similar condition for your messages.

ContentLicense: CC BY-SA 3.0

Body:
I need to communicate and pass values to a serial connected device using RS232 Protocol. I need to pass commands through the 8 bytes of data and then be able to receive the response afterwards.. Im not sure how to write this in PySerial so if anyone can help out it would be great (9600 Baud, 8 data bits, No parity, and 1 stop bit.)

import serial
ser = serial.Serial('/dev/ttyUSB0')  # open serial port
print(ser.name)         # check which port was really used
ser.write(b'hello')     # write a string
ser.close()             # close port

The Timer Manager Command structure consists of one start byte, one command byte, five bytes of data, and a one byte checksum.  Each message packet is formatted as follows:

BYTE 0  BYTE 1    BYTE 2    BYTE 3     BYTE 4   BYTE 5    BYTE 6    BYTE 7
200     COMMAND   DATA1     DATA2      DATA3    DATA4     DATA5     CK SUM

Im looking to receive the following back from the machine:
If command was successfully received, the Timer Manager will respond with:

  BYTE 0    BYTE 1  BYTE 2
   6            0       6

The actual data that I want to send is this
Data i need to pass to the timer is structured this way:

   BYTE 0   BYTE 1  BYTE 2  BYTE 3  BYTE 4  BYTE 5  BYTE 6  BYTE 7
      200       31      4      0        0        0       0  235

Is this passed via bytearray ?

      ser.write( bytearray(200,31,4,0,0,0,0,235) );

Body:
I generally have something like this to do binary IO over a serial port:

from timeit import default_timer as clk
from serial import Serial, SerialException

class TimeManager(object):
    def __init__(self, port, baudrate=9600):
        self.ser = Serial(port, baudrate=baudrate)
        self.ser.open()
        self.ser.flushInput()
        self.ser.flushOutput()

    def send(self, tx):
        tx = bytearray(tx)
        try:
            self.ser.write(tx)
            self.ser.flush()
        except SerialException as e:
            if e.args == (5, "WriteFile", "Access is denied."):
                # This occurs on win32 when a USB serial port is
                # unplugged and replugged.  It should be fixed by
                # closing and reopening the port, which should happen
                # in the error handling of our caller.
                raise IOError(errno.ENOENT, "Serial port disappeared.",
                              self.ser.portstr)
            else:
                raise

    def receive(self):
        rx = bytearray()
        delay = 10e-3 # s
        timeout = 1 # s
        end_time = clk() + timeout
        while True:
            time_remaining = end_time - clk()
            if time_remaining < 0:
                break
            rx += self.ser.read(self.ser.inWaiting())
            if 0 in rx:
                break
            time.sleep(delay)

        if time_remaining <= 0:
            raise IOError(errno.ETIMEDOUT, "Communication timed out.")

        return rx

tm = TimeManager("/dev/ttyS0")

My device sends null terminated messages (the if 0 in rx: line).  You'd have to figure out a similar condition for your messages.


问:
How can I insert HTML widget objects (Leaflet map or HTML table) in an HTML markdown document?
I have tried a number of things including print(leafletMap) and just calling the object itself. Is there a specific function that I am to wrap my object in in order to get it to render in the document? </p>

答:
if you use Rstudio create a RMarkdown File or RHMTL file then include into a chunk code like this (you will need package knitr to convert into hmtl)

```<code>```{r setup, include=TRUE}

library(leaflet)
m<-leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")

m
```
</code>```

otherwise you can save like an html document with the following code
like suggested in this post https://stackoverflow.com/a/31642030/7600734

```<code>library(htmlwidgets)
saveWidget(m, file="m.html")
</code>```

Body:
if you use Rstudio create a RMarkdown File or RHMTL file then include into a chunk code like this (you will need package knitr to convert into hmtl)

```{r setup, include=TRUE}

library(leaflet)
m<-leaflet() %>%
  addTiles() %>%  # Add default OpenStreetMap map tiles
  addMarkers(lng=174.768, lat=-36.852, popup="The birthplace of R")

m
```

otherwise you can save like an html document with the following code
like suggested in this post https://stackoverflow.com/a/31642030/7600734

library(htmlwidgets)
saveWidget(m, file="m.html")


问:
Rails 4 Authenticity Token
I was working on a new Rails 4 app (on Ruby 2.0.0-p0) when I ran into some authenticity token problems.

While writing a controller that responds to json (using the respond_to class method), I got to the create action I started getting ActionController::InvalidAuthenticityToken exceptions when I tried to create a record using curl.

I made sure I set -H "Content-Type: application/json" and I set the data with -d "<my data here>" but still no luck.

I tried writing the same controller using Rails 3.2 (on Ruby 1.9.3) and I got no authenticity token problems whatsoever. I searched around and I saw that there were some changes with authenticity tokens in Rails 4. From what I understand, they are no longer automatically inserted in forms anymore? I suppose this is somehow affecting non-HTML content types.

Is there any way to get around this without having to request a HTML form, snatching the authenticity token, then making another request with that token? Or am I completely missing something that's completely obvious?

Edit: I just tried creating a new record in a new Rails 4 app using a scaffold without changing anything and I'm running into the same problem so I guess it's not something I did.

答:
If you're using jQuery with rails, be wary of allowing entry to methods without verifying the authenticity token.

jquery-ujs can manage the tokens for you

You should have it already as part of the jquery-rails gem, but you might need to include it in application.js with

```<code>//= require jquery_ujs
</code>```

That's all you need - your ajax call should now work

For more information, see:
https://github.com/rails/jquery-ujs

Title: Rails 4 Authenticity Token

Body:
If you're using jQuery with rails, be wary of allowing entry to methods without verifying the authenticity token.

jquery-ujs can manage the tokens for you

You should have it already as part of the jquery-rails gem, but you might need to include it in application.js with

//= require jquery_ujs

That's all you need - your ajax call should now work

For more information, see:
https://github.com/rails/jquery-ujs


问:
for each loop in java not working with a array that changes as loop progresses
In this I have provided an array of arrays which changes as loop progresses , and the result was not as expected.
Please tell me why that happened.

```<code>public class forEach2 {

public static void main(String[] args) {

    int a [][] = {{ 1,2,3},{4 ,5,6},{7,8,9}};
    int proArr = 0;
    for (int pro : a[proArr] ){
        System.out.println(pro);
        proArr ++;
    }

}
</code>```

result -

```<code>1
2
3
</code>```

here , as the loop starts the value of proArr (which is handling the Array of Arrays , array 'a' to be more specific) changes but that puts no effect o the result.

the result is the data of a[0];

why is this happening in the for loop of Java ?

答:
```<code>int a [][] = {{ 1,2,3},{4 ,5,6},{7,8,9}};
for (int[] pro : a){
    for(int p : pro){
        System.out.println(p);
    }
}
</code>```

UPDATE:

To only first array:

```<code>for (int pro : a[0]){
    System.out.println(pro);
}
</code>```

Output:

```<code>1
2
3
</code>```

Body:
In this I have provided an array of arrays which changes as loop progresses , and the result was not as expected.
Please tell me why that happened.

public class forEach2 {

public static void main(String[] args) {

    int a [][] = {{ 1,2,3},{4 ,5,6},{7,8,9}};
    int proArr = 0;
    for (int pro : a[proArr] ){
        System.out.println(pro);
        proArr ++;
    }

}

result -

1
2
3

here , as the loop starts the value of proArr (which is handling the Array of Arrays , array 'a' to be more specific) changes but that puts no effect o the result.

the result is the data of a[0];

why is this happening in the for loop of Java ?

Body:
int a [][] = {{ 1,2,3},{4 ,5,6},{7,8,9}};
for (int[] pro : a){
    for(int p : pro){
        System.out.println(p);
    }
}

UPDATE:

To only first array:

for (int pro : a[0]){
    System.out.println(pro);
}

Output:

1
2
3


问:
Unable to get the backup log file when using RotatingFileHandler from python
Brief :

base.py:

```<code>import logging
from logging.handlers import TimedRotatingFileHandler
import os

slogFile = os.path.join(os.getcwd(), 'LOGS', 'App_Debug.log')
if True != os.path.isdir(os.path.join(os.getcwd(), 'LOGS')):
    os.mkdir(os.path.join(os.getcwd(), 'LOGS'))
logging.basicConfig(filename=slogFile, level=logging.DEBUG)
logging.basicConfig(format='%(asctime)s %(message)s')
logger = logging.getLogger("myApp")
fmt = logging.Formatter(fmt='%(asctime)s %(message)s')
size=1024*1024*1 #1mb file size
logger = logging.getLogger("myApp")
fmt = logging.Formatter(fmt='%(asctime)s %(message)s')

hdlr = logging.handlers.RotatingFileHandler(filename = slogFile ,mode='w', maxBytes=size, backupCount=5, encoding=None, delay=0)
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)</em>
</code>```

app_main1.py:

```<code>import base

base.logger.debug('xxx')
</code>```

app_main2.py:

```<code>import base

base.logger.debug('xxx')
</code>```

NOTE : for my application i am using another module that also recording the logs into the same file .

I am getting this error:

```<code>Traceback (most recent call last):

 File "C:\Python27\lib\logging\handlers.py", line 78, in emit

   self.doRollover()

 File "C:\Python27\lib\logging\handlers.py", line 141, in doRollover

  os.rename(self.baseFilename, dfn)

WindowsError: [Error 32] The process cannot access the file because it is being used by another process
</code>```

Logged from file app_main1.py, line 59

Could you explain this to me?

I want do backup the log file when its reaches the max(1mb) size.

答:
I got the same error while developing a flask application. To solve the problem, I had to change the environmental variable from
"FLASK_DEBUG=1" to "FLASK_DEBUG=0". The reason being that turning debugging on leads to threading errors. I got the solution after reading this blog

Body:
Brief :

base.py:

import logging
from logging.handlers import TimedRotatingFileHandler
import os

slogFile = os.path.join(os.getcwd(), 'LOGS', 'App_Debug.log')
if True != os.path.isdir(os.path.join(os.getcwd(), 'LOGS')):
    os.mkdir(os.path.join(os.getcwd(), 'LOGS'))
logging.basicConfig(filename=slogFile, level=logging.DEBUG)
logging.basicConfig(format='%(asctime)s %(message)s')
logger = logging.getLogger("myApp")
fmt = logging.Formatter(fmt='%(asctime)s %(message)s')
size=1024*1024*1 #1mb file size
logger = logging.getLogger("myApp")
fmt = logging.Formatter(fmt='%(asctime)s %(message)s')

hdlr = logging.handlers.RotatingFileHandler(filename = slogFile ,mode='w', maxBytes=size, backupCount=5, encoding=None, delay=0)
hdlr.setFormatter(fmt)
logger.addHandler(hdlr)

app_main1.py:

import base

base.logger.debug('xxx')

app_main2.py:

import base

base.logger.debug('xxx')

NOTE : for my application i am using another module that also recording the logs into the same file .

I am getting this error:

Traceback (most recent call last):

 File "C:\Python27\lib\logging\handlers.py", line 78, in emit

   self.doRollover()

 File "C:\Python27\lib\logging\handlers.py", line 141, in doRollover

  os.rename(self.baseFilename, dfn)

WindowsError: [Error 32] The process cannot access the file because it is being used by another process

Logged from file app_main1.py, line 59

Could you explain this to me?

I want do backup the log file when its reaches the max(1mb) size.


问:
raw resource from an Activity to an other Activity to be played with SoundPool
This is my project:

Activity 1

```<code>    int ThePlayedSound= R.raw.Sound_ID;

    Intent MyIntent= new Intent(this, Main2Activity.class);
           MyIntent.putExtra("key",ThePlayedSound);
    startActivity(MyIntent);
</code>```

Activity 2

I want to play the raw source with a Sound Pool With a clicking button so:

```<code>    Intent MyIntent=getIntent();
    int ThePlayedSound= MyIntent.getIntExtra("key", 0);

    Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);
    Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);

    button=(Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Sound_Pool_thing.play(Click,1,1,1,0,1);

        }
    });
</code>```

Edited :
and when i try to open the app I got Unfortunately , My_App has stopped

I can't figure it out ..Help =)

Editing adding the complete code for the second Activity

```<code>public class Main2Activity extends AppCompatActivity {
    Button button;
    SoundPool Sound_Pool_thing;
    int Click;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2_main);

        Intent MyIntent=getIntent();
        int ThePlayedSound= MyIntent.getIntExtra("key", 0);

        Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);

        Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);

        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sound_Pool_thing.play(Click,1,1,1,0,1);

            }
        });

    }
}
</code>```

答:
@Claudenix, I guess the problem is with your file name used for sound file i.e Sound_ID.

int ThePlayedSound= R.raw.Sound_ID;

try renaming the file in your raw folder in lowercase for eg:- "sound_id"

Hope this helps.

Body:
This is my project:

Activity 1

    int ThePlayedSound= R.raw.Sound_ID;

    Intent MyIntent= new Intent(this, Main2Activity.class);
           MyIntent.putExtra("key",ThePlayedSound);
    startActivity(MyIntent);

Activity 2

I want to play the raw source with a Sound Pool With a clicking button so:

    Intent MyIntent=getIntent();
    int ThePlayedSound= MyIntent.getIntExtra("key", 0);

    Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);
    Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);

    button=(Button)findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Sound_Pool_thing.play(Click,1,1,1,0,1);

        }
    });

Edited :
and when i try to open the app I got Unfortunately , My_App has stopped

I can't figure it out ..Help =)

Editing adding the complete code for the second Activity

public class Main2Activity extends AppCompatActivity {
    Button button;
    SoundPool Sound_Pool_thing;
    int Click;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity2_main);

        Intent MyIntent=getIntent();
        int ThePlayedSound= MyIntent.getIntExtra("key", 0);

        Sound_Pool_thing= new SoundPool(1, AudioManager.STREAM_MUSIC,0);

        Click = Sound_Pool_thing.load(this,ThePlayedSound , 1);

        button=(Button)findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Sound_Pool_thing.play(Click,1,1,1,0,1);

            }
        });

    }
}


问:
Upload entire Bitbucket repo to S3 using Bitbucket Pipeline
I'm using Bitbuckets Pipeline.  I want it to push the entire contents of my repo (very small) to S3.  I don't want to have to zip it up, push to S3 and then unzip things.  I just want it to take the existing file/folder structure in my Bitbucket repo and push that to S3.

What should the yaml file and .py file look like to accomplish this?

Here is the current yaml file:

```<code>image: python:3.5.1

pipelines:
  branches:
    master:
      - step:
          script:
            # - apt-get update # required to install zip
            # - apt-get install -y zip # required if you want to zip repository objects
            - pip install boto3==1.3.0 # required for s3_upload.py
            # the first argument is the name of the existing S3 bucket to upload the artefact to
            # the second argument is the artefact to be uploaded
            # the third argument is the the bucket key
            # html files
            - python s3_upload.py my-bucket-name html/index_template.html html/index_template.html # run the deployment script
            # Example command line parameters. Replace with your values
            #- python s3_upload.py bb-s3-upload SampleApp_Linux.zip SampleApp_Linux # run the deployment script
</code>```

And here is my current python:

```<code>from __future__ import print_function
import os
import sys
import argparse
import boto3
from botocore.exceptions import ClientError

def upload_to_s3(bucket, artefact, bucket_key):
    """
    Uploads an artefact to Amazon S3
    """
    try:
        client = boto3.client('s3')
    except ClientError as err:
        print("Failed to create boto3 client.\n" + str(err))
        return False
    try:
        client.put_object(
            Body=open(artefact, 'rb'),
            Bucket=bucket,
            Key=bucket_key
        )
    except ClientError as err:
        print("Failed to upload artefact to S3.\n" + str(err))
        return False
    except IOError as err:
        print("Failed to access artefact in this directory.\n" + str(err))
        return False
    return True

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("bucket", help="Name of the existing S3 bucket")
    parser.add_argument("artefact", help="Name of the artefact to be uploaded to S3")
    parser.add_argument("bucket_key", help="Name of the S3 Bucket key")
    args = parser.parse_args()

    if not upload_to_s3(args.bucket, args.artefact, args.bucket_key):
        sys.exit(1)

if __name__ == "__main__":
    main()
</code>```

This requires me to list every single file in the repo in the yaml file as another command.  I just want it to grab everything and upload it to S3.

答:
For deploying a static website to Amazon S3 I have this  bitbucket-pipelines.yml configuration file:

```<code>image: attensee/s3_website

pipelines:
  default:
    - step:
        script:
          - s3_website push
</code>```

I’m using the attensee/s3_website docker image because that one has the awesome s3_website tool installed.
The configuration file of s3_website (s3_website.yml) [create this file in the root directory of the repository in Bitbucket] looks something like this:

```<code>s3_id: <%= ENV['S3_ID'] %>
s3_secret: <%= ENV['S3_SECRET'] %>
s3_bucket: bitbucket-pipelines
site : .
</code>```

We have to define the environment variables S3_ID and S3_SECRET in environment variable ,from bit-bucket settings

Thankx to https://www.savjee.be/2016/06/Deploying-website-to-ftp-or-amazon-s3-with-BitBucket-Pipelines/
for the solution

Body:
I'm using Bitbuckets Pipeline.  I want it to push the entire contents of my repo (very small) to S3.  I don't want to have to zip it up, push to S3 and then unzip things.  I just want it to take the existing file/folder structure in my Bitbucket repo and push that to S3.

What should the yaml file and .py file look like to accomplish this?

Here is the current yaml file:

image: python:3.5.1

pipelines:
  branches:
    master:
      - step:
          script:
            # - apt-get update # required to install zip
            # - apt-get install -y zip # required if you want to zip repository objects
            - pip install boto3==1.3.0 # required for s3_upload.py
            # the first argument is the name of the existing S3 bucket to upload the artefact to
            # the second argument is the artefact to be uploaded
            # the third argument is the the bucket key
            # html files
            - python s3_upload.py my-bucket-name html/index_template.html html/index_template.html # run the deployment script
            # Example command line parameters. Replace with your values
            #- python s3_upload.py bb-s3-upload SampleApp_Linux.zip SampleApp_Linux # run the deployment script

And here is my current python:

from __future__ import print_function
import os
import sys
import argparse
import boto3
from botocore.exceptions import ClientError

def upload_to_s3(bucket, artefact, bucket_key):
    """
    Uploads an artefact to Amazon S3
    """
    try:
        client = boto3.client('s3')
    except ClientError as err:
        print("Failed to create boto3 client.\n" + str(err))
        return False
    try:
        client.put_object(
            Body=open(artefact, 'rb'),
            Bucket=bucket,
            Key=bucket_key
        )
    except ClientError as err:
        print("Failed to upload artefact to S3.\n" + str(err))
        return False
    except IOError as err:
        print("Failed to access artefact in this directory.\n" + str(err))
        return False
    return True

def main():

    parser = argparse.ArgumentParser()
    parser.add_argument("bucket", help="Name of the existing S3 bucket")
    parser.add_argument("artefact", help="Name of the artefact to be uploaded to S3")
    parser.add_argument("bucket_key", help="Name of the S3 Bucket key")
    args = parser.parse_args()

    if not upload_to_s3(args.bucket, args.artefact, args.bucket_key):
        sys.exit(1)

if __name__ == "__main__":
    main()

This requires me to list every single file in the repo in the yaml file as another command.  I just want it to grab everything and upload it to S3.

Body:
For deploying a static website to Amazon S3 I have this  bitbucket-pipelines.yml configuration file:

image: attensee/s3_website

pipelines:
  default:
    - step:
        script:
          - s3_website push

I’m using the attensee/s3_website docker image because that one has the awesome s3_website tool installed.
The configuration file of s3_website (s3_website.yml) [create this file in the root directory of the repository in Bitbucket] looks something like this:

s3_id: <%= ENV['S3_ID'] %>
s3_secret: <%= ENV['S3_SECRET'] %>
s3_bucket: bitbucket-pipelines
site : .

We have to define the environment variables S3_ID and S3_SECRET in environment variable ,from bit-bucket settings

Thankx to https://www.savjee.be/2016/06/Deploying-website-to-ftp-or-amazon-s3-with-BitBucket-Pipelines/
for the solution


问:
In kibana-TimeLion can we change y-axis?
I am using Kibana-4.6.4

My json is

```<code>{"ExchangeName":"BITFINEX",
 "CurrencyPair":"ETHBTC",
 "MachineTime":"2017-06-01T14:24:17.099141+05:30",
 "OrderSide":"bids",
 "OrderId":"2685192234",
 "Price":0.09369,
 "Quantity":7.40463042
}
</code>```

In kibana Timelion I want to change yaxis as a price, any query is there? Is it possible?

答: You can write .es(metric='avg:Price')

Body:
I am using Kibana-4.6.4

My json is

{"ExchangeName":"BITFINEX",
 "CurrencyPair":"ETHBTC",
 "MachineTime":"2017-06-01T14:24:17.099141+05:30",
 "OrderSide":"bids",
 "OrderId":"2685192234",
 "Price":0.09369,
 "Quantity":7.40463042
}

In kibana Timelion I want to change yaxis as a price, any query is there? Is it possible?

Body: You can write .es(metric='avg:Price')


问:
Multi Rectangles Positions fix for Customized Stickers Printing in SSRS
I have an implementation where we need 6 blocks for sticker printing in a page.
The position is to be fixed for each rectangle as attached:
theReportLayout .
I have used 6 different parameterized datasets for each tabllix and kept that in each of the rectangle respectively and based on parameters the visibility is handled.
But when only one parameter is selected for e.g., the 4th one  is selected the rectangle is displayed at position 1 with slight downwards.
Same goes with any one selection which is an issue.
I need the position fixed for whichever single or multi selection is used.
Please suggest.
Thanks in advance
Sunny.</p>

答: I'm assuming that when you say you need the positions fixed, that you want all six rectangles to stay in those positions regardless of what parameters are selected. Try putting all 6 rectangles in a parent rectangle to fix the locations on the report.</p>


问:
Make a overlay appear on text hover
I'm looking for a way to make my background image darken by hovering over an anchor within the div container that the background image is attached to.

There has been an instance where it did work but there was a enormous amount of flickering when the mouse was moved within the anchor.

答:
You can use JavaScript for it.

HTML:

```<code><a href="something.example.com/something" onmousehover="darkenIt(this);" />
</code>```

CSS:

```<code>a{
background-image: url("img/image.jpg");
}
</code>```

The JavaScript:

```<code>function darkenIt(x){
    x.style.backgroundImage = 'url("img/dark-image.jpg");';
}
</code>```

I don't know how to darken a photo using CSS. Thus, I shown you the code with two different images. If you know how to do it, you can use it.

You can use only CSS for it too. You can use a:hover after using a class.

Enjoy :D

Title: Make a overlay appear on text hover

Body:
You can use JavaScript for it.

HTML:

<a href="something.example.com/something" onmousehover="darkenIt(this);" />

CSS:

a{
background-image: url("img/image.jpg");
}

The JavaScript:

function darkenIt(x){
    x.style.backgroundImage = 'url("img/dark-image.jpg");';
}

I don't know how to darken a photo using CSS. Thus, I shown you the code with two different images. If you know how to do it, you can use it.

You can use only CSS for it too. You can use a:hover after using a class.

Enjoy :D


问:
Error while installing chrome extension through Python - selenium
I am trying to install chrome extension using Python Selenium.
When I click Add to chrome button a pop up(don't know whether it is a java scripted) is generated asking: "Add extension", "Cancel". I want to click "Add extension" but I am getting following error:

selenium.common.exceptions.NoAlertPresentException: Message: no alert open

My code:

```<code>from selenium import webdriver
import time

driver=webdriver.Chrome()
driver.implicitly_wait(30)
driver.get("https://chrome.google.com/webstore/detail/buyhatke/jaehkpjddfdgiiefcnhahapilbejohhj?hl=en")
time.sleep(15)
element=driver.find_element_by_css_selector("body > div.F-ia-k.S-ph.S-Rc-qa > div.h-F-f-k.F-f-k > div > div > div.e-f-o > div.h-e-f-Ra-c.e-f-oh-Md-zb-k >
div.dd-Va.g-c-wb.g-eg-ua-Uc-c-za.g-c-Oc-td-jb-oa.g-c")
element.click()
alert = driver.switch_to.alert
alert.accept()
</code>```

help me to install it.

Updated code:

```<code>from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import os

executable_path = "C:\\Users\\SACHIN\\AppData\\Local\\Programs\\Python\\Python36\\chromedriver"
os.environ["webdriver.chrome.driver"] = executable_path

chrome_options = Options()
chrome_options.add_extension("C:\\Users\\SACHIN\\AppData\\Local\\Google\\chrome\\User Data\\Default\\Extensions\\jaehkpjddfdgiiefcnhahapilbejohhj\\
3.4.143_0")

driver = webdriver.Chrome(executable_path=executable_path,chrome_options=chrome_options)
driver.get("http://stackoverflow.com")
driver.quit()
</code>```

答:
This is because the download option pop up that you are trying to select using switch_to.alert is not actually a JS alert pop up. You can not select is using Selenium's switch_to methods. You need to use the DesiredCapabilities class to select this option and then use it in your code.

As per the ChromeDriver documentation, given here, please use the packed( the one with .crx extension ) or unpacked extension file (directory containing the extension, including a manifest.json file) and load it using DesiredCapabilities. This can be done using

```<code>     from selenium.webdriver.chrome.options import Options

     executable_path = "path_to_webdriver"
     os.environ["webdriver.chrome.driver"] = executable_path

     chrome_options = Options()
     chrome_options.add_extension('path_to_extension')

     driver = webdriver.Chrome(executable_path=executable_path,chrome_options=chrome_options)
     driver.get("http://stackoverflow.com")
     driver.quit()
</code>```

Body:
I am trying to install chrome extension using Python Selenium.
When I click Add to chrome button a pop up(don't know whether it is a java scripted) is generated asking: "Add extension", "Cancel". I want to click "Add extension" but I am getting following error:

selenium.common.exceptions.NoAlertPresentException: Message: no alert open

My code:

from selenium import webdriver
import time

driver=webdriver.Chrome()
driver.implicitly_wait(30)
driver.get("https://chrome.google.com/webstore/detail/buyhatke/jaehkpjddfdgiiefcnhahapilbejohhj?hl=en")
time.sleep(15)
element=driver.find_element_by_css_selector("body > div.F-ia-k.S-ph.S-Rc-qa > div.h-F-f-k.F-f-k > div > div > div.e-f-o > div.h-e-f-Ra-c.e-f-oh-Md-zb-k >
div.dd-Va.g-c-wb.g-eg-ua-Uc-c-za.g-c-Oc-td-jb-oa.g-c")
element.click()
alert = driver.switch_to.alert
alert.accept()

help me to install it.

Updated code:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
import os

executable_path = "C:\\Users\\SACHIN\\AppData\\Local\\Programs\\Python\\Python36\\chromedriver"
os.environ["webdriver.chrome.driver"] = executable_path

chrome_options = Options()
chrome_options.add_extension("C:\\Users\\SACHIN\\AppData\\Local\\Google\\chrome\\User Data\\Default\\Extensions\\jaehkpjddfdgiiefcnhahapilbejohhj\\
3.4.143_0")

driver = webdriver.Chrome(executable_path=executable_path,chrome_options=chrome_options)
driver.get("http://stackoverflow.com")
driver.quit()

Body:
This is because the download option pop up that you are trying to select using switch_to.alert is not actually a JS alert pop up. You can not select is using Selenium's switch_to methods. You need to use the DesiredCapabilities class to select this option and then use it in your code.

As per the ChromeDriver documentation, given here, please use the packed( the one with .crx extension ) or unpacked extension file (directory containing the extension, including a manifest.json file) and load it using DesiredCapabilities. This can be done using

     from selenium.webdriver.chrome.options import Options

     executable_path = "path_to_webdriver"
     os.environ["webdriver.chrome.driver"] = executable_path

     chrome_options = Options()
     chrome_options.add_extension('path_to_extension')

     driver = webdriver.Chrome(executable_path=executable_path,chrome_options=chrome_options)
     driver.get("http://stackoverflow.com")
     driver.quit()


问:
Find quoted text and color it green with javascript similar to 4chan greentext?
For example text like:

```<code>>11 years old
>twin brother dies
>parents dont let me go to his funeral or tell me where it is
>tells me it would be innapropriate to be there as it could confuse people
i dided
</code>```

How do I match > in an element and turn it green? The functionality should be similar to 4chans "greentext" meaning that the "i dided" part up there should not turn green

答:
Try this, it matches > at the start of the line and then anything after it (on the same line)

>.*/g

/g is used to match globally.

Example:

https://regex101.com/r/WXEoaW/2

Body:
For example text like:

>11 years old
>twin brother dies
>parents dont let me go to his funeral or tell me where it is
>tells me it would be innapropriate to be there as it could confuse people
i dided

How do I match > in an element and turn it green? The functionality should be similar to 4chans "greentext" meaning that the "i dided" part up there should not turn green


问:
Angular 2 Bind a variable to a header in html
I'm trying to bind a variable to a header to show what the current step is (ie, 'You are on step 1 of 10'). I have it working for a textarea and can't figure out why it doesn't work for a header.

```<code>private mainStepText: String = "Welcome";
<div class="mainWindow">
   <textarea [(ngModel)]="mainStepText"></textarea>
</div>
</code>```

What I have so far is

```<code>private testLabel: String = "This is a test label for html";
<div class="test">
  <h3 class="labelName" [(ngModel)]="testLabel"></h3>
</div>
</code>```

Right now it throws an error

"ERROR Error: Uncaught (in promise): Error: No value accessor for form control with unspecified name attribute
Error: No value accessor for form control with unspecified name attribute"

答:
Instead of ngModel in the tag. Just do:

```<code><h3 class="labelName">{{testLabel}}</h3>
</code>```

and set testLabel in your component

Body:
I'm trying to bind a variable to a header to show what the current step is (ie, 'You are on step 1 of 10'). I have it working for a textarea and can't figure out why it doesn't work for a header.

private mainStepText: String = "Welcome";

   <textarea [(ngModel)]="mainStepText"></textarea>

What I have so far is

private testLabel: String = "This is a test label for html";

Right now it throws an error

"ERROR Error: Uncaught (in promise): Error: No value accessor for form control with unspecified name attribute
Error: No value accessor for form control with unspecified name attribute"

Body:
Instead of ngModel in the tag. Just do:

<h3 class="labelName">{{testLabel}}</h3>

and set testLabel in your component


问:
What is the Best way to handle a lot of data on a Recycleview
I need to load a long list of data (5000-1000) on a RecycleView, and each items of the RecycleView has many details, so 5 TextView, 1 ImageView and a ProgressBar. All the data are stored on the SQLite DB.
Is it better to load an ArrayList<Object> which contains all the data and them set it to the adapter or is it better to load the data on the adapter?
Please consider I have other thing to do on the adapter like retriving the images (with Glide).
Any suggestion or consideration would be helpful!

Thank you

答:
You can try cursorRecyclarViewAdapter

https://gist.github.com/skyfishjy/443b7448f59be978bc59

```<code>public class MyRecyclerAdapter extends Adapter<MyRecyclerAdapter.ViewHolder> {

// Because RecyclerView.Adapter in its current form doesn't natively
// support cursors, we wrap a CursorAdapter that will do all the job
// for us.
CursorAdapter mCursorAdapter;

Context mContext;

public MyRecyclerAdapter(Context context, Cursor c) {

    mContext = context;

    mCursorAdapter = new CursorAdapter(mContext, c, 0) {

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // Inflate the view here
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // Binding operations
        }
    };
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    View v1;

    public ViewHolder(View itemView) {
        super(itemView);
        v1 = itemView.findViewById(R.id.v1);
    }
}

@Override
public int getItemCount() {
    return mCursorAdapter.getCount();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // Passing the binding operation to cursor loader
    mCursorAdapter.getCursor().moveToPosition(position); //EDITED: added this line as suggested in the comments below, thanks :)
    mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());

}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // Passing the inflater job to the cursor-adapter
    View v = mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent);
    return new ViewHolder(v);
}
}
</code>```

Body:
You can try cursorRecyclarViewAdapter

https://gist.github.com/skyfishjy/443b7448f59be978bc59

public class MyRecyclerAdapter extends Adapter<MyRecyclerAdapter.ViewHolder> {

// Because RecyclerView.Adapter in its current form doesn't natively
// support cursors, we wrap a CursorAdapter that will do all the job
// for us.
CursorAdapter mCursorAdapter;

Context mContext;

public MyRecyclerAdapter(Context context, Cursor c) {

    mContext = context;

    mCursorAdapter = new CursorAdapter(mContext, c, 0) {

        @Override
        public View newView(Context context, Cursor cursor, ViewGroup parent) {
            // Inflate the view here
        }

        @Override
        public void bindView(View view, Context context, Cursor cursor) {
            // Binding operations
        }
    };
}

public static class ViewHolder extends RecyclerView.ViewHolder {
    View v1;

    public ViewHolder(View itemView) {
        super(itemView);
        v1 = itemView.findViewById(R.id.v1);
    }
}

@Override
public int getItemCount() {
    return mCursorAdapter.getCount();
}

@Override
public void onBindViewHolder(ViewHolder holder, int position) {
    // Passing the binding operation to cursor loader
    mCursorAdapter.getCursor().moveToPosition(position); //EDITED: added this line as suggested in the comments below, thanks :)
    mCursorAdapter.bindView(holder.itemView, mContext, mCursorAdapter.getCursor());

}

@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
    // Passing the inflater job to the cursor-adapter
    View v = mCursorAdapter.newView(mContext, mCursorAdapter.getCursor(), parent);
    return new ViewHolder(v);
}
}


问:
jQuery hasClass and if
I have a problem with jquery hasClass.

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

var body = $('body'),
    leftPane = $('.pane-left');

leftPane.on('click', function () {

    body.removeClass('left-closed');
    body.addClass('left-open');
    $('.pane-left h2').fadeIn(600);

    setTimeout(function() {
        rightPane.fadeOut(0);
        $('.pane-left-wrap').fadeIn(100);
        $('.pane-left-wrap .secondary-nav li:first-child').fadeIn(100);
        $('.pane-left-wrap .secondary-nav li:nth-child(2)').fadeIn(600);
        $('.pane-left-wrap .secondary-nav li:nth-child(3)').fadeIn(1200);
        $('.pane-left-wrap .secondary-nav li:nth-child(4)').fadeIn(1800);
        $('.pane-left-wrap .secondary-nav li:nth-child(5)').fadeIn(2400);
    }, 600);

});

if(body.hasClass('left-open')) {

    leftPane.on('click', function () {

        body.removeClass('left-open');
        body.addClass('left-closed');
        $('.pane-left h2').fadeOut(600);

    });

}

});
</code>```

I click pane-left and left-open is added to my body tag. Then i click again but the code inside my if() is unreachable. Why is that?

答:
Move the check for <code>.left-open</code> into the click handler. </p>

```<code>$(document).ready(function () {
    var body = $('body'),
    leftPane = $('.pane-left');

    leftPane.on('click', function () {

        // Added for check 'left-open' class.
        if(!body.hasClass('left-open')) {
            body.removeClass('left-closed');
            body.addClass('left-open');
            $('.pane-left h2').fadeIn(600);

            setTimeout(function() {
                rightPane.fadeOut(0);
                $('.pane-left-wrap').fadeIn(100);
                $('.pane-left-wrap .secondary-nav li:first-child').fadeIn(100);
                $('.pane-left-wrap .secondary-nav li:nth-child(2)').fadeIn(600);
                $('.pane-left-wrap .secondary-nav li:nth-child(3)').fadeIn(1200);
                $('.pane-left-wrap .secondary-nav li:nth-child(4)').fadeIn(1800);
                $('.pane-left-wrap .secondary-nav li:nth-child(5)').fadeIn(2400);
            }, 600);
        }

        // Moved this function inside click event.
        if(body.hasClass('left-open')) {
            leftPane.on('click', function () {
                body.removeClass('left-open');
                body.addClass('left-closed');
                $('.pane-left h2').fadeOut(600);
            });
        }
    });
});
</code>```

Title: jQuery hasClass and if

Body:
I have a problem with jquery hasClass.

$(document).ready(function () {

var body = $('body'),
    leftPane = $('.pane-left');

leftPane.on('click', function () {

    body.removeClass('left-closed');
    body.addClass('left-open');
    $('.pane-left h2').fadeIn(600);

    setTimeout(function() {
        rightPane.fadeOut(0);
        $('.pane-left-wrap').fadeIn(100);
        $('.pane-left-wrap .secondary-nav li:first-child').fadeIn(100);
        $('.pane-left-wrap .secondary-nav li:nth-child(2)').fadeIn(600);
        $('.pane-left-wrap .secondary-nav li:nth-child(3)').fadeIn(1200);
        $('.pane-left-wrap .secondary-nav li:nth-child(4)').fadeIn(1800);
        $('.pane-left-wrap .secondary-nav li:nth-child(5)').fadeIn(2400);
    }, 600);

});

if(body.hasClass('left-open')) {

    leftPane.on('click', function () {

        body.removeClass('left-open');
        body.addClass('left-closed');
        $('.pane-left h2').fadeOut(600);

    });

}

});

I click pane-left and left-open is added to my body tag. Then i click again but the code inside my if() is unreachable. Why is that?

Body:
Move the check for .left-open into the click handler.

$(document).ready(function () {
    var body = $('body'),
    leftPane = $('.pane-left');

    leftPane.on('click', function () {

        // Added for check 'left-open' class.
        if(!body.hasClass('left-open')) {
            body.removeClass('left-closed');
            body.addClass('left-open');
            $('.pane-left h2').fadeIn(600);

            setTimeout(function() {
                rightPane.fadeOut(0);
                $('.pane-left-wrap').fadeIn(100);
                $('.pane-left-wrap .secondary-nav li:first-child').fadeIn(100);
                $('.pane-left-wrap .secondary-nav li:nth-child(2)').fadeIn(600);
                $('.pane-left-wrap .secondary-nav li:nth-child(3)').fadeIn(1200);
                $('.pane-left-wrap .secondary-nav li:nth-child(4)').fadeIn(1800);
                $('.pane-left-wrap .secondary-nav li:nth-child(5)').fadeIn(2400);
            }, 600);
        }

        // Moved this function inside click event.
        if(body.hasClass('left-open')) {
            leftPane.on('click', function () {
                body.removeClass('left-open');
                body.addClass('left-closed');
                $('.pane-left h2').fadeOut(600);
            });
        }
    });
});


问:
Get the id from a Img without the ID
i'm creating  a simple bootstrap gallery thumbnail with images that are being called from database. I succeed in calling all the info, but now i'm struggling with getting the id of each image. This is my code:

```<code> <div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
    <p><a href="#" onclick="return getID(this);" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>
</code>```

And this is my function in javascript:

```<code>function getID(e)
{
    var x = e.src;
    alert(x);
}
</code>```

But it is not working, how do I get the id of each image if is being called from a database?

答:
Why don't you get in the same way you wrote?</p>

```<code><div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
    <p><a href="#" onclick="return getID(<?php echo $row['ID_Category']?>);" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>

function getID(id)
{
    alert(id);
}
</code>```

Title: Get the id from a Img without the ID

Body:
i'm creating  a simple bootstrap gallery thumbnail with images that are being called from database. I succeed in calling all the info, but now i'm struggling with getting the id of each image. This is my code:

  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">

<?php echo $row['ID_Category']?>

<?php echo $row['Categories'] ?>

Button Button

And this is my function in javascript:

function getID(e)
{
    var x = e.src;
    alert(x);
}

But it is not working, how do I get the id of each image if is being called from a database?

Body:
Why don't you get in the same way you wrote?

<div class="col-sm-6 col-md-4">
<div class="thumbnail">
  <img id="<?php echo $row['ID_Category']?>" src="<?php echo $row['category_image'] ?>" alt="<?php $row['Categories'] ?>">
  <div class="caption">
    <h3><?php echo $row['ID_Category']?></h3>
    <p><?php echo $row['Categories'] ?></p>
    <p><a href="#" onclick="return getID(<?php echo $row['ID_Category']?>);" class="btn btn-primary" role="button">Button</a> <a href="#" class="btn btn-default" role="button">Button</a></p>
  </div>
</div>

function getID(id)
{
    alert(id);
}


问:
Getting HTTP 412 with CasperJS
I'm writing some CasperJS scripts that allow me to login sites from console. However, when I try to login https://www.zara.com/us/, I keep getting HTTP 412 Precondition Failed. I've tried --ssl-protocol=any and --ignore-ssl-erros=true but it doesn't fix the problem. Does anyone know how to fix this?

Thanks!

答:
You may also try --web-security=false, but I do not think your problem is related to HTTPS. With this simple script, I get a 200 code (even though I run it without any options):

```<code>var casper = require('casper').create();

casper.start('https://www.zara.com/us/');

casper.then(function () {
  this.echo(this.getTitle());
});

casper.run();
</code>```

There is most likely something wrong in your code when you fill forms or in the HTTP headers of your request. For the record, here is the description of the 412 error (MDN):

The HTTP 412 Precondition Failed client error response code indicates
  that access to the target resource has been denied. This happens with
  conditional requests on methods other than GET or HEAD when the
  condition defined by the If-Unmodified-Since or If-None-Match headers
  is not fulfilled. In that case, the request, usually an upload or a
  modification of a resource, cannot be made and this error response is
  sent back.

Title: Getting HTTP 412 with CasperJS

Body:
You may also try --web-security=false, but I do not think your problem is related to HTTPS. With this simple script, I get a 200 code (even though I run it without any options):

var casper = require('casper').create();

casper.start('https://www.zara.com/us/');

casper.then(function () {
  this.echo(this.getTitle());
});

casper.run();

There is most likely something wrong in your code when you fill forms or in the HTTP headers of your request. For the record, here is the description of the 412 error (MDN):

The HTTP 412 Precondition Failed client error response code indicates
  that access to the target resource has been denied. This happens with
  conditional requests on methods other than GET or HEAD when the
  condition defined by the If-Unmodified-Since or If-None-Match headers
  is not fulfilled. In that case, the request, usually an upload or a
  modification of a resource, cannot be made and this error response is
  sent back.


答:
Here is a possible dynamic solution. Please note that the number of columns in the resulting table depends from the input data, which is usually a bad idea. For this reason it will be tricky to put this code inside a stored procedure.

Nonetheless here is a TSQL fragment that should answer your question:

```<code>--create a custom type that will be used in the final dynamic call
if exists (select * from sys.types where name = 'TestTableType')
    drop type TestTableType
create type TestTableType as table([index] int,[sub_index] int, [data] nvarchar(max))

go

--this table contains your input data
declare @tem table([index] int, [date] datetime , [sub_index] int, [angle] decimal (19,6),[length] decimal (19,6))
--temp table used to calculate maximum number of columns to show
declare @counters table([index] int,[sub_index] int, [counter] int)
--temp table that will hold denormalized values (one row for each index/subindex couple)
declare @denormalized_data TestTableType
--this variables contains the maximum number of columns to show
declare @max_columns int
--this variable will contain the dunamically generated TSQL query that will give the final result
declare @dynamic_query nvarchar(max)
--support variables used to generate dynamic query
declare @counter int
declare @counter_str nvarchar(max)

--1. populate input data
insert into @tem select  681 , '20161019 15:49',  1 ,   30,    333
insert into @tem select  681 , '20161019 15:49',  1 ,   60,    666
insert into @tem select  682 , '20161019 15:52',  2 ,    0,    44
insert into @tem select  682 , '20161019 15:52',  2 ,    45,   77
insert into @tem select  682 , '20161019 15:52',  2 ,    90,   67
--insert into @tem select  682 , '20161019 15:52',  2 ,    8,    88

--2. calculate the number of columns to show
insert into @counters
select [index],[sub_index], COUNT(*) from @tem group by [index],[sub_index]

select @max_columns =  max([counter]) from @counters

--3. denormalize data using an XML-based approach to obtain one row for each index/subindex couple
insert into @denormalized_data
SELECT
  [index],[sub_index],
 '<MyData>'+ STUFF((
    SELECT '  <angle>' +  CAST([angle] AS VARCHAR(MAX))  + '</angle><length>' + CAST([length] AS VARCHAR(MAX)) +'</length>'
    FROM @tem
    WHERE ([index] = Results.[index] and [sub_index] = Results.[sub_index])
    FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
  ,1,2,'') +  '</MyData>' AS NameValues
FROM @tem Results
GROUP BY [index],[sub_index]

--4. generate a dynamic TSQL query with the correct number of columns
set @counter = 0
set @dynamic_query=' SELECT [index],[sub_index],   '
while       @counter < @max_columns
  begin
     set @counter = @counter +1
     set @counter_str =  CAST(@counter  as nvarchar(max))
     set @dynamic_query = @dynamic_query + ' CONVERT(XML,[data]).value(''/MyData[1]/angle['+  @counter_str + ']'',''varchar(100)'') AS angle'+  @counter_str + ',  '
     set @dynamic_query = @dynamic_query + ' CONVERT(XML,[data]).value(''/MyData[1]/length['+  @counter_str + ']'',''varchar(100)'') AS length'+  @counter_str + ',  '
  end

set @dynamic_query = substring(@dynamic_query,1,LEN(@dynamic_query) - 1) + ' FROM @denormalized_d '

exec sp_executesql @dynamic_query, N'@denormalized_d TestTableType readonly', @denormalized_data
</code>```

Here is the output with 3 distinct values:

Here is the output with 4 distinct values (just uncomment the line --insert into @tem select  682 , '20161019 15:52',  2 ,    8,    88 ):

Title: Make one row out of number of rows in a query

Body:
I have two tables with a relationship of one to many.
After executing a query, I got the result table:

+-------+------------------+-----------+-------+--------+
| index |       date       | sub_index | angle | length |
+-------+------------------+-----------+-------+--------+
|   681 | 19/10/2016 15:49 |         1 |    30 |    333 |
|   681 | 19/10/2016 15:49 |         1 |    60 |    666 |
|   682 | 19/10/2016 15:52 |         2 |     0 |     44 |
|   682 | 19/10/2016 15:52 |         2 |    45 |     77 |
|   682 | 19/10/2016 15:52 |         2 |    90 |     67 |
+-------+------------------+-----------+-------+--------+

But the user asked for the information to be flat. Such as the following:

+-------+------------------+-----------+--------+---------+--------+---------+--------+---------+
| index |       date       | sub_index | angle1 | length1 | angle2 | length2 | angle3 | length3 |
+-------+------------------+-----------+--------+---------+--------+---------+--------+---------+
|   681 | 19/10/2016 15:49 |         1 |     30 |     333 |     60 |     666 |        |         |
|   682 | 19/10/2016 15:52 |         2 |      0 |      44 |     45 |      77 |     90 |      67 |
+-------+------------------+-----------+--------+---------+--------+---------+--------+---------+

The number of angles and lengths is unknown and could be any number of items.

I read about a PIVOT, but I don't really know how to use it in this example, because of the changed columns (angle1, angle2...) and because I read that PIVOT need some function (MAX, COUNT, ...) and I need the value as is...

Body:
Here is a possible dynamic solution. Please note that the number of columns in the resulting table depends from the input data, which is usually a bad idea. For this reason it will be tricky to put this code inside a stored procedure.

Nonetheless here is a TSQL fragment that should answer your question:

--create a custom type that will be used in the final dynamic call
if exists (select * from sys.types where name = 'TestTableType')
    drop type TestTableType
create type TestTableType as table([index] int,[sub_index] int, [data] nvarchar(max))

go

--this table contains your input data
declare @tem table([index] int, [date] datetime , [sub_index] int, [angle] decimal (19,6),[length] decimal (19,6))
--temp table used to calculate maximum number of columns to show
declare @counters table([index] int,[sub_index] int, [counter] int)
--temp table that will hold denormalized values (one row for each index/subindex couple)
declare @denormalized_data TestTableType
--this variables contains the maximum number of columns to show
declare @max_columns int
--this variable will contain the dunamically generated TSQL query that will give the final result
declare @dynamic_query nvarchar(max)
--support variables used to generate dynamic query
declare @counter int
declare @counter_str nvarchar(max)

--1. populate input data
insert into @tem select  681 , '20161019 15:49',  1 ,   30,    333
insert into @tem select  681 , '20161019 15:49',  1 ,   60,    666
insert into @tem select  682 , '20161019 15:52',  2 ,    0,    44
insert into @tem select  682 , '20161019 15:52',  2 ,    45,   77
insert into @tem select  682 , '20161019 15:52',  2 ,    90,   67
--insert into @tem select  682 , '20161019 15:52',  2 ,    8,    88

--2. calculate the number of columns to show
insert into @counters
select [index],[sub_index], COUNT(*) from @tem group by [index],[sub_index]

select @max_columns =  max([counter]) from @counters

--3. denormalize data using an XML-based approach to obtain one row for each index/subindex couple
insert into @denormalized_data
SELECT
  [index],[sub_index],
 '<MyData>'+ STUFF((
    SELECT '  <angle>' +  CAST([angle] AS VARCHAR(MAX))  + '</angle><length>' + CAST([length] AS VARCHAR(MAX)) +'</length>'
    FROM @tem
    WHERE ([index] = Results.[index] and [sub_index] = Results.[sub_index])
    FOR XML PATH(''),TYPE).value('(./text())[1]','VARCHAR(MAX)')
  ,1,2,'') +  '</MyData>' AS NameValues
FROM @tem Results
GROUP BY [index],[sub_index]

--4. generate a dynamic TSQL query with the correct number of columns
set @counter = 0
set @dynamic_query=' SELECT [index],[sub_index],   '
while       @counter < @max_columns
  begin
     set @counter = @counter +1
     set @counter_str =  CAST(@counter  as nvarchar(max))
     set @dynamic_query = @dynamic_query + ' CONVERT(XML,[data]).value(''/MyData[1]/angle['+  @counter_str + ']'',''varchar(100)'') AS angle'+  @counter_str + ',  '
     set @dynamic_query = @dynamic_query + ' CONVERT(XML,[data]).value(''/MyData[1]/length['+  @counter_str + ']'',''varchar(100)'') AS length'+  @counter_str + ',  '
  end

set @dynamic_query = substring(@dynamic_query,1,LEN(@dynamic_query) - 1) + ' FROM @denormalized_d '

exec sp_executesql @dynamic_query, N'@denormalized_d TestTableType readonly', @denormalized_data

Here is the output with 3 distinct values:

Here is the output with 4 distinct values (just uncomment the line --insert into @tem select  682 , '20161019 15:52',  2 ,    8,    88 ):


问:
Android running onChildAdded method every time view is accessed through startActivity
I was wondering why my android application is running fireBase onChildAdded every time I access the view through start activity. I only want to read from the fireBase database once, and from then on I use onResume to populate the list with the last entry in the databas (if any were added).

However it is running the onChildAdded every time I use startActitivity to access the view. So this means it doesn't happen when I press the back button to this view.

It's slowing down my application a lot having to repopulate the list from the database every time the user goes back to this page from the home-screen.

Here's a video showcasing how much faster it is when I press back to access the screen when compared to accessing it from the home-screen and pressing on "nightclub" card: https://www.youtube.com/watch?v=VJxsHT14PU8&feature=youtu.be

My onCreate Method:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    // start tracing to "/sdcard/calc.trace"
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nightclub_search);

    // Map and camera Positions
    // Retrieve location and camera position from saved instance state.
    if (savedInstanceState != null) {
        mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
        mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    // Build the Play services client for use by the Fused Location Provider and the Places API.
    // Use the addApi() method to request the Google Places API and the Fused Location Provider.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */,
                    this /* OnConnectionFailedListener */)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    // List View
    listView = (ListView) findViewById(R.id.venueList);
    listView.setOnItemClickListener(this);
    venueList = new ArrayList<>();
    arrayAdapter = new ArrayAdapter<>(nightclub_search.this, R.layout.list_layout, venueList);

    // Fill the list view from the fireBase
    fillListView();

    // Button
    Button addClub = (Button) findViewById(R.id.addClub);
    addClub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(nightclub_search.this, venue_add.class);
            startActivity(i);
        }
    });
}
</code>```

This is how I am calling the view from the home-screen:

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);

    CardView cardBar = (CardView) findViewById(R.id.cardBar);
    CardView cardNightclub = (CardView) findViewById(R.id.cardNightClub);

    cardBar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(home_screen.this, bar_search.class);
            startActivity(intent);
        }
    });
    cardNightclub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(home_screen.this, nightclub_search.class);
            startActivity(intent);
        }
    });
}}
</code>```

And finally this is how I populate the list from firebase which is called within onCreate (and nowhere else):

```<code>// Fills the list for the initial load of the application
protected void fillListView(){

    // Loading bar
    dialog = new ProgressDialog(nightclub_search.this);
    dialog.setMessage("Loading Venues...");
    dialog.show();

    // Separate this from the main thread so that it runs faster
    Runnable run = new Runnable() {
        @Override
        public void run() {
            myRef.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    // Loading dialog for getting fireBase entries
                    count++;
                    Log.d("Firebase", "onChildAddedFROMFILLLISTVIEW:" + dataSnapshot.getKey());
                    // A new venue has been added, add it to the displayed list
                    Nightclub nightclub = dataSnapshot.getValue(Nightclub.class);
                    clubList.add(nightclub);
                    venueList.add(nightclub.name);
                    // Read in location and add marker on map
                    addMarkers(nightclub, days);
                    // Add to listView
                    listView.setAdapter(arrayAdapter);
                    // Remove the loading bar when we've reached this point
                    if (count >= (dataSnapshot.getChildrenCount() - 1)){
                        count = 0;
                        dialog.dismiss();
                    }
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    };

    Thread fillListThread = new Thread(run);
    fillListThread.start();

}
</code>```

答:
The startActivity(Intent intent) method creates a new activity instance unless you set some flags to it. To recover an existing activity instance through intent try using this:

```<code>Intent i = new Intent(nightclub_search.this, venue_add.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);
</code>```

or add this to your Activity tag on manifest:

```<code><activity
    android:name="com.company.ActivityName"
    android:launchMode="singleTask">
</activity>
</code>```

Body:
I was wondering why my android application is running fireBase onChildAdded every time I access the view through start activity. I only want to read from the fireBase database once, and from then on I use onResume to populate the list with the last entry in the databas (if any were added).

However it is running the onChildAdded every time I use startActitivity to access the view. So this means it doesn't happen when I press the back button to this view.

It's slowing down my application a lot having to repopulate the list from the database every time the user goes back to this page from the home-screen.

Here's a video showcasing how much faster it is when I press back to access the screen when compared to accessing it from the home-screen and pressing on "nightclub" card: https://www.youtube.com/watch?v=VJxsHT14PU8&feature=youtu.be

My onCreate Method:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // start tracing to "/sdcard/calc.trace"
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_nightclub_search);

    // Map and camera Positions
    // Retrieve location and camera position from saved instance state.
    if (savedInstanceState != null) {
        mLastKnownLocation = savedInstanceState.getParcelable(KEY_LOCATION);
        mCameraPosition = savedInstanceState.getParcelable(KEY_CAMERA_POSITION);
    }

    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);

    // Build the Play services client for use by the Fused Location Provider and the Places API.
    // Use the addApi() method to request the Google Places API and the Fused Location Provider.
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .enableAutoManage(this /* FragmentActivity */,
                    this /* OnConnectionFailedListener */)
            .addConnectionCallbacks(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();

    // List View
    listView = (ListView) findViewById(R.id.venueList);
    listView.setOnItemClickListener(this);
    venueList = new ArrayList<>();
    arrayAdapter = new ArrayAdapter<>(nightclub_search.this, R.layout.list_layout, venueList);

    // Fill the list view from the fireBase
    fillListView();

    // Button
    Button addClub = (Button) findViewById(R.id.addClub);
    addClub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(nightclub_search.this, venue_add.class);
            startActivity(i);
        }
    });
}

This is how I am calling the view from the home-screen:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_home_screen);

    CardView cardBar = (CardView) findViewById(R.id.cardBar);
    CardView cardNightclub = (CardView) findViewById(R.id.cardNightClub);

    cardBar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(home_screen.this, bar_search.class);
            startActivity(intent);
        }
    });
    cardNightclub.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(home_screen.this, nightclub_search.class);
            startActivity(intent);
        }
    });
}}

And finally this is how I populate the list from firebase which is called within onCreate (and nowhere else):

// Fills the list for the initial load of the application
protected void fillListView(){

    // Loading bar
    dialog = new ProgressDialog(nightclub_search.this);
    dialog.setMessage("Loading Venues...");
    dialog.show();

    // Separate this from the main thread so that it runs faster
    Runnable run = new Runnable() {
        @Override
        public void run() {
            myRef.addChildEventListener(new ChildEventListener() {
                @Override
                public void onChildAdded(DataSnapshot dataSnapshot, String s) {
                    // Loading dialog for getting fireBase entries
                    count++;
                    Log.d("Firebase", "onChildAddedFROMFILLLISTVIEW:" + dataSnapshot.getKey());
                    // A new venue has been added, add it to the displayed list
                    Nightclub nightclub = dataSnapshot.getValue(Nightclub.class);
                    clubList.add(nightclub);
                    venueList.add(nightclub.name);
                    // Read in location and add marker on map
                    addMarkers(nightclub, days);
                    // Add to listView
                    listView.setAdapter(arrayAdapter);
                    // Remove the loading bar when we've reached this point
                    if (count >= (dataSnapshot.getChildrenCount() - 1)){
                        count = 0;
                        dialog.dismiss();
                    }
                }

                @Override
                public void onChildChanged(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onChildRemoved(DataSnapshot dataSnapshot) {

                }

                @Override
                public void onChildMoved(DataSnapshot dataSnapshot, String s) {

                }

                @Override
                public void onCancelled(DatabaseError databaseError) {

                }
            });
        }
    };

    Thread fillListThread = new Thread(run);
    fillListThread.start();

}

Body:
The startActivity(Intent intent) method creates a new activity instance unless you set some flags to it. To recover an existing activity instance through intent try using this:

Intent i = new Intent(nightclub_search.this, venue_add.class);
i.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(i);

or add this to your Activity tag on manifest:

<activity
    android:name="com.company.ActivityName"
    android:launchMode="singleTask">
</activity>


问:
How can i do multiple stationary tests for multiple timeseries in a dataframe
I have the following df:

```<code>head(vardata)
       Month repo Callrate  WPI GDP  FED    nse   usd
1 2001-04-01 9.00     7.49 5.41 4.6 4.50 1125.2 46.79
2 2001-05-01 8.75     8.03 5.60 4.6 4.00 1167.9 46.92
3 2001-06-01 8.50     7.24 5.30 4.6 3.75 1107.9 47.00
4 2001-07-01 8.50     7.19 5.23 5.3 3.75 1072.8 47.14
5 2001-08-01 8.50     6.94 5.41 5.3 3.50 1053.8 47.13
6 2001-09-01 8.50     7.30 4.52 5.3 3.00  913.9 47.65
</code>```

I want to conduct Box.test, adf.test, and kpss.test for all the 7 var with following set of rules:

Say I set a significance level of 5%. Then the rules are:

1) For the Box.test, if p-value < 0.05 => stationary

2) For the adf.test, if p-value < 0.05 => stationary

3) For the kpss.test, if p-value > 0.05 => stationary (note change of inequality)

Individually i did the tests as:

```<code>Box.test(ts(df$repo),lag=20,type="Ljung-Box")

    Box-Ljung test

data:  ts(df$repo)
X-squared = 1100, df = 20, p-value <2e-16

adf.test(ts(df$repo),alternative = "stationary")

    Augmented Dickey-Fuller Test

data:  ts(df$repo)
Dickey-Fuller = -2.7, Lag order = 5, p-value = 0.3
alternative hypothesis: stationary

kpss.test(ts(df$repo))

    KPSS Test for Level Stationarity

data:  ts(df$repo)
KPSS Level = 0.32, Truncation lag parameter = 3, p-value = 0.1

# to extract p values
Box.test(ts(df$repo),lag=20,type="Ljung-Box")$p.value
adf.test(ts(df$repo),alternative = "stationary")$p.value
kpss.test(ts(df$repo))$p.value
</code>```

This was done one at a time for all the variables.....

But I would like to do all these tests in one go for all the var & outputted in some sort of a data frame if possible maybe something like this:

```<code>   var         box.pvalue  box  adf.pvalue adf  kpss.pvalue kpss
   repo          0.03      TRUE    0.03   TRUE     0.03    FALSE
   Callrate      0.03      TRUE    0.03   TRUE     0.03    FALSE
   WPI           0.03      TRUE    0.03   TRUE     0.03    FALSE
   GDP           0.03      TRUE    0.03   TRUE     0.03    FALSE
   FED           0.51      FALSE   0.03   TRUE     0.03    FALSE
   nse           0.03      TRUE    0.03   TRUE     0.03    FALSE
   usd           0.45      FALSE   0.03   TRUE     0.03    FALSE
</code>```

Where TRUE= series is stationary ; FALSE= series is NON-stationary

update--- my attempt

stationarity tests for multiple time series

```<code>multi_stat_tests<- function(df){
  for(i in 1:dim(df)[2]){
    df_multi<-data.frame(var=names(df)[i],box.pvalue=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value,adf.pvalue=adf.test(ts(df[,i]),alternative = "stationary")$p.value,kpss.pvalue=kpss.test(ts(df[,i]))$p.value,
box=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value<0.05,
adf=adf.test(ts(df[,i]),alternative = "stationary")$p.value<0.05,
kpss=kpss.test(ts(df[,i]))$p.value>0.05
)
    return(df_multi)
  }
}

>multi_stat_tests(df[,2:8])

  var box.pvalue    adf.pvalue   kpss.pvalue  box   adf  kpss
1 repo          0     0.2859         0.1     TRUE  FALSE TRUE
</code>```

Its just picking up only one var......its not iterating across all the variables...missing something here....HELP required!!!!!

答:
You return result in the first iteration of loop, that is why you only get result for the first variable. I think this achieves what you want.

```<code>multi_stat_tests<- function(df){
    p <- ncol(df)
    df_multi <- data.frame(var=names(df),
                           box.pvalue=sapply(df, function(v) Box.test(ts(v),lag=20,type="Ljung-Box")$p.value),
                           adf.pvalue=sapply(df, function(v) adf.test(ts(v),alternative = "stationary")$p.value),
                           kpss.pvalue=sapply(df, function(v) kpss.test(ts(v))$p.value)
                           )
    df_multi$box <- df_multi$box.pvalue < 0.05
    df_multi$adf <- df_multi$adf.pvalue < 0.05
    df_multi$kpss <- df_multi$kpss.pvalue > 0.05
    df_multi
}
</code>```

Addition:

If you don't want to have row names,

```<code>multi_stat_tests<- function(df){
    p <- ncol(df)
    df_multi <- data.frame(var=names(df),
                           box.pvalue=sapply(df, function(v) Box.test(ts(v),lag=20,type="Ljung-Box")$p.value),
                           adf.pvalue=sapply(df, function(v) adf.test(ts(v),alternative = "stationary")$p.value),
                           kpss.pvalue=sapply(df, function(v) kpss.test(ts(v))$p.value)
                           )
    df_multi$box <- df_multi$box.pvalue < 0.05
    df_multi$adf <- df_multi$adf.pvalue < 0.05
    df_multi$kpss <- df_multi$kpss.pvalue > 0.05
    row.names(df_multi) <- c()
    df_multi
}
</code>```

OwnerDisplayName: Nishant

Body:
I have the following df:

head(vardata)
       Month repo Callrate  WPI GDP  FED    nse   usd
1 2001-04-01 9.00     7.49 5.41 4.6 4.50 1125.2 46.79
2 2001-05-01 8.75     8.03 5.60 4.6 4.00 1167.9 46.92
3 2001-06-01 8.50     7.24 5.30 4.6 3.75 1107.9 47.00
4 2001-07-01 8.50     7.19 5.23 5.3 3.75 1072.8 47.14
5 2001-08-01 8.50     6.94 5.41 5.3 3.50 1053.8 47.13
6 2001-09-01 8.50     7.30 4.52 5.3 3.00  913.9 47.65

I want to conduct Box.test, adf.test, and kpss.test for all the 7 var with following set of rules:

Say I set a significance level of 5%. Then the rules are:

1) For the Box.test, if p-value < 0.05 => stationary

2) For the adf.test, if p-value < 0.05 => stationary

3) For the kpss.test, if p-value > 0.05 => stationary (note change of inequality)

Individually i did the tests as:

Box.test(ts(df$repo),lag=20,type="Ljung-Box")

    Box-Ljung test

data:  ts(df$repo)
X-squared = 1100, df = 20, p-value <2e-16

adf.test(ts(df$repo),alternative = "stationary")

    Augmented Dickey-Fuller Test

data:  ts(df$repo)
Dickey-Fuller = -2.7, Lag order = 5, p-value = 0.3
alternative hypothesis: stationary

kpss.test(ts(df$repo))

    KPSS Test for Level Stationarity

data:  ts(df$repo)
KPSS Level = 0.32, Truncation lag parameter = 3, p-value = 0.1

# to extract p values
Box.test(ts(df$repo),lag=20,type="Ljung-Box")$p.value
adf.test(ts(df$repo),alternative = "stationary")$p.value
kpss.test(ts(df$repo))$p.value

This was done one at a time for all the variables.....

But I would like to do all these tests in one go for all the var & outputted in some sort of a data frame if possible maybe something like this:

   var         box.pvalue  box  adf.pvalue adf  kpss.pvalue kpss
   repo          0.03      TRUE    0.03   TRUE     0.03    FALSE
   Callrate      0.03      TRUE    0.03   TRUE     0.03    FALSE
   WPI           0.03      TRUE    0.03   TRUE     0.03    FALSE
   GDP           0.03      TRUE    0.03   TRUE     0.03    FALSE
   FED           0.51      FALSE   0.03   TRUE     0.03    FALSE
   nse           0.03      TRUE    0.03   TRUE     0.03    FALSE
   usd           0.45      FALSE   0.03   TRUE     0.03    FALSE

Where TRUE= series is stationary ; FALSE= series is NON-stationary

update--- my attempt

stationarity tests for multiple time series

multi_stat_tests<- function(df){
  for(i in 1:dim(df)[2]){
    df_multi<-data.frame(var=names(df)[i],box.pvalue=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value,adf.pvalue=adf.test(ts(df[,i]),alternative = "stationary")$p.value,kpss.pvalue=kpss.test(ts(df[,i]))$p.value,
box=Box.test(ts(df[,i]),lag=20,type="Ljung-Box")$p.value<0.05,
adf=adf.test(ts(df[,i]),alternative = "stationary")$p.value<0.05,
kpss=kpss.test(ts(df[,i]))$p.value>0.05
)
    return(df_multi)
  }
}

>multi_stat_tests(df[,2:8])

  var box.pvalue    adf.pvalue   kpss.pvalue  box   adf  kpss
1 repo          0     0.2859         0.1     TRUE  FALSE TRUE

Its just picking up only one var......its not iterating across all the variables...missing something here....HELP required!!!!!

Body:
You return result in the first iteration of loop, that is why you only get result for the first variable. I think this achieves what you want.

multi_stat_tests<- function(df){
    p <- ncol(df)
    df_multi <- data.frame(var=names(df),
                           box.pvalue=sapply(df, function(v) Box.test(ts(v),lag=20,type="Ljung-Box")$p.value),
                           adf.pvalue=sapply(df, function(v) adf.test(ts(v),alternative = "stationary")$p.value),
                           kpss.pvalue=sapply(df, function(v) kpss.test(ts(v))$p.value)
                           )
    df_multi$box <- df_multi$box.pvalue < 0.05
    df_multi$adf <- df_multi$adf.pvalue < 0.05
    df_multi$kpss <- df_multi$kpss.pvalue > 0.05
    df_multi
}

Addition:

If you don't want to have row names,

multi_stat_tests<- function(df){
    p <- ncol(df)
    df_multi <- data.frame(var=names(df),
                           box.pvalue=sapply(df, function(v) Box.test(ts(v),lag=20,type="Ljung-Box")$p.value),
                           adf.pvalue=sapply(df, function(v) adf.test(ts(v),alternative = "stationary")$p.value),
                           kpss.pvalue=sapply(df, function(v) kpss.test(ts(v))$p.value)
                           )
    df_multi$box <- df_multi$box.pvalue < 0.05
    df_multi$adf <- df_multi$adf.pvalue < 0.05
    df_multi$kpss <- df_multi$kpss.pvalue > 0.05
    row.names(df_multi) <- c()
    df_multi
}


问:
is there a Collection Subscription Inheritance passed onto child templates
Consider below hierarchy of templates,

'A' has 2 template 'B' and 'C'.

'B' has 2 templates 'D' and 'E'.

my question is whether the meteor collection subcription made in template 'A' is available in the helper for template 'E' since 'A' has 'B' and 'B' has 'E'?

NOTE: if YES/NO why?

答:
The subscription data is bounded to the scope you subscribe to.
You can Template.instance().subscribe('subscription_name'). The data will then be available to the Template instance.

Also also can Meteor.subscribe('subscription_name'). The data will then be scoped to the Meteor environment. In this case the will data be accessible from the child templates as well. This isn't recommendable for sensitive data, though.

Last alternative is, like in Afifs answer, to give the child template the data with a parameter, which is effective and neat.


问:
How can I delete a remote tag?
How can I delete a Git tag that has already been pushed?</p>

答:
Seems like a lot of work for something xargs already does. Looking back through this thread, I'm guessing the slowness with xargs that you experienced is because the original answer used xargs -n 1 when it didn't really need to.

This is equivalent to your method one except that xargs automatically deals with the maximum command line length:

```<code>git tag | sorting_processing_etc | xargs git push --delete origin
</code>```

xargs can run processes in parallel too. Method 2 with xargs:

```<code>git tag | sorting_processing_etc | xargs -P 5 -n 100 git push --delete origin
</code>```

The above uses a maximum of 5 processes to handle a maximum of 100 arguments in each process. You can experiment with the arguments to find what works best for your needs.

ContentLicense: CC BY-SA 4.0

Title: How can I delete a remote tag?

Body:
Seems like a lot of work for something xargs already does. Looking back through this thread, I'm guessing the slowness with xargs that you experienced is because the original answer used xargs -n 1 when it didn't really need to.

This is equivalent to your method one except that xargs automatically deals with the maximum command line length:

git tag | sorting_processing_etc | xargs git push --delete origin

xargs can run processes in parallel too. Method 2 with xargs:

git tag | sorting_processing_etc | xargs -P 5 -n 100 git push --delete origin

The above uses a maximum of 5 processes to handle a maximum of 100 arguments in each process. You can experiment with the arguments to find what works best for your needs.


问:
Help with making menu button for jQueryMobile
new to jquery and jquerymobile.

All I want to do is hide the main menu, and create a "Menu" button on the top nav bar.  When user clicks on this button a pop up appears with the "top-menu".

I cheated and on the mobile.css I turned the "top-menu" to display:none to initially hide it.

EDIT

Got it closer, but not perfect.  Now on Menu click (was looking for onTouch or onTap but couldn't find API info) menu appears.  Is there a way that instead of it appearing it opens on a pop up window?

Also, for some reason data theme or icon not showing up either.

```<code>$(document).ready(function(){
    $('#header').append('<div data-role="navbar"><ul><li class="mainMenu"><a href="#" data-iconpos="top" data-icon="grid" data-theme="b">Menu</a></li><li><a href="#">facebook</a></li><li><a href="#">Twitter</a></li></ul></div>');
    $('.mainMenu').click(function() {
      $('#top-menu').toggle('fast', function() {
        // Animation complete.
      });
    });
});
</code>```

答:
The JQM CSS is not applied to what you add manually to the DOM. You have to call .page() on that item.

For details see http://jquerymobiledictionary.dyndns.org/faq.html - question about DOM additions

[edit]

This might be better than hacking it: http://jquerymobile.com/demos/1.0a2/#docs/toolbars/bars-fullscreen.html

[as a response to your edit]

First of all - try not to use javascript for what it's not needed. Why fill the header with javascript if you don't need it? You didn't use any variables there.

Second thing - you didn't read my tutorial. NO jquery mobile specific stuff will be applied if you create new DOM content after document is ready. If you do that, you have to call .page() on new content. That's why it still doesn't work.

Events are avaliable in the docs&demos section http://jquerymobile.com/demos/1.0a2/ just have to click events.

Finally - there are no popups in mobile phones. If you ment a dialog take a look at dialogs in JQM docs.

Jquery was a totally different approach to javascript and jquery mobile is also a new idea. Your intuitions and experience from jquery will remain useless for some time, until you get the idea of jqm and what it's for.

This might happen quicker if you read a bit on progressive enhancement.

Good luck.

Body:
new to jquery and jquerymobile.

All I want to do is hide the main menu, and create a "Menu" button on the top nav bar.  When user clicks on this button a pop up appears with the "top-menu".

I cheated and on the mobile.css I turned the "top-menu" to display:none to initially hide it.

EDIT

Got it closer, but not perfect.  Now on Menu click (was looking for onTouch or onTap but couldn't find API info) menu appears.  Is there a way that instead of it appearing it opens on a pop up window?

Also, for some reason data theme or icon not showing up either.

$(document).ready(function(){
    $('#header').append('

Menu

facebook

Twitter

');
    $('.mainMenu').click(function() {
      $('#top-menu').toggle('fast', function() {
        // Animation complete.
      });
    });
});