问:
Access SQL return nth row for each given field

My problem

Let's say I have a query that returns the following data:

```<code>id     date
--    ------
1     2015-01-12
1     ... // here I might have X more rows
1     2015-06-30
2     2015-01-12
2     ... // here I might have Y more rows
2     2015-05-20
...
</code>```

Given that X, Y >= 120 and X != Y and the order of the query is id, date ASC I want a way to retrieve the record number 120 for id 1 and the 120 for the id 2 (and so on for each different ID), something like:

```<code>id      date
--    --------
1     2015-03-24 // this is the record 120 for id = 1
2     2015-04-26 // this is the record 120 for id = 2
...
</code>```

Notice that the dates don't follow a sequential order (you may have a gap between one row and the next one).

Is there a direct SQL solution for my problem? (I know I can use vba to achieve my goal but I rather stay with SQL)

As a clarification note, see this example. Given the following resultset:

```<code>id     date
--    ------
1     2015-01-12  // this is record 1 for id = 1
1     2015-01-13  // this is record 2 for id = 1
1     2015-01-20  // this is record 3 for id = 1
1     2015-01-21  // this is record 4 for id = 1
...
1     2015-03-22  // this is record 118 for id = 1
1     2015-03-23  // this is record 119 for id = 1
1     2015-03-24  // this is record 120 for id = 1
1     2015-03-25  // this is record 121 for id = 1
...
1     2015-06-30  // this is the last row for id = 1
2     2015-01-12  // this is record 1 for id = 2
2     2015-01-13  // this is record 2 for id = 2
...
2     2015-04-25  // this is record 120 for id = 2
...
2     2015-05-20  // this is the last record for id = 2
</code>```

The result should be:

```<code>id      date
--    --------
1     2015-03-24
2     2015-04-26
</code>```

Remember, I have at least 120 records for each ID, this is a fact (I have a query that gives only the IDs with more than 119 records)

Attempted solution

I've tried to play with the SELECT TOP directive, but I fail to achieve the results I want as I cannot apply it direcly: I don't want the top 120 and then get the last row as I want the last one of the TOP 120 for each ID.

Edited for (a second) clarification

My goal would be to have something like:

```<code>SELECT id, 120thRow(date)
FROM table
GROUP BY id;
</code>```

unfortunatelly I don't know how to implement the 120thRow function in access.

答:
Hi I think this must work for you.

```<code>with Records AS
(select row_number() over(order by sort_column_name) as 'row', *
       from table_name) select * from records where row=n
</code>```

sort_column_name – mention the name of the column which is sorting the table.

n – row number

table_name – mention the name of the table table name

Body:
My problem

Let's say I have a query that returns the following data:

id     date
--    ------
1     2015-01-12
1     ... // here I might have X more rows
1     2015-06-30
2     2015-01-12
2     ... // here I might have Y more rows
2     2015-05-20
...

Given that X, Y >= 120 and X != Y and the order of the query is id, date ASC I want a way to retrieve the record number 120 for id 1 and the 120 for the id 2 (and so on for each different ID), something like:

id      date
--    --------
1     2015-03-24 // this is the record 120 for id = 1
2     2015-04-26 // this is the record 120 for id = 2
...

Notice that the dates don't follow a sequential order (you may have a gap between one row and the next one).

Is there a direct SQL solution for my problem? (I know I can use vba to achieve my goal but I rather stay with SQL)

As a clarification note, see this example. Given the following resultset:

id     date
--    ------
1     2015-01-12  // this is record 1 for id = 1
1     2015-01-13  // this is record 2 for id = 1
1     2015-01-20  // this is record 3 for id = 1
1     2015-01-21  // this is record 4 for id = 1
...
1     2015-03-22  // this is record 118 for id = 1
1     2015-03-23  // this is record 119 for id = 1
1     2015-03-24  // this is record 120 for id = 1
1     2015-03-25  // this is record 121 for id = 1
...
1     2015-06-30  // this is the last row for id = 1
2     2015-01-12  // this is record 1 for id = 2
2     2015-01-13  // this is record 2 for id = 2
...
2     2015-04-25  // this is record 120 for id = 2
...
2     2015-05-20  // this is the last record for id = 2

The result should be:

id      date
--    --------
1     2015-03-24
2     2015-04-26

Remember, I have at least 120 records for each ID, this is a fact (I have a query that gives only the IDs with more than 119 records)

Attempted solution

I've tried to play with the SELECT TOP directive, but I fail to achieve the results I want as I cannot apply it direcly: I don't want the top 120 and then get the last row as I want the last one of the TOP 120 for each ID.

Edited for (a second) clarification

My goal would be to have something like:

SELECT id, 120thRow(date)
FROM table
GROUP BY id;

unfortunatelly I don't know how to implement the 120thRow function in access.

Body:
Hi I think this must work for you.

with Records AS
(select row_number() over(order by sort_column_name) as 'row', *
       from table_name) select * from records where row=n

sort_column_name – mention the name of the column which is sorting the table.

n – row number

table_name – mention the name of the table table name


来源: stackexchange

问:
how to execute a single api which is parameterized multiple iteration in a postman collection?
i have a group of  api's in postman in collection and execute in collection runner multiple times using a csv or json file and configuring iterations to required number upto this is ok. but my requirement is to run only selected apis to iterate which are parameterized not all  api's .Every time it is executing full collection suite is there any option to configure it.

please help me thanks in advance

答:
I'm not sure to understand clearly but if what you want is to execute only some selected requests among your collection, you may use the setNextRequest feature (refer to http://blog.getpostman.com/2016/03/23/conditional-workflows-in-postman/). It may help you as you can specify which request to play under certain conditions.

```<code>if (selection condition == true)
    setNextRequest(request_i_want)
</code>```

That would allow you to 'jump' to the requests that fulfill your selection requirement.

hope this helps

Alexandre

ContentLicense: CC BY-SA 3.0

Body:
I'm not sure to understand clearly but if what you want is to execute only some selected requests among your collection, you may use the setNextRequest feature (refer to http://blog.getpostman.com/2016/03/23/conditional-workflows-in-postman/). It may help you as you can specify which request to play under certain conditions.

if (selection condition == true)
    setNextRequest(request_i_want)

That would allow you to 'jump' to the requests that fulfill your selection requirement.

hope this helps

Alexandre


问:
How to make model class for following JSON response in swift iOS
Hi i am beginner  for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below

MY requirement is how to map that model classes to Array and how to display them in tableList can some one help me please

JsonResponse:-

```<code>[{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVippler" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVippler" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]
</code>```

mapping:

Club:-

```<code>class Club {

    var id: String = ""
    var name: String = ""
    var imageUrl: String = ""
    var hasVip: Bool = false
    var desc: String = ""
    var location: [Location] = []

}
</code>```

Location:-

```<code>class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""
    var underground: [String] = []

}
</code>```

NSURlSession code:-

```<code>class BackGroundPostCall: NSObject {

    var delegate:PostProtocol?

    func callPostService(url:String,params:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                    print("Response: \(json)")
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()
    }
}
</code>```

答:
For mapping you can use Alamofire's extension ObjectMapper.

Ex:

```<code>[{
"_id" : "5470def9e0c0be27780121d7",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
"name" : "Mondo",
"hasVip" : false,
"location" : {
    "city" : "Madrid"
}
}, {
    "_id" : "540b2ff281b30f3504a1c72f",
    "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
    "name" : "Teatro Kapital",
    "hasVippler" : false,
    "location" : {
        "address" : "Atocha, 125",
        "city" : "Madrid"
    }
}, {
    "_id" : "540cd44581b30f3504a1c73b",
    "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
    "name" : "Charada",
    "hasVippler" : false,
    "location" : {
        "address" : "La Bola, 13",
        "city" : "Madrid"
    }
}]
</code>```

And mapper class:

```<code>import ObjectMapper

class Location: Mappable {
    var address: String?
    var city: String?

    required init?(map: Map){

    }

    func mapping(map: Map) {
        address <- map["address"]
        city <- map["city"]
    }
}

class Club: Mappable {
    var id: String?
    var imageUrl: Int?
    var name: String?
    var hasVip: Bool = false
    var location: Location?

    required init?(map: Map){

    }

    func mapping(map: Map) {
        id <- map["_id"]
        imageUrl <- map["imageUrl"]
        name <- map["name"]
        hasVip <- map["hasVippler"]
        location <- map["location"]
    }
}
</code>```

And this way very flexible and transparent to use.

https://github.com/Alamofire/Alamofire
https://github.com/tristanhimmelman/AlamofireObjectMapper

Using example:

```<code>Alamofire.request(URL).responseArray { (response: DataResponse<[Club]>) in

    let clubs = response.result.value

    if let clubs = clubs {
        for club in clubs {
            print(club.name)
            print(club.location.city)
        }
    }
}
</code>```

Body:
Hi i am beginner  for swift ios and my requirement is have to display Json response to table list i got response from web-services and response seems like below

MY requirement is how to map that model classes to Array and how to display them in tableList can some one help me please

JsonResponse:-

[{
  "_id" : "5470def9e0c0be27780121d7",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
  "name" : "Mondo",
  "hasVip" : false,
  "location" : {
    "city" : "Madrid"
  }
}, {
  "_id" : "540b2ff281b30f3504a1c72f",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
  "name" : "Teatro Kapital",
  "hasVippler" : false,
  "location" : {
    "address" : "Atocha, 125",
    "city" : "Madrid"
  }
}, {
  "_id" : "540cd44581b30f3504a1c73b",
  "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
  "name" : "Charada",
  "hasVippler" : false,
  "location" : {
    "address" : "La Bola, 13",
    "city" : "Madrid"
  }
}]

mapping:

Club:-

class Club {

