问:
What is the difference between mode and class in R?
I am learning R (I started just this week), and I've been struggling with the concepts of typeof, mode, storage.mode and class. I've been searching up and down (official R documentation, StackOverflow, Google, etc.), and I haven't been able to find any clear explanation of the difference between these. (A few StackOverflow and CrossValidated answers have not really helped clear me up.) Finally (I hope), I think I understand it, and so my question is to verify if my understanding is correct.

mode vs storage.mode: mode and storage.mode are basically the same thing, except for a tiny difference in how the "single" datatype is handled.

mode vs typeof: Very similar, except for a few differences, most notably that both (typeof "integer" and "double") = (mode "numeric"); and both (typeof "special" and "builtin" = (mode "function").

class: Class is based on R's object-oriented class hierarchy. I'm having a hard time finding this graphically laid out, but the best I've been able to find is this diagram:

(If anyone can point me to a more accurate R class hierarchy, I'll replace it.)

Although the class names don't correspond exactly with the results of the R class() function, I believe the hierarchy is basically accurate. My understanding is that the "class" of an object--that is, the result of the class() function--is the root class in the hierarchy. So, for example, "Vector" is not a root class and so it never shows up as the result of the class() function. The root class might rather be "StrVector" ("character") or "BoolVector" ("logical"). In contrast, "Matrix" is itself a root class; hence, its class is "matrix".

Apparently, R supports multiple inheritance, and so some objects can have more than one class.

typeof/mode/storage.mode vs class: This is what was hardest part for me to understand. My understanding now is this: typeof/mode/storage.mode (which I will refer to henceforth simply as "mode") is basically the most complex datatype that an R object can hold as one of its values. So, for example, since matrixes, arrays and vectors can hold only one vector datatype, their mode (that is, the most complex datatype they can hold) is typically numeric, character or logical, even though their class (their position in the class hierarchy) is something completely different.

Where this gets most interesting (that is, confusing) is with objects like lists. A mode of "list" means that each value in the object can itself be a list (that is, an object that can hold diverse datatypes). Thus, regardless of if the class itself is "list", there are multiple objects (e.g. data frames) that can contain diverse values, and whose mode is therefore "list", even if their class is something else.

So, in summary, my understanding is:

typeof/mode/storage.mode (almost the same thing) is basically the most complex datatype that an R object can hold as one of its values; whereas

class is an object's object-oriented classification according to the R class hierarchy.

Is my understanding accurate? If not, could someone please give a more accurate explanation?

答:
'mode' is a mutually exclusive classification of objects according to
their basic structure.  The 'atomic' modes are numeric, complex,
character and logical.  Recursive objects have modes such as 'list' or
'function' or a few others.  An object has one and only one mode.

'class' is a property assigned to an object that determines how generic
functions operate with it.  It is not a mutually exclusive
classification.  If an object has no specific class assigned to it, such
as a simple numeric vector, it's class is usually the same as its mode,
by convention.

Changing the mode of an object is often called 'coercion'.  The mode of
an object can change without necessarily changing the class.  e.g.

```<code>> x <- 1:16
> mode(x)
[1] "numeric"
> dim(x) <- c(4,4)
> mode(x)
[1] "numeric"
> class(x)
[1] "matrix"
> is.numeric(x)
[1] TRUE
> mode(x) <- "character"
> mode(x)
[1] "character"
> class(x)
[1] "matrix"
</code>```

However:

```<code>> x <- factor(x)
> class(x)
[1] "factor"
> mode(x)
[1] "numeric"
</code>```

At this stage, even though x has mode numeric again, its new class,
factor, inhibits it being used in arithmetic operations.

In practice, mode is not used very much, other than to define a class
implicitly when no explicit class has been assigned.

Body:
'mode' is a mutually exclusive classification of objects according to
their basic structure.  The 'atomic' modes are numeric, complex,
character and logical.  Recursive objects have modes such as 'list' or
'function' or a few others.  An object has one and only one mode.

'class' is a property assigned to an object that determines how generic
functions operate with it.  It is not a mutually exclusive
classification.  If an object has no specific class assigned to it, such
as a simple numeric vector, it's class is usually the same as its mode,
by convention.

Changing the mode of an object is often called 'coercion'.  The mode of
an object can change without necessarily changing the class.  e.g.

> x <- 1:16
> mode(x)
[1] "numeric"
> dim(x) <- c(4,4)
> mode(x)
[1] "numeric"
> class(x)
[1] "matrix"
> is.numeric(x)
[1] TRUE
> mode(x) <- "character"
> mode(x)
[1] "character"
> class(x)
[1] "matrix"

However:

> x <- factor(x)
> class(x)
[1] "factor"
> mode(x)
[1] "numeric"

At this stage, even though x has mode numeric again, its new class,
factor, inhibits it being used in arithmetic operations.

In practice, mode is not used very much, other than to define a class
implicitly when no explicit class has been assigned.


来源: stackexchange

问:
Convert large CSV file to excel using Python 3
this is my code covert CSV file to .xlsx file, for small size CSV file this code is working fine, but when I tried for larger size CSV files, Its shows an error.

```<code>import os
import glob
import csv
from xlsxwriter.workbook import Workbook

for csvfile in glob.glob(os.path.join('.', 'file.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'r', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
    workbook.close()
</code>```

the error is

```<code>File "CsvToExcel.py", line 12, in <module>
for r, row in enumerate(reader):
_csv.Error: field larger than field limit (131072)
Exception ignored in: <bound method Workbook.__del__ of
<xlsxwriter.workbook.Workbook object at 0x7fff4e731470>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/xlsxwriter/workbook.py", line
153, in __del__
Exception: Exception caught in workbook destructor. Explicit close() may be
required for workbook.
</code>```

答:
While using large files, it's better to use 'constant_memory' for controlled memory usage like:

```<code>workbook = Workbook(csvfile + '.xlsx', {'constant_memory': True}).
</code>```

Ref: xlsxwriter.readthedocs.org/en/latest/working_with_memory.html

ContentLicense: CC BY-SA 4.0

Body:
this is my code covert CSV file to .xlsx file, for small size CSV file this code is working fine, but when I tried for larger size CSV files, Its shows an error.

import os
import glob
import csv
from xlsxwriter.workbook import Workbook

for csvfile in glob.glob(os.path.join('.', 'file.csv')):
    workbook = Workbook(csvfile[:-4] + '.xlsx')
    worksheet = workbook.add_worksheet()
    with open(csvfile, 'r', encoding='utf8') as f:
        reader = csv.reader(f)
        for r, row in enumerate(reader):
            for c, col in enumerate(row):
                worksheet.write(r, c, col)
    workbook.close()

the error is

File "CsvToExcel.py", line 12, in <module>
for r, row in enumerate(reader):
_csv.Error: field larger than field limit (131072)
Exception ignored in: <bound method Workbook.__del__ of
<xlsxwriter.workbook.Workbook object at 0x7fff4e731470>>
Traceback (most recent call last):
File "/usr/local/lib/python3.5/dist-packages/xlsxwriter/workbook.py", line
153, in __del__
Exception: Exception caught in workbook destructor. Explicit close() may be
required for workbook.

Body:
While using large files, it's better to use 'constant_memory' for controlled memory usage like:

workbook = Workbook(csvfile + '.xlsx', {'constant_memory': True}).

Ref: xlsxwriter.readthedocs.org/en/latest/working_with_memory.html

ContentLicense: CC BY-SA 3.0


问:
Putting footer at the bottom
I am currently making an app. However, my footer is directly below the button. I would like my footer to be at the bottom of the app instead. I will attach a link to the picture of how it is looking like right now.

```<code><body>
    <div data-role="page" id="mainpage">
        <div data-role="header" class="header" data-position="fixed">
            <a href="index.html" class="ui-btn ui-icon-home ui-btn-icon-left">Home</a>
            <h1><b>Converter App</b></h1>
        </div>

        <div class="app">
            <a href="converter.html" class="ui-btn">Converter</a>
        </div>

        <footer data-role="footer">
            <h4>Copyright 2017</h4>
        </footer>
    </div>
    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="scripts/platformOverrides.js"></script>
    <script type="text/javascript" src="scripts/index.js"></script>
</body>
</code>```

I have added the CSS below as requested.

```<code>.ui-header-fixed,
.ui-footer-fixed {
    left: 0;
    right: 0;
    width: 100%;
    position: fixed;
    z-index: 1000;
}
</code>```

https://imgur.com/a/ECjxq

答:
What you want is to first specify a minimum height of the app container like body, #main-page { min-height: 100vh; }

then stick the footer in the bottom

body, #mainpage {
  min-height: 100vh;
  position: relative;
}

.ui-header-fixed,
.ui-footer-fixed {
  left: 0;
  right: 0;
  width: 100%;
  position: fixed;
  z-index: 1000;
}

.ui-footer-fixed {
  bottom: 0;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-role="page" id="mainpage">
  <div data-role="header" class="header" data-position="fixed">
    Home
    <h1><b>Converter App</b></h1>
  </div>

  <div class="app">
    Converter
  </div>

  <footer data-role="footer" class="ui-footer-fixed">
    <h4>Copyright 2017</h4>
  </footer>
</div></code>```

You may also want to slightly modify the html structure in order to make your footer always visible.

Title: Putting footer at the bottom

Body:
I am currently making an app. However, my footer is directly below the button. I would like my footer to be at the bottom of the app instead. I will attach a link to the picture of how it is looking like right now.

            Home

Converter App

            Converter

Copyright 2017

I have added the CSS below as requested.

.ui-header-fixed,
.ui-footer-fixed {
    left: 0;
    right: 0;
    width: 100%;
    position: fixed;
    z-index: 1000;
}

https://imgur.com/a/ECjxq

Body:
What you want is to first specify a minimum height of the app container like body, #main-page { min-height: 100vh; }

then stick the footer in the bottom

body, #mainpage {
  min-height: 100vh;
  position: relative;
}

.ui-header-fixed,
.ui-footer-fixed {
  left: 0;
  right: 0;
  width: 100%;
  position: fixed;
  z-index: 1000;
}

.ui-footer-fixed {
  bottom: 0;
}

<div data-role="page" id="mainpage">
  <div data-role="header" class="header" data-position="fixed">
    <a href="index.html" class="ui-btn ui-icon-home ui-btn-icon-left">Home</a>
    <h1><b>Converter App</b></h1>
  </div>

  <div class="app">
    <a href="converter.html" class="ui-btn">Converter</a>
  </div>

  <footer data-role="footer" class="ui-footer-fixed">
    <h4>Copyright 2017</h4>
  </footer>
</div>

You may also want to slightly modify the html structure in order to make your footer always visible.


问:
Match textcase javascript
I want to match the case of a string to that of an example string.
For example.

```<code>var str = "hello world"
var example1 = "My Text Is Great"
var example2 = "my Text Is Great"
var example3 = "My text is great"
answer1 = someGreatFunction(str,example1)//should return Hello World
answer2 = someGreatFunction(str,example2)//should return hello World
answer3 = someGreatFunction(str,example3)//should return Hello world
</code>```

I hope this helps you understand what I want.
I don't want to worry about quotation marks or any form of punctuation.
But if it includes a support for that it will be great.

P.S. I haven't tried doing anything till now because I am clueless.

P.S. If you think this question is duplicate please don't mark it so. Maybe I had already looked through the solutions but didn't found anything satisfying.

答:
You can use the following approach

Get an array of lowerCase and upperCase indicators first

Example

```<code>"My Text Is Great".split(" ").map( s => s.toLowerCase() == s ? "L" : "U" )
</code>```

Use the flags at their specific indices to convert them to appropriate case.

Example

```<code>"hello world".split(/\s/).map((s, i) => (indicators[i] == "U" ? s.charAt(0).toUpperCase() : s.charAt(0).toLowerCase() ) + s.substring(1) ).join(" ");
</code>```

Demo

function matchCase(input, master) {
  var indicators = master.split(" ").map(s => s.toLowerCase() == s ? "L" : "U");
  return input.split(/\s/).map((s, i) => (indicators[i] == "U" ? s.charAt(0).toUpperCase() : s.charAt(0).toLowerCase() ) + s.substring(1) ).join(" ");
}

var example1 = "My Text Is Great"
var example2 = "my Text Is Great"
var example3 = "My text is great"

console.log( matchCase( "hello world", example1 ) );
console.log( matchCase( "hello world", example2 ) );
console.log( matchCase( "hello world", example3 ) );```

Title: Match textcase javascript

Body:
I want to match the case of a string to that of an example string.
For example.

var str = "hello world"
var example1 = "My Text Is Great"
var example2 = "my Text Is Great"
var example3 = "My text is great"
answer1 = someGreatFunction(str,example1)//should return Hello World
answer2 = someGreatFunction(str,example2)//should return hello World
answer3 = someGreatFunction(str,example3)//should return Hello world

I hope this helps you understand what I want.
I don't want to worry about quotation marks or any form of punctuation.
But if it includes a support for that it will be great.

P.S. I haven't tried doing anything till now because I am clueless.

P.S. If you think this question is duplicate please don't mark it so. Maybe I had already looked through the solutions but didn't found anything satisfying.

Body:
You can use the following approach

Get an array of lowerCase and upperCase indicators first

Example

"My Text Is Great".split(" ").map( s => s.toLowerCase() == s ? "L" : "U" )

Use the flags at their specific indices to convert them to appropriate case.

Example

"hello world".split(/\s/).map((s, i) => (indicators[i] == "U" ? s.charAt(0).toUpperCase() : s.charAt(0).toLowerCase() ) + s.substring(1) ).join(" ");

Demo

function matchCase(input, master) {
  var indicators = master.split(" ").map(s => s.toLowerCase() == s ? "L" : "U");
  return input.split(/\s/).map((s, i) => (indicators[i] == "U" ? s.charAt(0).toUpperCase() : s.charAt(0).toLowerCase() ) + s.substring(1) ).join(" ");
}

var example1 = "My Text Is Great"
var example2 = "my Text Is Great"
var example3 = "My text is great"

console.log( matchCase( "hello world", example1 ) );
console.log( matchCase( "hello world", example2 ) );
console.log( matchCase( "hello world", example3 ) );


问:
How to check what is the latest version of a dependency to use in gradle
I've always added dependencies like this:

```<code>dependencies {
    compile 'com.android.support:mediarouter-v7:19.+'
}
</code>```

but in the recent versions of Android Studio, they recommend not to use the + as it can lead to errors. How to know what's the latest version? I can try every combination of 19.y.x until gradle complains, but what's the real way do check?

edit: sometimes, that page helps me figure it out.

答:
Recently, I have found this.

Go to File -> Project Structure

Select the Module, where you want to add the dependency.

Go to the Dependencies Tab

Click + and Choose Library Dependency

Choose whichever Library you need from the list.

(There is also an option for Search, never tried though.)

That's it.

Done.

Thank You.

Body:
I've always added dependencies like this:

dependencies {
    compile 'com.android.support:mediarouter-v7:19.+'
}

but in the recent versions of Android Studio, they recommend not to use the + as it can lead to errors. How to know what's the latest version? I can try every combination of 19.y.x until gradle complains, but what's the real way do check?

edit: sometimes, that page helps me figure it out.


问:
How to use ajax in reactjs on localhost
Below is my code:
While using local url I am getting the error

"Failed to load http://localhost/reactjs/my-app/lib/ajax.php: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access"

But when I used live url such as "https://jsonplaceholder.typicode.com/todos" its working fine.

```<code>$.ajax({
url: 'http://localhost/reactjs/lib/ajax.php',
//url: 'https://jsonplaceholder.typicode.com/todos',
 type: 'GET',
dataType: 'jsonp',
//contentType: "application/json; charset=utf-8",
//jsonp: "json_callback",
crossOrigin: true,
//cors: true,
//data: {user_name:username, user_type: usertype, password: password,mode: 'Login' },
success: function(data){
alert(data);
},
error: function(error){
console.log(error);
 }
});
</code>```

答:
Add this on php side :

```<code>header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");
</code>```

And this url http://localhost/reactjs/my-app/lib/ajax.php should be http://localhost/reactjs/lib/ajax.php

Title: How to use ajax in reactjs on localhost

Body:
Below is my code:
While using local url I am getting the error

"Failed to load http://localhost/reactjs/my-app/lib/ajax.php: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access"

But when I used live url such as "https://jsonplaceholder.typicode.com/todos" its working fine.

$.ajax({
url: 'http://localhost/reactjs/lib/ajax.php',
//url: 'https://jsonplaceholder.typicode.com/todos',
 type: 'GET',
dataType: 'jsonp',
//contentType: "application/json; charset=utf-8",
//jsonp: "json_callback",
crossOrigin: true,
//cors: true,
//data: {user_name:username, user_type: usertype, password: password,mode: 'Login' },
success: function(data){
alert(data);
},
error: function(error){
console.log(error);
 }
});

Body:
Add this on php side :

header('Access-Control-Allow-Origin: *');

header('Access-Control-Allow-Methods: GET, POST');

header("Access-Control-Allow-Headers: X-Requested-With");

And this url http://localhost/reactjs/my-app/lib/ajax.php should be http://localhost/reactjs/lib/ajax.php


问:
opencv cascade.detectMultiScale creates error: (-215) !empty()
I am following this tutorial to understand haar features. While writing following code:

```<code>import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('Sachin.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
</code>```

getting following error:

```<code>File "<ipython-input-6-0b479e459b0f>", line 1, in <module>
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    error: /home/travis/miniconda/conda-bld/conda_1486587069159/work/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale
</code>```

(Sachin is the image i downloaded from google, of size (237,237,3) and after converting gray it is (237,237) with min=23, max=210. I am using opencv 3.1.0 with python 3.6, installed using command conda install -c menpo opencv3. i am trying for this solution but unable to find xml file in my desktop. How to solve problem.

答:
You need to specify the full paths to the XML files for Haar Cascade.

On Ubuntu 16.04, these files can be found in /usr/share/opencv/haarcascades.

Body:
I am following this tutorial to understand haar features. While writing following code:

import numpy as np
import cv2
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eye_cascade = cv2.CascadeClassifier('haarcascade_eye.xml')
img = cv2.imread('Sachin.jpeg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)

getting following error:

File "<ipython-input-6-0b479e459b0f>", line 1, in <module>
    faces = face_cascade.detectMultiScale(gray, 1.3, 5)

    error: /home/travis/miniconda/conda-bld/conda_1486587069159/work/opencv-3.1.0/modules/objdetect/src/cascadedetect.cpp:1639: error: (-215) !empty() in function detectMultiScale

(Sachin is the image i downloaded from google, of size (237,237,3) and after converting gray it is (237,237) with min=23, max=210. I am using opencv 3.1.0 with python 3.6, installed using command conda install -c menpo opencv3. i am trying for this solution but unable to find xml file in my desktop. How to solve problem.


问:
Using email address from external HTML file to send email via google apps script
I'm creating a function within Google Apps whereby I need to email the spreadsheet I am working on as a PDF. The user should click on a button and a dialogue box should open whereby they can enter email address, subject and message and send the email from there.

I've created the email dialogue as a sidebar with the following HTML:

```<code><!DOCTYPE html>
<html>
    <head>
       <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
       <base target="_top">
    </head>
    <body>
       <form>
         <div class="form-group">
           <label for="exampleInputEmail1">Email address</label>
           <input type="email" class="form-control" id="exampleInputEmail1" ar.  ia-describedby="emailHelp" value="d.bage@group-miki.com">
         </div>
         <div class="form-group">
            <label for="subject">Subject</label>
            <input type="input" class="form-control" id="subject" value="Contract    renewal - Miki Travel">
         </div>
         <div class="form-group">
             <label for="subject">Message</label>
             <textarea class="form-control" rows="12" id="text"></textarea>
         </div>

         <button type="submit" class="btn btn-primary">Submit</button>
       </form>
    </body>
</html>
</code>```

However, when I'm writing the script to send the email, how do I store the content of the email box here as variable to use for sending the email? The same will apply obviously to the subject and the message itself.

答:
You can send pdf but Google App script does support below extension file
.xls and .xlsx  in mail service of google API through google app script its only supports pdf and image format attach file
go through this link u will get more info regrading this

https://developers.google.com/apps-script/reference/base/blob#getAs(String)

if u still try to attach .xlsx and .xls file it through an error its does not support
i already faced this issue but u can download as xlsx format through javascript.

Body:
I'm creating a function within Google Apps whereby I need to email the spreadsheet I am working on as a PDF. The user should click on a button and a dialogue box should open whereby they can enter email address, subject and message and send the email from there.

I've created the email dialogue as a sidebar with the following HTML:

<!DOCTYPE html>

       <link rel = "stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.2/css/bootstrap.min.css">
       <base target="_top">

       <form>

           Email address
           <input type="email" class="form-control" id="exampleInputEmail1" ar.  ia-describedby="emailHelp" value="d.bage@group-miki.com">

            Subject
            <input type="input" class="form-control" id="subject" value="Contract    renewal - Miki Travel">

             Message
             <textarea class="form-control" rows="12" id="text"></textarea>

         <button type="submit" class="btn btn-primary">Submit</button>
       </form>

However, when I'm writing the script to send the email, how do I store the content of the email box here as variable to use for sending the email? The same will apply obviously to the subject and the message itself.


问:
How to perform segue from inside UIView
How can a prepare a segue properly from inside a UIView NOT UIViewController

My UIViewController has a container view and inside that container view has a button.

```<code>class myInnerView: UIView {
    ...
    func myButton(gesture: UIGestureRecognizer){
        //calling a perform segue from another UIViewController does not recognize the SegueID
        //ViewController().self.showProfile(self.id) -- DOES NOT WORK
    }
}

class ViewController: UIViewController {
    ...
    func showProfile(id: String){
        ...
        self.performSegueWithIdentifier("toViewProfile", sender: self)
    }
}
</code>```

答:
You need to tap gesture for view to navigate</p>

```<code>let customView = myInnerView()
let gestureRec = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
myView.addGestureRecognizer(customView)

func someAction(_ sender:UITapGestureRecognizer){
    let controller = storyboard?.instantiateViewController(withIdentifier: "someViewController")
    self.present(controller!, animated: true, completion: nil)
    // swift 2
    // self.presentViewController(controller, animated: true, completion: nil)
}
</code>```

Title: How to perform segue from inside UIView

Body:
How can a prepare a segue properly from inside a UIView NOT UIViewController

My UIViewController has a container view and inside that container view has a button.

class myInnerView: UIView {
    ...
    func myButton(gesture: UIGestureRecognizer){
        //calling a perform segue from another UIViewController does not recognize the SegueID
        //ViewController().self.showProfile(self.id) -- DOES NOT WORK
    }
}

class ViewController: UIViewController {
    ...
    func showProfile(id: String){
        ...
        self.performSegueWithIdentifier("toViewProfile", sender: self)
    }
}

Body:
You need to tap gesture for view to navigate

let customView = myInnerView()
let gestureRec = UITapGestureRecognizer(target: self, action:  #selector (self.someAction (_:)))
myView.addGestureRecognizer(customView)

func someAction(_ sender:UITapGestureRecognizer){
    let controller = storyboard?.instantiateViewController(withIdentifier: "someViewController")
    self.present(controller!, animated: true, completion: nil)
    // swift 2
    // self.presentViewController(controller, animated: true, completion: nil)
}


问:
Terminating app due to uncaught exception 'NSGenericException', reason: '*** Collection <__NSArrayM: 0x117540> was mutated while being enumerated
Im gettin the  "Collection was mutates while beign enumerated" exception when my code is like this as follows:

```<code>NSString *poiStr = nil;
    int SuccessValue=0;
    NSMutableArray* poisArray=[[NSMutableArray alloc]init];
    for (id<MKAnnotation> annotation in mainMapView.annotations)
    {
        MKAnnotationView* anView = [mainMapView viewForAnnotation: annotation];
        if(anView)
        {

            POI* locationPOI = (POI*)[anView annotation];
            printf("\n Location poi shape groupId:%s=====%s",[locationPOI.shapeSpaceGroupId UTF8String],[poiStr UTF8String]);
            if((poiStr == nil) || ([poiStr isEqualToString:locationPOI.shapeSpaceGroupId]))
            {

                poiStr = locationPOI.shapeSpaceGroupId;
                [poisArray addObject:locationPOI];
                SuccessValue++;
            }
            printf("\n successValue:%d",SuccessValue);
            if(SuccessValue==2)
            {
                POI* poi=[poisArray objectAtIndex:0];
                [mainMapView removeAnnotation:poi];
                SuccessValue--;
            }

        }

    }
</code>```

Can anyone please suggest me what's the wrong in the code and how to solve the issues.

Thanks to all,
Madan.

答:
Basically you are modifying the list in the loop you are iterating over it. The line that causes the problem is:

```<code>[mainMapView removeAnnotation:poi];
</code>```

as you are iterating over mainMapView.annotations. A possible solution is to accumulate the elements you want to delete in a different list and remove them after the loop.

Based on your code, a possible solution would be:

```<code>     NSString *poiStr = nil;
    int SuccessValue=0;
    NSMutableArray* poisArray=[[NSMutableArray alloc]init];
    NSMutableArray *to_delete = [[NSMutableArray alloc] init];
    for (id<MKAnnotation> annotation in mainMapView.annotations)
    {
        MKAnnotationView* anView = [mainMapView viewForAnnotation: annotation];
        if(anView)
        {

            POI* locationPOI = (POI*)[anView annotation];
            printf("\n Location poi shape groupId:%s=====%s",[locationPOI.shapeSpaceGroupId UTF8String],[poiStr UTF8String]);
            if((poiStr == nil) || ([poiStr isEqualToString:locationPOI.shapeSpaceGroupId]))
            {

                poiStr = locationPOI.shapeSpaceGroupId;
                [poisArray addObject:locationPOI];
                SuccessValue++;
            }
            printf("\n successValue:%d",SuccessValue);
            if(SuccessValue==2)
            {
                POI* poi=[poisArray objectAtIndex:0];
                //[mainMapView removeAnnotation:poi];
                [to_delete addObject:poi];
                SuccessValue--;
            }

        }

    }
    for (id<MKAnnotation> annotation in to_delete)
           [mainMapView removeAnnotation:poi];

    [to_delete release];
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Im gettin the  "Collection was mutates while beign enumerated" exception when my code is like this as follows:

NSString *poiStr = nil;
    int SuccessValue=0;
    NSMutableArray* poisArray=[[NSMutableArray alloc]init];
    for (id<MKAnnotation> annotation in mainMapView.annotations)
    {
        MKAnnotationView* anView = [mainMapView viewForAnnotation: annotation];
        if(anView)
        {

            POI* locationPOI = (POI*)[anView annotation];
            printf("\n Location poi shape groupId:%s=====%s",[locationPOI.shapeSpaceGroupId UTF8String],[poiStr UTF8String]);
            if((poiStr == nil) || ([poiStr isEqualToString:locationPOI.shapeSpaceGroupId]))
            {

                poiStr = locationPOI.shapeSpaceGroupId;
                [poisArray addObject:locationPOI];
                SuccessValue++;
            }
            printf("\n successValue:%d",SuccessValue);
            if(SuccessValue==2)
            {
                POI* poi=[poisArray objectAtIndex:0];
                [mainMapView removeAnnotation:poi];
                SuccessValue--;
            }

        }

    }

Can anyone please suggest me what's the wrong in the code and how to solve the issues.

Thanks to all,
Madan.

Body:
Basically you are modifying the list in the loop you are iterating over it. The line that causes the problem is:

[mainMapView removeAnnotation:poi];

as you are iterating over mainMapView.annotations. A possible solution is to accumulate the elements you want to delete in a different list and remove them after the loop.

Based on your code, a possible solution would be:

     NSString *poiStr = nil;
    int SuccessValue=0;
    NSMutableArray* poisArray=[[NSMutableArray alloc]init];
    NSMutableArray *to_delete = [[NSMutableArray alloc] init];
    for (id<MKAnnotation> annotation in mainMapView.annotations)
    {
        MKAnnotationView* anView = [mainMapView viewForAnnotation: annotation];
        if(anView)
        {

            POI* locationPOI = (POI*)[anView annotation];
            printf("\n Location poi shape groupId:%s=====%s",[locationPOI.shapeSpaceGroupId UTF8String],[poiStr UTF8String]);
            if((poiStr == nil) || ([poiStr isEqualToString:locationPOI.shapeSpaceGroupId]))
            {

                poiStr = locationPOI.shapeSpaceGroupId;
                [poisArray addObject:locationPOI];
                SuccessValue++;
            }
            printf("\n successValue:%d",SuccessValue);
            if(SuccessValue==2)
            {
                POI* poi=[poisArray objectAtIndex:0];
                //[mainMapView removeAnnotation:poi];
                [to_delete addObject:poi];
                SuccessValue--;
            }

        }

    }
    for (id<MKAnnotation> annotation in to_delete)
           [mainMapView removeAnnotation:poi];

    [to_delete release];


问:
Graphviz (4net) to DOT conversion
I have the following code (converted from C# using graphviz4net):

```<code>digraph g {
graph [rankdir="LR" ,compound="true" ];
    subgraph cluster0 {
        graph [label="Ready" ];
        1 [  ];
    };
    subgraph cluster2 {
        graph [label="Paused" ];
        3 [  ];
    };
    1 -> 3 [ ltail="cluster0" ,lhead="cluster2" ,comment="4"  ];
    3 -> 1 [ ltail="cluster2" ,lhead="cluster0" ,comment="5"  ];
}
</code>```

I'm checking the converted image on http://www.graphviz-dev.appspot.com/.

The image is like this:

I'm programming in C#. I have 2 questions:

1 - How to fix the arrows in C#?

2 - How to make the ellipses disapear in C#?

*I know I can use node [shape = none], but I don't know how to set it in C#.

UPDATE:

Now I've got the following code:

```<code>digraph g {
graph [rankdir="LR" ,compound="true" ];
    subgraph cluster0 {
        graph [label="Ready\n\nPurchaser:\noperation1,operation2,Supplier:\noperation1,operation3," ];
        1 [ shape="none" ,fontcolor="white"  ];
    };
    subgraph cluster2 {
        graph [label="Paused\n\nPurchaser:\noperation1,operation3,Supplier:\noperation2,operation3," ];
        3 [ shape="none" ,fontcolor="white"  ];
    };
    subgraph cluster4 {
        graph [label="Completed\n\nPurchaser:\noperation4,Supplier:\noperation4," ];
        5 [ shape="none" ,fontcolor="white"  ];
    };
    1 -> 3 [ ltail="cluster0" ,lhead="cluster2" ,comment="6"  ];
    1 -> 5 [ ltail="cluster0" ,lhead="cluster4" ,comment="7"  ];
    3 -> 1 [ ltail="cluster2" ,lhead="cluster0" ,comment="8"  ];
    3 -> 5 [ ltail="cluster2" ,lhead="cluster4" ,comment="9"  ];
}
</code>```

Which gives me:

Don't worry about the label problems, I'll fix that.

The C# code is as it follows:

```<code>Graph<State> Graph = new Graph<State> { Rankdir = RankDirection.LeftToRight };
</code>```

A stringBuilder generates the subgraphs

```<code>// returns new SubGraph<State>{ Label = stringBuilder.ToString()};
var stringNewBlock = ConvertBlockToSubgraph(state);
</code>```

Inside ConvertBlockToSubgraph

```<code>foreach (var allowedOperation in allowedOperationList)
            {
                stringBuilder.Append(allowedOperation.Key +":\\n");

                foreach (var operation in allowedOperation.Value)
                {
                    stringBuilder.Append(!operation.Equals(lastAllowedOperation) ? operation + ",": operation);
                }
            }
</code>```

Back to outside world:

```<code>var subgraphNewBlock = new SubGraph<State>{ Label = stringBuilder.ToString()};

stringNewBlock.AddVertex(state);
Graph.AddSubGraph(stringNewBlock);
</code>```

Then I generate the Edges with:

```<code>public override IBlockHandling<State> GenerateLinks()
{
    foreach (var state in statesDictionary.Values)
    {
        foreach (var nextPossibleState in state.GetNextPossibleStateList())
        {
            if (statesDictionary.ContainsKey(nextPossibleState))
            {
                var sourceSubGraph = Graph.SubGraphs.Single(x => x.Label.Contains(state.GetMainHeaderName()));
                var destinationSubGraph = Graph.SubGraphs.Single(x => x.Label.Contains(nextPossibleState));
                var edge = new Edge<SubGraph<State>>(sourceSubGraph, destinationSubGraph);
                Graph.AddEdge(edge);
            }

        }
    }

    return this;
}
</code>```

Then I convert to the DOT Format with:

```<code>    public override IBlockHandling<State> ConvertDtoToDot()
    {
        var writer = new StringWriter();
        new GraphToDotConverter().Convert(writer, Graph, new AttributesProvider());
        var result = writer.GetStringBuilder().ToString().Trim();

        Console.WriteLine(result);

        return this;
    }
</code>```

The problem I still have are the arrows looking weird.

Any suggestions?

答:
If your problem is in the arrows shape, please see the below code:

```<code>var edge = new Edge<SubGraph<State>>(sourceSubGraph, destinationSubGraph ,
     new Arrow(),  new DiamondArrow());
</code>```

For more info please check the below :

Graphviz4Net

Title: Graphviz (4net) to DOT conversion

Body:
I have the following code (converted from C# using graphviz4net):

digraph g {
graph [rankdir="LR" ,compound="true" ];
    subgraph cluster0 {
        graph [label="Ready" ];
        1 [  ];
    };
    subgraph cluster2 {
        graph [label="Paused" ];
        3 [  ];
    };
    1 -> 3 [ ltail="cluster0" ,lhead="cluster2" ,comment="4"  ];
    3 -> 1 [ ltail="cluster2" ,lhead="cluster0" ,comment="5"  ];
}

I'm checking the converted image on http://www.graphviz-dev.appspot.com/.

The image is like this:

I'm programming in C#. I have 2 questions:

1 - How to fix the arrows in C#?

2 - How to make the ellipses disapear in C#?

*I know I can use node [shape = none], but I don't know how to set it in C#.

UPDATE:

Now I've got the following code:

digraph g {
graph [rankdir="LR" ,compound="true" ];
    subgraph cluster0 {
        graph [label="Ready\n\nPurchaser:\noperation1,operation2,Supplier:\noperation1,operation3," ];
        1 [ shape="none" ,fontcolor="white"  ];
    };
    subgraph cluster2 {
        graph [label="Paused\n\nPurchaser:\noperation1,operation3,Supplier:\noperation2,operation3," ];
        3 [ shape="none" ,fontcolor="white"  ];
    };
    subgraph cluster4 {
        graph [label="Completed\n\nPurchaser:\noperation4,Supplier:\noperation4," ];
        5 [ shape="none" ,fontcolor="white"  ];
    };
    1 -> 3 [ ltail="cluster0" ,lhead="cluster2" ,comment="6"  ];
    1 -> 5 [ ltail="cluster0" ,lhead="cluster4" ,comment="7"  ];
    3 -> 1 [ ltail="cluster2" ,lhead="cluster0" ,comment="8"  ];
    3 -> 5 [ ltail="cluster2" ,lhead="cluster4" ,comment="9"  ];
}

Which gives me:

Don't worry about the label problems, I'll fix that.

The C# code is as it follows:

Graph<State> Graph = new Graph<State> { Rankdir = RankDirection.LeftToRight };

A stringBuilder generates the subgraphs

// returns new SubGraph<State>{ Label = stringBuilder.ToString()};
var stringNewBlock = ConvertBlockToSubgraph(state);

Inside ConvertBlockToSubgraph

foreach (var allowedOperation in allowedOperationList)
            {
                stringBuilder.Append(allowedOperation.Key +":\\n");

                foreach (var operation in allowedOperation.Value)
                {
                    stringBuilder.Append(!operation.Equals(lastAllowedOperation) ? operation + ",": operation);
                }
            }

Back to outside world:

var subgraphNewBlock = new SubGraph<State>{ Label = stringBuilder.ToString()};

stringNewBlock.AddVertex(state);
Graph.AddSubGraph(stringNewBlock);

Then I generate the Edges with:

public override IBlockHandling<State> GenerateLinks()
{
    foreach (var state in statesDictionary.Values)
    {
        foreach (var nextPossibleState in state.GetNextPossibleStateList())
        {
            if (statesDictionary.ContainsKey(nextPossibleState))
            {
                var sourceSubGraph = Graph.SubGraphs.Single(x => x.Label.Contains(state.GetMainHeaderName()));
                var destinationSubGraph = Graph.SubGraphs.Single(x => x.Label.Contains(nextPossibleState));
                var edge = new Edge<SubGraph<State>>(sourceSubGraph, destinationSubGraph);
                Graph.AddEdge(edge);
            }

        }
    }

    return this;
}

Then I convert to the DOT Format with:

    public override IBlockHandling<State> ConvertDtoToDot()
    {
        var writer = new StringWriter();
        new GraphToDotConverter().Convert(writer, Graph, new AttributesProvider());
        var result = writer.GetStringBuilder().ToString().Trim();

        Console.WriteLine(result);

        return this;
    }

The problem I still have are the arrows looking weird.

Any suggestions?

Body:
If your problem is in the arrows shape, please see the below code:

var edge = new Edge<SubGraph<State>>(sourceSubGraph, destinationSubGraph ,
     new Arrow(),  new DiamondArrow());

For more info please check the below :

Graphviz4Net


问:
NFC tag v1.0 & arduino UNO
My teacher just gave me a NFC tag v1.0 for a project. I have to use my phone to unlock a door.

I searched on internet and I just found this code:

```<code>#include "NfcTag.h"
#include <Wire.h>

NfcTag nfcTag;
int led = 5;
bool flag = false;
bool preFlag = false;
void setup(){
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  nfcTag.init();
}

void loop(){
  flag = nfcTag.readByte(EEPROM_I2C_LENGTH-1) == 0xff?true:false;
  if(flag != preFlag){
    Serial.println("get remote NFC control signal!");
    if(flag == true){
      Serial.println("led will light up!");
      digitalWrite(led,HIGH);
    }else{
      Serial.println("led will turn dark!");
      digitalWrite(led,LOW);
    }
    preFlag = flag;
  }
  delay(5*1000);
}
</code>```

This come from their wiki: http://wiki.seeed.cc/Grove-NFC_Tag/

I can connect with the phone and use it to change blocks. The problem is that when I try it, the LED just doesn't work at all. I tried the LED and he is working, I also tried the Digital pin on the Arduino UNO with the LED and it works as well. Also, the monitor doesn't show any off those printLn.

I used this way to connect them:

SCL - RX

SDA - TX

GND - GND

5V - VCC

I also used a code to debug, but no matter what address I use to readByte, I will always get the number 127 even after using the phone to change it with the app.

```<code>#include "NfcTag.h"
#include <Wire.h>

NfcTag nfcTag;
bool flag = false;
bool preFlag = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("starting sequence");
  nfcTag.init();
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("checking for nfc");
  //flag = nfcTag.readByte(EEPROM_I2C_LENGTH-1) == 0xff?true:false;
  //Serial1.println(flag);
  Serial.println(nfcTag.getICNumber());
  Serial.println(nfcTag.getAFI());
  Serial.println(nfcTag.getRFU());
  Serial.println(nfcTag.getMemoryVolume());
  Serial.println("result:");
  Serial.println(nfcTag.readByte(EEPROM_I2C_LENGTH-1)); //I tried changeing manualy the value, but the output still 127.

  delay(2000);

}
</code>```

Output:

```<code>checking for nfc
127
127
32639
8355711
result:
127
</code>```

If I could put the LED working, I have already a transistor with a power converter on the exit of the pin5, so the door can be unlocked.

By the way, I don't know why sometimes the NFC doesn't work and after some tries it start working again.

Any help will be appreciate :) Thanks.

答:
The correct connection for the I2C pins is:

SCL - PC5 (Analog A5)

SDA - PC4 (Analog A4)

This part supports Uart communications as you wired it. The link you provided for the part you are using only support I2C and will not work as you wired it.

Title: NFC tag v1.0 & arduino UNO

Body:
My teacher just gave me a NFC tag v1.0 for a project. I have to use my phone to unlock a door.

I searched on internet and I just found this code:

#include "NfcTag.h"
#include <Wire.h>

NfcTag nfcTag;
int led = 5;
bool flag = false;
bool preFlag = false;
void setup(){
  Serial.begin(9600);
  pinMode(led,OUTPUT);
  nfcTag.init();
}

void loop(){
  flag = nfcTag.readByte(EEPROM_I2C_LENGTH-1) == 0xff?true:false;
  if(flag != preFlag){
    Serial.println("get remote NFC control signal!");
    if(flag == true){
      Serial.println("led will light up!");
      digitalWrite(led,HIGH);
    }else{
      Serial.println("led will turn dark!");
      digitalWrite(led,LOW);
    }
    preFlag = flag;
  }
  delay(5*1000);
}

This come from their wiki: http://wiki.seeed.cc/Grove-NFC_Tag/

I can connect with the phone and use it to change blocks. The problem is that when I try it, the LED just doesn't work at all. I tried the LED and he is working, I also tried the Digital pin on the Arduino UNO with the LED and it works as well. Also, the monitor doesn't show any off those printLn.

I used this way to connect them:

SCL - RX

SDA - TX

GND - GND

5V - VCC

I also used a code to debug, but no matter what address I use to readByte, I will always get the number 127 even after using the phone to change it with the app.

#include "NfcTag.h"
#include <Wire.h>

NfcTag nfcTag;
bool flag = false;
bool preFlag = false;

void setup() {
  // put your setup code here, to run once:
  Serial.begin(115200);
  Serial.println("starting sequence");
  nfcTag.init();
}

void loop() {
  // put your main code here, to run repeatedly:
  Serial.println("checking for nfc");
  //flag = nfcTag.readByte(EEPROM_I2C_LENGTH-1) == 0xff?true:false;
  //Serial1.println(flag);
  Serial.println(nfcTag.getICNumber());
  Serial.println(nfcTag.getAFI());
  Serial.println(nfcTag.getRFU());
  Serial.println(nfcTag.getMemoryVolume());
  Serial.println("result:");
  Serial.println(nfcTag.readByte(EEPROM_I2C_LENGTH-1)); //I tried changeing manualy the value, but the output still 127.

  delay(2000);

}

Output:

checking for nfc
127
127
32639
8355711
result:
127

If I could put the LED working, I have already a transistor with a power converter on the exit of the pin5, so the door can be unlocked.

By the way, I don't know why sometimes the NFC doesn't work and after some tries it start working again.

Any help will be appreciate :) Thanks.


问:
date value is converted from dd-mm-yyyy to dd/mm/yyyy while converting excel to html using aspose.cells for java
I have a cell in excel formatted as date with value '31-03-2017' but when I am exporting the excel to html it is getting converted to '31/03/2017'.

'03-31-2017' again a date formatted cell but coming up as expected, if I have to speculate looks like there is a problem with dd-MM-yyyy format.

I am using "aspose-cells-8.7.0" library.

Any help is highly appreciated.

Code snippet

```<code>Workbook workbook = new Workbook(new FileInputStream(new File("filePath")));
workbook.calculateFormula();
HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
htmlSaveOptions.setPresentationPreference(true);
htmlSaveOptions.setParseHtmlTagInCell(false);
htmlSaveOptions.setExportHiddenWorksheet(false);
workbook.save("outputPath", htmlSaveOptions);
</code>```

答:
Such issue occurs because of Language and Region Settings of your machine i.e. OS (Operating System). Please see the following screenshot. You can change your region and country and number and date formats from such interfaces.

Now, whenever you will change your region or language, your dates will look different because your dates are in built-in formats and they don't have custom formats.

In order to test this, please change the region and open your Excel file in Microsoft Excel and you will see, your dates now look different.

It means, you should load your workbook with the correct region and language settings. Here is the sample code for your reference. Please read its comments.

Java

```<code>//Please load your workbook with correct Language and Region - Country Code
LoadOptions loadOptions = new LoadOptions();
loadOptions.setLanguageCode(CountryCode.USA);
loadOptions.setRegion(CountryCode.USA);

//Pass the load options while loading workbook
Workbook workbook = new Workbook(new FileInputStream(new File("filePath")), loadOptions);
</code>```

Note: I am working as Developer Evangelist at Aspose

Body:
I have a cell in excel formatted as date with value '31-03-2017' but when I am exporting the excel to html it is getting converted to '31/03/2017'.

'03-31-2017' again a date formatted cell but coming up as expected, if I have to speculate looks like there is a problem with dd-MM-yyyy format.

I am using "aspose-cells-8.7.0" library.

Any help is highly appreciated.

Code snippet

Workbook workbook = new Workbook(new FileInputStream(new File("filePath")));
workbook.calculateFormula();
HtmlSaveOptions htmlSaveOptions = new HtmlSaveOptions();
htmlSaveOptions.setPresentationPreference(true);
htmlSaveOptions.setParseHtmlTagInCell(false);
htmlSaveOptions.setExportHiddenWorksheet(false);
workbook.save("outputPath", htmlSaveOptions);

Body:
Such issue occurs because of Language and Region Settings of your machine i.e. OS (Operating System). Please see the following screenshot. You can change your region and country and number and date formats from such interfaces.

Now, whenever you will change your region or language, your dates will look different because your dates are in built-in formats and they don't have custom formats.

In order to test this, please change the region and open your Excel file in Microsoft Excel and you will see, your dates now look different.

It means, you should load your workbook with the correct region and language settings. Here is the sample code for your reference. Please read its comments.

Java

//Please load your workbook with correct Language and Region - Country Code
LoadOptions loadOptions = new LoadOptions();
loadOptions.setLanguageCode(CountryCode.USA);
loadOptions.setRegion(CountryCode.USA);

//Pass the load options while loading workbook
Workbook workbook = new Workbook(new FileInputStream(new File("filePath")), loadOptions);

Note: I am working as Developer Evangelist at Aspose


问:
how to write Couchbase`s Spatial view
could i write like this?

```<code>function (doc,meta) {

emit([[doc.range1, doc.range2],[doc.range3, doc.range4]], doc.comment);

}
</code>```

i just want to find data use two range.I found a example that is

```<code>emit([10.9, 48.4, [1000, 2000]], null);
</code>```

the range  [1000,2000] does it can filter data?

答:
supposing you have a json document shaped this way

```<code>{
  "resourceId": "3c0d9906-4e88-4b12-b96b-9d7377a503a9",
  "_type": "com.sample.model.Position",
  "updated": 1510790620782,
  "point": {
  "coordinates": [15.704621,40.2755],
 "type": "Point"
 }
}
</code>```

you can write a spatial view this way

```<code>function (doc) {
if (typeof doc.point !== 'undefined' && doc._type == "com.sample.model.Position") {
    var date = Date.parse(doc.updated) / 1000;
    emit(doc.point, doc.resourceId);
    }
}
</code>```

you can use the browser to design your docuement:
go to http://localhost:8091
enter index -> view menu
from there you can test the view with real document from your data
this create the index; to query the index you can use the geo funcions even with rest as described by

official documentation

hope it helps

Title: how to write Couchbase`s Spatial view

Body:
could i write like this?

function (doc,meta) {

emit([[doc.range1, doc.range2],[doc.range3, doc.range4]], doc.comment);

}

i just want to find data use two range.I found a example that is

emit([10.9, 48.4, [1000, 2000]], null);

the range  [1000,2000] does it can filter data?

Body:
supposing you have a json document shaped this way

{
  "resourceId": "3c0d9906-4e88-4b12-b96b-9d7377a503a9",
  "_type": "com.sample.model.Position",
  "updated": 1510790620782,
  "point": {
  "coordinates": [15.704621,40.2755],
 "type": "Point"
 }
}

you can write a spatial view this way

function (doc) {
if (typeof doc.point !== 'undefined' && doc._type == "com.sample.model.Position") {
    var date = Date.parse(doc.updated) / 1000;
    emit(doc.point, doc.resourceId);
    }
}

you can use the browser to design your docuement:
go to http://localhost:8091
enter index -> view menu
from there you can test the view with real document from your data
this create the index; to query the index you can use the geo funcions even with rest as described by

official documentation

hope it helps


答:
With

```<code>footer {
    position: fixed;
    left: 0;
    bottom: 0;
}
</code>```

you need to add

```<code>#mainpage{
height:100vh;}
</code>```

.ui-header-fixed,
.ui-footer-fixed {
left: 0;
right: 0;
width: 100%;
position: fixed;
z-index: 1000;
}
footer {
    position: fixed;
    left: 0;
    bottom: 0;
}
#mainpage{
height:100vh;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div data-role="page" id="mainpage">
        <div data-role="header" class="header" data-position="fixed">
            Home
            <h1><b>Converter App</b></h1>
        </div>

        <div class="app">
            Converter
        </div>

        <footer data-role="footer">
            <h4>Copyright 2017</h4>
        </footer>
    </div>

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="scripts/platformOverrides.js"></script>
    <script type="text/javascript" src="scripts/index.js"></script></code>```

Title: Putting footer at the bottom

Body:
I am currently making an app. However, my footer is directly below the button. I would like my footer to be at the bottom of the app instead. I will attach a link to the picture of how it is looking like right now.

            Home

Converter App

            Converter

Copyright 2017

I have added the CSS below as requested.

.ui-header-fixed,
.ui-footer-fixed {
    left: 0;
    right: 0;
    width: 100%;
    position: fixed;
    z-index: 1000;
}

https://imgur.com/a/ECjxq

Body:
With

footer {
    position: fixed;
    left: 0;
    bottom: 0;
}

you need to add

#mainpage{
height:100vh;}

.ui-header-fixed,
.ui-footer-fixed {
left: 0;
right: 0;
width: 100%;
position: fixed;
z-index: 1000;
}
footer {
    position: fixed;
    left: 0;
    bottom: 0;
}
#mainpage{
height:100vh;}

<div data-role="page" id="mainpage">
        <div data-role="header" class="header" data-position="fixed">
            <a href="index.html" class="ui-btn ui-icon-home ui-btn-icon-left">Home</a>
            <h1><b>Converter App</b></h1>
        </div>

        <div class="app">
            <a href="converter.html" class="ui-btn">Converter</a>
        </div>

        <footer data-role="footer">
            <h4>Copyright 2017</h4>
        </footer>
    </div>

    <script type="text/javascript" src="cordova.js"></script>
    <script type="text/javascript" src="scripts/platformOverrides.js"></script>
    <script type="text/javascript" src="scripts/index.js"></script>


问:
How to filter out the elements of the List so that the List only contains elements of distinct A.getId()?
I have a List that contains some objects A with the attribute id. What I need is the list to contain only one object for an id.

```<code>public List<A> findAllA() {
    List<A> aList; // fetches the elements from db

    HashMap<Long, A> aMap = new HashMap<>();
    for (A a: aList) {
        aMap.put(a.getId(), a);
    }

    return new ArrayList<>(aMap.values());
}
</code>```

So I put my list elements in a HashMap, because a HashMap holds distinct keys. Then a new ArrayList with the values of the map is returned. This does work fine, but is there a more efficient way to achieve the result? Or at least a shorter one?

答:
Just going by your logic, you can try like this also</p>

```<code>public List<A> findAllA() {
        List<A> aList; // fetches the elements from db

        HashMap<Long, A> aMap = new HashMap<>();
        List<Long> processedList = new ArrayList<>();
        for (A a: aList) {
            if(!processedList.contains(a.getId())) {
                processedList.add(a.getId());
                aMap.put(a.getId(), a);
            }
        }

        return new ArrayList<>(aMap.values());
    }
</code>```

Title: How to filter out the elements of the List<A> so that the List<A> only contains elements of distinct A.getId()?

Body:
I have a List that contains some objects A with the attribute id. What I need is the list to contain only one object for an id.

public List findAllA() {
    List aList; // fetches the elements from db

    HashMap<Long, A> aMap = new HashMap<>();
    for (A a: aList) {
        aMap.put(a.getId(), a);
    }

    return new ArrayList<>(aMap.values());
}

So I put my list elements in a HashMap, because a HashMap holds distinct keys. Then a new ArrayList with the values of the map is returned. This does work fine, but is there a more efficient way to achieve the result? Or at least a shorter one?

Body:
Just going by your logic, you can try like this also

public List<A> findAllA() {
        List<A> aList; // fetches the elements from db

        HashMap<Long, A> aMap = new HashMap<>();
        List<Long> processedList = new ArrayList<>();
        for (A a: aList) {
            if(!processedList.contains(a.getId())) {
                processedList.add(a.getId());
                aMap.put(a.getId(), a);
            }
        }

        return new ArrayList<>(aMap.values());
    }


问:
How can I pad an integer with zeros on the left?
How do you left pad an int with zeros when converting to a String in java?

I'm basically looking to pad out integers up to 9999 with leading zeros (e.g. 1 = 0001).

答:
Use java.lang.String.format(String,Object...) like this:

```<code>String.format("%05d", yournumber);
</code>```

for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

The full formatting options are documented as part of java.util.Formatter.

OwnerDisplayName: Omar Kooheji

Body:
Use java.lang.String.format(String,Object...) like this:

String.format("%05d", yournumber);

for zero-padding with a length of 5. For hexadecimal output replace the d with an x as in "%05x".

The full formatting options are documented as part of java.util.Formatter.

OwnerDisplayName: uzhin


问:
Why is `ereg` deprecated in PHP?
Why is ereg deprecated in PHP?

I had a lot of functions which used this, now they always give warning.

What is the alternative of this too?

答:
One possible reason is for performance concerns, as already answered by others.

I'd like to add another (yet) possible reason:

Assume you wrote some code like this (PHP 5.3):

```<code><?php
$arg=$_GET['key'];
if (ereg('^[A-Za-z0-9]+$', $arg) === FALSE){
    die('Invalid key');
}
# Do some other things with $arg
?>
</code>```

One could bypass it by supplying this URL:

```<code>foo.php?key=A%00text
                ^~~~
</code>```

with the text part being arbitrarily anything he wants, which leaves a huge security flaw in the code. preg_match() however, does not have this issue. So you'd better migrate all your code to preg, as ereg is no longer available at all in PHP 6.0.

Title: Why is `ereg` deprecated in PHP?

Body:
One possible reason is for performance concerns, as already answered by others.

I'd like to add another (yet) possible reason:

Assume you wrote some code like this (PHP 5.3):

<?php
$arg=$_GET['key'];
if (ereg('^[A-Za-z0-9]+$', $arg) === FALSE){
    die('Invalid key');
}
# Do some other things with $arg
?>

One could bypass it by supplying this URL:

foo.php?key=A%00text
                ^~~~

with the text part being arbitrarily anything he wants, which leaves a huge security flaw in the code. preg_match() however, does not have this issue. So you'd better migrate all your code to preg, as ereg is no longer available at all in PHP 6.0.


问:
Schedule Alarm manager to run a method every Thursday
For example i want to have an alarm that will fire every Thursday at 12PM
How would i do this?

I have something implemented but isnt working properly,with the code that i have, today is wednesday 15, if change the date of the phone to 16 thrusday, the app doesnt do anything, if i change the date of the phone for the next wednesday 22 the phone sends a notification, but only should send on thursdays.

Here is my code:

MainActivity:

```<code>protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        base.OnCreate(bundle);
        AsNumAssemblyHelper.HoldAssembly();
        global::Xamarin.Forms.Forms.Init(this, bundle);
        ImageCircleRenderer.Init();

        Intent alarmIntent = new Intent(this, typeof(AlarmReceiver));
        PendingIntent pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
        AlarmManager alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();

        //AlarmType.RtcWakeup – it will fire up the pending intent at a specified time, waking up the device
        alarmManager.SetRepeating(AlarmType.RtcWakeup,BootReceiver.FirstReminder(), BootReceiver.reminderInterval, pending);
        PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, alarmIntent, 0);

        LoadApplication(new App());

    }
</code>```

BootReceiver:

```<code>[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootReceiver : BroadcastReceiver
{

    //the interval currently every one minute
    //to set it to dayly change the value to 24 * 60 * 60 * 1000
    public static long reminderInterval = AlarmManager.IntervalDay * 7;
    //public static long reminderInterval = 30 * 1000;

    public static long FirstReminder()
    {
        Java.Util.Calendar calendar = Java.Util.Calendar.Instance;
        calendar.Set(Java.Util.CalendarField.DayOfWeek, Calendar.Thursday);
        return calendar.TimeInMillis;

    }

    public override void OnReceive(Context context, Intent intent)
    {
        Console.WriteLine("BootReceiver: OnReceive");
        var alarmIntent = new Intent(context, typeof(AlarmReceiver));
        var pending = PendingIntent.GetBroadcast(context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
        AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);

        alarmManager.SetRepeating(AlarmType.RtcWakeup, FirstReminder(), reminderInterval, pending);
        PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, alarmIntent, 0);
    }
}
</code>```

AlarmReceiver:

```<code>[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        try
        {
                var title = "Something";
                var message = "Something";

                Intent backIntent = new Intent(context, typeof(MainActivity));
                backIntent.SetFlags(ActivityFlags.NewTask);

                var builder =
                    new Notification.Builder(context)
                        .SetContentTitle(title)
                        .SetContentText(message)
                        .SetAutoCancel(true)
                        .SetSmallIcon(Resource.Drawable.icon)
                        .SetDefaults(NotificationDefaults.All);
                var notification = builder.Build();
                var manager = NotificationManager.FromContext(context);
                manager.Notify(1331, notification);
            }

        }
        catch (Exception)
        {

        }
    }
}
</code>```

答:
For api levels below 19 you should use AlarmManager.setRepeating() and your alarms will trigger exactly at specified time. But as the document said,  when your device api levels 19 and above this will no longer work.

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

Also while using alarmManager.SetExact() method :

The alarm will be delivered as nearly as possible to the requested trigger time.

So if you would like to achieve exact repeating alarm, as @Dus said  here is two suggestions :

Accept the time delays(but maybe consider using JobSchedular which is more recommended and will save you battery).

Or :

Use SetExactAndAllowWhileIdle which might cause you battery issues(use this carefully, too many alarms will be bad for your battery).
This method isn't repeating, so you have to declare the next job to be run at the service which the pendingIntent opens.

Convert Dus's code to C# :

```<code>AlarmManager alarmManager = (AlarmManager)this.GetSystemService(Context.AlarmService);
var ALARM_TYPE = AlarmType.RtcWakeup;
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
{
    alarmManager.SetExactAndAllowWhileIdle(ALARM_TYPE, calendar.TimeInMillis, pendingIntent);
}
else if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
{
    alarmManager.SetExact(ALARM_TYPE, calendar.TimeInMillis, pendingIntent);
}
else if
{
    alarmManager.Set(ALARM_TYPE, calendar.TimeInMillis, pendingIntent);
}
</code>```

Update :

The idea behind doze is to attempt to prevent draining the battery. Repeated alarms drain battery, so the builtin way to repeat alarms by passing an extra parameter was removed in android 6. So it requires you to manually reschedule the alarm.

You could reschedule the alarm immediately when it fires,  before doing anything else that could go wrong and prevent the alarm from being rescheduled.

Update 2 :

A simple demo about use SetExactAndAllowWhileIdle method to implement a repeating alarm, hope this can help you.

The first time set an alarm :

```<code>var intent = new Intent(this, typeof(RepeatingAlarm));
var source = PendingIntent.GetBroadcast(this, 0, intent, 0);

// Schedule the alarm!
var am = (AlarmManager)GetSystemService(AlarmService);

//After 15s, use the RepeatingAlarm to show a toast
am.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 15 * 1000, source);
</code>```

In the RepeatingAlarm :

```<code>[BroadcastReceiver]
public class RepeatingAlarm : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        //Every time the `RepeatingAlarm` is fired, set the next alarm
        var intentForRepeat = new Intent(context, typeof(RepeatingAlarm));
        var source = PendingIntent.GetBroadcast(context, 0, intent, 0);
        var am = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);
        am.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 15 * 1000, source);

        Toast.MakeText(context, "repeating_received and after 15s another alarm will be fired", ToastLength.Short).Show();
    }
}
</code>```

Body:
For example i want to have an alarm that will fire every Thursday at 12PM
How would i do this?

I have something implemented but isnt working properly,with the code that i have, today is wednesday 15, if change the date of the phone to 16 thrusday, the app doesnt do anything, if i change the date of the phone for the next wednesday 22 the phone sends a notification, but only should send on thursdays.

Here is my code:

MainActivity:

protected override void OnCreate(Bundle bundle)
    {
        TabLayoutResource = Resource.Layout.Tabbar;
        ToolbarResource = Resource.Layout.Toolbar;
        base.OnCreate(bundle);
        AsNumAssemblyHelper.HoldAssembly();
        global::Xamarin.Forms.Forms.Init(this, bundle);
        ImageCircleRenderer.Init();

        Intent alarmIntent = new Intent(this, typeof(AlarmReceiver));
        PendingIntent pending = PendingIntent.GetBroadcast(this, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
        AlarmManager alarmManager = GetSystemService(AlarmService).JavaCast<AlarmManager>();

        //AlarmType.RtcWakeup – it will fire up the pending intent at a specified time, waking up the device
        alarmManager.SetRepeating(AlarmType.RtcWakeup,BootReceiver.FirstReminder(), BootReceiver.reminderInterval, pending);
        PendingIntent pendingIntent = PendingIntent.GetBroadcast(this, 0, alarmIntent, 0);

        LoadApplication(new App());

    }

BootReceiver:

[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionBootCompleted })]
public class BootReceiver : BroadcastReceiver
{

    //the interval currently every one minute
    //to set it to dayly change the value to 24 * 60 * 60 * 1000
    public static long reminderInterval = AlarmManager.IntervalDay * 7;
    //public static long reminderInterval = 30 * 1000;

    public static long FirstReminder()
    {
        Java.Util.Calendar calendar = Java.Util.Calendar.Instance;
        calendar.Set(Java.Util.CalendarField.DayOfWeek, Calendar.Thursday);
        return calendar.TimeInMillis;

    }

    public override void OnReceive(Context context, Intent intent)
    {
        Console.WriteLine("BootReceiver: OnReceive");
        var alarmIntent = new Intent(context, typeof(AlarmReceiver));
        var pending = PendingIntent.GetBroadcast(context, 0, alarmIntent, PendingIntentFlags.UpdateCurrent);
        AlarmManager alarmManager = (AlarmManager)context.GetSystemService(Context.AlarmService);

        alarmManager.SetRepeating(AlarmType.RtcWakeup, FirstReminder(), reminderInterval, pending);
        PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, alarmIntent, 0);
    }
}

