text:
Q: How to display serial number in datagridview? i am using windows application with C#.
I want to display Serial number in datagridview.

A: You need to bind DataBindingComplete event of datagridview.
private void gridStateZone_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        LoadSerial(gridStateZone);
    }

private void LoadSerial(DataGridView grid)
    {
        foreach (DataGridViewRow row in grid.Rows)
        {
            grid.Rows[row.Index].HeaderCell.Value = string.Format("{0}  ", row.Index + 1).ToString();
            row.Height = 25;
        }
    }

It's work for me.

A: In WinForms Applications, to display the row number in the row header, we could use the RowPostPaint event of DataGridView control.

Usage: Suppose grid is named as dgvUserDetails

Delegate
this.dgvUserDetails.RowPostPaint += new System.Windows.Forms.DataGridViewRowPostPaintEventHandler(this.dgvUserDetails_RowPostPaint);

Code
private void dgvUserDetails_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
{
        using (SolidBrush b = new SolidBrush(dgvUserDetails.RowHeadersDefaultCellStyle.ForeColor))
        {
              e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4);
        }
}

Don't try to manipulate the Code part much because the X and Y are calculated co-ordinates in the row header area or you can customizse test it yourself to see the various results.
Result

link

A: private void grid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e )
    {
        using (SolidBrush b = new SolidBrush(((DataGridView)sender).RowHeadersDefaultCellStyle.ForeColor))
        {
            e.Graphics.DrawString((e.RowIndex + 1).ToString(), e.InheritedRowStyle.Font, b, e.RowBounds.Location.X + 10, e.RowBounds.Location.Y + 4);
        }
    }

A: private void DgvSupplierInfo_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
    {
        if (dgvSupplierInfo == null)
            return;

        int sno = 1;
        string columnName = "columnName";
        string headerText = "headerText";

        if (dgvSupplierInfo.Columns.Contains(columnName))
            dgvSupplierInfo.Columns.Remove(columnName);
        {
            dgvSupplierInfo.Columns.Add(columnName, headerText);
        }

        dgvSupplierInfo.Columns[columnName].DisplayIndex = 0;

        foreach (DataGridViewRow row in dgvSupplierInfo.Rows)
            row.Cells[columnName].Value = sno++;

        dgvSupplierInfo.AutoResizeColumns();
    }


text:
Q: org.json.JSONException: JSONObject["status"] is not a JSONObject I am now currently using a weather API from http://wiki.swarma.net/index.php?title=%E5%BD%A9%E4%BA%91%E5%A4%A9%E6%B0%94API/v2 and wished to convert the JSONObject into printable Strings. However, when I am working on the following code, two errors occurred:
public class getApi {
    private static final String WEATHER_MAP_URL = "https://api.caiyunapp.com/v2/TAkhjf8d1nlSlspN/121.6544,25.1552/realtime.json";
    private static final String WEATHER_TEST_API = "TAkhjf8d1nlSlspN";