    var id: String = ""
    var name: String = ""
    var imageUrl: String = ""
    var hasVip: Bool = false
    var desc: String = ""
    var location: [Location] = []

}

Location:-

class Location {

    var country: String = ""
    var city: String = ""
    var address: String = ""
    var zip: String = ""
    var underground: [String] = []

}

NSURlSession code:-

class BackGroundPostCall: NSObject {

    var delegate:PostProtocol?

    func callPostService(url:String,params:NSDictionary){

        print("url is===>\(url)")

        let request = NSMutableURLRequest(URL: NSURL(string:url)!)

        let session = NSURLSession.sharedSession()
        request.HTTPMethod = "POST"

        //Note : Add the corresponding "Content-Type" and "Accept" header. In this example I had used the application/json.
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")

        request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(params, options: [])

        let task = session.dataTaskWithRequest(request) { data, response, error in
            guard data != nil else {
                print("no data found: \(error)")
                return
            }

            do {
                if let json = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? NSArray {
                    print("Response: \(json)")
                } else {
                    let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)// No error thrown, but not NSDictionary
                    print("Error could not parse JSON: \(jsonStr)")
                }
            } catch let parseError {
                print(parseError)// Log the error thrown by `JSONObjectWithData`
                let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
                print("Error could not parse JSON: '\(jsonStr)'")
            }
        }

        task.resume()
    }
}

Body:
For mapping you can use Alamofire's extension ObjectMapper.

Ex:

[{
"_id" : "5470def9e0c0be27780121d7",
"imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/5470def9e0c0be27780121d7_180.png",
"name" : "Mondo",
"hasVip" : false,
"location" : {
    "city" : "Madrid"
}
}, {
    "_id" : "540b2ff281b30f3504a1c72f",
    "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540b2ff281b30f3504a1c72f_180.png",
    "name" : "Teatro Kapital",
    "hasVippler" : false,
    "location" : {
        "address" : "Atocha, 125",
        "city" : "Madrid"
    }
}, {
    "_id" : "540cd44581b30f3504a1c73b",
    "imageUrl" : "https:\/\/s3-eu-west-1.amazonaws.com\/api-static\/clubs\/540cd44581b30f3504a1c73b_180.png",
    "name" : "Charada",
    "hasVippler" : false,
    "location" : {
        "address" : "La Bola, 13",
        "city" : "Madrid"
    }
}]

And mapper class:

import ObjectMapper

class Location: Mappable {
    var address: String?
    var city: String?

    required init?(map: Map){

    }

    func mapping(map: Map) {
        address <- map["address"]
        city <- map["city"]
    }
}

class Club: Mappable {
    var id: String?
    var imageUrl: Int?
    var name: String?
    var hasVip: Bool = false
    var location: Location?

    required init?(map: Map){

    }

    func mapping(map: Map) {
        id <- map["_id"]
        imageUrl <- map["imageUrl"]
        name <- map["name"]
        hasVip <- map["hasVippler"]
        location <- map["location"]
    }
}

And this way very flexible and transparent to use.

https://github.com/Alamofire/Alamofire
https://github.com/tristanhimmelman/AlamofireObjectMapper

Using example:

Alamofire.request(URL).responseArray { (response: DataResponse<[Club]>) in

    let clubs = response.result.value

    if let clubs = clubs {
        for club in clubs {
            print(club.name)
            print(club.location.city)
        }
    }
}


问:
Android: DialogFragment show throws illegalstateexception after web service call
In my app I am showing a dialog fragment after I get response from web service. I am calling this service from onCreate. In between if app goes to background, it crashes with exception

```<code>Fatal Exception: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
   at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1493)
   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1511)
   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:638)
   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:617)
   at android.support.v4.app.DialogFragment.show(DialogFragment.java:139)
   at com.activity.MainActivity.showAcceptancePopup(MainActivity.java:1655)
   at com.activity.MainActivity.access$1000(MainActivity.java:164)
   at com.activity.MainActivity$28.onResponse(MainActivity.java:1568)
   at com.activity.MainActivity$28.onResponse(MainActivity.java:1547)
   at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
   at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
   at android.os.Handler.handleCallback(Handler.java:751)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6123)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)
</code>```

I have gone through this blog post. Still having doubt, from where should I call dialogFragment.show() as it depends on the data provided by the server.

Or else should I move the API call from onCreate to onResumeFragment?

答:
The solution here is to using commitAllowingStateLoss(); instead of commit() for your fragment transaction, as according by the documentation

Like commit() but allows the commit to be executed after an activity's
  state is saved

Hope this helps.

Body:
In my app I am showing a dialog fragment after I get response from web service. I am calling this service from onCreate. In between if app goes to background, it crashes with exception

Fatal Exception: java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
   at android.support.v4.app.FragmentManagerImpl.checkStateLoss(FragmentManager.java:1493)
   at android.support.v4.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1511)
   at android.support.v4.app.BackStackRecord.commitInternal(BackStackRecord.java:638)
   at android.support.v4.app.BackStackRecord.commit(BackStackRecord.java:617)
   at android.support.v4.app.DialogFragment.show(DialogFragment.java:139)
   at com.activity.MainActivity.showAcceptancePopup(MainActivity.java:1655)
   at com.activity.MainActivity.access$1000(MainActivity.java:164)
   at com.activity.MainActivity$28.onResponse(MainActivity.java:1568)
   at com.activity.MainActivity$28.onResponse(MainActivity.java:1547)
   at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:65)
   at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
   at android.os.Handler.handleCallback(Handler.java:751)
   at android.os.Handler.dispatchMessage(Handler.java:95)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6123)
   at java.lang.reflect.Method.invoke(Method.java)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:757)

I have gone through this blog post. Still having doubt, from where should I call dialogFragment.show() as it depends on the data provided by the server.

Or else should I move the API call from onCreate to onResumeFragment?


问:
How to enable disable sup tag in javascript
i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.

my view:

```<code>  <label>code<sup id="star" disabled>*</sup></label>
      >Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
        > id="no"/>onchange="starenable()"/>no
</code>```

my javascript:

```<code> function starenable() {
        if (document.getElementById('yes').checked) {
            document.getElementById("star").disabled = false;
        } else if (document.getElementById('no').checked) {
            document.getElementById("star").disabled = true;
        }
    }
</code>```

i tried this but no change in view. any ideas?

答:
Input have disable attribute .Change the sub with input .And  align the html code on proper format.Then add the * depend on checked radio button

Updated

note: sub tag not have a disable attribute

function starenable() {
  if (document.getElementById('yes').checked) {
    document.getElementById("star").disabled = false;
  } else if (document.getElementById('no').checked) {
    document.getElementById("star").disabled = true;
  }
  document.getElementById("star").innerHTML = document.getElementById('yes').checked ? '*' : '';
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>code <sub id="star"></sub></label> Add to electronic
<input type="radio" name="yes" id="yes" onchange="starenable()" />yes
<input type="radio" name="yes" id="no" onchange="starenable()"/>no</code>```

Body:
i have 2 radio buttons and one text box i need to make(*)appear on the textbox when yes radiobutton is clicked and removed when no radio button is clicked.

my view:

  code*
      >Add to electronic<input type="radio" name="yes" id="yes"/>onchange="starenable()"/><input type="radio" name="yes"
        > id="no"/>onchange="starenable()"/>no

my javascript:

 function starenable() {
        if (document.getElementById('yes').checked) {
            document.getElementById("star").disabled = false;
        } else if (document.getElementById('no').checked) {
            document.getElementById("star").disabled = true;
        }
    }

i tried this but no change in view. any ideas?

Body:
Input have disable attribute .Change the sub with input .And  align the html code on proper format.Then add the * depend on checked radio button

Updated

note: sub tag not have a disable attribute

function starenable() {
  if (document.getElementById('yes').checked) {
    document.getElementById("star").disabled = false;
  } else if (document.getElementById('no').checked) {
    document.getElementById("star").disabled = true;
  }
  document.getElementById("star").innerHTML = document.getElementById('yes').checked ? '*' : '';
}

<label>code <sub id="star"></sub></label> Add to electronic
<input type="radio" name="yes" id="yes" onchange="starenable()" />yes
<input type="radio" name="yes" id="no" onchange="starenable()"/>no


问:
How to open .pptx files in android webview
I am trying to open .pptx file n android webview with google docs its throwing error unable to load but its able to load .ppt type urls.any help is appreciated</p>

答:
try this</p>

```<code> WebView webview = (WebView)findViewById(R.id.containWebView);
webview.setWebViewClient(new AppWebViewClients());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.loadUrl("http://docs.google.com/gview?embedded=true&url="
            + "YOUR_DOC_URL_HERE");

 public class AppWebViewClients extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // TODO Auto-generated method stub
    view.loadUrl(url);
    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    // TODO Auto-generated method stub
    super.onPageFinished(view, url);

 }
}
</code>```

Body:
try this

 WebView webview = (WebView)findViewById(R.id.containWebView);
webview.setWebViewClient(new AppWebViewClients());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setUseWideViewPort(true);
webview.loadUrl("http://docs.google.com/gview?embedded=true&url="
            + "YOUR_DOC_URL_HERE");

 public class AppWebViewClients extends WebViewClient {

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // TODO Auto-generated method stub
    view.loadUrl(url);
    return true;
}

@Override
public void onPageFinished(WebView view, String url) {
    // TODO Auto-generated method stub
    super.onPageFinished(view, url);

 }
}


问:
SVProgressHUD Can't show the status
When I use [SVProgressHUD show], delay 2 seconds, then use [SVProgressHUD dismiss], the HUD dismiss.

But when I use [SVProgressHUD showErrorWithStatus:@"test"], the hud can' show.

Can someone stay me why?

```<code>  - (void)viewDidLoad {
       [super viewDidLoad];
       [SVProgressHUD show];
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"test"];
       });
   }