AlarmReceiver:

[BroadcastReceiver]
public class AlarmReceiver : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        try
        {
                var title = "Something";
                var message = "Something";

                Intent backIntent = new Intent(context, typeof(MainActivity));
                backIntent.SetFlags(ActivityFlags.NewTask);

                var builder =
                    new Notification.Builder(context)
                        .SetContentTitle(title)
                        .SetContentText(message)
                        .SetAutoCancel(true)
                        .SetSmallIcon(Resource.Drawable.icon)
                        .SetDefaults(NotificationDefaults.All);
                var notification = builder.Build();
                var manager = NotificationManager.FromContext(context);
                manager.Notify(1331, notification);
            }

        }
        catch (Exception)
        {

        }
    }
}

Body:
For api levels below 19 you should use AlarmManager.setRepeating() and your alarms will trigger exactly at specified time. But as the document said,  when your device api levels 19 and above this will no longer work.

Note: Beginning with API 19 (KITKAT) alarm delivery is inexact: the OS will shift alarms in order to minimize wakeups and battery use. There are new APIs to support applications which need strict delivery guarantees; see setWindow(int, long, long, PendingIntent) and setExact(int, long, PendingIntent). Applications whose targetSdkVersion is earlier than API 19 will continue to see the previous behavior in which all alarms are delivered exactly when requested.