    public static JSONObject getWeatherJson() {
        try {
            URL url = new URL( WEATHER_MAP_URL );
            HttpURLConnection connection =
                    (HttpURLConnection)url.openConnection();

            connection.addRequestProperty( "x-api-key", WEATHER_TEST_API );
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader( connection.getInputStream()) );

            StringBuffer json = new StringBuffer( 1024 );
            String tmp;
            while( (tmp = reader.readLine()) != null )
                json.append(tmp).append("\n");
            reader.close();

            JSONObject data = new JSONObject( json.toString() );
            if(data.getJSONObject("status").toString() != "ok" ) {
                return null;
            }
            return data;
        }
        catch(Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    public static void main( String[] args ) {
        JSONObject WeatherJson = getWeatherJson();
        try {
            JSONArray details = WeatherJson.getJSONObject("result").getJSONObject("hourly").
                    getJSONArray("skycon");
            System.out.println(details.getJSONObject(0).getJSONObject("value").toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

The JSONObject structure, which is also shown in the link above, is like this:
{
    "status":"ok",
    "lang":"zh_CN",
    "server_time":1443418212,
    "tzshift":28800,
    "location":[
        25.1552, //latitude
        121.6544 //longitude
    ],
    "unit":"metric",
    "result":{
        "status":"ok",
        "hourly":{
            "status":"ok",
            "skycon":[
                {
                    "value":"Rain",
                    "datetime":"2015-09-28 13:00"
                },
                {
                 ...
                }]
           }
      }
}

The error occurred:
org.json.JSONException: JSONObject["status"] is not a JSONObject.
    at org.json.JSONObject.getJSONObject(JSONObject.java:557)
    at getApi.getWeatherJson(getApi.java:34)
    at getApi.main(getApi.java:45)
Exception in thread "main" java.lang.NullPointerException
    at getApi.main(getApi.java:47)

I have looked at similar posts on the topic is not a JSONObject Exception but found that none of them can help me. I suspect that something is wrong with requesting the data, so actually, getWeatherJson() returns a null object and results in the NullPointerException and JSONObjectException.
Can anyone help me with the code?

A: According to the getJSONObject() Javadoc, this method will throw an exception if the returned object isn't a true JSON object, which it isn't because "status" is a string. As such, try using data.getString("status").

A: The status field in the JSON document you have posted is not an object. In JSON, objects are enclosed in with {} brackets. The result node however, is a nested object which holds the status key/value pair. Try the following:
JSONObject data = new JSONObject(json.toString());
  if(data.getJSONObject("result").get("status").toString() != "ok" ) {
    return null;
  }

redpajama_set_name: RedPajamaStackExchange


text: Q: How to add smaller ticks between main ticks in Matplotlib I'm using matplotlib to make some plots, and I was wondering if you have any idea about adding smaller ticks in between the main ones, like in this image:


text:
Q: Only retrieve specific data from a row in DynamoDB using JavaScript
Using DynamoDb and the "read" function provided here how would I go about only retrieving specific items (e.g. only firstname, lastname and city)
I would probably have to add some kind of filter, however i was not able to find anything that I could use.
This is my table structure (with bpNumber being the primary key):
Item:{
            "salutationCode": "02",
            "lastName1": "Berg",
            "firstName": "Anne",
            "street": "Am Dächle",
            "streetNumber": "22/2",
            "zipcode": "33425",
            "countryCode": "DE",
            "city": "Hausen",
            "bpNumber": 222,
            "dateOfBirth": "1955-07-01",
            "attri": [
              {
                "attri1":"nonono"
              },
              {
                "attri2": "yeayeayea"
              }
            ]

        }

and this the "read" method I'm using:
read(){
        var docClient = new AWS.DynamoDB.DocumentClient()

        var table = "businessPartnersData";

        var bpNumber = 222;

        var params = {
            TableName: table,
            Key:{
                "bpNumber": bpNumber
            }
        };

        docClient.get(params, function(err, data) {
            if (err) {
                console.error("Unable to read item. Error JSON:", JSON.stringify(err, null, 2));
            } else {
                console.log("GetItem succeeded:", JSON.stringify(data, null, 2));
            }
        });
  }

Thank you for you time!

A: You can use ProjectionExpression:
params.ProjectionExpression = "firstname, lastname, city";

This will only return these attributes in the resultset, for all items.


text:
Q: Find by more than one x_path for my web-scraper (Python, Selenium) The elements in the web-page I'm scraping are found by one of two x_paths even though the elements are almost the same. Basically, some of the elements have an icon next to them and some of them don't. But I'm not interested in the icon, I'm just scraping the numbers next to it.
For data with an icon I use:
driver.find_elements_by_xpath('//a[@class="in-match"]')

For data without an icon, I use:
driver.find_elements_by_xpath('//td[@class="table-main__detail-odds table-main__detail-odds--first"]')

I need my scraper to be able to look for either of these two things. It is important that it looks for them simultaneously so that the order scraped is the same as the order that the data appears on the page.
This seems like a simple question, but I'm really not sure how to do it.
Thanks.

A: You can use or condition in your XPath to match both condtions like shown below:
locator = '//a[@class="in-match" or @class="table-main__detail-odds table- main__detail-odds--first"]'
driver.find_elements_by_xpath(locator)

This will match elements with both class.


text:
Q: Game theory/probability puzzle Part 1:
You play a game where there is a box with 100$ and there are two players, each of you should write a number 0-100 on paper, then you show your numbers, if the sum is higher than 100 then each of you get 0 dollars, else you get what you wrote. What is your strategy?
Part 2:
You play the same game but your opponent told you that he is putting 80 (he might change his mind) - what is your plan?

For part 1, I think the Nash equilibria are (my number, opponent's number) = (x, 100 - x) for x between 0 and 100? Is this right, and if so, how to choose between them to pick your move? I was thinking about saying 50 as my number for symmetry/aesthetic reasons but would be interested in how one is supposed to tackle this problem. I drew out a reward matrix and tried iterated removal of weakly dominated strategies to get (50, 50) as the only cell remaining - would be grateful for any thoughts on the validity of this.
For part 2, I thought, if you're allowed to say something to the opponent, you could say that you were going to put 50, to try to force your opponent down to 50? Again I have no idea how to approach this. Any help would be much appreciated.

A: The question of choosing a NE among several options is an open question - there is no general mechanism to choose among them (think about Battle of the Sexes, for a very simple example). In many papers, the "punch line" is adding some restriction or addition to the model that ruins other equilibria or somehow helps players choose one.
Here, the only symmetric equilibrium is indeed $(50,50)$, but all the $(x,100-x)$ equilibria are also good.
The same goes for the second part. Without ability to credibly commit to $80$, his $80$ is more or less worthless.

A: For the second part, I think I'd say to her "I'll choose the same number as you do". This hints to the other player that she should choose $50$, because both larger and smaller numbers result in lower payments ($0$ if higher, $x<50$ if lower). Of course, this depends on the credibility of your "threat".


text:
Q: PHP OCI: how to roll back ANY open connections I'm using PHP's OCI library to communicate with Oracle. In every function there is a try...catch to catch any exceptions. In the catch part I call my own error handling function.
When an exception occurs I want to rollback ALL open connections to oracle, preferably in my error handling function. Is this possible?
Thanks

#

#

It's a bit hacky, but here's how I solved the problem.
In my connect() function which connects to Oracle, I put this code:
if(!isset($GLOBALS['OPEN_CONNECTIONS'])){
  $GLOBALS['OPEN_CONNECTIONS'] = array();
  $GLOBALS['OPEN_CONNECTIONS'][] = $this;
}else{
  $GLOBALS['OPEN_CONNECTIONS'][] = $this;
}

This stores a list of all open connections in the global scope.
In my error handling function, I do this:
//rollback all open connections
if(isset($GLOBALS['OPEN_CONNECTIONS'])){
  foreach($GLOBALS['OPEN_CONNECTIONS'] as $con){
    $con->rollback();
  }
}

This way, I can rollback all open connections without having to pass them into my error handler.


text:
Q: Blur Modifier in Jetpack Compose Doesn't Work in Preview I'm trying to use the Modifier.blur feature of Jetpack Compose for a project for work and it seems to not do anything in the preview. I'm using it like this:
Column(modifier = Modifier
    .blur(30.dp)) {
    // Screen content here
}

The screen content isn't blurred at all. I've even tried applying blur to the individual composables in the box and that also doesn't change the preview. Am I missing something here?

A: Modifier.blur() works only on Android 12+ devices so you probably do not want to use it anyways since it will not work for almost all your users (at least at the time I am writing this that barely any devices run Android 12).
It's due to all blur-related features being added on Android 12+ and they are not backward compatible. So you always do need unofficial methods to implement blur if you do want it to work for devices running Android 11 or lower.
It not working on the preview can be due to this or might simply be a bug since Compose is still a new technology. I could not find any reported bugs related to blur so if it's a bug, they are not aware of it. If you are sure it is a bug you should report it to Google's issue tracker so it can get fixed ASAP.


text:
Q: AWS sam template extraneous key that should be valid Trying to create a dataset and template in a bitbucket pipeline using aws sam and it returns the error
Model validation failed (#: extraneous key [DataSourceArn] is not permitted

I've tried
xxxxDataset:
  Type: AWS::QuickSight::DataSet
  Properties:
    AwsAccountId: !Ref "AWS::AccountId"
    Name: !Sub 'xxxxDataset${PlatformParameter}'
    ImportMode: 'DIRECT_QUERY'
    PhysicalTableMap:
      RelationalTable:
        Catalog: 'AwsDataCatalog'
        DataSourceArn: !Sub 'arn:aws:quicksight:${RegionParameter}:${AWS::AccountId}:datasource/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

and
xxxxDataset:
  Type: AWS::QuickSight::DataSet
  Properties:
    AwsAccountId: !Ref "AWS::AccountId"
    Name: !Sub 'xxxxDataset${PlatformParameter}'
    ImportMode: 'DIRECT_QUERY'
    S3Source:
      DataSourceArn: !Sub 'arn:aws:quicksight:${RegionParameter}:${AWS::AccountId}:datasource/xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'

both give the same error while DataSourceArn is a valid key according to the documentation. I'm referring to cloudformation doc https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/aws-resource-quicksight-dataset.html but there may be differences with aws-sam for which I haven't found quicksight documentation...
Thanks any help appreciated


text:
Q: unit testing rxjs 5 So I'm still very new to rxjs.
Currently using tape js for unit tests in my code base. I've looked into marble diagram testing, but it's really not clicking for me.
My question :
How to unit test a search call that makes use of rxjs observable? I'm interested in asserting that the _handleSearchResults function is called with the observable completes. Similarly how to test if the observable fails, that the _handleSearchError is called.
this.searchSubject is a rx subject
searchChanged(query) {
    this.searchSubject.next(query);
}

Search subject is defined with the switchmap which is really what I want to unit test when calling searchChanged.
 this.searchSubject.switchMap(searchQuery => {
        return Rx.Observable.fromPromise(this._queryAutoComplete(searchQuery));
    })
    .subscribe(this._handleSearchResults.bind(this), this._handleSearchError.bind(this));


text:
Q: Which computer is eating all the bandwidth? I have a belkin wireless router and four computers (2PC's + 2 Mac's) that connect to it regularly. Recently we have been consuming a lot of bandwidth. Is there a way to find out which computer is consuming most of the bandwidth without having to install monitoring software on all of the computers? (no two computers have the same OS!). Can I just install software one one PC and solve this problem?
EDIT: The router model number is F5D7632-4
EDIT: One PC with windows XP is connected directly by cable to the router.

A: See the overview for ntop

*

*Analyse IP traffic and sort it according to the source/destination

*Display IP Traffic Subnet matrix (who's talking to who?)

EDIT
Ntop can show traffic statistics between other PCs and the internet, you just have to make sure the computer running ntop is able to see all the traffic. Modern ethernet switches segregate traffic so the a computer only sees traffic addressed to it. A managed switch will allow you to set up port-mirroring to the computer running ntop.
It seems the Belkin's built-in switch doesn't support Port-mirroring. Maybe you could interpose a suitable inexpensive switch between the Belkin and the four wired PCs.
Old ethernet hubs (not switches) also allow any computer to see all traffic. I have an old Netgear EN104 10-Base-T hub I used to use for this. I see they are available for a few dollars
See ntop blog about this
If the PCs are on the WLAN you'll need a different solution.
http://www.tech-faq.com/how-to-monitor-wireless-traffic.html
There are commercial products that claim to do this. E.g.
http://www.tamos.com/products/commwifi/
If the Belkin F5D7632-4 supported RMON or Netflow, you might be able to use that.

A: If you are worried about consuming your Internet account bandwidth and your ISP has a monitoring tool, you could switch on one computer at a time for a fixed period and see how much the ISP tool says has been used.


text:
Q: iOS10 __weak pointer made retainCount +1 When I use __weak pointer refer to an NSObject, the unexpected retainCount is shown.
The test code and result are as the image below.

Here is the code:
    id obj1 = [[NSObject alloc] init];
    id __weak obj2 = obj1;
    NSLog(@"obj1: %ld", CFGetRetainCount((__bridge CFTypeRef)obj1));        // line 31
    NSLog(@"obj2: %ld", CFGetRetainCount((__bridge CFTypeRef)obj2));        // line 32
    NSLog(@"obj1 again: %ld", CFGetRetainCount((__bridge CFTypeRef)obj1));  // line 33

So~ My confusion is that, obj2's retainCount is expected to 1, Why retainCount is 2?
I've read from book: the __weak pointer registered the object to the autoreleasepool, so the retain count + 1.
However, obj1 and obj2 refer to the same memory address, in that case, the obj1's retainCount should also become 2. But, it still remain in 1.
I know retainCount is unreliable but I'm so curious about how this came. (My environment is Xcode 8.3.3, iOS 10.3)
Greatly appreciate if anyone can explain this to a beginner :)

A: The exact value of the retain count is generally an implementation detail that depends on the compiler, the Objective-C language runtime, and any other libraries involved (like Foundation). But it's reasonable to wonder why it behaves this way, as long as you don't depend on the behavior.
Either your book is wrong, or you misunderstood it. Using __weak doesn't put the object in the autoreleasepool.
Here is what is happening on line 32 (the one with the @"obj2: %ld" format string).
To safely pass an object reference to a function or method (like NSLog), it has to be a strongly-held reference. So the compiler generates a call to objc_loadWeakRetained on obj2. This function atomically increments the retain count of the object and returns the reference. Thus the retain count of the object goes from 1 to 2 before the object reference is passed to NSLog.
Then, after NSLog returns, the compiler generates a call to objc_release. Thus the retain count goes back down from 2 to 1 by the third NSLog.
If you want to be sure what's happening, look at the assembler output of the compiler. You can ask Xcode to show it to you:

Here's the relevant part of the assembly:
    .loc    2 0 9 discriminator 1   ## /Users/mayoff/TestProjects/test/test/main.m:0:9
    leaq    -32(%rbp), %rdi
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    .loc    2 16 66 is_stmt 1       ## /Users/mayoff/TestProjects/test/test/main.m:16:66
    callq   _objc_loadWeakRetained
    movq    %rax, %rbx
Ltmp4:
    .loc    2 16 29 is_stmt 0       ## /Users/mayoff/TestProjects/test/test/main.m:16:29
    movq    %rbx, %rdi
    callq   _CFGetRetainCount
    movq    %rax, %rcx
Ltmp5:
Ltmp20:
## BB#3:
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    ##DEBUG_VALUE: obj1 <- %R15
Ltmp6:
    .loc    2 16 9 discriminator 1  ## /Users/mayoff/TestProjects/test/test/main.m:16:9
    leaq    L__unnamed_cfstring_.4(%rip), %rdi
    xorl    %eax, %eax
    movq    %rcx, %rsi
    callq   _NSLog
Ltmp7:
Ltmp21:
## BB#4:
    ##DEBUG_VALUE: obj2 <- [%RBP+-32]
    ##DEBUG_VALUE: obj1 <- %R15
    .loc    2 16 9 discriminator 2  ## /Users/mayoff/TestProjects/test/test/main.m:16:9
    movq    %rbx, %rdi
    callq   *_objc_release@GOTPCREL(%rip)

Line 16 is (in my test) the one that uses obj2. You can see the call to objc_loadWeakRetained before the call to CFGetRetainCount, and the call to objc_release after NSLog returns.


text:
Q: gsutil: why ls returns directory itself I got
$ gsutil ls gs://ml_models_c/ref7/test/model/2/
gs://ml_models_c/ref7/test/model/2/                        <= why this?
gs://ml_models_c/ref7/test/model/2/saved_model.pb
gs://ml_models_c/ref7/test/model/2/variables/
$ gsutil ls gs://seldon-models/tfserving/mnist-model/1/
gs://seldon-models/tfserving/mnist-model/1/saved_model.pb
gs://seldon-models/tfserving/mnist-model/1/variables/

Why there is gs://ml_models_c/ref7/test/model/2/ in the first command output?
Why the second command does not return itself?
It seems that I can rm it.
Thanks

A: At the API level, Cloud Storage doesn't have the concept of folders, everything is stored as long file names that might have slashes in them.
In this case, you likely have an object named gs://ml_models_c/ref7/test/model/2/, but no object named gs://seldon-models/tfserving/mnist-model/1/
If you don't need the gs://ml_models_c/ref7/test/model/2/ object, you can delete it and it will no longer show in the results for gsutil ls


text:
Q: Angular construct ViewModel from different promises In my Angular project i have a Promise that returns an array of Products:
{"Products":[{"Code":123},{"Code":456}]}

Then for each product code, i must call two other promises that return Price and Quantity respectively.
I use ui-router and my current implementation code in my resolve is below :
$stateProvider.state('root.products', {
                    abstract: true,
                    url: '/products',
                    template: '

',
                    resolve: {
                        products: ['ProductsService', function (ProductsService) {
                            return ProductsService.getProducts()
                                .then(function (response){
                                    var data = response.data;
                                    return data.Products.map(function (product) {

                                        var viewModelProduct = {};

                                        angular.copy(product, viewModelProduct);

                                        //get Price for Each Product
                                        ProductsService.getPrice(product.Code)
                                            .then(function (response) {
                                                viewModelProduct.Price = response.data.Info.Price;
                                            })

                                        //get Quantity for Each Product
                                        ProductsService.getQuantity(product.Code)
                                           .then(function (response) {
                                               viewModelProduct.Quantity = response.data.Info.Quantity;
                                           })

                                        return viewModelProduct;
                                    });
                                });
                                }]
                        }
                        })

It works but my question is if i can write it better. I read about the use of $q and $q.all but I don't really know how to use them.
Is there any way i can write the above code, better and safer??
Thanks in advance for your help!

A:
It works but my question is if i can write it better.

Yes. You can write promise chain. The advantage is: Error propagates, you can catch it on the end of the chain and its not piramide like async call in Javascript
See flow example bellow:

[EDIT]
if the order is not critical you can use $q.all that gets list of promises and notify you when all of them resolved successfully.
It should be something like:
       $q.all([
            ProductsService.getPrice(product.Code),
            ProductsService.getQuantity(product.Code)
           ])
            .then(function(result){

            viewModelProduct.Price   = result[0].data.Info.Price;
            iewModelProduct.Quantity = result[1].data.Info.Quantity;

          }, function(error) {
              alert(error.message);
          });

or even:
     var promises = [];
     promises.push(ProductsService.getPrice(product.Code));
     promises.push(ProductsService.getQuantity(product.Code));

       $q.all(promises).then(function(result){

            viewModelProduct.Price   = result[0].data.Info.Price;
            iewModelProduct.Quantity = result[1].data.Info.Quantity;

          }, function(error) {
              alert(error.message);
          });

A: If you need to execute promises one after other you will use chains like Maxim mentioned.
More one topic:

*

*https://docs.angularjs.org/api/ng/service/$q

*http://solutionoptimist.com/2013/12/27/javascript-promise-chains-2/
If you need to execute more promises and then resolve it you will use "$q.all".
See documenttion:

*

*https://docs.angularjs.org/api/ng/service/$q

UPDATE
Not sure if I understand well but you should use combination of q.all and chaining.
Again, sorry if I didn't understand you well.
var p1 = ProductsService.getPrice(product.Code)
 .then(function (response) {
    return response.data.Info.Price;
 });

var p2 = ProductsService.getQuantity(product.Code)
         .then(function (response) {
         return response.data.Info.Quantity;
 });

    return $q.all([p1,p2]); // next "then" will get array with price and quantity respectively.


text:
Q: Built-in function name as identifier name When we assign to a name that refers a built-in function, it did not complain. However, when we try to use it within the same built-in function chr(chr), we get the issue cause of class in symbols...
Question is, whether this holds as a bug in the python interpreter ??
for chr in range[69,91]:
    print(chr)      # no Error

But when
print(chr(chr))   # Throws an error.

A: I think you are confusing scopes and namespaces.
If you hadn't assigned any value to chr, then an attempt to reference its value would result in finding the name in the built-in scope, where it refers to a built-in function.
After the assignment performed by the for loop, you assigning a value to chr in the current scope, so the lookup for chr succeeds in that scope, without referring to the built-in scope.
When you write chr(chr), both references are looked up in the current scope, where the name chr is found to refer to an instance of int. There aren't two namespaces, where the first use (which looks like a function call) is distinct from the second use.

A: you can use this:
toChar = chr
for chr in range(69,91):
    print(toChar(chr))


text:
Q: Parse shell script in Jenkinsfile for testing When running a jenkins pipeline, I often make error in the shell script (sh) and I only detect that error when I run the pipeline. Is there a way to parse the script (using groovy compiler maybe?) and see the actual shell script that would be run by Jenkins beforehand?
An example would be the shell script in the pipeline script below:
pipeline {
   agent any
   stages {
      stage('test') {
         sh """
            echo \${PWD}
         """
      }
   }
}


text:
Q: How can i use php jquery in yii2? I want to make an image to be a pop-up when I click on it. It's like a bigger preview of its default size without moving to another page. I have this jQuery that works on PHP, but since this is yii2 I'm stuck on this.
Here is the jQuery:

I want to implement that jQuery in this view:
<?php

use yii\helpers\Html;
use yii\grid\GridView;
use yii\bootstrap\Modal;
use frontend\models\PengurusAktif;
use frontend\models\ProfilBem;

/* @var $this yii\web\View */
/* @var $searchModel frontend\models\AlbumBemSearch */
/* @var $dataProvider yii\data\ActiveDataProvider */

$this->title = 'Album Bem';
?>

    <?php
    $tahun = PengurusAktif::find()->one();
    $idprofil = ProfilBem::find()->where(['tahun' => $tahun->tahun_aktif])->one();
    ?>
    <?= Html::a('Visi Misi', ['/bem/visimisi', 'id' => $tahun->tahun_aktif], ['class' => 'btn btn-primary']) ?>
    <?= Html::a('Struktur Organisasi', ['profil-bem/profilebem', 'id' => $idprofil->id_profil_bem], ['class' => 'btn btn-primary']) ?>
    <?= Html::a('Pengumuman BEM', ['/pengumuman/pengumumanbem'], ['class' => 'btn btn-primary']) ?>
    <?= Html::a('Event Bem', ['/event/eventbem'], ['class' => 'btn btn-primary']) ?>
    <?php
    if (Yii::$app->user->can('sekretarisBem')) {
        echo Html::a('Forum BPH BEM', ['/forum/forumbem'], ['class' => 'btn btn-primary']);
    }
    ?>
    <?= Html::a('Poling BEM', ['/bem/pollingbem'], ['class' => 'btn btn-primary']) ?>
    <?= Html::a('Album BEM', ['/album-bem/index'], ['class' => 'btn btn-primary']) ?>

<?= Html::encode($this->title) ?>

    <?php // echo $this->render('_search', ['model' => $searchModel]);  ?>

        <?php
        if (Yii::$app->user->can('sekretarisBem')) {
            echo Html::button('Create Album Bem', ['value' => yii\helpers\Url::to(['create']), 'class' => 'btn btn-success', 'id' => 'modalButton']);
            Modal::begin([
                'id' => 'modal',
                'size' => 'modal-lg',
            ]);
            echo "

";
            Modal::end();
        }
        ?>

    <?php
    foreach ($dataProvider as $dataAlbum) {
        echo $dataAlbum->judul . "
";
        echo $dataAlbum->kegiatan . "
";
        ?>

            <?php

            if ($dataAlbum->foto1 != NULL) {
                ?>

                    <a  class="thumbnail magnifier" href="<?= Yii::$app->request->baseUrl ?>/Upload/imagesBemAlbum/foto/<?= $dataAlbum->foto1; ?>">
                        <img src="<?= Yii::$app->request->baseUrl ?>/Upload/imagesBemAlbum/foto/<?= $dataAlbum->foto1; ?>" width="150px" height="200px">

                <?php
            }
            if ($dataAlbum->foto2 != NULL) {
                ?>

                        <img src="<?= Yii::$app->request->baseUrl ?>/Upload/imagesBemAlbum/foto/<?= $dataAlbum->foto2; ?>" width="150px" height="200px">

                <?php
            }
            if ($dataAlbum->foto3 != NULL) {
                ?>

                        <img src="<?= Yii::$app->request->baseUrl ?>/Upload/imagesBemAlbum/foto/<?= $dataAlbum->foto3; ?>" width="150px" height="200px">

                <?php
            }
            if ($dataAlbum->foto4 != NULL) {
                ?>

                        <img src="<?= Yii::$app->request->baseUrl ?>/Upload/imagesBemAlbum/foto/<?= $dataAlbum->foto4; ?>" width="150px" height="200px">

                <?php
            }
            if ($dataAlbum->foto5 != NULL) {
                ?>

                        <img src="<?= Yii::$app->request->baseUrl ?>/Upload/imagesBemAlbum/foto/<?= $dataAlbum->foto5; ?>" width="150px" height="200px">

                <?php
            }
            ?>

        <?php
        if (Yii::$app->user->can('sekretarisBem')) {
            echo Html::a('Update', ['update', 'id' => $dataAlbum->id_album_bem], ['class' => 'btn btn-primary']);
            echo Html::a('Delete', ['delete', 'id' => $dataAlbum->id_album_bem], [
                'class' => 'btn btn-danger',
                'data' => [
                    'confirm' => 'Are you sure you want to delete this item?',
                    'method' => 'post',
                ],
            ]);
        }
        ?>
        <?php
    }
    ?>

Can anybody please help me with this thing? If you need more code, just say.

A: If you want insert jquery code to view file, use registeJS method http://www.yiiframework.com/doc-2.0/yii-web-view.html#registerJs()-detail
Also good practice to use AssetBundle to register script files.
Delete
 from view and use \yii\web\JqueryAsset::register($this);
\yii\bootstrap\BootstrapPluginAsset::register($this); at the top of your view


text:
Q: Jenkins - NGINX reverse proxy broken I just moved our jenkins to a new machine behind a reverse proxy, before it was straight on the intranet. And I've started seeing the error "It appears that your reverse proxy setup is broken."
So I copied the recommended nginx config straight, modifying slightly for our needs but the warning remains, leaving me slightly confused and posting here.
upstream jenkins {
  keepalive 32; # keepalive connections
  server 127.0.0.1:8080; # jenkins ip and port
}

server {
  listen          80;       # Listen on port 80 for IPv4 requests

  server_name     jenkins.domain.tld;

  #this is the jenkins web root directory (mentioned in the /etc/default/jenkins file)
  root            /usr/share/jenkins;

  access_log      /var/log/nginx/jenkins/access.log;
  error_log       /var/log/nginx/jenkins/error.log;
  ignore_invalid_headers off; #pass through headers from Jenkins which are considered invalid by Nginx server.

  location ~ "^/static/[0-9a-fA-F]{8}\/(.*)$" {
    #rewrite all static files into requests to the root
    #E.g /static/12345678/css/something.css will become /css/something.css
    rewrite "^/static/[0-9a-fA-F]{8}\/(.*)" /$1 last;
  }

  location /userContent {
    #have nginx handle all the static requests to the userContent folder files
    #note : This is the $JENKINS_HOME dir
    root /var/lib/jenkins/;
    if (!-f $request_filename){
      #this file does not exist, might be a directory or a /**view** url
      rewrite (.*) /$1 last;
      break;
    }
    sendfile on;
  }

  location @jenkins {
      sendfile off;
      proxy_pass         http://jenkins;
      proxy_redirect     default;
      proxy_http_version 1.1;

      proxy_set_header   Host              $host;
      proxy_set_header   X-Real-IP         $remote_addr;
      proxy_set_header   X-Forwarded-For   $proxy_add_x_forwarded_for;
      proxy_set_header   X-Forwarded-Proto $scheme;
      proxy_max_temp_file_size 0;

      #this is the maximum upload size
      client_max_body_size       10m;
      client_body_buffer_size    128k;

      proxy_connect_timeout      90;
      proxy_send_timeout         90;
      proxy_read_timeout         90;
      proxy_request_buffering    off; # Required for HTTP CLI commands in Jenkins > 2.54
      proxy_set_header Connection ""; # Clear for keepalive
  }

  location / {
    # Optional configuration to detect and redirect iPhones
    if ($http_user_agent ~* '(iPhone|iPod)') {
      rewrite ^/$ /view/iphone/ redirect;
    }

    try_files $uri @jenkins;
  }
}

So it's reached at jenkins.domain.tld and I'm out of ideas on how to troubleshoot this. The requests log properly, nothing in the error log, jenkins seems to work in other ways....but the proxy tests gives a 404?
$: curl -iL -e http://jenkins.domain.tld/jenkins/manage    http://jenkins.domain.tld/jenkins/administrativeMonitor/hudson.diagnosis.ReverseProxySetupMonitor/test
HTTP/1.1 404 Not Found
Server: nginx/1.10.3 (Ubuntu)
Date: Mon, 26 Mar 2018 06:50:30 GMT
Content-Type: text/html;charset=iso-8859-1
Content-Length: 391
Connection: keep-alive
X-Content-Type-Options: nosniff
Cache-Control: must-revalidate,no-cache,no-store

<meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
<title>Error 404 Not Found</title>

HTTP ERROR 404

Problem accessing /jenkins/administrativeMonitor/hudson.diagnosis.ReverseProxySetupMonitor/test. Reason:

    Not Found

Powered by Jetty:// 9.4.z-SNAPSHOT

Jenkins URL in system config is also set to jenkins.domain.tld.


text:
Q: "error: subscripted value is neither array nor pointer nor vector" I'm coding a something that should find an optimal answer to the following problem:

You have a vector of ints that you have to put in decrescent order by doing the "flip" operation, that is, given an i position in the vector of size n you should switch the values of i and n-1, the values of i+1 and n-2 and so on and so forth. The goal is to find and optimal way to put the vector in order, that is, with the minimal number of flips

I decided to use the A* algorithim to find the answer, since it's important to find an optimal answer, and to store all the information I needed to, I choose to use the following struct:
typedef struct{
            int *v, *flips,g, h;
} node;

in which v would be a state of the solution, flips would store my choices, g would hold the value of the g function, and h the value of the heuristic.
So to write the program I made a vector of the type node as in:
estados=malloc(n*sizeof(node));

and the idea was to use each position of the node vector to store a state so it could be compared and expanded and etc. For the most part the compiler isn't complaining much but in these functions:
int funcaoh(node estados,int n,int goal[], int pos){
    int cont=0, i;
    for(i=0;i<n;i++){
        if(estados[pos].v[i]!=goal[i]){
            cont++;
        }
    }
    return (cont/2);
}

void criaNode(node x[], int n, int pos){
    int i;
    x[pos].v =malloc(n*sizeof(int));
    x[pos].flips =malloc(n*sizeof(int));
    for(i=0;i<n;i++){
        x[pos].flips[i]=-1;
        x[pos].v[i]=-1;
    }
    x[pos].h=0;
    x[pos].g=0;
    return;
}

I get the error "error: subscripted value is neither array nor pointer nor vector" in the if statement of the funcaoh function and the "warning: incompatible implicit declaration of built-in function 'malloc' [enabled by default]"  warning on the first malloc statement but not on the second oddly enough. The same happens in another few similar instances of the code, I suspect the warnig might just be me using malloc in the wrong way because I'm getting the same warning in other places that really shouldn't be a problem such as in:
 entrada=malloc(n * sizeof(int));

But the main thing is getting the struct vector working because it's obviously quite integral to the success of the program. If I were to guess, I suppose it has to do with the use of struct as a vector, maybe it doesn't work the way I think it does? I don't know, though.
P.S. I'm Brazilian so some parts of the code are written in Portuguese, mostly just the names of variable and of functions, if necessary I could translate them.

A: In funcaoh():
int funcaoh(node estados,int n,int goal[], int pos){

estados is a simple structure, not a pointer to a structure, so you can't subscript it, etc.  That's what the compiler said; I have to agree with it.
You presumably need one of these (they're equivalent):
int funcaoh(node *estados, int n, int goal[], int pos) { … }

int funcaoh(node estados[], int n, int goal[], int pos) { … }


text:
Q: C++ code exiting randomly after reading different number of lines in a file I am trying to read mesh data from a fluent mesh file. The code works perfectly till it reads node data. While reading cell data, it exits randomly by giving random negative number or what() std::bad_alloc. I am not able to understand the reason behind this behaviour. Please help me to resolve the issue. I tried printing different variables, but it works perfectly just before it exits. Here is what I have been able to put together till now
#include <sstream>
#include <iostream>
#include <fstream>
#include <vector>

int str_to_int( std::string s);
double str_to_double( std::string s);
int strhex_to_int(std::string s);
std::vector<std::string> convert_string_to_vector(std::string line);
void GetDimension();
void GetNodes();
void GetCells();
void GetFaces();
void GetBcNames();

std::ifstream meshFile ;
std::string fileLine;
std::vector<std::string> lineVector;
int nDim, nNodes, nCells, nFaces;
double *nodePoints;
int *cellData, *faceData;

int main()
{
    int property;
    meshFile.open("test.msh", std::ifstream::in);
    if (meshFile.is_open())
    {
        while ( !meshFile.eof() )
        {
            std::getline(meshFile,fileLine);
            //std::cout << fileLine << "\n";
            lineVector = convert_string_to_vector(fileLine);
            if(lineVector.empty())
                continue;
            else
                property = str_to_int( lineVector[0] );

            //std::cout << property << "\n";
            /*
            for(int j=0; j < lineVector.size(); j++)
            {
                std::cout << lineVector[j] << "\n";
            }
            */
            switch(property)
            {
                case 0:
                    std::cout << "Comment Detected\n";
                    lineVector.clear();
                    break;
                case 2:
                    GetDimension();
                    break;
                case 10:
                    GetNodes();
                    break;
                case 12:
                    GetCells();
                    break;
                case 13:
                    GetFaces();
                case 39:
                    GetBcNames();
                default:
                    std::cout << "Problem with mesh file\n";
            }
        }

    }
    else std::cout << "Unable to open file";
}

void GetDimension()
{
    nDim = str_to_int(lineVector[1]);
    std::cout << "Problem Dimension: " << nDim << "\n";
    lineVector.clear();
}

void GetNodes()
{
    int nodeZoneId, startNode, endNode, nodeType;
    std::string fileLine;
    nodeZoneId = str_to_int(lineVector[1]);
    if (nodeZoneId == 0)
    {
        nNodes = strhex_to_int( lineVector[3]);
        std::cout << "Total Nodes = " << nNodes << "\n";
        lineVector.clear();
        if (nDim ==  2)
            nodePoints = new double[nNodes*2];
        else
            nodePoints = new double[nNodes*3];
    }
    else
    {
        startNode = strhex_to_int( lineVector[2]);
        endNode = strhex_to_int( lineVector[3]);
        nodeType = str_to_int(lineVector[4]);
        std::cout << "Reading nodes from "<< startNode << " to " << endNode << " of type " << nodeType << " for zone = " << nodeZoneId << "\n";
        lineVector.clear();
        for( int j = startNode - 1; j < endNode; j++)
        {
            //std::cout << j << "\n";
            std::getline(meshFile,fileLine);
            if (fileLine.empty())
            {
                std::cout << "No Nodes found in file!" << "\n";
                break;
            }
            //std::cout << fileLine << "\n";
            lineVector = convert_string_to_vector(fileLine);

            if(lineVector.empty())
                j--;
            else
            {
                if(nDim == 2)
                {
                    //std::cout << lineVector[0] << "\t" << lineVector[1] << "\n";
                    nodePoints[0*nNodes + j] = str_to_double(lineVector[0]);
                    nodePoints[1*nNodes + j] = str_to_double(lineVector[1]);
                    std::cout << nodePoints[0*nNodes + j] << " " << nodePoints[1*nNodes + j] << "\n";
                    lineVector.clear();
                }
                else
                {
                    //std::cout << lineVector[0] << "\t" << lineVector[1] << "\t" << lineVector[2] << "\n";
                    nodePoints[0*nNodes + j] = str_to_double(lineVector[0]);
                    nodePoints[1*nNodes + j] = str_to_double(lineVector[1]);
                    nodePoints[2*nNodes + j] = str_to_double(lineVector[2]);
                    std::cout << nodePoints[0*nNodes + j] << " " << nodePoints[1*nNodes + j] << " " << nodePoints[2*nNodes + j] << "\n";
                    lineVector.clear();
                }
            }
        }
    }
    //std::getline(meshFile,fileLine);
    //std::cout << fileLine << "\n";
    //std::getline(meshFile,fileLine);
    //std::cout << fileLine << "\n";
    //lineVector.clear();
}

void GetCells()
{
    int cellZoneId, startCell, endCell, cellType;
    std::string fileLine;

    cellZoneId = str_to_int(lineVector[1]);
    //std::cout << cellZoneId << "\n";
    if (cellZoneId == 0)
    {
        nCells = strhex_to_int(lineVector[3]);
        //std::cout << "Total Cells = " << nCells << "\n";
        lineVector.clear();
        cellData = new int(nCells*2);
    }
    else
    {
        startCell = strhex_to_int(lineVector[2]);
        endCell = strhex_to_int(lineVector[3]);
        cellType = str_to_int(lineVector[5]);
        std::cout << "Reading cells from "<< startCell << " to " << endCell << " of type " << cellType << " for zone = " << cellZoneId << "\n";
        lineVector.clear();

        if(cellType != 0)
        {
            for(int j = startCell - 1; j < endCell; j++)
            {
                    cellData[0*nCells + j] = cellZoneId;
                    cellData[1*nCells + j] = cellType;
            }
        }
        else
        {
            for(int j = startCell - 1; j < endCell; j++)
            {
                std::getline(meshFile,fileLine);
                //std::cout << fileLine << "\n";
                if (fileLine.empty())
                {
                    //std::cout << "No Cells found in file!" << "\n";
                    break;
                }
                lineVector = convert_string_to_vector(fileLine);
                if(lineVector.empty())
                    j--;
                else
                {
                    int k = 0;
                    //std::cout << lineVector.size() << "\t" << k << "\n";
                    while(k < lineVector.size())
                    {
                        cellData[0*nCells + j] = cellZoneId;
                        //std::cout << j << "\t" << lineVector[k] << "\n";
                        cellData[1*nCells + j] = str_to_int(lineVector[k]);
                        k++;
                        std::cout << nCells*2 << "\t" << 0*nCells + j << "\t" << 1*nCells + j << "\n";
                        j++;
                    }
                    lineVector.clear();
                    j--;
                }
            }
        }
    }
}

void GetFaces()
{
    nDim = str_to_int(lineVector[1]);
    lineVector.clear();
}

void GetBcNames()
{
    nDim = str_to_int(lineVector[1]);
    lineVector.clear();
}

std::vector<std::string> convert_string_to_vector(std::string line)
{
    std::stringstream ss;
    std::vector<std::string> stringVector;
    stringVector.clear();
    ss << line;

    std::getline(ss, line);
    ss.clear();
    std::size_t prev = 0, pos;
    //std::cout << line << "\n";
    while ((pos = line.find_first_of(" ()", prev)) != std::string::npos)
    {
        //std::cout << prev << "\t" << pos << "\n";
        if (pos > prev)
        {
            //std::cout << line.substr(prev,pos-prev) << "\t";
            stringVector.push_back(line.substr(prev, pos-prev));
        }
        prev = pos+1;
    }
    //std::cout << "\n";
    if (prev < line.length())
        stringVector.push_back(line.substr(prev, std::string::npos));

    /*
    for(int j=0; j < stringVector.size(); j++)
    {
        std::cout << stringVector[j] << "\t";
    }
    std::cout << "\n";
    */
    return stringVector;
}

int str_to_int(std::string s)
{
    //std::cout << s << "\t";
    std::istringstream temps(s);
    int temp;
    temps >> temp;
    //std::cout << temp << "\n";
    return temp;
}

double str_to_double(std::string s)
{
    //std::cout << s << "\n";
    std::istringstream temps(s);
    double temp;
    temps >> temp;
    //std::cout << temp << "\n";
    return temp;
}
int strhex_to_int(std::string s)
{
    //std::cout << s << "\n";
    std::stringstream temps;
    temps << std::hex << s;
    int temp;
    temps >> temp;
    //std::cout << temp << "\n";
    return temp;
}

Also please indicate if there is a better way to do the same job with C++
The input file is huge so its uploaded here
https://drive.google.com/file/d/0Bz_4p6XclzrncU5BZG5MZUtNUmM/view?usp=sharing


text:
Q: Change the z-order of activity animations on Android Is there a way how to invert the z-order of activity animations? Basically when you start new activity it is added to the backstack and its window is added over the window of the previous activity. When returning back sometimes later the activity which which is taken from the backstack show its window underneath the top activity. Most time it makes completely sense, but I have a following issue with that behavior.
I have a widget which points somewhere deep into the app structure. So I have to manually create the back stack when the user clicks on the up button in action bar. But then I actually call startActivity with new intent pointing at a new activity with back stack attached to it..and here we go to the issue..The actvity actually animates from the top, instead of being animated as usual when poping from back stack the standard way.
you can see the flow on the following picture

here is a code snippet of how I am recreating the task back stack and navigating the user to the parent activity. also way below you can see a screenshot of the animation..Basically the window which is on top should be on bottom (it is higher in the app hiearchy). FYI all those animations are done via standard XML window animations and fired with overridePendingTransition calls. I tried to modify z-adjustment within those animations, but it seems like it only does affect various layers in one particular animation..
if (NavUtils.shouldUpRecreateTask(this, upIntent)) {
       NavUtils.navigateUpTo(this, upIntent);
} else {
      TaskStackBuilder.create(this)
                        .addNextIntentWithParentStack(upIntent)
                        .startActivities();

}

A: Old question, but I've had the same problem. The solution is to add the attribute android:zAdjustment="top" or android:zAdjustment="bottom" in our animation definitions. Example:
nothing_background.xml
<?xml version="1.0" encoding="utf-8"?>
  <translate
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:zAdjustment="bottom"
    android:duration="400"
    android:fromXDelta="0%p"
    android:toXDelta="0%p" >
  </translate>

fade_in_foreground.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:zAdjustment="top">
    <alpha
        android:fromAlpha="0.0"
        android:toAlpha="1.0"
        android:interpolator="@android:anim/accelerate_interpolator"
        android:duration="400" />
</set>

In you code that triggers the transition:
Intent intent = new Intent(FromActivity.this, ToActivity.class);
Bundle animate = ActivityOptions.makeCustomAnimation(getApplicationContext(),
  R.anim.nothing_background, R.anim.fade_in_foreground).toBundle();
startActivity(intent, animate);


text:
Q: Attention MSO Users! Meta will now be shutdown due to "Why did I lose rep questions?" for the next several weeks.
That is all.

A: I seem to have gained 90 points on SO.  What's more, my rep-score page has a smiley face at the end, and that has brightened my day.  To whom may I direct my thanks and praise?

A: At least we survived the initial batch of questions. Now we just have to wait for the next 24 hours as people wake from sleep and start checking SOFU.

A: Well the rep change is sure to liven things up and its always good to shake up the system to see if it improves things.  The worst that can happen is that the change is hugely unpopular and counter-productive - at which point the change can be reversed.
The crunch will come if the change is hugely unpopular but beneficial!
But if the change has a positive impact on the site (I know that will be difficult to imagine if you've lost a bunch of rep - mines only gone down 19 as a result of the change) then everyone benefits regardless of short-term rep hurt.


text:
Q: Do I need to publish deployment scripts for deploying AGPL licensed work (MongoDB) MongoDB is dual-licensed with AGPL (the engine) and ASL 2.0 (the drivers). In a nutshell, merely using MongoDB through the drivers does not dictate to release your source code (due to drivers' ASL 2.0 license).
AFAIK, only if you directly call the mongo engine, you need to give out your code that's using it (but still not the application code that talks to mongo via the drivers).
Check this MongoDB blog entry: http://blog.mongodb.org/post/103832439/the-agpl
What if you deploy (install, configure) mongodb in your deployment scripts. And then start/stop/restart those processes. And then maybe create some users via mongo shell. Do you need to publish your deployment scripts?
(A bonus question: how can they publish the drivers as ASL 2.0 if those drivers use the AGPL-licensed part of MongoDB over the network? Because they are authors of both?)

A: Cue the usual "I'm not a lawyer" disclaimer.
This saying, GPL licenses aim to protect the users right to study the code of a piece of software, even if modified and redistributed. AGPL adds another channel of "redistribution" by explicitly stating that exposing the software to use through network systems entails the same consequences as redistributing it.
In your case, however, you are NOT modifying the MongoDB software. You merely creating related, but distinct, works that happen to interact with MongoDB. Just like a web application which uses Mongo as its storage engine, your deployment script are therefore NOT required to be published.
Relevant quote from the linked blog post is here:

The copyleft applies only to the mongod and mongos database programs.

You aren't modifying either of those two programs, so the copyleft doesn't apply.


text:
Q: in ionic when i minimize the app and open again reload the alway first page  Hello i am app developer using ionic framework, in this problem  when copy the text from another app and go back to the my app , App is reload from the main screen. but minimize before open in our app is different screen.

so please help us

A: Add some action. For example
$ionicPlatform.registerBackButtonAction(function (){
    if($ionicHistory.currentStateName() === 'home' || $ionicHistory.currentStateName() === 'login'){
        $ionicPopup.confirm({
            title: 'Exit',
            template: 'Are you sure?'
        }).then(function(option){
            if(option === true){
                navigator.app.exitApp();
            } else {
                console.log('Do nothing');
            }
        });
    } else {
        navigator.app.backHistory();
    }
}, 100);

Instead of home, login you can mention the state name that you are there at the time of copy action


text:
Q: xsl loop with new name for template tag I am trying to use a loop iteration in xslt. I want to loop through all the text with tei of "orgName", and generate a different popover-body for each one. I hope it would be something like (div class="Org-popover-body-1),(div class="Org-popover-body-2)... What should I put in ??? Thanks beforehand.
  <xsl:template match="tei:orgName">
    <xsl:for-each select="orgName">

      <xsl:attribute name="href">
      <xsl:text>#</xsl:text>
      <xsl:value-of select="@key" />
      </xsl:attribute>

Orgnization Information

  </xsl:for-each>
 <xsl:apply-templates/>
</xsl:template>

A: I think what you need are Attribute Value Templates, so you would write this...

You probably want to do this in the id of the hidden div to (to avoid multiple divs with the same id)

And similarly in the data-popover-content-2 attribute
... data-popover-content-2="#a{position()}" ...


text:
Q: How do i upgrade my android target API in Meteor I am building an android app with Meteor/Cordova. My meteor is currently version 1.5, Cordova 4.3.0. My default build uses API 25 but when I try to submit my APK to the play store, I get this message:
Your app currently targets API level 25 and must target at least API level 26 to ensure it is built on the latest APIs optimized for security and performance. Change your app's target API level to at least 26

.
How do I upgrade to API level 26?

A: inside mobile-config.js add
App.setPreference('android-targetSdkVersion', '26');

A: Go to gradle, and search for targetSdkVersion = 25 . Change it to use android targetSdkVersion = 26


text:
Q: Dropping prepositions before weekdays when using "morning," "afternoon," and "evening." Is it grammatically correct to omit prepositions in phrases like "I am available Friday morning" or "I can meet you Monday afternoon"? And would it be acceptable in formal situations? If you know any sources I'd be grateful if you include them.
Thank you so much.


text:
Q: How to select an unordered list in selenium C# .. Not able to catch I am trying to find the ul id "mainTimeSheet" and li item weekly report by id = timesheetReport but not getting it.
I am new to C# selenium.
Below is the code i am trying in C# :
//var drop = driver.FindElement(By.XPath("//ul[@id='mainTimeSheet']"));

var drop = driver.FindElement(By.Id("mainTimeSheet")).
               FindElement(By.XPath(".//li[@id='timesheetReport']"));

drop.Click();

HTML Code:

     Time Sheet

        Weekly Report

         Submit Timesheet

      <a id="timeSheetDetailReport" href="/sheetsReportsasd.aspx"
   Day Wise Report

A: Please check in the dev tools (Google chrome) if we have unique entry in HTML DOM or not.
Steps to check:
Press F12 in Chrome -> go to element section -> do a CTRL  + F -> then paste the xpath and see, if your desired element is getting highlighted with 1/1 matching node.
Xpath to check:
//li//a[@id='timesheetReport']

If it shows 1/1 matching node then
click it like this:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement timeSheet = wait.Until(e => e.FindElement(By.XPath("//ul[@id='mainTimeSheet']")));
timeSheet.Click();

IWebElement weeklyReport= wait.Until(e => e.FindElement(By.XPath("//li//a[@id='timesheetReport']")));
weeklyReport.Click();

Update:
to resolve  selenium.common.exceptions.ElementNotInteractableException:
You should debug your code like below:

*

*Make sure the browser is launched in full screen using
driver.Manage().Window.Maximize();

*Use ActionChains:
Actions actionProvider = new Actions(driver);
actionProvider.MoveToElement(new WebDriverWait(driver, TimeSpan.FromSeconds(10)).Until(e => e.FindElement(By.XPath("//ul[@id='mainTimeSheet']")))).Click().Build().Perform();

*Use ExecuteScript:
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
IWebElement timeSheet = wait.Until(e => e.FindElement(By.XPath("//ul[@id='mainTimeSheet']")));
((IJavaScriptExecutor)driver).ExecuteScript("arguments[0].click(); ", timeSheet);


text:
Q: Graphics2D Error I'm trying to create ASCII art and this error keeps showing up. I'm not sure what's wrong.
Exception in thread "main" java.lang.IllegalArgumentException: Antialiased text mode is not compatible with Global antialiasing enable key
    at sun.java2d.SunGraphics2D.setRenderingHint(SunGraphics2D.java:1187)
    at visualgrammar.Visualgrammar.main(Visualgrammar.java:21)
This is my code:
package visualgrammar;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

public class Vg {

public static void main(String[] args) {
    int width = 150;
    int height = 30;

    BufferedImage image = new BufferedImage(width,height, BufferedImage.TYPE_INT_RGB);
    Graphics a = image.getGraphics();
    a.setFont(new Font("SansSerif", Font.BOLD, 22));

    Graphics2D a2 = (Graphics2D) a;
    a2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
    a2.drawString("VISUAL GRAMMAR", 10, 20);

    for(int y=0; y<height;y++) {
        StringBuilder builder = new StringBuilder();
        for (int x=0; x < width; x++) {
        builder.append(image.getRGB(x, y)== -16777216 ? "" : "VG");
}

        System.out.println(builder);

    }
}
}


text:
Q: prove that $[(n-1)!/n]$ is even for n>4 '[]' refers to the greatest integer function.
I have tried expanding the factorial and applying greatest integer function properties but could not prove it.

A: @Peter above proves it for $n$ being prime, and points out that if $n$ is composite and greater than $4$, then $\frac{(n-1)!}n$ is an integer, so we can disregard the greatest integer brackets. It remains to show that this integer is even.
I will do this by counting the number of factors $2$ in $(n-1)!$ and in $n$, and see that there are too many of them in $(n-1)!$ to be cancelled out by $n$ (as long as $n>4$).
Each even number less than or equal to $n-1$ contributes at least one factor $2$ to $(n-1)!$. There are $\left\lfloor\frac{n-1}2\right\rfloor$ of those. Each factor of $4$ contributes at least one more. There are $\left\lfloor\frac{n-1}4\right\rfloor$ of those. In total, that means that if we write $(n-1)!$ as $2^k \cdot m$ where $m$ is odd, then $k> \frac{3n}4 - 2$, which in turn implies that $2^k > n$. We can do the same to $n$, getting $n = 2^r\cdot p$ with $p$ odd, and $2^r\leq n$. We now have
$$
\frac{(n-1)!}{n} = \frac{2^k\cdot m}{2^r\cdot p} \\
= \frac{2^k}{2^r}\cdot\frac{m}{p}
$$
Both the fractions on the last line must be integers, and especially since $2^k> n\geq 2^r$, the left fraction must be an even integer, and we're done.


text:
Q: MMA gives error when a different PDF expression is used for the same distribution I have the following MMA code. Note that the function I declared at the very beginning is the PDF of square of a Nakagami Distributed random variable. With $m=1$ and $P=1$, $f(h)$ becomes Exponential Distribution with rate parameter 1, i.e., ExponentialDistribution[1]

A: A PDF is not a distribution. To convert a PDF to its associated distribution use ProbabilityDistribution
Clear[λ, pb, Ps, μ]

f[h_] := 1/Gamma[m]*(m/P)^m*h^(m - 1)*Exp[-(m*h)/P];
m = 1; P = 1;

α = 4; δ = 2/α;

int = Assuming[{A > 0, r > 0, λ > 0},
  Integrate[(1 - Exp[-x*h*r^(-1/δ)])*pb*λ*π, {r, A,
    Infinity}, GenerateConditions -> False]]

(*  -pb π r λ - (pb π^(3/2) λ Erfc[r Sqrt[h μ]])/(
 2 Sqrt[h μ])  *)

LI = Assuming[{A > 0, r > 0, λ > 0, x > 0},
  Exp[-Expectation[int,
      h \[Distributed] ProbabilityDistribution[f[h], {h, 0, Infinity}]]] //
   FullSimplify]

(*  E^(pb π λ (r + ArcCot[r Sqrt[μ]]/Sqrt[μ]))  *)

Note that this is the same result obtained with h\[Distributed]ExponentialDistribution[1]
LI === Assuming[{A > 0, r > 0, λ > 0, x > 0},
  Exp[-Expectation[int, h \[Distributed] ExponentialDistribution[1]]] //
   FullSimplify]

(*  True  *)

x = s*Ps; A = r;
M = LI;

s = μ*r^α/Ps; B = M;

λ = 4; pb = 1/2; Ps = 19.9526; μ = 1.2589;

AverageProbSuccess[B_, λ_] :=
 NIntegrate[B*2*π*λ*r*Exp[-π*λ*r^2], {r, 0, Infinity}]

AverageProbSuccess[B, λ]

(*  0.8346  *)

A: This is an extended comment.  f[h] as defined while clearly a probability density function is not of the type of function that Expectation expects.  Consider the difference between the two functions f and g below:
f[h_] := 1/Gamma[m]*(m/P)^m*h^(m - 1)*Exp[-(m*h)/P]

(* Head *)
Head[f]
(* Symbol *)

(* PDF *)
f[h]
(* (E^(-((h m)/P)) h^(-1 + m) (m/P)^m)/Gamma[m] *)

(* Mean *)
Integrate[h f[h], {h, 0, ∞}]
(* ConditionalExpression[P, (Re[m] != 0 || m ∉ Reals) && 1 + Re[m] > 0 && Re[m/P] > 0]  *)

And now g
g := ProbabilityDistribution[1/Gamma[m]*(m/P)^m*h^(m - 1)*Exp[-(m*h)/P],
{h, 0, ∞},
Assumptions -> {m > 1, P > 0}]

(* Head *)
Head[g]
(* ProbabilityDistribution *)

(* PDF *)
PDF[g, h]
(* Piecewise[{{(h^(-1 + m)*(m/P)^m)/(E^((h*m)/P)*Gamma[m]), h > 0}}, 0] *)

(* Mean *)
Expectation[h, h \[Distributed] g]
(* P *)


text:
Q: Sending message on wso2 socket, getting exception I am trying to send a message over TCP in wso2 framework. I am getting this exception in log:
[2015-08-20 12:21:50,098] ERROR - TCPWorker Error while processing TCP request through the Axis2 engine
java.lang.NullPointerException
        at org.wso2.carbon.tenant.dispatcher.MultitenantDispatcher.findService(MultitenantDispatcher.java:47)
        at org.apache.axis2.engine.AbstractDispatcher.invoke(AbstractDispatcher.java:94)
        at org.apache.axis2.engine.Phase.invokeHandler(Phase.java:340)
        at org.apache.axis2.engine.Phase.invoke(Phase.java:313)
        at org.apache.axis2.engine.AxisEngine.invoke(AxisEngine.java:261)
        at org.apache.axis2.engine.AxisEngine.receive(AxisEngine.java:167)
        at org.apache.axis2.transport.tcp.TCPWorker.run(TCPWorker.java:68)
        at org.apache.axis2.transport.base.threads.NativeWorkerPool$1.run(NativeWorkerPool.java:172)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
        at java.lang.Thread.run(Thread.java:745)

Following is the axis2 conf to start TCP:
<transportReceiver name="local" class="org.wso2.carbon.core.transports.local.CarbonLocalTransportReceiver"/>

<transportReceiver name="tcp" class="org.apache.axis2.transport.tcp.TCPTransportListener">
                <parameter name="transport.tcp.port">6060</parameter>
</transportReceiver>

And wso2.xml:
<definitions xmlns="http://ws.apache.org/ns/synapse">

    <sequence name="fault">
        <makefault>
            <code xmlns:tns="http://www.w3.org/2003/05/soap-envelope" value="tns:Receiver"/>
            <reason value="Mediation failed."/>
        </makefault>
        <send/>
    </sequence>

    <proxy xmlns="http://ws.apache.org/ns/synapse"
           name="TCPProxy"
           transports="https,http"
           statistics="disable"
           trace="disable"
           startOnLoad="true">
        <target>
            <inSequence>
                <log level="full"/>
            </inSequence>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <parameter name="transport.tcp.port">6060</parameter>
        <parameter name="transport.tcp.contentType">application/xml</parameter>
        <description/>
    </proxy>
</definitions>

A: It sounds like no proxy service can be found in the ESB when a message is received on tcp port 6060.
I'm not used to tcp transport in WSO2 but I wonder if the "transports" attribute in you proxy definition should contain "tcp" instead of "https,http" :
<proxy xmlns="http://ws.apache.org/ns/synapse"
           name="TCPProxy"
           transports="tcp"
           statistics="disable"
           trace="disable"
           startOnLoad="true">
        <target>
            <inSequence>
                <log level="full"/>
            </inSequence>
            <outSequence>
                <send/>
            </outSequence>
        </target>
        <parameter name="transport.tcp.port">6060</parameter>
        <parameter name="transport.tcp.contentType">application/xml</parameter>
        <description/>
    </proxy>


text:
Q: Screen orientation on tablet error I have a strange issue. I have an LG g700 tablet and I want to set the orientation locked. But when i test it on my nexus 5 it works well with the following code:
window.screen.orientation.lock("landscape")

But when i do the same code on my tablet it doesn't work and it gives an error like:
Uncaught (in promise) DOMException: The page needs to be fullscreen in order to call lockOrientation(). {message: "The page needs to be fullscreen in order to call lockOrientation().", name: "SecurityError", code: 18, INDEX_SIZE_ERR: 1, DOMSTRING_SIZE_ERR: 2…}code: 18message: "The page needs to be fullscreen in order to call lockOrientation()."name: "SecurityError"__proto__: DOMException

Is there an solution for this?

A: This can be done only on full screen mode. So I suggest you add a timeout before calling screen.orientation just to make sure that full screen is active and ready.
if (document.fullScreen || document.mozFullScreen || document.webkitIsFullScreen) {
   setTimeout(function(){
      window.screen.orientation.lock("landscape");
   }    , 200);
}


text:
Q: prove pointwise convergence and uniform convergence I have been buggin on this question for a few hours now.
Q. for n = 1, 2, 3, ...  let $f_n : [0, +\infty) \rightarrow \mathbb R$ be defined by
$f_n = \frac{xn + sin (\frac{x}{n^2})}{2(n + \sqrt x )}$
Show that $f_n$ converges pointwise on $[0, +\infty)$ and determine whether $f_n$ converges uniformly on $[0, +\infty)$ or not.
I have tried to come up with a solution on my own but I'm not sure if it's correct.
My attempt:
$\forall x \in [0, +\infty),$
$$\lim_{n \to \infty} f_n (x) = \lim_{n \to \infty} \frac{xn}{2(n + \sqrt x)} + \lim_{n \to \infty} \frac{sin (\frac{x}{n^2})}{2(n + \sqrt x)}$$
$$= \lim_{n \to \infty} \frac{xn}{n(2+\frac{2\sqrt x}{n})} + \lim_{n \to \infty} \frac{sin (\frac{x}{n^2})}{2(n+ \sqrt x)}$$
$$= \lim_{n \to \infty} \frac{x}{(2+\frac{2\sqrt x}{n})} + \lim_{n \to \infty} \frac{sin (\frac{x}{n^2})}{2(n+ \sqrt x)}$$
As $n \to \infty$, $\lim_{n \to \infty} \frac{x}{(2+\frac{2\sqrt x}{n})}$ becomes $\frac{x}{2}$ and $\lim_{n \to \infty} \frac{sin (\frac{x}{n^2})}{2(n+ \sqrt x)}$ becomes zero.
So $f_n \to f$ defined by $f : [0, +\infty) \to \mathbb R,$
$f(x) =
\begin{cases}
0,  & \text{if $x = 0$ } \\[2ex]
\frac{x}{2}, & \text{if $x \neq 0$}
\end{cases}$
So $f_n$ converges pointwisely.
However, for uniform convergence,
$$|f_n(x) - f(x)| = |\frac{xn + sin(\frac{x}{n^2})}{2(n + \sqrt x)} - \frac{x(n + \sqrt x)}{2(n + \sqrt x)}|$$
$$= |\frac{sin(\frac{x}{n^2})-x^\frac{3}{2}}{2(n+ \sqrt x)}|$$
if we set $x = n^2$
$$= |\frac{sin 1 - n^3}{2(n + \sqrt n^2)}| = |\frac{sin 1}{4n} - \frac{n^2}{4}|$$
$$\Rightarrow \lim_{n \to \infty} ||f_n - f|| \neq 0$$
Hence $f_n$ does not converge uniformly.
$ $
Is my solution reasonably correct?
Thanks


text:
Q: Do EnderStorage Ender Chests prevent strangers from accessing them if they make a chest with the same color code by accident? Please note that this is a question about the minecraft mod EnderStorage, NOT vanilla ender chests.

The EnderStorage mod has custom ender chests which can be privatised by using different dyes on the 3 color slots.
When it comes to using those on a server, what happens if someone accidentally makes an ender chest with the same color code as the one I'm using? Will that person be able to see the contents of my ender chest, or is there something in place to prevent that?

A: By default, all EnderStorage chests with the same color code will connect to each other, regardless of who placed those chests. However, you can make an EnderStorage chest private by right clicking on the latch with a diamond. This will cause the chest to also be associated with you, and will now only connect that chest to other diamond-latched chests with the same color code.


text:
Q: Powershell: copy-item deletes file I have a client that removes/writes files every 10 seconds on my laptop. I also have a Powershell script that is supposed to copy files whenever they are changed, to a network location.
Now to the problem: sometimes, quite often, one or two of the files on the remote network location gets deleted. But I have nothing in the script that is supposed to delete any file, only copy.
How come this happens? See the script below:
$block = {
function CreateCopyFile
{
    param ($message, $event)
    # function to call when event is raised
    # do a robocopy or whatever

    $path = $Event.SourceEventArgs.FullPath
    $targetpath = $targetFolder + "/" + $Event.SourceEventArgs.Name

    Copy-Item $path $targetFolder
}

$watchedFolder = "C:\Users\test\Documents\folder"
$targetFolder = "\\TRICASTER-MINI\DataLink Watch Folder"
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $watchedFolder

Register-ObjectEvent -InputObject $watcher -EventName Created -SourceIdentifier File.Created -Action { CreateCopyFile "Created" $event }
Register-ObjectEvent -InputObject $watcher -EventName Changed -SourceIdentifier File.Changed -Action { CreateCopyFile "Changed" $event }
}

$encodedBlock = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($block))

Start-Process PowerShell.exe -verb Runas -argumentlist '-WindowStyle Hidden', '-NoExit', '-EncodedCommand', $encodedBlock


text:
Q: How to write an angularjs directive that makes use of both scope and attributes and refer it thru compiled partial? I want to write a directive which takes advantage of custom attributes, as follows:
<plant-stages
    title="Exploration
du cycle de
développement
de la plante"
></plant-stages>

The controller is currently as follows:
app.directive('plantStages', function () {
    return {
        restrict: 'AE',
        templateUrl: 'corn.figure.plant.stages.html',
        link: function (scope, element, attrs) {
        scope.title = attrs.title;
        }
    };
});

The partial is as follows:

{{title}}

            BBCH : {{stage.bbch}}

            {{stage.displayName}}

The partial makes use of some scope model variables.
And {{title}} should support plain HTML injection out of the view which embeds it, hence should be compiled. I tried to support this but without success.
What modification should I make to have the HTML compiled?
A bonus question: when I pass the attribute in, I create a dummy title variable in the scope that persists where it should only be local. How would one make changes to handle this?

A: If you want to wrap HTML in your custom directive take a look at the transclude option (see docs):
module.directive('myDirective', function() {
  return {
    restrict: 'E',
    transclude: true,
    template: '

'
  };
});

This enables you to place HTML within the directive tag which can be used in the template:

  <my-directive>

Test

  </my-directive>

In case you really want to pass HTML via an attribute use ng-bind-html. This requires the ngSanitize module:
module.directive('myDirective', function () {
  return {
    restrict: 'E',
    template: '

',
        scope: {
            title:'@'
        }
    };
});

I added this to your fiddle.


text:
Q: Determining the encoding of a file uploaded to Google App Engine I have a website based on GAE and Python, and I'd like the user to be able to upload a text file for processing. My implementation is based on standard code from the docs (see http://code.google.com/appengine/docs/python/blobstore/overview.html) and my text file upload handler essentially looks like this:
class Uploader(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        blob_reader = blobstore.BlobReader(blob_info.key())
        for line in blob_reader:
            line = line.rstrip().decode('cp1252')
            do_something(line)
        blob_reader.close()

This works fine for a text file encoded with Code Page 1252, which is what you get when using Windows Notepad and saving with what it calls an "ANSI" encoding. But if you use this handler with a file that has been saved with Notepad's UTF-8 encoding, and contains, say, some Cyrillic characters or a u-umlaut, you'll end up with gibberish. For such a file, changing decode('cp1252') to decode('utf_8') will do the trick. (Well, there's also the possibility of a byte order mark (BOM) at the beginning, but that's easily stripped away.)
But how do you know which decoding to use? The BOM isn't guaranteed to be there, and I don't see any other way to know, other than to ask the user—who probably doesn't know either. Is there a reliable method for determining the encoding? I don't necessarily have to use the blobstore if some other means solves it.
And then there's the encoding that Windows Notepad calls "Unicode" which is a UTF-16 little endian encoding. I could find no decoding (including "utf_16_le") that correctly decodes a file saved with this encoding. Can one of these files be read?

A: May be this will help: Python: Is there a way to determine the encoding of text file?.

A: Following the response from demalexx, my upload handler now determines the encoding using chardet (http://pypi.python.org/pypi/chardet) which, from what I can tell, works extremely well.
Along the way I've discovered that using "for line in blob_reader" to read uploaded text files is extremely troublesome. Instead, if you don't mind reading your entire file in one gulp the solution is easy. (Note the stripping away of one BOM sequence, and the splitting of lines across CR/LF.)
class Uploader(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        text = blobstore.BlobReader(blob_info.key()).read()
        encoding = chardet.detect(text)['encoding']
        if encoding is not None:
            for line in text.decode(encoding).lstrip(u'\ufeff').split(u'\x0d\x0a'):
                do_something(line)

If you want to read piecemeal from your uploaded file, you're in for a world of pain. The problem is that "for line in blob_reader" apparently reads up to where a line-feed (\x0a) byte is found, which is disastrous when reading a utf_16_le encoded file as it chops a \x0a\x00 sequence in half!
I don't recommend it, but here's an upload handler that will successfully process files stored by all the encodings in Windows 7 Notepad (namely, ANSI, UTF-8, Unicode and Unicode big endian) a line at a time. As you can see, stripping away the line termination sequences is cumbersome.
class Uploader(blobstore_handlers.BlobstoreUploadHandler):
    def post(self):
        upload_files = self.get_uploads('file')
        blob_info = upload_files[0]
        blob_reader = blobstore.BlobReader(blob_info.key())
        encoding = chardet.detect(blob_reader.read(10000))['encoding']
        if encoding is not None:
            blob_reader.seek(0)
            for line in blob_reader:
                if line[:2] in ['\xff\xfe','\xfe\xff']:
                    start = 2
                elif line[:3] == '\xef\xbb\xbf':
                    start = 3
                else:
                    start = 0
                if encoding == 'UTF-16BE':
                    if line[-4:] == '\x00\x0d\x00\x0a':
                        line = line[start:-4]
                    elif start > 0:
                        line = line[start:]
                elif encoding == 'UTF-16LE':
                    if line[start] == '\x00':
                        start += 1
                    if line[-3:] == '\x0d\x00\x0a':
                        line = line[start:-3]
                    elif start > 0:
                        line = line[start:]
                elif line[-2:] == '\x0d\x0a':
                    line = line[start:-2]
                elif start > 0:
                    line = line[start:]
                do_something(line.decode(encoding))

This is undoubtedly brittle, and my tests have been restricted to those four encodings, and only for how Windows 7 Notepad creates files. Note that before reading a line at a time I'm grabbing up to 10000 characters for chardet to analyze. That's only a guess as to how many bytes it might need. This clumsy double-read is another reason to avoid this solution.


text:
Q: Conservation of momentum leading to damage What would be an intuitive way to damage objects in a physics game using impulses? Since momentum is conserved, so is impulse (the change in momentum for any two time periods) in a closed system.
So if I have the impulse of a collision (that is, the change in momentum during a time interval for one of the two bodies) what would be the intuitive way to damage both the objects. Should each object receive the same damage based on the impulse of the overall system, or should the damage incurred be split unevenly based on the relative mass of each object? My intuition is that objects with larger mass would have higher hit-points, and so would be less affected if the same damage was incurred to both the objects in the collision.

A: Objects are not damaged by momentum $\vec{p}$ they are damaged by force $\vec{F}$. When two objects collide their momenta changes because of forces they apply each other while being in contact. According to 2nd Newton's law the force can be calculated as follows:
$$
\vec{F} = \frac{d\vec{p}}{dt}
$$
So the force is determined by the time of interaction. When two objects contact their surfaces are flexed. The bigger is the flex the higher is the force which changes the momentum. At some moment of time the relative normal momentum (and velocity) becomes zero and the objects start move backward.
At this moment the force and the flex is maximal. If the surface (armor) is not strong enough for this flex the object is damaged. This can happen long before the relative normal velocity become zero. In that case the interaction between internal parts of the objects started.
Momentum
Hence damage is not determined only by momentum. It is determined by the force and the ability of the object resist it. The force is not constant during the collision and its maximal value depends on momentum and the time of interaction of the surfaces. The time of interaction depends on both flexibility and strength.
When a basketball hits the floor its momentum changes from $\vec{p}$ to almost $-\vec{p}$ so the total change is almost $2p$. When a glass hits the floor its momentum becomes zero so the change is $p$. The ball has higher flexibility and strength and is not destroyed even though the momentum change is two times higher.
Another example is a bullet that hits a door. It makes hole before the door opens. The force is huge but the momentum of the door is almost not changed because the time necessary to reach critical flex is too short. When one pushes the door with his finger the force is small and does not destroy the surface before the flex stop the finger. The door gets enough momentum to start move.
Energy
When the surface is flexed in irreversible way or damaged some part of kinetic energy of the objects turns into kinetic energy of their parts, heat, sound, light etc. This is called inelastic collision. Elastic collision means no damage. If you need a good model this should be taken into account.

A: There is a whole field of interest in breaking things realistically in computer games and movie CG effects.
Basically the impulse of the collision has to, like you say, be propagated internally in the objects that collide. This is a very complex problem if you want to do it realistically, essentially you need to solve the stress diagram of any number of suitably small pieces of the object and fracture them as the propagated impulse breaks their connections.
Some games get around this by letting the artist create "pre-fractured" models with known sub-parts that can be split upon an impulse over a certain threshold at a certain place. This is more flexible than it sounds because the artist can create the pre-fracturing using mechanical engineering programs, so the fracturing itself is realistic, but the exact impulse -> fracture shape will be mostly inexact.
In either case, simply using the mass of the two colliding objects to determine which should break, is overly simplistic (overall mass is not an accurate predictor of "breakability"), but a computer game is a work of art and not an accurate simulation in most cases, so if you implement it and it feels right, go for it :)
Here is a discussion from the Bullet Physics forum about fracturing collision-shapes depending on the impulse (somewhat technical but you might get some inspiration). Bullet is a well-known open-source 3D physics library used in hundreds of computer-games and Hollywood movies.


text:
Q: Getting the same error again and again [Error: A non-recoverable sign in failure occurred] I am getting same problem again and again for last 10 days. I am using React Native CLI and trying to achieve Social Logins through Firebase.
Here's my main app.js file
import { Button, StyleSheet, Text, View } from 'react-native'
import React from 'react'
import auth from '@react-native-firebase/auth';
import { GoogleSignin } from '@react-native-google-signin/google-signin';

export default function App() {
  GoogleSignin.configure({
    webClientId: '22141653705-prn44vqplfc5gnnvta1agv60mqb59tht.apps.googleusercontent.com',
  });
  const signInWithGoogleAsync = async () => {
// Get the users ID token
      try{
        const { idToken } = await GoogleSignin.signIn();

      // Create a Google credential with the token
      const googleCredential = auth.GoogleAuthProvider.credential(idToken);

      // Sign-in the user with the credential
      const user_sign_in = auth().signInWithCredential(googleCredential);

      user_sign_in.then((user) => {
        console.log(user);
      })
      .catch((error)=>{
        console.log(error);
      })
      }
      catch(error){
        console.log(error);

      }
  }
  return (
    <View style={{flex:1,justifyContent:'center',alignItems:'center'}}>
      <Button title="Sign in with Google" onPress={signInWithGoogleAsync} />
    </View>
  )
}

const styles = StyleSheet.create({})

Here's my google-services.json file
{
  "project_info": {
    "project_number": "22141653705",
    "project_id": "rn-firebase-c65e0",
    "storage_bucket": "rn-firebase-c65e0.appspot.com"
  },
  "client": [
    {
      "client_info": {
        "mobilesdk_app_id": "1:22141653705:android:412f6758b9a9e4c400b318",
        "android_client_info": {
          "package_name": "com.testfirebase"
        }
      },
      "oauth_client": [
        {
          "client_id": "22141653705-jmmnfqj5g1vsjd10b3aneobfqopcdas0.apps.googleusercontent.com",
          "client_type": 1,
          "android_info": {
            "package_name": "com.testfirebase",
            "certificate_hash": "203e8b51da549d3be63bb70183478696cda25b5f"
          }
        },
        {
          "client_id": "22141653705-prn44vqplfc5gnnvta1agv60mqb59tht.apps.googleusercontent.com",
          "client_type": 3
        }
      ],
      "api_key": [
        {
          "current_key": "AIzaSyD2pTmhBUQA4ZtT6WEBuG88wAdnmY8Mw1Q"
        }
      ],
      "services": {
        "appinvite_service": {
          "other_platform_oauth_client": [
            {
              "client_id": "22141653705-prn44vqplfc5gnnvta1agv60mqb59tht.apps.googleusercontent.com",
              "client_type": 3
            }
          ]
        }
      }
    }
  ],
  "configuration_version": "1"
}

Here are my screenshots for SHA keys and other configurations:
SHA 1 keys of debug Android Test
WebClientId
SHA Fingerprints


text:
Q: jQuery: Having trouble with not and multiple selectors for CSS I've got a number of divs (CSS class 'group'), and when one is clicked in, the others are hidden and the clicked on one is expanded (gaining the 'detailed' CSS class). Then, when the expanded div ('.group .detailed) is clicked on, it should resize and lose the 'detailed' class. My problem is, I can't get click events on 'group' divs that also contain 'detailed' to be ignored by my first jquery function and activate my second jquery function. Here's my code:
$('.group:not(.detailed)').mousedown(function(){
    var $self = $(this);
    var speed = 3250;
    var offset = {x : $self.offset().left, y : $self.offset().top};

    readyAnimation();

    $('.group').not($self).addClass('hide');
    $self.animate({'width' : '100%', 'height' : '+=' + '300px'}, {left: 'offset.x' + 'px', top: 'offset.y' + 'px'}, speed);

    function readyAnimation () {
        $self.css({display : 'block'});
        $self.css({'-webkit-box-sizing' : 'border-box', '-moz-box-sizing' : 'border-box', 'box-sizing' : 'border-box'});
        $self.css({margin : '0px'});
    };

    $self.addClass('detailed');
});

$('.group.detailed').mousedown(function(){
    var $self = $(this);
    var size = '300px';
    var speed = 3250;

    console.log("it worked");

    resetAnimation();

    $self.animate({'width' : size, 'height' : size}, speed)
    $('.group').removeClass('hide');

    function resetAnimation () {
        $self.css({display : ''}); //Empty quotes resets the CSS value to what it was originally (in the CSS file)
        $self.css({'-webkit-box-sizing' : '', '-moz-box-sizing' : '', 'box-sizing' : ''});
        $self.css({margin : ''});
    };

    $self.removeClass('detailed');
});

I don't think I need to post my HTML and CSS for this, but they can be seen here in a previous question I asked. Thanks for reading.
EDIT: Here's a link to the fiddle
EDIT 2: See vahapwns, Jonathan and giordanolima's answers for working demonstrations of the code. By combining the two functions togother and using an if statement checking for 'detailed', problems arising from the first function overriding the second are solved. Thanks everybody for your input.

A: take your two jQuery selections and merge them into one, use an if() to check if it's .detailed or not. you should also move those extra functions outside so that they're only defined once each.
i have rearranged the logic for you, now you need to fine tune the animation sequence: http://jsfiddle.net/V93dq/2/

A: @vahanpwns is correct, try this one:
http://jsfiddle.net/V93dq/1/
Basically you can use the hasClass jQuery method.
$('.group').mousedown(function(){
    var $self = $(this);

    if($self.hasClass("detailed")){

    }else{

    }
});

A: Take a look here...
I used the condition hassClass... I think was better... And i prevent the link Default...
Finddle
function readyAnimation (mySelf) {
    mySelf.css({display : 'block'});
    mySelf.css({'-webkit-box-sizing' : 'border-box', '-moz-box-sizing' : 'border-box', 'box-sizing' : 'border-box'});
    mySelf.css({margin : '0px'});
};

function resetAnimation (mySelf) {
    mySelf.css({display : ''});
    mySelf.css({'-webkit-box-sizing' : '', '-moz-box-sizing' : '', 'box-sizing' : ''});
    mySelf.css({margin : ''});
};

$('.group').mousedown(function(){
    if(!$(this).hasClass("detailed")){
        var $self = $(this);
        var speed = 3250;
        var offset = {x : $self.offset().left, y : $self.offset().top};
        readyAnimation($self);
        $('.group').not($self).addClass('hide');
        $self.animate({'width' : '100%', 'height' : '+=' + '300px'}, {left: 'offset.x' + 'px', top: 'offset.y' + 'px'}, speed);
        $self.addClass('detailed');
    }else{
        var $self = $(this);
        var size = '300px';
        var speed = 3250;
        resetAnimation($self);
        $self.animate({'width' : size, 'height' : size}, speed)
        $('.group').removeClass('hide');
        $self.removeClass('detailed');
    }

}).find('a').click(function(e){e.preventDefault();});;


text:
Q: Is $h(x)=x^\frac{3}{2}$, $D_h=[0,\infty)$ uniformly continuous?
Is $h(x)=x^\frac{3}{2}$, $D_h=[0,\infty)$ uniformly continuous ?

My attempt:
i) since $h$ is continuous on $[0,2]$ then it is uniformly continuous on $[0,2]$.
ii) If $x,u \in [1,\infty)$, then
$|h(x)-h(u)|=|x^\frac{3}{2} - u^\frac{3}{2} |$
$=\frac{|(x-u)||(x^2+xu+u^2)|}{| x^\frac{3}{2} +u^\frac{3}{2} |}$
$\leq \frac{|(x-u)|(|x|^2+|xu|+|u|^2)|}{| x^\frac{3}{2} +u^\frac{3}{2} |} $
I want to prove that $\frac{|(x-u)|(|x|^2+|xu|+|u|^2)|}{| x^\frac{3}{2} +u^\frac{3}{2} |} \leq a |x-u|$
Then take $\delta = \frac{\epsilon }{a}$ to get that
$\forall x,u \in [1,\infty), |x-u|<\delta \implies |h(x)-h(u)|<\epsilon$
How can I complete please?

A: It is not uniformly continuous. Take the sequences $a_n=(n+1)^{\frac{2}{3}}$ and $b_n=n^{\frac{2}{3}}$. Then $\lim_{n\to\infty} (a_n-b_n)=0$ but $\lim_{n\to\infty} (h(a_n)-h(b_n))\ne 0$.


text:
Q: Firewall blocks access to grails repo refresh dependencies fails due to firewall+proxy combonation.
The corporate IT is not going to make an exception. I have found that I can do a recursive wget on the  repo url and generate duplicate their folder structure.
What can I do locally so that all developers can use this "mirror" by default?
If the above is not possible, where does grail usually put these files on a windows based installation?

A: Try adding local repo to your BuildConfig and of course make it accessible over your LAN, or perhaps tell other devs to make their local cloned repos. The path to this local repo could be ENVARIONMENT_VARIABLE, too (that makes it fully customizable)
repositories {
    grailsPlugins()
    grailsHome()
    mavenCentral()
    mavenRepo('/path/to/my-local-maven-repo')
}

http://jdpgrailsdev.github.io/blog/2014/02/10/grails_maven_local_repo.html

A: You have a couple of options here.
First, if it's just a normal proxy than you can configure grails to utilise it. Take note of the following grails commands:

*

*grails add-proxy

*grails set-proxy
These in turn will establish a file in your home directory in .grails called ProxySettings.groovy (i.e. ~/.grails/ProxySettings) that is then used by all grails commands for all projects.
However, if you're behind a Microsoft NTLM proxy (as I am) then I'd suggest still doing the above by making use of Java NTLM Proxy.
(Keep in mind though, that the grails wrapper does not use the above ProxySettings.groovy and then you need to use the standard JAVA_OPTS of -Dhttp.proxyPort, -Dhttp.proxyHost, etc.)
But I appreciate maybe you've done all that and you still want to avoid the proxy. I'd suggest the next solution - and one that should be considered anyway - is setting up a corporate/internal Maven repository server with something like Artifactory or Nexus.
Lastly, there is the instruction from MamyKryzysKryzysKryzys with using mavenRepo( <localPath> ). More info on that is available in the grails doco.
Finally, to address your question of "where does grail usually put these files". Under the hood grails is simply using maven so it's stored in your normal maven local repo which is ~/.m2/repository.
Good luck! Proxies make things hard, but once you figure your solution it's a thing of the past. Personally, we now use a combination of the Java NTLM Proxy and an internal Artifactory server.


text:
Q: How to render key value pairs from object react This is object data that I have stored in my this.state.profile from an API request.
What I need to do know is render the values from the keys to the web broswer. I am trying with the code below which does not work. Also how do I render the objects within side this object? This is all so confusing :(
{
    "localizedLastName": "King",
    "lastName": {
        "localized": {
            "en_US": "King"
        },
        "preferredLocale": {
            "country": "US",
            "language": "en"
        }
    },
    "firstName": {
        "localized": {
            "en_US": "Benn"
        },
        "preferredLocale": {
            "country": "US",
            "language": "en"
        }
    },
    "profilePicture": {
        "displayImage": "urn:li:digitalmediaAsset:C5603AQGjLGZPOyRBBA"
    },
    "id": "fm0B3D6y3I",
    "localizedFirstName": "Benn"
}

How I am trying to render it:
const { profile } = this.state;

const profileList = Object.keys(profile).map((key,value)=>{
  return (

{key}{value.toString()}

  );
})

{ profileList }

A: try:
return (
   {Object.entries(profile).map(([key,value]) => {

{key} : {value.toString()}

   })}
)

the iteration needs to happen inside of the return.

A: You could build up your object outside your render call like below and just render it (elements).
var elements = [];
for (var prop in this.state.profile) {
    elements.push(
{prop} : {this.state.profile[prop].toString()}
)
}

If it's not working my guess would be your state isn't initialised or your target js version doesn't support Object.entries

A: First of all, you need to deal with nested objects:
{
    ...
    "firstName": {
        "localized": {
            "en_US": "Benn"
        },
        "preferredLocale": {
            "country": "US",
            "language": "en"
        }
    }...
}

If you try to render the value on the key firstName, you will get a object as value, and React can't render objects as elements.
And if you call toString() on it, you will get [Object object] as value.
To solve this, you gonna need some recursion:
const objToString = obj => {
  let result = [];

  Object.keys(key => {
    if(typeof obj[key] === 'object'){
      let children = (
{key} : {objToString(obj[key])}
)
      result.push(children)
    } else
      result.push(
{key} : {obj[key]}
)
  })
}

...

const profileList = objToString(profile)

This should give you this something like:
...

firstName:

localized:

en_US: Benn

...