</code>```

答:
The SVProgressHUD.showInfoWithStatus will hide the message after some time. so probably second HUD won't show cause it is still remove the first one.  [SVProgressHUD show];

If you wanna update don't call dismiss [SVProgressHUD dismiss];

Title: SVProgressHUD Can't show the status

Body:
When I use [SVProgressHUD show], delay 2 seconds, then use [SVProgressHUD dismiss], the HUD dismiss.

But when I use [SVProgressHUD showErrorWithStatus:@"test"], the hud can' show.

Can someone stay me why?

  - (void)viewDidLoad {
       [super viewDidLoad];
       [SVProgressHUD show];
       dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.f * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
            [SVProgressHUD showErrorWithStatus:@"test"];
       });
   }


问:
How to prmisify .native function of mongo into bluebird promise?
I am using sails and connecting two databases mysql and mongo with my app, I am stuck where I have to promisify the .native functions of sailsjs mongo adapter.

```<code>Activities.native(function(err, activities) {
  if (err) return res.serverError(err);
  activities.find({}).toArray(function (err, results) {
        if (err){
          return err;
        }else{
          console.log(results);
          return results;
        }

     });
});
</code>```

I want this function to be promisified with bluebird . any help ?

答:
You can always wrap that inside a promise and continue using promise logic like this:</p>

```<code>function doTheNativeQuery() {
    return new Promise(function (resolve, reject) {

        Activities.native(function (err, activities) {
            if (err) return reject(err);

            activities.find({}).toArray(function (err, results) {
                if (err) return reject(err);

                resolve(results);
            });
        });
    });
}

doTheNativeQuery().then() ....
</code>```

Body:
I am using sails and connecting two databases mysql and mongo with my app, I am stuck where I have to promisify the .native functions of sailsjs mongo adapter.

Activities.native(function(err, activities) {
  if (err) return res.serverError(err);
  activities.find({}).toArray(function (err, results) {
        if (err){
          return err;
        }else{
          console.log(results);
          return results;
        }

     });
});

I want this function to be promisified with bluebird . any help ?

Body:
You can always wrap that inside a promise and continue using promise logic like this:

function doTheNativeQuery() {
    return new Promise(function (resolve, reject) {

        Activities.native(function (err, activities) {
            if (err) return reject(err);

            activities.find({}).toArray(function (err, results) {
                if (err) return reject(err);

                resolve(results);
            });
        });
    });
}

doTheNativeQuery().then() ....


问:
Error message "python-pylint 'C0103:Invalid constant name"
I'm confused about the error(s) in this photo:

I don't know how to fix them. My program is a Python-Flask web frame. When I use Visual Studio Code to debug my program, Pylint shows these errors. I know this problem doesn't matter, but it makes me annoyed. How can I fix it?

```<code># -*- coding: utf-8 -*-
import sys
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
#from flask_wtf import Form
#from wtforms import StringField, SubmitField
#from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy

reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/test?'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)

if __name__ == '__main__':
    db.create_all()
    app.run()
</code>```

答:
Rename those variables to be all caps.

Such as

```<code>app = Flask(__name__)      => APP = Flask(__name__)
bootstrap = Bootstrap(app) => BOOTSTRAP = Bootstrap(app)
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm confused about the error(s) in this photo:

I don't know how to fix them. My program is a Python-Flask web frame. When I use Visual Studio Code to debug my program, Pylint shows these errors. I know this problem doesn't matter, but it makes me annoyed. How can I fix it?

# -*- coding: utf-8 -*-
import sys
from flask import Flask
from flask_bootstrap import Bootstrap
from flask_moment import Moment
#from flask_wtf import Form
#from wtforms import StringField, SubmitField
#from wtforms.validators import Required
from flask_sqlalchemy import SQLAlchemy

reload(sys)
sys.setdefaultencoding('utf-8')

app = Flask(__name__)
app.config['SECRET_KEY'] = 'hard to guess string'
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://root:@localhost:3306/test?'
app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = True

bootstrap = Bootstrap(app)
moment = Moment(app)
db = SQLAlchemy(app)

if __name__ == '__main__':
    db.create_all()
    app.run()

Body:
Rename those variables to be all caps.

Such as

app = Flask(__name__)      => APP = Flask(__name__)
bootstrap = Bootstrap(app) => BOOTSTRAP = Bootstrap(app)


问:
java 8 findFirst vs map on optional
Given this code:

```<code>class Foo {
  Integer attr;
  public Integer getAttr() {return attr;}
}

List<Foo> list = new ArrayList<>();
list.add(new Foo());

list.stream().map(Foo::getAttr).findAny().orElse(null);  //A
list.stream().findAny().map(Foo::getAttr).orElse(null);  //B
</code>```

Line A throws

java.lang.NullPointerException: null

while line B returns null.

What is the cause of this behaviour? Both findAny() and map() return Optional<T>.

答:
```<code>list.stream().map(Foo::getAttr).findAny().orElse(null);
</code>```

Java doc for streams says that Stream: "returns a stream consisting of the results of applying the given function to the elements of this stream", and findAny() "could return aNullPointerException - if the element selected is null". In your class Foo, Integer(not int) by default is set to null because is declared but not initialized. see Primitives see default values and Object initialization in Java

Initialization is different for:
A) Class Members (Objects and primitives)
B) Local Variables

Title: java 8 findFirst vs map on optional

Body:
Given this code:

class Foo {
  Integer attr;
  public Integer getAttr() {return attr;}
}

List<Foo> list = new ArrayList<>();
list.add(new Foo());

list.stream().map(Foo::getAttr).findAny().orElse(null);  //A
list.stream().findAny().map(Foo::getAttr).orElse(null);  //B

Line A throws

java.lang.NullPointerException: null

while line B returns null.

What is the cause of this behaviour? Both findAny() and map() return Optional<T>.

Body:
list.stream().map(Foo::getAttr).findAny().orElse(null);

Java doc for streams says that Stream: "returns a stream consisting of the results of applying the given function to the elements of this stream", and findAny() "could return aNullPointerException - if the element selected is null". In your class Foo, Integer(not int) by default is set to null because is declared but not initialized. see Primitives see default values and Object initialization in Java

Initialization is different for:
A) Class Members (Objects and primitives)
B) Local Variables


问:
How to show approved comments in Laravel
I want to show post's comments (approved = true) We have a single post with a random slug/id, But the problem is: How can I show approved comments with that specific post id !?

I think i have to use something like this following example :

```<code>Post::find($id)->Comments()->whereApproved(true)->get()
</code>```

Comments Table :

答:
If approved is a column in comments table you should use this :

```<code>Post::with(['comments' => function ($query) {
    $query->where('approved', true);
}])->get();
</code>```

This code returns all posts with approved comments

So you can use it in your blade

```<code>$post->Comments
</code>```

Don't forget to use foreach or looping

Body:
I want to show post's comments (approved = true) We have a single post with a random slug/id, But the problem is: How can I show approved comments with that specific post id !?

I think i have to use something like this following example :

Post::find($id)->Comments()->whereApproved(true)->get()

Comments Table :

Body:
If approved is a column in comments table you should use this :

Post::with(['comments' => function ($query) {
    $query->where('approved', true);
}])->get();

This code returns all posts with approved comments

So you can use it in your blade

$post->Comments

Don't forget to use foreach or looping


问:
How to reduce the apk size of Android app which need openCv lib( only for Image processing)
I'm building an Android app with min SDK 15, which uses OpenCV library.The problem is when I build apk size of it is more than 60 MB which is not very great.

I checked the app file, I could see that the size is too big due to libopencv_java3.so file in all architectures like amr64, armeabi, mips, x86 etc.

I am using opneCv only for image processing.This library has a lot of other features like video processing, 3d image, object detection and much more, which I don't need in my app like

If I remove all those files and build APK, then size will be reduced 50 MB, but to make this app work I need to install OpenCVManager to run my app.

Is there any way by which I can reduce my apk size?

Or is it possible just to extract only the feature from OpenCV which I am interested in and create .so for those features?

答:
You can not remove the library libopencv_java3.so, it's mandatory.

Is there any way by which I can reduce my apk size?

Without modify the library libopencv_java3.so, you can build multiple apks for different architectures rather than package a flat APK. Only one arch of libopencv_java3.so will be packaged into your split APK. For example, you can use the configuration below to build only for x86, armeabi-v7a and mips architectures in your build.gradle

```<code>splits {
    abi {
      enable true
      reset()
      include "x86", "armeabi-v7a", "mips"
      universalApk false
    }
  }
</code>```

More information about reduce apk size by splitting, see here.

Or is it possible just to extract only the feature from OpenCV which I am interested in and create .so for those features?

Yes, of course. The building process for opencv is fully customized. If you have already know how to build opencv for Android, go to step 2 directly.

step 1

get the source of opencv

create directory opencv_build

change to root directory of opencv you just cloned

invoke the build script platforms/android/build_sdk.py --ndk_path $ANDROID_NDK_ROOT --sdk_path $ANDROID_SDK_ROOT ../opencv_build .

Note

The build procedure need android command to build apk, so the Android SDK tool version must less than 25.3.0, from 25.3.0, android command has been removed.

step 2

Assume the step 1 above run properly. Here I take armeabi-v7a as an example.

Go to directory opencv_build/o4a/lib/armeabi-v7a

You will find many *.a for different opencv module, the library libopencv_java3.so also in this directory

Create a tiny version share library from the module you need, e.g

```<code>$ arm-linux-androideabi-gcc -shared -o libopencv_tiny.so --sysroot=$ANDROID_NDK_ROOT/platforms/android-9/arch-arm -Wl,--whole-archive libopencv_core.a libopencv_imgcodecs.a libopencv_imgproc.a -Wl,--no-whole-archive
$ du -h libopencv_tiny.so
5.2M    libopencv_tiny.so
$ arm-linux-androideabi-strip --strip-unneeded libopencv_tiny.so
$ du -h libopencv_tiny.so
4.1M    libopencv_tiny.so
$ du -h libopencv_java3.so
9.8M    libopencv_java3.so
</code>```