Also while using alarmManager.SetExact() method :

The alarm will be delivered as nearly as possible to the requested trigger time.

So if you would like to achieve exact repeating alarm, as @Dus said  here is two suggestions :

Accept the time delays(but maybe consider using JobSchedular which is more recommended and will save you battery).

Or :

Use SetExactAndAllowWhileIdle which might cause you battery issues(use this carefully, too many alarms will be bad for your battery).
This method isn't repeating, so you have to declare the next job to be run at the service which the pendingIntent opens.

Convert Dus's code to C# :

AlarmManager alarmManager = (AlarmManager)this.GetSystemService(Context.AlarmService);
var ALARM_TYPE = AlarmType.RtcWakeup;
if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.M)
{
    alarmManager.SetExactAndAllowWhileIdle(ALARM_TYPE, calendar.TimeInMillis, pendingIntent);
}
else if (Build.VERSION.SdkInt >= Android.OS.BuildVersionCodes.Lollipop)
{
    alarmManager.SetExact(ALARM_TYPE, calendar.TimeInMillis, pendingIntent);
}
else if
{
    alarmManager.Set(ALARM_TYPE, calendar.TimeInMillis, pendingIntent);
}

Update :

The idea behind doze is to attempt to prevent draining the battery. Repeated alarms drain battery, so the builtin way to repeat alarms by passing an extra parameter was removed in android 6. So it requires you to manually reschedule the alarm.

You could reschedule the alarm immediately when it fires,  before doing anything else that could go wrong and prevent the alarm from being rescheduled.

Update 2 :

A simple demo about use SetExactAndAllowWhileIdle method to implement a repeating alarm, hope this can help you.

The first time set an alarm :

var intent = new Intent(this, typeof(RepeatingAlarm));
var source = PendingIntent.GetBroadcast(this, 0, intent, 0);

// Schedule the alarm!
var am = (AlarmManager)GetSystemService(AlarmService);

//After 15s, use the RepeatingAlarm to show a toast
am.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 15 * 1000, source);

In the RepeatingAlarm :

[BroadcastReceiver]
public class RepeatingAlarm : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        //Every time the `RepeatingAlarm` is fired, set the next alarm
        var intentForRepeat = new Intent(context, typeof(RepeatingAlarm));
        var source = PendingIntent.GetBroadcast(context, 0, intent, 0);
        var am = (AlarmManager)Android.App.Application.Context.GetSystemService(Context.AlarmService);
        am.SetExactAndAllowWhileIdle(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime() + 15 * 1000, source);

        Toast.MakeText(context, "repeating_received and after 15s another alarm will be fired", ToastLength.Short).Show();
    }
}


问:
Calling variables from another function
Trying to call a variable from a sub function, but "sheet" is not defined. Any suggestions on how to call it? </p>