The tiny version which include core, image codecs and image proc has a size 4.1M after strip, but the full version libopencv_java3.so has a size of 9.8M.

I use libopencv_tiny.so as the name just for convenience, you have to use the same name libopencv_java3.so in your project. Otherwise System.loadLibrary in Java can not find the native library.

For the rest of the architecture you need, e.g arm64-v8a, do the same.

Body:
You can not remove the library libopencv_java3.so, it's mandatory.

Is there any way by which I can reduce my apk size?

Without modify the library libopencv_java3.so, you can build multiple apks for different architectures rather than package a flat APK. Only one arch of libopencv_java3.so will be packaged into your split APK. For example, you can use the configuration below to build only for x86, armeabi-v7a and mips architectures in your build.gradle

splits {
    abi {
      enable true
      reset()
      include "x86", "armeabi-v7a", "mips"
      universalApk false
    }
  }

More information about reduce apk size by splitting, see here.

Or is it possible just to extract only the feature from OpenCV which I am interested in and create .so for those features?

Yes, of course. The building process for opencv is fully customized. If you have already know how to build opencv for Android, go to step 2 directly.

step 1

get the source of opencv

create directory opencv_build

change to root directory of opencv you just cloned

invoke the build script platforms/android/build_sdk.py --ndk_path $ANDROID_NDK_ROOT --sdk_path $ANDROID_SDK_ROOT ../opencv_build .

Note

The build procedure need android command to build apk, so the Android SDK tool version must less than 25.3.0, from 25.3.0, android command has been removed.

step 2

Assume the step 1 above run properly. Here I take armeabi-v7a as an example.

Go to directory opencv_build/o4a/lib/armeabi-v7a

You will find many *.a for different opencv module, the library libopencv_java3.so also in this directory

Create a tiny version share library from the module you need, e.g

$ arm-linux-androideabi-gcc -shared -o libopencv_tiny.so --sysroot=$ANDROID_NDK_ROOT/platforms/android-9/arch-arm -Wl,--whole-archive libopencv_core.a libopencv_imgcodecs.a libopencv_imgproc.a -Wl,--no-whole-archive
$ du -h libopencv_tiny.so
5.2M    libopencv_tiny.so
$ arm-linux-androideabi-strip --strip-unneeded libopencv_tiny.so
$ du -h libopencv_tiny.so
4.1M    libopencv_tiny.so
$ du -h libopencv_java3.so
9.8M    libopencv_java3.so

The tiny version which include core, image codecs and image proc has a size 4.1M after strip, but the full version libopencv_java3.so has a size of 9.8M.

I use libopencv_tiny.so as the name just for convenience, you have to use the same name libopencv_java3.so in your project. Otherwise System.loadLibrary in Java can not find the native library.

For the rest of the architecture you need, e.g arm64-v8a, do the same.


问:
What is fairness in multi-threading programming?
What is thread fairness or fairness in concurrent/multi-threaded programming?

I have googled, there is loads of info on multi-threading but not exactly on fairness.

Can some one explain. An example is most welcome.

答:
Fairness basically resembles to the likelihood that different threads are able to advance whatever they are doing. 100% fairness means: all threads should be advancing their work in almost equal portions; 0% fairness means that one single thread might be advancing all the time, and all other threads never (or almost never) make any progress.

It very much depends on your requirements how exactly fairness is required or achieved.

Example: the zOS operating system has a component called the workload manager. This component works policy based. It allows you to say for example: "no matter what, I want that application X always gets 80% of CPU power; Y is important too, Z I dont care". That could mean: when the system gets under intensive load (so 100% of the CPUs consumed all the time) - X gets 80%, Y gets 20%, and Z gets nothing.

Taking this "process" view down to threads: in an unfair setup, threads might be starving. Meaning: some threads are able to advance, but other threads never get CPU cycles, therefore they can never do what they are supposed to do. And please note: thread fairness is not (necessarily) connected to system load.

See here for further reading.


问:
C++: how to build my own utility library?
I am starting to be proficient enough with C++ so that I can write my own C++ based scripts (to replace bash and PHP scripts I used to write before).

I find that I am starting to have a very small collection of utility functions and sub-routines that I'd like to use in several, otherwise unrelated C++ scripts.

I know I am not supposed to reinvent the wheel and that I could use external libraries for some of the utilities I'm creating for myself. However, it's fun to create my own utility functions, they are perfectly tailored to the job I have in mind, and it's for me a large part of the learning process. I'll see about using more polished external libraries when I am proficient enough to work on more serious, long term projects.

So, the question is: how do I manage my personal utility library in a way that the functions can be easily included in my various scripts?

I am using linux/Kubuntu, vim, g++, etc. and mostly coding CLI scripts.

Don't assume too much in terms of experience! ;) Links to tutorials or places where relevant topics are properly documented are welcome.

答:
Unless it's very large, you should probably just keep your utility library in a .h file (for the declarations) and a .cpp file (for the implementation).

Just copy both files into your project folders and use #include "MyLibrary.h", or set the appropriate directory settings so you can use #include <MyLibrary.h> without copying the files each time you want to use them.

If the library gains substantial size, you might consider looking into static libraries.

ContentLicense: CC BY-SA 2.5


问:
Website does not render correctly on mobile browser(s) after upload to server
I'm not an expert in web and I composed and updated my website recently. I ran all the test that I could on DreamWeaver CC and tested on multiple mobile devices (tablet, android and iphone); all seems to work fine. Until I uploaded the site to my server, the site start to act weird.

1st problem:
It is a portfolio website with individual pages to corresponding projects. On each project page, the first image on the lightbox has always gone missing; but clicking into the lightbox I can find the missing image (the preview image and the lightbox image share the same source so if the lightbox can find the image it implies that the image is on the server and the path is correct).

2nd problem:
when the browser is shrink below certain size, a toggle menu will replace the content on the header, clicking the toggle menu will show a pop up menu to site links. For some reason, after uploading the site to server, the toggle menu pop up never work.

3rd problem:
The above problem is never apparent on desktop browser(all image shows up correctly; toggle menu works). To make the problem more complicated, I can't confirm if it is device or browser oriented problem. For example, the site works on chrome browser on my iphone and nexus 5(android), but problem occurs on my xperia tablet(android) chrome browser; on my xperia tablet, the site works perfectly on firefox.

Does anybody has any idea what the potential cause to the problem, and perhaps a direction to a solution?

Here's the link to my site: http://www.itsatommy.com

Thank you for your time and look forward to any reply.

答: Looks fine to me (Google Chrome), you need to use media queries for some certain resolutions. You also need to use some cross browser css tags lide "-webkit, -moz, -o" etc.</p>


问:
Dispose widget error message
When I try to dispose any widget or an object - for example

myPopupWidget.dispose()

I have this message in my browser console:

"000706 qx.ui.core.queue.Layout: Error in the 'Layout'
  queue:TypeError: Cannot read property 'setStyles' of null TypeError:
  Cannot read property 'setStyles' of null".

What am I doing wrong?

答:
Looking at your example, you're trying do dispose a widget attached to your root's application. So, first you have to remove this widget from it's parent and then dispose it :

```<code>popuPP.exclude();
//or
this.getRoot().remove(popuPP);
//then
popuPP.dispose();
</code>```

Or you can use destroy (it removes this widget from its parent and disposes it) :

```<code>popuPP.destroy();
</code>```

Title: Dispose widget error message

Body:
Looking at your example, you're trying do dispose a widget attached to your root's application. So, first you have to remove this widget from it's parent and then dispose it :

popuPP.exclude();
//or
this.getRoot().remove(popuPP);
//then
popuPP.dispose();

Or you can use destroy (it removes this widget from its parent and disposes it) :

popuPP.destroy();


问:
Automatically generate list of tor exit nodes
I want to automatically generate a list of tor exit nodes that can reach a certain IP address. I scoured the internetfor a while and came across this piece of code from http://sjoerd-hemminga.com/blog/2012/10/block-tor-exit-nodes-using-iptables/

```<code>if [[ -z "$1" ]]; then
  echo Usage: $0 "<your host's ip>"
  exit 1
fi

hostip=$1

for i in $(wget https://check.torproject.org/cgi-bin/TorBulkExitList.py\?ip=$hostip -O- -q |\
    grep -E '^[[:digit:]]+(\.[[:digit:]]+){3}$'); do
  sudo iptables -A INPUT -s "$i" -j DROP
done
</code>```

Can someone please help me understand this code better, because every time I try to run it, it produces errors.

Any alternate answers are welcomed but I would like if they are in Python.