```<code>function getDate(){
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mnthYearDate);
}

function getValue(){
getDate();
var target = sheet.getRange("A1").getValue();
}
</code>```

答:
The variable 'sheet' here is only known in your function getDate because you defined it there. To make it available to other functions, define it outside like what I did here.

```<code>var sheet;

function getDate(){
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
 sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(12345);
}

function getValue(){
    getDate();
    var target = sheet.getRange("A1").getValue();
    Logger.log(target);
}
</code>```

Title: Calling variables from another function

Body:
Trying to call a variable from a sub function, but "sheet" is not defined. Any suggestions on how to call it?

function getDate(){
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(mnthYearDate);
}

function getValue(){
getDate();
var target = sheet.getRange("A1").getValue();
}

Body:
The variable 'sheet' here is only known in your function getDate because you defined it there. To make it available to other functions, define it outside like what I did here.

var sheet;

function getDate(){
var mnthYearDate = Utilities.formatDate(new Date,"EST","MMM yyyy");
 sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(12345);
}

function getValue(){
    getDate();
    var target = sheet.getRange("A1").getValue();
    Logger.log(target);
}


问:
How to build a Markov's chain transition probability matrix
I am learning R on my own and I am having some troubles trying to build a transition probability matrix in Rstudio using the markovchain package. First I tried to calculate the transition probabilities of a DNA sequence.