答:
Here(https://github.com/RD17/DeTor) is a simple REST API to determine whether a request was made from TOR network or not.

The request is:
curl -X GET http://detor.ambar.cloud/.

The response is

{
  "sourceIp": "104.200.20.46",
  "destIp": "89.207.89.82",
  "destPort": "8080",
  "found": true
}

Body:
I want to automatically generate a list of tor exit nodes that can reach a certain IP address. I scoured the internetfor a while and came across this piece of code from http://sjoerd-hemminga.com/blog/2012/10/block-tor-exit-nodes-using-iptables/

if [[ -z "$1" ]]; then
  echo Usage: $0 "<your host's ip>"
  exit 1
fi

hostip=$1

for i in $(wget https://check.torproject.org/cgi-bin/TorBulkExitList.py\?ip=$hostip -O- -q |\
    grep -E '^[[:digit:]]+(\.[[:digit:]]+){3}$'); do
  sudo iptables -A INPUT -s "$i" -j DROP
done

Can someone please help me understand this code better, because every time I try to run it, it produces errors.

Any alternate answers are welcomed but I would like if they are in Python.


问:
TYPO3 login BE user via code
TYPO3 version 7.6.18. How login BE user via code ? Is it possible? Help me please.

may be something like that ?

```<code>if(empty($GLOBALS['TSFE']->fe_user->user['uid'])) {
            $login = new StandartLogin();
            $login->login($username, $password);
        }
</code>```

but it works fo FE user

答:
Maybe the extension simulatebe is enough for you.

It can automatically create a backend login when a frontend user logs in: https://docs.typo3.org/typo3cms/extensions/simulatebe/Introduction/Index.html

Title: TYPO3 login BE user via code

Body:
TYPO3 version 7.6.18. How login BE user via code ? Is it possible? Help me please.

may be something like that ?

if(empty($GLOBALS['TSFE']->fe_user->user['uid'])) {
            $login = new StandartLogin();
            $login->login($username, $password);
        }

but it works fo FE user


问:
What does threadsafe mean?
Recently I tried to Access a textbox from a thread (other than the UI thread) and an exception was thrown. It said something about the "code not being thread safe" and so I ended up writing a delegate (sample from MSDN helped) and calling it instead.

But even so I didn't quite understand why all the extra code was necessary.

Update:
Will I run into any serious problems if I check

```<code>Controls.CheckForIllegalCrossThread..blah =true
</code>```

答:
In real world example for the layman is

Let's suppose you have a bank account with the internet and mobile banking and your account have only $10.
You performed transfer balance to another account using mobile banking, and the meantime, you did online shopping using the same bank account.
If this bank account is not threadsafe, then the bank allows you to perform two transactions at the same time and then the bank will become bankrupt.

Threadsafe means that an object's state doesn't change if simultaneously multiple threads try to access the object.

Title: What does threadsafe mean?

Body:
Recently I tried to Access a textbox from a thread (other than the UI thread) and an exception was thrown. It said something about the "code not being thread safe" and so I ended up writing a delegate (sample from MSDN helped) and calling it instead.

But even so I didn't quite understand why all the extra code was necessary.

Update:
Will I run into any serious problems if I check

Controls.CheckForIllegalCrossThread..blah =true


问:
Better way to search character in vector of vectors in scala
I have a requirement where I have to search a character in vector of vectors. I have written a method which is very crude. What is a better way to search an element in vector of vectors.

Here is my code:

```<code>def search( xs: Vector[Vector[Char]], char: Char, rowIndex: Int): Pos = xs.headOption match {
  case None =>  Pos(-1, -1)
  case Some(row) => {
    val tuple = searchHelper(row, char, 0)
    if(tuple._1)
      Pos(rowIndex, tuple._2)
    else
      search(xs.tail, char, rowIndex +1)
  }
}

def searchHelper(xs: Vector[Char], char: Char, colIndex: Int): (Boolean, Int) = xs.headOption match {
  case None => (false, colIndex)
  case Some(col) =>
    if(col == char)
      (true, colIndex)
    else
      searchHelper(xs.tail, char, colIndex +1)
}

search(vector, c, 0)
</code>```

Here is the input:

```<code>val input =
  """ooo-------
    |oSoooo----
    |ooooooooo-
    |-ooooooooo
    |-----ooToo
    |------ooo-""".stripMargin

val vector =
  Vector(input.split("\n").map(str => Vector(str: _*)): _*)

val c = 'S'
</code>```

答:
If, with better, you mean more concise, you could try leveraging the methods on Scalas collections:

```<code>def search( xs: Vector[Vector[Char]], c: Char ): (Int, Int) = {
    var innerIndex = -1
    val outerIndex = xs.indexWhere { inner =>
        innerIndex = inner.indexOf(c)
        innerIndex > -1
    }
    (outerIndex, innerIndex)
}
</code>```

This assumes that you only need the first occurence of that character.

indexWhere terminates as soon as the innerIndex is larger than -1.

Maybe another possibility, which goes more in your recursive direction (and without a mutable var), but also with minimal iterations:

```<code>@tailrec
def search(xs: Vector[Vector[Char]], c: Char, n: Int = 0): (Int, Int) = {
  if (n > xs.size - 1) (-1, -1)
  else
    xs(n).indexOf(c) match {
      case -1 => search(xs, c, n + 1)
      case i => (n, i)
    }
}
</code>```

Body:
I have a requirement where I have to search a character in vector of vectors. I have written a method which is very crude. What is a better way to search an element in vector of vectors.

Here is my code:

def search( xs: Vector[Vector[Char]], char: Char, rowIndex: Int): Pos = xs.headOption match {
  case None =>  Pos(-1, -1)
  case Some(row) => {
    val tuple = searchHelper(row, char, 0)
    if(tuple._1)
      Pos(rowIndex, tuple._2)
    else
      search(xs.tail, char, rowIndex +1)
  }
}

def searchHelper(xs: Vector[Char], char: Char, colIndex: Int): (Boolean, Int) = xs.headOption match {
  case None => (false, colIndex)
  case Some(col) =>
    if(col == char)
      (true, colIndex)
    else
      searchHelper(xs.tail, char, colIndex +1)
}

search(vector, c, 0)

Here is the input:

val input =
  """ooo-------
    |oSoooo----
    |ooooooooo-
    |-ooooooooo
    |-----ooToo
    |------ooo-""".stripMargin

val vector =
  Vector(input.split("\n").map(str => Vector(str: _*)): _*)

val c = 'S'

Body:
If, with better, you mean more concise, you could try leveraging the methods on Scalas collections:

def search( xs: Vector[Vector[Char]], c: Char ): (Int, Int) = {
    var innerIndex = -1
    val outerIndex = xs.indexWhere { inner =>
        innerIndex = inner.indexOf(c)
        innerIndex > -1
    }
    (outerIndex, innerIndex)
}

This assumes that you only need the first occurence of that character.

indexWhere terminates as soon as the innerIndex is larger than -1.

Maybe another possibility, which goes more in your recursive direction (and without a mutable var), but also with minimal iterations:

@tailrec
def search(xs: Vector[Vector[Char]], c: Char, n: Int = 0): (Int, Int) = {
  if (n > xs.size - 1) (-1, -1)
  else
    xs(n).indexOf(c) match {
      case -1 => search(xs, c, n + 1)
      case i => (n, i)
    }
}


问:
Creating arrays with your own data structures
From what I understand in order to initialize a array you would call something like this:

```<code>from array import *
array_example = array([type of some sort],[entries into the array])
</code>```

where type of some sort could be anything such as an integer. My question is if there is any way for me use a data structure I have defined(Letter) and use that type when initializing an array.

Here is what I tried:

```<code>x = Letter('A')
i = type(x)
array = array(i,[x])
</code>```

where I then get the following error:

builtins.TypeError: array() argument 1 must be a unicode character, not type

Sorry if it's a stupid question

```<code>class Letter:

    def __init__(self, letter):
        """
        -------------------------------------------------------
        Initialize a Letter object.
        Use: l = Letter(char)
        -------------------------------------------------------
        Preconditions:
            letter - an single uppercase letter of the alphabet (str)
        Postconditions:
            Letter values are set.
        -------------------------------------------------------
        """
        assert letter.isalpha() and letter.isupper(), "Invalid letter"

        self.letter = letter
        self.count = 0
        self.comparisons = 0
        return

    def __str__(self):
        """
        -------------------------------------------------------
        Creates a formatted string of Letter data.
        Use: print(m)
        Use: s = str(m)
        -------------------------------------------------------
        Postconditions:
            returns:
            the value of self.letter (str)
        -------------------------------------------------------
        """
        return "{}: {}, {}".format(self.letter, self.count, self.comparisons)

    def __eq__(self, rs):
        """
        -------------------------------------------------------
        Compares this Letter against another Letter for equality.
        Use: l == rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if name and origin match, False otherwise (boolean)
        -------------------------------------------------------
        """
        self.count += 1
        self.comparisons += 1
        result = self.letter == rs.letter
        return result

    def __lt__(self, rs):
        """
        -------------------------------------------------------
        Determines if this Letter comes before another.
        Use: f < rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if Letter precedes rs, False otherwise (boolean)
        -------------------------------------------------------
        """
        self.comparisons += 1
        result = self.letter < rs.letter
        return result

    def __le__(self, rs):
        """
        -------------------------------------------------------
        Determines if this Letter precedes or is or equal to another.
        Use: f <= rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if this Letter precedes or is equal to rs,
              False otherwise (boolean)
        -------------------------------------------------------
        """
        self.comparisons += 1
        result = self.letter <= rs.letter
        return result
</code>```

答:
As the documentation shows, an array can only contain basic types - integers, bytes, etc.

But there doesn't seem to be any reason why you can't just use a list here.

Body:
From what I understand in order to initialize a array you would call something like this:

from array import *
array_example = array([type of some sort],[entries into the array])

where type of some sort could be anything such as an integer. My question is if there is any way for me use a data structure I have defined(Letter) and use that type when initializing an array.

Here is what I tried:

x = Letter('A')
i = type(x)
array = array(i,[x])

where I then get the following error:

builtins.TypeError: array() argument 1 must be a unicode character, not type

Sorry if it's a stupid question

class Letter:

    def __init__(self, letter):
        """
        -------------------------------------------------------
        Initialize a Letter object.
        Use: l = Letter(char)
        -------------------------------------------------------
        Preconditions:
            letter - an single uppercase letter of the alphabet (str)
        Postconditions:
            Letter values are set.
        -------------------------------------------------------
        """
        assert letter.isalpha() and letter.isupper(), "Invalid letter"

        self.letter = letter
        self.count = 0
        self.comparisons = 0
        return

    def __str__(self):
        """
        -------------------------------------------------------
        Creates a formatted string of Letter data.
        Use: print(m)
        Use: s = str(m)
        -------------------------------------------------------
        Postconditions:
            returns:
            the value of self.letter (str)
        -------------------------------------------------------
        """
        return "{}: {}, {}".format(self.letter, self.count, self.comparisons)

    def __eq__(self, rs):
        """
        -------------------------------------------------------
        Compares this Letter against another Letter for equality.
        Use: l == rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if name and origin match, False otherwise (boolean)
        -------------------------------------------------------
        """
        self.count += 1
        self.comparisons += 1
        result = self.letter == rs.letter
        return result

    def __lt__(self, rs):
        """
        -------------------------------------------------------
        Determines if this Letter comes before another.
        Use: f < rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if Letter precedes rs, False otherwise (boolean)
        -------------------------------------------------------
        """
        self.comparisons += 1
        result = self.letter < rs.letter
        return result

    def __le__(self, rs):
        """
        -------------------------------------------------------
        Determines if this Letter precedes or is or equal to another.
        Use: f <= rs
        -------------------------------------------------------
        Preconditions:
            rs - [right side] Letter to compare to (Letter)
        Postconditions:
            returns:
            result - True if this Letter precedes or is equal to rs,
              False otherwise (boolean)
        -------------------------------------------------------
        """
        self.comparisons += 1
        result = self.letter <= rs.letter
        return result


问:
Set a hidden property to a ListBox Item - C#
hey,
Does anybody knows a way to set a hidden value to a ListBox Item.
As an alternative i can use another listbox simultaneously.
Thanks. </p>

答:
You are probably looking for the Tag property. It holds an object type, which means you can save a reference to anything in there.

Although before setting on using the tag property, take a look at ItemsSource. Basically you can tie a collection of things to be the provider for your listbox, it's usually a superior alternative to dealing with Listbox items individually.


问:
Mipmap drawables for icons
Since Android 4.3 (Jelly Bean) we can now make use of the res/mipmap folders to store "mipmap" images.

For example, Chrome for Android stores its icons in these folders instead of the more normal res/drawable folders.

How are these mipmap images different from the other familiar drawable images?

I see that in my manifest, we use the @mipmap/ qualifier, instead of @drawable/, which makes sense given the resource folder name:

```<code><activity
    android:name=".MipmapDemp"
    android:icon="@mipmap/ic_launcher" />
</code>```

References:

The Android 4.3 APIs document has the following to say:

Using a mipmap as the source for your bitmap or drawable is a simple
  way to provide a quality image and various image scales, which can be
  particularly useful if you expect your image to be scaled during an
  animation.

Android 4.2 (API level 17) added support for mipmaps in the Bitmap
  class—Android swaps the mip images in your Bitmap when you've supplied
  a mipmap source and have enabled setHasMipMap(). Now in Android 4.3,
  you can enable mipmaps for a BitmapDrawable object as well, by
  providing a mipmap asset and setting the android:mipMap attribute in a
  bitmap resource file or by calling hasMipMap().

I don't see anything in there that helps me to understand.

XML Bitmap resources have an android:mipMap property:

Boolean. Enables or disables the mipmap hint. See setHasMipMap() for
  more information. Default value is false.

This does not apply to launcher icons as far as I can see.

The question was raised on Google Groups (The purpose of resource name "mipmap"?!), to which Romain Guy replied:

It's useful to provide an image at a larger resolution that would
  normally be computed (for instance, on an mdpi device, Launcher might
  want the larger hdpi icon to display large app shortcuts.)

I feel like this almost makes sense of it, but not quite.

I'm still inclined to go with Randy Sugianto's follow up:

What are the advantages of this? Is there any guide how to use
  mipmaps, probably for better launcher icons?

Of course, Wikipedia has a page for "Mipmap", which refers to an older technique invented in 1983, that I can't quite relate to the current Android implementation.

Should we be storing all our app icons in res/mipmap folders these days, and what are the guidelines for these mipmap images?

Update #1

Here's a blog post that tries to explain it a bit.

Mipmapping for drawables in Android 4.3

But the image used in that blog post shows what looks like one file with many logos in it. This is not what I see in Chrome's mipmap folder.

Chrome's mipmap-hdpi folder contains three images. One is the Chrome logo, on its own.

Strangely, it is 72x72, not 48x48 which I would expect to see.

Perhaps that is all there is to this - we just need to keep bigger icons in the mipmap folders?

Update #2

The Android Developers Blog post of 23/10/2014 again confirms the idea of using the mipmap folders for application icons:

Getting Your Apps Ready for Nexus 6 and Nexus 9

When talking about the Nexus 6 screen density, the author writes:

It’s best practice to place your app icons in mipmap- folders (not the
  drawable- folders) because they are used at resolutions different from
  the device’s current density. For example, an xxxhdpi app icon can be
  used on the launcher for an xxhdpi device.

Update #3

Note that Android Studio creates the ic_launcher.png icons in the mipmap... folders rather than the drawable... folders that Eclipse used to create them in.

答:
There are two cases you deal with when working with images in Android:

You want to load an image for your device density and you are going to use it “as is”, without changing its actual size. In this case you
  should work with drawables and Android will give you the best fitting
  image.

You want to load an image for your device density, but this image is going to be scaled up or down. For instance this is needed when you
  want to show a bigger launcher icon, or you have an animation, which
  increases image’s size. In such cases, to ensure best image quality,
  you should put your image into mipmap folder. What Android will do is,
  it will try to pick up the image from a higher density bucket instead
  of scaling it up.

SO

Thus, the rule of thumb to decide where to put your image into would
  be:

Launcher icons always go into mipmap folder.

Images, which are often scaled up (or extremely scaled down) and whose quality is critical for the app, go into mipmap folder as
  well.

All other images are usual drawables.

Citation from this article.

Title: Mipmap drawables for icons

Body:
Since Android 4.3 (Jelly Bean) we can now make use of the res/mipmap folders to store "mipmap" images.

For example, Chrome for Android stores its icons in these folders instead of the more normal res/drawable folders.

How are these mipmap images different from the other familiar drawable images?

I see that in my manifest, we use the @mipmap/ qualifier, instead of @drawable/, which makes sense given the resource folder name:

<activity
    android:name=".MipmapDemp"
    android:icon="@mipmap/ic_launcher" />

References:

The Android 4.3 APIs document has the following to say:

Using a mipmap as the source for your bitmap or drawable is a simple
  way to provide a quality image and various image scales, which can be
  particularly useful if you expect your image to be scaled during an
  animation.

Android 4.2 (API level 17) added support for mipmaps in the Bitmap
  class—Android swaps the mip images in your Bitmap when you've supplied
  a mipmap source and have enabled setHasMipMap(). Now in Android 4.3,
  you can enable mipmaps for a BitmapDrawable object as well, by
  providing a mipmap asset and setting the android:mipMap attribute in a
  bitmap resource file or by calling hasMipMap().

I don't see anything in there that helps me to understand.

XML Bitmap resources have an android:mipMap property:

Boolean. Enables or disables the mipmap hint. See setHasMipMap() for
  more information. Default value is false.

This does not apply to launcher icons as far as I can see.

The question was raised on Google Groups (The purpose of resource name "mipmap"?!), to which Romain Guy replied:

It's useful to provide an image at a larger resolution that would
  normally be computed (for instance, on an mdpi device, Launcher might
  want the larger hdpi icon to display large app shortcuts.)

I feel like this almost makes sense of it, but not quite.

I'm still inclined to go with Randy Sugianto's follow up:

What are the advantages of this? Is there any guide how to use
  mipmaps, probably for better launcher icons?

Of course, Wikipedia has a page for "Mipmap", which refers to an older technique invented in 1983, that I can't quite relate to the current Android implementation.

Should we be storing all our app icons in res/mipmap folders these days, and what are the guidelines for these mipmap images?

Update #1

Here's a blog post that tries to explain it a bit.

Mipmapping for drawables in Android 4.3

But the image used in that blog post shows what looks like one file with many logos in it. This is not what I see in Chrome's mipmap folder.

Chrome's mipmap-hdpi folder contains three images. One is the Chrome logo, on its own.

Strangely, it is 72x72, not 48x48 which I would expect to see.

Perhaps that is all there is to this - we just need to keep bigger icons in the mipmap folders?

Update #2

The Android Developers Blog post of 23/10/2014 again confirms the idea of using the mipmap folders for application icons:

Getting Your Apps Ready for Nexus 6 and Nexus 9

When talking about the Nexus 6 screen density, the author writes:

It’s best practice to place your app icons in mipmap- folders (not the
  drawable- folders) because they are used at resolutions different from
  the device’s current density. For example, an xxxhdpi app icon can be
  used on the launcher for an xxhdpi device.

Update #3

Note that Android Studio creates the ic_launcher.png icons in the mipmap... folders rather than the drawable... folders that Eclipse used to create them in.


答: As you can see in the docs a python array can only hold numerical values.

Title: Creating arrays with your own data structures


问:
Google Maps API JS Marker - Django
In Django, I am trying to populate the google maps api by rendering the template with info from views.

I can get the results to return to the template however I am having difficulty implementing it into the javascript tag with Django.  Any suggestions.

I would like the django data to return into the addmarker function in JS

Python - Django Views

```<code>    def maps_multi(request):

        address_list = CustomerOrder.objects.filter(city__icontains = 'CA').distinct() # pulls all unique addresses in California
        address_list1 = address_list[0:3] # temporarily select first three addresses from list to test

        geolocator = GoogleV3()

        add_list=[]
        for x in address_list1:
            add_city = x.city
            location = geolocator.geocode(add_city)
            add_list.append(location)
            print(add_list)

        context = {'location': add_list}

        return render(request, 'orderdisplay/maps_multi.html', context)

//JAVASCRIPT

      // New map
      var map = new google.maps.Map(document.getElementById('map'), options);

      // INSERT Lat Lng via django here
      addMarker({coords:{lat:33.6846, lng:-117.8265}});
      addMarker({coords:{lat:34.0522, lng:-118.2437}});
      addMarker({coords:{lat:33.9533, lng:-117.3962}});

      // Add Marker Function
      function addMarker(props){
        var marker = new google.maps.Marker({
          position: props.coords,
          map:map,
          icon:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
        });

       }
    }
  </script>
  <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=*****&callback=initMap">
    </script>
</code>```

答:
I assume your js code is placed within your orderdisplay/maps_multi.html template. Then you can simply do this:</p>

```<code>// New map
var map = ...

// INSERT Lat Lng via django here

{% for location in add_list %}
    addMarker({coords:{
        lat: {{ location.latitude|stringformat:'f' }},
        lng: {{ location.longitude|stringformat:'f' }}
        }
    });
{% endfor %}
</code>```

Title: Google Maps API JS Marker - Django

Body:
In Django, I am trying to populate the google maps api by rendering the template with info from views.

I can get the results to return to the template however I am having difficulty implementing it into the javascript tag with Django.  Any suggestions.

I would like the django data to return into the addmarker function in JS

Python - Django Views

    def maps_multi(request):

        address_list = CustomerOrder.objects.filter(city__icontains = 'CA').distinct() # pulls all unique addresses in California
        address_list1 = address_list[0:3] # temporarily select first three addresses from list to test

        geolocator = GoogleV3()

        add_list=[]
        for x in address_list1:
            add_city = x.city
            location = geolocator.geocode(add_city)
            add_list.append(location)
            print(add_list)

        context = {'location': add_list}

        return render(request, 'orderdisplay/maps_multi.html', context)

//JAVASCRIPT

      // New map
      var map = new google.maps.Map(document.getElementById('map'), options);

      // INSERT Lat Lng via django here
      addMarker({coords:{lat:33.6846, lng:-117.8265}});
      addMarker({coords:{lat:34.0522, lng:-118.2437}});
      addMarker({coords:{lat:33.9533, lng:-117.3962}});

      // Add Marker Function
      function addMarker(props){
        var marker = new google.maps.Marker({
          position: props.coords,
          map:map,
          icon:'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png'
        });

       }
    }
  </script>