```<code>ATTCAACACATCCAGCCACATGCTCCGAGAGGAGGCAGAGGGCCCCCGGAATGATGCTTACCGAGATTCTTGTTTTTATCCTCGTGGTTGTTTAAAAACGAGTTGAAACTGACGGCATGTCGGACTATAAGCTACTTACTCACCATAGACGTGACCATAGGCCCTAAAACGTTACCGAGATATTCACTTCTAATAACAGTTGTCGGCAGAGCCAAAAGGCCGGGTGATAATACTTTAAAAAGGGAGTTGATTGTTGTATCTAATCCTAGAATGTCAAGAGCGACCATAACAAGATAATTCGGCAGAGCCAGAAAGCGTTCAAGGACTAGAACCATACCGAGACGCAAACGTTCAGGTCGAACTCTAATACCGATTAGT
</code>```

But how can the transition probability matrix be calculated in a sequence like this, I was thinking of using R indexes but I don't really know how to calculate those transition probabilities.

Is there a way of doing this in R?
I am guessing that the output of those probabilities in a matrix should be something like this:

```<code>     A    T    C    G
  A 0.60 0.10 0.10 0.20
  T 0.10 0.50 0.30 0.10
  C 0.05 0.20 0.70 0.05
  G 0.40 0.05 0.05 0.50
</code>```