Body:
I assume your js code is placed within your orderdisplay/maps_multi.html template. Then you can simply do this:

// New map
var map = ...

// INSERT Lat Lng via django here

{% for location in add_list %}
    addMarker({coords:{
        lat: {{ location.latitude|stringformat:'f' }},
        lng: {{ location.longitude|stringformat:'f' }}
        }
    });
{% endfor %}


答: Python arrays can be used with a limited set of predefined types. You cannot use them with custom types. The first argument is indeed a single character, and it specifies which of the allowed types the array will contain. See here.


问:
Execute function on button press (unity3d/C#)
Basically, what I'm trying to do is when pressing Z - it executes function to spin, and X - it executes function to stop spinning. Before, I had UI buttons which worked perfectly fine, now I try doing it by button but nothing happens.

Also, if you can suggest on how to make it start spinning and stop spinning by only pressing "Space" button, that'd be great.

Heres my code so far:

```<code>using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class spin : MonoBehaviour
{
    public float speed = 500f;
    public Button starter;
    public Button stopper;
    bool isSpinning = false;

    IEnumerator spinnerCoroutine;

    void Start()
    {
        //The spin function
        spinnerCoroutine = spinCOR();

        //Button btn = starter.GetComponent<Button>();
        //Button butn = stopper.GetComponent<Button>();

        //butn.onClick.AddListener(FidgetSpinnerStop);
        //btn.onClick.AddListener(FidgetSpinnerStart);

        if (Input.GetKey(KeyCode.Z)) {

            FidgetSpinnerStart();
        }

        if (Input.GetKey(KeyCode.X)) {
            FidgetSpinnerStop();
        }
    }

    IEnumerator spinCOR()
    {
        //Spin forever untill FidgetSpinnerStop is called
        while (true)
        {
            transform.Rotate(Vector3.up, speed * Time.deltaTime);
            //Wait for the next frame
            yield return null;
        }
    }

    void FidgetSpinnerStart()
    {
        //Spin only if it is not spinning
        if (!isSpinning)
        {
            isSpinning = true;
            StartCoroutine(spinnerCoroutine);
        }
    }

    void FidgetSpinnerStop()
    {
        //Stop Spinning only if it is already spinning
        if (isSpinning)
        {
            StopCoroutine(spinnerCoroutine);
            isSpinning = false;
        }
    }
}
</code>```

Thanks.

答:
Your input logic is only executed once, when Start() is executed.

Put it in the Update() method to check for it every frame.

In this case remove the coroutine and put its logic (without the while-loop) into the Update() method aswell.

```<code>public class spin : MonoBehaviour
{
    [SerializeField]
    private float speed = 500f;

    [SerializeField]
    private Button starter;

    [SerializeField]
    private Button stopper;

    [SerializeField]
    bool isSpinning = false;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Z))
        {
            isSpinning = true ;
        }

        if (Input.GetKeyDown(KeyCode.X))
        {
            isSpinning = false ;
        }

        if( isSpinning )
        {
             transform.Rotate(Vector3.up, speed * Time.deltaTime)
        }
    }
}
</code>```

Further reading

Body:
Basically, what I'm trying to do is when pressing Z - it executes function to spin, and X - it executes function to stop spinning. Before, I had UI buttons which worked perfectly fine, now I try doing it by button but nothing happens.

Also, if you can suggest on how to make it start spinning and stop spinning by only pressing "Space" button, that'd be great.

Heres my code so far:

using UnityEngine;
using System.Collections;
using UnityEngine.UI;

public class spin : MonoBehaviour
{
    public float speed = 500f;
    public Button starter;
    public Button stopper;
    bool isSpinning = false;

    IEnumerator spinnerCoroutine;

    void Start()
    {
        //The spin function
        spinnerCoroutine = spinCOR();

        //Button btn = starter.GetComponent<Button>();
        //Button butn = stopper.GetComponent<Button>();

        //butn.onClick.AddListener(FidgetSpinnerStop);
        //btn.onClick.AddListener(FidgetSpinnerStart);

        if (Input.GetKey(KeyCode.Z)) {

            FidgetSpinnerStart();
        }

        if (Input.GetKey(KeyCode.X)) {
            FidgetSpinnerStop();
        }
    }

    IEnumerator spinCOR()
    {
        //Spin forever untill FidgetSpinnerStop is called
        while (true)
        {
            transform.Rotate(Vector3.up, speed * Time.deltaTime);
            //Wait for the next frame
            yield return null;
        }
    }

    void FidgetSpinnerStart()
    {
        //Spin only if it is not spinning
        if (!isSpinning)
        {
            isSpinning = true;
            StartCoroutine(spinnerCoroutine);
        }
    }

    void FidgetSpinnerStop()
    {
        //Stop Spinning only if it is already spinning
        if (isSpinning)
        {
            StopCoroutine(spinnerCoroutine);
            isSpinning = false;
        }
    }
}

Thanks.

Body:
Your input logic is only executed once, when Start() is executed.

Put it in the Update() method to check for it every frame.

In this case remove the coroutine and put its logic (without the while-loop) into the Update() method aswell.

public class spin : MonoBehaviour
{
    [SerializeField]
    private float speed = 500f;

    [SerializeField]
    private Button starter;

    [SerializeField]
    private Button stopper;

    [SerializeField]
    bool isSpinning = false;

    void Update()
    {
        if (Input.GetKeyDown(KeyCode.Z))
        {
            isSpinning = true ;
        }

        if (Input.GetKeyDown(KeyCode.X))
        {
            isSpinning = false ;
        }

        if( isSpinning )
        {
             transform.Rotate(Vector3.up, speed * Time.deltaTime)
        }
    }
}

Further reading


问:
How to change heatmap.2 color range in R?
I'm using gplot to produce a heatmap showing log2-fold changes of a treatment groups versus paired controls. With the following code:

```<code> heatmap.2(as.matrix(SeqCountTable), col=redgreen(75),
           density.info="none", trace="none", dendrogram=c("row"),
            symm=F,symkey=T,symbreaks=T, scale="none")
</code>```

I output a heat map with real fold change values (i.e., non Row-Z score) which is what I'm after, in the Red-Black-Green color scheme that is every biologist's favorite!

The actual range of log2-fold change is -3/+7, with many values in the -2/-1 and +1/+2 range, which appear as dark red/green (respectively). This makes the whole heatmap quite dark and so difficult to interpret.

Is there a way of skewing the color gradient to make it less linear? That is, so that the gradient from black to quite bright occurs over a smaller range?

And / or change the color range to be asymmetric, i.e., to run from -3/+7, as the data does, rather than -7/+7 as the scale currently does, with black still centered on zero?

答:
Here's another option for those not using heatmap.2 (aheatmap is good!)

Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:

```<code>breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)
</code>```

Body:
I'm using gplot to produce a heatmap showing log2-fold changes of a treatment groups versus paired controls. With the following code:

 heatmap.2(as.matrix(SeqCountTable), col=redgreen(75),
           density.info="none", trace="none", dendrogram=c("row"),
            symm=F,symkey=T,symbreaks=T, scale="none")

I output a heat map with real fold change values (i.e., non Row-Z score) which is what I'm after, in the Red-Black-Green color scheme that is every biologist's favorite!

The actual range of log2-fold change is -3/+7, with many values in the -2/-1 and +1/+2 range, which appear as dark red/green (respectively). This makes the whole heatmap quite dark and so difficult to interpret.

Is there a way of skewing the color gradient to make it less linear? That is, so that the gradient from black to quite bright occurs over a smaller range?

And / or change the color range to be asymmetric, i.e., to run from -3/+7, as the data does, rather than -7/+7 as the scale currently does, with black still centered on zero?

Body:
Here's another option for those not using heatmap.2 (aheatmap is good!)

Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:

breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)