答:
Create DNA

```<code>DNA <- "ATTCAACACATCCAGCCACATGCTCCGAGAGGAGGCAGAGGGCCCCCGGAATGATGCTTACCGAGATTCTTGTTTTTATCCTCGTGGTTGTTTAAAAACGAGTTGAAACTGACGGCATGTCGGACTATAAGCTACTTACTCACCATAGACGTGACCATAGGCCCTAAAACGTTACCGAGATATTCACTTCTAATAACAGTTGTCGGCAGAGCCAAAAGGCCGGGTGATAATACTTTAAAAAGGGAGTTGATTGTTGTATCTAATCCTAGAATGTCAAGAGCGACCATAACAAGATAATTCGGCAGAGCCAGAAAGCGTTCAAGGACTAGAACCATACCGAGACGCAAACGTTCAGGTCGAACTCTAATACCGATTAGT"
</code>```

Split it character by character

```<code>DNA_list <- unlist(strsplit(DNA, split = ""))
</code>```

Retrieve unique elements

```<code>DNA_unique <- unique(DNA_list)
</code>```

Create an empty matrix

```<code>matrix <- matrix(0, ncol = length(DNA_unique), nrow=length(DNA_unique))
</code>```

Fill it: to elt i and element i + 1 and add one in the corresponding cell of the matrix.

```<code>for (i in 1:(length(DNA_list) - 1)){
  index_of_i <- DNA_unique == DNA_list[i]
  index_of_i_plus_1 <- DNA_unique == DNA_list[i + 1]
  matrix[index_of_i, index_of_i_plus_1] = matrix[index_of_i, index_of_i_plus_1] + 1
}
</code>```

Normalize it

```<code>matrix <- matrix / rowSums(matrix)

> matrix
          [,1]      [,2]      [,3]      [,4]
[1,] 0.3000000 0.2166667 0.2250000 0.2583333
[2,] 0.3068182 0.2954545 0.2159091 0.1818182
[3,] 0.2857143 0.2142857 0.2619048 0.2380952
[4,] 0.3764706 0.2235294 0.1882353 0.2117647
</code>```

NB: There might be a way to perform it in a faster way if you have really large DNA to compute. But here it seeems to be fast enough.

Body:
I am learning R on my own and I am having some troubles trying to build a transition probability matrix in Rstudio using the markovchain package. First I tried to calculate the transition probabilities of a DNA sequence.

ATTCAACACATCCAGCCACATGCTCCGAGAGGAGGCAGAGGGCCCCCGGAATGATGCTTACCGAGATTCTTGTTTTTATCCTCGTGGTTGTTTAAAAACGAGTTGAAACTGACGGCATGTCGGACTATAAGCTACTTACTCACCATAGACGTGACCATAGGCCCTAAAACGTTACCGAGATATTCACTTCTAATAACAGTTGTCGGCAGAGCCAAAAGGCCGGGTGATAATACTTTAAAAAGGGAGTTGATTGTTGTATCTAATCCTAGAATGTCAAGAGCGACCATAACAAGATAATTCGGCAGAGCCAGAAAGCGTTCAAGGACTAGAACCATACCGAGACGCAAACGTTCAGGTCGAACTCTAATACCGATTAGT

But how can the transition probability matrix be calculated in a sequence like this, I was thinking of using R indexes but I don't really know how to calculate those transition probabilities.

Is there a way of doing this in R?
I am guessing that the output of those probabilities in a matrix should be something like this:

     A    T    C    G
  A 0.60 0.10 0.10 0.20
  T 0.10 0.50 0.30 0.10
  C 0.05 0.20 0.70 0.05
  G 0.40 0.05 0.05 0.50

Body:
Create DNA

DNA <- "ATTCAACACATCCAGCCACATGCTCCGAGAGGAGGCAGAGGGCCCCCGGAATGATGCTTACCGAGATTCTTGTTTTTATCCTCGTGGTTGTTTAAAAACGAGTTGAAACTGACGGCATGTCGGACTATAAGCTACTTACTCACCATAGACGTGACCATAGGCCCTAAAACGTTACCGAGATATTCACTTCTAATAACAGTTGTCGGCAGAGCCAAAAGGCCGGGTGATAATACTTTAAAAAGGGAGTTGATTGTTGTATCTAATCCTAGAATGTCAAGAGCGACCATAACAAGATAATTCGGCAGAGCCAGAAAGCGTTCAAGGACTAGAACCATACCGAGACGCAAACGTTCAGGTCGAACTCTAATACCGATTAGT"

Split it character by character

DNA_list <- unlist(strsplit(DNA, split = ""))

Retrieve unique elements

DNA_unique <- unique(DNA_list)

Create an empty matrix

matrix <- matrix(0, ncol = length(DNA_unique), nrow=length(DNA_unique))

Fill it: to elt i and element i + 1 and add one in the corresponding cell of the matrix.

for (i in 1:(length(DNA_list) - 1)){
  index_of_i <- DNA_unique == DNA_list[i]
  index_of_i_plus_1 <- DNA_unique == DNA_list[i + 1]
  matrix[index_of_i, index_of_i_plus_1] = matrix[index_of_i, index_of_i_plus_1] + 1
}

Normalize it

matrix <- matrix / rowSums(matrix)

> matrix
          [,1]      [,2]      [,3]      [,4]
[1,] 0.3000000 0.2166667 0.2250000 0.2583333
[2,] 0.3068182 0.2954545 0.2159091 0.1818182
[3,] 0.2857143 0.2142857 0.2619048 0.2380952
[4,] 0.3764706 0.2235294 0.1882353 0.2117647

NB: There might be a way to perform it in a faster way if you have really large DNA to compute. But here it seeems to be fast enough.


问:
Wait for $http result before initializing angular app
I have an angular app that needs to do a quick http request to get some config information before the rest of the application is initiated, at least before the controllers. Looked into using $UrlRouterProvider, but I did not figure out how to make the app wait for the http be done.

What I need to be finished:

```<code> $http({method: 'GET', url: '/config'}).then(function(res) {
      configProvider.setConfig(res.data.config);
 }
</code>```

答:
Resolve must be declared on state, not on the view

change

```<code>.state('app', {
    abstract: true,
    url:'/',
    views: {
        "content": {
            templateUrl: "myurl.html"
        },
        resolve {
            myVar: ['$http', 'myService', function($http, myService) {
                   return $http({method: 'GET', url:'url'})
                            .then(function(res) { //do stuff })
</code>```

to

```<code>.state('app', {
    abstract: true,
    url:'/',
    views: {
        "content": {
            templateUrl: "myurl.html"
        }
    },
    resolve {
            myVar: ['$http', 'myService', function($http, myService) {
                   return $http({method: 'GET', url:'url'})
                            .then(function(res) { //do stuff })...
</code>```

Body:
I have an angular app that needs to do a quick http request to get some config information before the rest of the application is initiated, at least before the controllers. Looked into using $UrlRouterProvider, but I did not figure out how to make the app wait for the http be done.

What I need to be finished:

 $http({method: 'GET', url: '/config'}).then(function(res) {
      configProvider.setConfig(res.data.config);
 }

Body:
Resolve must be declared on state, not on the view

change

.state('app', {
    abstract: true,
    url:'/',
    views: {
        "content": {
            templateUrl: "myurl.html"
        },
        resolve {
            myVar: ['$http', 'myService', function($http, myService) {
                   return $http({method: 'GET', url:'url'})
                            .then(function(res) { //do stuff })

to

.state('app', {
    abstract: true,
    url:'/',
    views: {
        "content": {
            templateUrl: "myurl.html"
        }
    },
    resolve {
            myVar: ['$http', 'myService', function($http, myService) {
                   return $http({method: 'GET', url:'url'})
                            .then(function(res) { //do stuff })...


问:
Adding variable inside .find() with data attribute
I have the following:

```<code>.find("[data-list='read']")
</code>```

and I want to add a JS variable inside, something like this:

```<code>.find("[data-list=''+ $variable +'']")
</code>```

Obviously, the two single quotations won't work in this case. Do I need to escape the single quotations in some way? What's the approach in JS?

答:
You just need to concatenate variable like this:</p>

```<code>.find("[data-list='" + read + "']")
</code>```

Body:
I have the following:

.find("[data-list='read']")

and I want to add a JS variable inside, something like this:

.find("[data-list=''+ $variable +'']")

Obviously, the two single quotations won't work in this case. Do I need to escape the single quotations in some way? What's the approach in JS?

Body:
You just need to concatenate variable like this:

.find("[data-list='" + read + "']")


问:
Ignoring DST when using Java Calendars
I have a GUI that plots time-series graphs. The user enters the dates they want to plot from and to by entering values in text boxes. For example, if they enter 25/07/13 22:00 and 26/07/13 00:00 the graph should plot data from 22:00:00 on the 25th through to 00:00:59 the following morning. The times the user enters are parsed into a Calendar object.

My problem comes with DST.

The user doesn't care about DST, so all they want to see is a graph between those two times. However, the Calendar objects do care about DST and so my "to" date is currently not 00:00, but 01:00. (I am in London and we are currently GMT + 1 hour for DST).

I want to effectively ignore DST and act as though everything is GMT + 0 when I want to plot graphs.

How can I do this?

答:
```<code>Calendar calendar = Calendar.getInstance();
calendar.set(calendar.DST_OFFSET, 0);
</code>```

Title: Ignoring DST when using Java Calendars


问:
Creating TAB-separated values from .xlsx with ssconvert
Due to commas within cell values, I am not able to use the ssconvert utility for .xls(x) to .csv conversion.

Is there a possibility to create tab-separated values directly from xlsx with ssconvert (command line spreadsheet format converter)?

ssconvert infile.xlsx outfile.tsv raises the error:

Unable to guess exporter to use

Hence, I have tried to generate a raw text file under specification of some export options, in particular, the separator:

ssconvert -O 'separator=\t format=raw' infile.xlsx outfile.txt

which results in output like value1\tvalue2\tvalue3, i.e., string \t is not translated into tabulator.

答:
When called from a shell-script: Put a real tab-character between allowed quotes, e.g:

```<code>ssconvert -O 'separator="   " format=raw' infile.xlsx outfile1.txt
ssconvert -O "separator=\"  \" format=raw" infile.xlsx outfile2.txt
ssconvert -O "separator='   ' format=raw" infile.xlsx outfile3.txt
</code>```

To type this directly into a command shell a  ctrl-v before the tab might be necessary.
Pasting this with the mouse will probably fail, as the tab will be replaced by spaces.

Body:
When called from a shell-script: Put a real tab-character between allowed quotes, e.g:

ssconvert -O 'separator="   " format=raw' infile.xlsx outfile1.txt
ssconvert -O "separator=\"  \" format=raw" infile.xlsx outfile2.txt
ssconvert -O "separator='   ' format=raw" infile.xlsx outfile3.txt

To type this directly into a command shell a  ctrl-v before the tab might be necessary.
Pasting this with the mouse will probably fail, as the tab will be replaced by spaces.


问:
Simplify Move and Maximise screen using Selenium (Ruby)
I am running my selenium tests using a ruby Framework having recently joined a new company. As I am working on 3 screens I have added in a browser step to move the browser window to my left most screen before maximising using </p>

```<code>@driver.manage.window.move_to(-1800, 1500)
@driver.manage.window.maximize
</code>```

<p>My question very simply is, having never used Ruby before, is there a way to refactor these 2 lines into 1 I have tried various ways but always get an error. </p>

答:
It's not possible in this place because both are returning string object so you can't cascade the calling like

```<code>@driver.manage.window.move_to(-1800, 1500).maximize
</code>```

But If it's very important for you, then I will tell you a way to do this, open the window.rb file where you can return the self from move_to function as shown below

```<code>  def move_to(x, y)
    @bridge.reposition_window Integer(x), Integer(y)
    self
  end
</code>```

And then you can make a call like this

```<code>@driver.manage.window.move_to(-1800, 1500).maximize
</code>```

Body:
I am running my selenium tests using a ruby Framework having recently joined a new company. As I am working on 3 screens I have added in a browser step to move the browser window to my left most screen before maximising using

@driver.manage.window.move_to(-1800, 1500)
@driver.manage.window.maximize

My question very simply is, having never used Ruby before, is there a way to refactor these 2 lines into 1 I have tried various ways but always get an error.

Body:
It's not possible in this place because both are returning string object so you can't cascade the calling like

@driver.manage.window.move_to(-1800, 1500).maximize

But If it's very important for you, then I will tell you a way to do this, open the window.rb file where you can return the self from move_to function as shown below

  def move_to(x, y)
    @bridge.reposition_window Integer(x), Integer(y)
    self
  end

And then you can make a call like this

@driver.manage.window.move_to(-1800, 1500).maximize


问:
How to have Nested Map RDD's in Spark
I have a text file like:-

```<code>ID,Hour,Ratio
100775,0.0,1.0
100775,1.0,1.0560344797302321
100775,2.0,1.1333317975785973
100775,3.0,1.1886133302168074
100776,4.0,1.2824427440125867
</code>```

I want a structure like MAP{Hour,MAP{ID,Ratio}}, to be stored as a RDD. The closest structure I could find was JavaPairRDD. I tried implementing a structure like  JavaPairRDD{Hour,MAP{ID,Ratio}}, however, this structure offers lookup() functionality, which returns LIST{MAP{ID,RATIO}}, which does not solve my use-case, as I essentially want to do

```<code>ratio = MAP.get(Hour).get(ID)
</code>```

Any pointers on how to best get this done.

UPDATE:-

After Ramesh's answer, I tried the following:-

```<code>JavaRDD<Map<String,Map<String,String>>> mapRDD =  data.map(line -> line.split(",")).map(array-> Collections
              .singletonMap(array[0],
                Collections
                .singletonMap
                (array[1],array[2])));
</code>```

However, there is no lookup() like functionality available here, correct?

答:
It's a common problem to work with a dataset in spark. Usually there is a dataset which contains some samples as each row in it and each column represents a feature for each sample.
But a common solution for the common problem is defining an Entity to support each column as its properties and each sample would be a RDD object.
To access each of these objects in the rdd can be done by using javapairrdd and set e.g. in this example HOUR as its key, the result would be something like:</p>

```<code>   Javapairrdd<INTEGER,Entity>
</code>```

Title: How to have Nested Map RDD's in Spark

Body:
I have a text file like:-

ID,Hour,Ratio
100775,0.0,1.0
100775,1.0,1.0560344797302321
100775,2.0,1.1333317975785973
100775,3.0,1.1886133302168074
100776,4.0,1.2824427440125867

I want a structure like MAP{Hour,MAP{ID,Ratio}}, to be stored as a RDD. The closest structure I could find was JavaPairRDD. I tried implementing a structure like  JavaPairRDD{Hour,MAP{ID,Ratio}}, however, this structure offers lookup() functionality, which returns LIST{MAP{ID,RATIO}}, which does not solve my use-case, as I essentially want to do

ratio = MAP.get(Hour).get(ID)

Any pointers on how to best get this done.

UPDATE:-

After Ramesh's answer, I tried the following:-

JavaRDD<Map<String,Map<String,String>>> mapRDD =  data.map(line -> line.split(",")).map(array-> Collections
              .singletonMap(array[0],
                Collections
                .singletonMap
                (array[1],array[2])));

However, there is no lookup() like functionality available here, correct?

Body:
It's a common problem to work with a dataset in spark. Usually there is a dataset which contains some samples as each row in it and each column represents a feature for each sample.
But a common solution for the common problem is defining an Entity to support each column as its properties and each sample would be a RDD object.
To access each of these objects in the rdd can be done by using javapairrdd and set e.g. in this example HOUR as its key, the result would be something like:

   Javapairrdd<INTEGER,Entity>


问:
Various Android Emulators
I've the default (comes with the SDK) and Samsung Galaxy Tab emulators in my SDK. I want to know what other third party (Motorola, LG, Sharp, etc) emulators are available, so that I can test my apps for more devices. Please provide the names with links.</p>

答:
I found this link a while back. It goes pretty in-depth on how to set up the sizing and capabilities for many devices. These are just alternative AVDs that run in the default emulator, though, and it might not be exactly what you're looking for.

http://mobile.tutsplus.com/tutorials/android/common-android-virtual-device-configurations/

Title: Various Android Emulators


问:
grep range of numbers
For the following text I need to count the lines that the number between parenthesis is in the range [10-20].

    This function's cyclomatic complexity is too high. (1)
    This function's cyclomatic complexity is too high. (2)
    This function's cyclomatic complexity is too high. (3)
    This function's cyclomatic complexity is too high. (4)
    This function's cyclomatic complexity is too high. (5)
    This function's cyclomatic complexity is too high. (6)
    This function's cyclomatic complexity is too high. (7)
    This function's cyclomatic complexity is too high. (8)
    This function's cyclomatic complexity is too high. (9)
    This function's cyclomatic complexity is too high. (10)
    This function's cyclomatic complexity is too high. (12)
    This function's cyclomatic complexity is too high. (13)
    This function's cyclomatic complexity is too high. (14)
    This function's cyclomatic complexity is too high. (15)
    This function's cyclomatic complexity is too high. (16)
    This function's cyclomatic complexity is too high. (17)
```

<p>Im trying the following commands:</p>

```cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10-20])"
cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10,11,12,13,14,15,16,17,18,20])"
```

But didnt work. Whats the correct way to do it?

答:
To list distinct strings for grep you surround them with \(\) and separate with \|, like this:

```<code>$ grep "This function's cyclomatic complexity is too high. (\(10\|11\|12\))" file
This function's cyclomatic complexity is too high. (10)
This function's cyclomatic complexity is too high. (12)
</code>```

Title: grep range of numbers

Body:
For the following text I need to count the lines that the number between parenthesis is in the range [10-20].

    This function's cyclomatic complexity is too high. (1)
    This function's cyclomatic complexity is too high. (2)
    This function's cyclomatic complexity is too high. (3)
    This function's cyclomatic complexity is too high. (4)
    This function's cyclomatic complexity is too high. (5)
    This function's cyclomatic complexity is too high. (6)
    This function's cyclomatic complexity is too high. (7)
    This function's cyclomatic complexity is too high. (8)
    This function's cyclomatic complexity is too high. (9)
    This function's cyclomatic complexity is too high. (10)
    This function's cyclomatic complexity is too high. (12)
    This function's cyclomatic complexity is too high. (13)
    This function's cyclomatic complexity is too high. (14)
    This function's cyclomatic complexity is too high. (15)
    This function's cyclomatic complexity is too high. (16)
    This function's cyclomatic complexity is too high. (17)

Im trying the following commands:

cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10-20])"
cat log.txt | grep -c "This function's cyclomatic complexity is too high. ([10,11,12,13,14,15,16,17,18,20])"

But didnt work. Whats the correct way to do it?

Body:
To list distinct strings for grep you surround them with \(\) and separate with \|, like this:

$ grep "This function's cyclomatic complexity is too high. (\(10\|11\|12\))" file
This function's cyclomatic complexity is too high. (10)
This function's cyclomatic complexity is too high. (12)