问:
How to set width AND pad integer witdth String Formatter in Java
Given I have the following integers:

```<code>1, 10, 100
</code>```

I want to pad them with zeroes to have exactly 3 digits:

```<code>001
010
100
</code>```

and I want to print them prefixed by 10 spaces:

```<code>      001 //assume 10 spaces from the beginning of the line
      010
      100
</code>```

I want to use Java formatter string to accomplish this but am only successful in accomplishing one of the above mention conditions but not both at once.

Below are 2 expressions that I created that accomplish each one of these conditions:

```<code>    @Test
    public void test1() {

        String[] langs = { "TEXTX", "TEXTXXX", "TEXTXX" };
        int[] nums = {1, 10, 100};

        for (int i = 0; i < 3; i++) {

            String s = langs[i];
            int n = nums[i];

            System.out.printf("%1$s%2$14s%3$03d\n", s, " ", n);
        }

    }
</code>```

According to documentation the formatter string has the below form:

```<code>%[argument_index$][flags][width][.precision]conversion
</code>```

but apparently the zero padding flag parameter cannot be followed by width parameter as it is being parsed as one number resulting in a "long width".

How can this be rewritten to accomplish the above mentioned conditions?

NOTE:

My only idea was to explicitly add a single space to the arguments and try to manipulate it as an argument. Something like this:

```<code>System.out.printf("%1$s%2$10s%3$03d\n", s, " ", n);
</code>```

EDIT:

My apologies, I just realized that I didn't fully described my question. These numbers need to follow certain other strings of different length, like this:

```<code>textX       001
textXXX     010
textXX      100
</code>```

So that the spacing is variable.

答:
This answer is based on your latest edit, which revealed this data:

```<code>textX       001
textXXX     010
textXX      100
</code>```

Assuming that the second column always has a width of 3, then your problem distills down to figuring out how many spaces need to be added after the first text column.  Here is how you could do this in Java 7:

```<code>String text = "textXXX";
int n = 10 - text.length();
String padding = String.format("%0" + n + "d", 0).replace("0", " ");
</code>```

In Java 8 you could this to get the padding string:

```<code>String padding = String.join("", Collections.nCopies(n, " "));
</code>```

Body:
Given I have the following integers:

1, 10, 100

I want to pad them with zeroes to have exactly 3 digits:

001
010
100

and I want to print them prefixed by 10 spaces:

      001 //assume 10 spaces from the beginning of the line
      010
      100

I want to use Java formatter string to accomplish this but am only successful in accomplishing one of the above mention conditions but not both at once.

Below are 2 expressions that I created that accomplish each one of these conditions:

    @Test
    public void test1() {

        String[] langs = { "TEXTX", "TEXTXXX", "TEXTXX" };
        int[] nums = {1, 10, 100};

        for (int i = 0; i < 3; i++) {

            String s = langs[i];
            int n = nums[i];

            System.out.printf("%1$s%2$14s%3$03d\n", s, " ", n);
        }

    }

According to documentation the formatter string has the below form:

%[argument_index$][flags][width][.precision]conversion

but apparently the zero padding flag parameter cannot be followed by width parameter as it is being parsed as one number resulting in a "long width".

How can this be rewritten to accomplish the above mentioned conditions?

NOTE:

My only idea was to explicitly add a single space to the arguments and try to manipulate it as an argument. Something like this:

System.out.printf("%1$s%2$10s%3$03d\n", s, " ", n);

EDIT:

My apologies, I just realized that I didn't fully described my question. These numbers need to follow certain other strings of different length, like this:

textX       001
textXXX     010
textXX      100

So that the spacing is variable.

Body:
This answer is based on your latest edit, which revealed this data:

textX       001
textXXX     010
textXX      100

Assuming that the second column always has a width of 3, then your problem distills down to figuring out how many spaces need to be added after the first text column.  Here is how you could do this in Java 7:

String text = "textXXX";
int n = 10 - text.length();
String padding = String.format("%0" + n + "d", 0).replace("0", " ");

In Java 8 you could this to get the padding string:

String padding = String.join("", Collections.nCopies(n, " "));


问:
How do I use a variable in the WHERE condition of a MySQL query using a php variable?
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.

The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.

For testing I selected a user I knew had a rapsheet and used

```<code>$usersql = "SELECT *
 FROM character_data_store
 WHERE character_data_store.`key` = 'RapSheet'
 AND character_data_store.character_id = '216'";
</code>```

Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.

I've tried using:

```<code>$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove

$usersql = "SELECT *
  FROM character_data_store
  WHERE character_data_store.'key' = 'RapSheet'
  AND character_data_store.character_id = '$correctPlayer'";
</code>```

I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:

```<code>$usersql = "SELECT *
  FROM character_data_store
  WHERE character_data_store.'key' = 'RapSheet'
  AND character_data_store.character_id = {$_SESSION['selpid']}";
</code>```

Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?

It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".

How do I use a variable in the WHERE condition of a MySQL query using a php variable?

答:
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be

```<code>$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";
</code>```

You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.

Body:
I'm using PHP session variable to track character ID's between two tables, characters and character_data_store.

The session ID definitely has the correct ID as I have had to print its value before it goes into the mySQL query.

For testing I selected a user I knew had a rapsheet and used

$usersql = "SELECT *
 FROM character_data_store
 WHERE character_data_store.`key` = 'RapSheet'
 AND character_data_store.character_id = '216'";

Obviously I can't use this for all users as I need to confirm the right one has been selected so thats where the session variable comes in.

I've tried using:

$correctPlayer = $_SESSION['selpid'];
echo $correctPlayer; #confirm it's the right id and then remove

$usersql = "SELECT *
  FROM character_data_store
  WHERE character_data_store.'key' = 'RapSheet'
  AND character_data_store.character_id = '$correctPlayer'";

I did some searching on SO and I found that int's need to have double quotes around them not single quotes, I tried that and had no luck but someone else suggested putting the session ID in exactly which I tried next:

$usersql = "SELECT *
  FROM character_data_store
  WHERE character_data_store.'key' = 'RapSheet'
  AND character_data_store.character_id = {$_SESSION['selpid']}";

Each time I do this I get mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given which SO tells me is because this operation results to false, I assume because it's not accepting the playerID from selpid or $correctPlayer?

It definitely works with the testing user where the playerID is inserted directly into the query. But I can't think of a way to do that since I need to match the playerID from table "characters" where the search is done against their first and last name and then pull the rapsheet data against the same playerID in table "character_data_store".

How do I use a variable in the WHERE condition of a MySQL query using a php variable?

Body:
You have obvious error in your code. You are missing quotes in {$_SESSION['selpid']} and you are using quotes in column name. Your query should be

$usersql = "SELECT * FROM character_data_store WHERE character_data_store.`key` = 'RapSheet' AND character_data_store.character_id = '{$_SESSION['selpid']}'";

You should not use quotes in column name, instead use backquotes(`) if you really need. I recommend prepared statements.


问:
how can i include files for all functions in php
i'm new in php as you know and i have some problems (like any new starts) and my problem is i cant include file like config.php to all functions in the files

i have just 3 files

in config.php i just connect to database in mysqli and the variable is $connect

in functions.php there is just a simple functions

```<code>include('config.php');
function rows($table){
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}
</code>```

in index.php

```<code>include('functions.php');
echo rows('books');
</code>```

and the problem is i cant get $connect variable from config.php to work in functions in functions.php file.

EDIT

when i include config.php inside the functions everything will be ok,
like this

```<code>function rows($table){
include('config.php');
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}
</code>```

but i don't want to do this because i want to include a config.php for all functions i have.

Thanks

答:
$connect exists in 'config.php'.

In your function(s), declare $connect as 'global' ie: it exists outside the scope of this function.

```<code>function rows($table){

    global $connect;

    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}
</code>```

Body:
i'm new in php as you know and i have some problems (like any new starts) and my problem is i cant include file like config.php to all functions in the files

i have just 3 files

in config.php i just connect to database in mysqli and the variable is $connect

in functions.php there is just a simple functions

include('config.php');
function rows($table){
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}

in index.php

include('functions.php');
echo rows('books');

and the problem is i cant get $connect variable from config.php to work in functions in functions.php file.

EDIT

when i include config.php inside the functions everything will be ok,
like this

function rows($table){
include('config.php');
    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}

but i don't want to do this because i want to include a config.php for all functions i have.

Thanks

Body:
$connect exists in 'config.php'.

In your function(s), declare $connect as 'global' ie: it exists outside the scope of this function.

function rows($table){

    global $connect;

    $gettables = mysqli_query($connect,"SELECT * FROM $table");
    $numrows = mysqli_num_rows($gettables);
    return($numrows);
}


问:
DEP0600 Error when deploying UWP project
After Visual Studio (Community 2015 Update 3) crashed on deploying a UWP project with a bluescreen (Unexpected Store Exception, this has happened before), i can not deploy any projects anymore. I tried with the project VS crashed on, previous versions of that project as well as completely empty new projects.

The error message is the following:

DEP0600 : The following unexpected error occurred during deployment:

'.', hexadecimal value 0x00, is an invalid character. Line 1, position 1.

Repairing Visual Studio made no difference.

I can not locate the problem, but assume something was corrupted during the crash. Would a complete reinstall of VS do more than just a repair here? Does this maybe even require more drastic steps?

Thanks,

Reinhold

答:
While working on a UWP app for Raspberry Pi 2 I experienced a similar DEP0600 error. Things like restarting Visual Studio or removing temp files didn't work.

It was only after I simply rebooted my Pi I was able to deploy again