问:
Why strange crash with mapview happen?
I have a very simple app. 1 navigationController with 2 viewControllers.

The first view has only a button.
The second view has a map view (MKMapView).
I checked show currentlocation property of this map view
I created outlet and then connect everything by using Builder Interface.

In the dealloc method of the second one, I set nil to delegate of mapview, and then release mapview outlet.

mapView.delegate = nil;
[mapview release];

When I tap the button in view1, view2 will be loaded, and then I tap back button. If I do it normally, everything works well. But If I do it very quickly, repeat many times. The app will be crashed.
If I do not release mapView or I do not check showcurrentlocation property, app works well.

I can't figure out why this happen. Anyone helps me solve this problem. Thanks so much !

答:
Try launching your app via Instruments with Zombie instrument added. It should show you overreleased object. You'd also should add the Allocations instrument with VM tracker to see how memory consumption goes over time. This way you'd get your answer very quick.

p.s. more code would help better.

Title: Why strange crash with mapview happen?


来源: stackexchange

问:
I'm trying to limit the number of displayed numbers in ng-repeat in html
Angular novice and working through a fibonacci sequence app. I would like to only ng-repeat/display the current number in the sequence instead of having all of the numbers stack up in the html page. Should I use a directive instead or is limitTo the solution to dynamically display only one number each time the button is clicked? I looked for other answers, but none really fit my problem. Thanks for any help!

Here is my code so far:

```<code><!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fibonacci</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">

</head>
<body ng-app="fib" ng-controller="nextFibCtrl">

<h2 ng-repeat="result in results track by $index" | "limitTo: 1"> {{ result }}
</h2>

<div>
<button type="button" class="reset" ng-click="clear()">RESET</button>
<button type="button" class="next" ng-click="nextNum()">NEXT FIB</button>
</div>

<script src =
 "https://ajax.googleapis.com/ajax/libs/angularjs/1.3.12/angular.js" >
</script>
<script src="script.js"></script>
</body>
</html>
</code>```

My script file:

```<code> var app = angular.module('fib', []);

 app.controller('nextFibCtrl', function($scope,){

 $scope.results = [0, 1];

 $scope.nextNum = function(){

     $scope.currentInt = $scope.results.length -1;

     $scope.nextInt = $scope.results[$scope.currentInt] +

     $scope.results[$scope.currentInt -1];

     $scope.results.push($scope.nextInt);

  }

      $scope.clear = function(){

      $scope.results = [0, 1];

  }

  });
</code>```

答:
The issue in your code are quotes, so instead of this:

```<code><h2 ng-repeat="result in results track by $index" | "limitTo: 1"> {{ result }}
</h2>
</code>```

Do this:

```<code><h2 ng-repeat="result in results track by $index" | limitTo:1> {{ result }}
</h2>
</code>```

But, considering that you want to display only one value, and you already have that value bound to the scope, just change the code to this:

```<code><h2> {{ $scope.nextInt }} </h2>
</code>```

I hope it helps

ContentLicense: CC BY-SA 3.0

Body:
Angular novice and working through a fibonacci sequence app. I would like to only ng-repeat/display the current number in the sequence instead of having all of the numbers stack up in the html page. Should I use a directive instead or is limitTo the solution to dynamically display only one number each time the button is clicked? I looked for other answers, but none really fit my problem. Thanks for any help!

Here is my code so far:

<!DOCTYPE html>

<meta charset="utf-8">
<title>Fibonacci</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Oswald" rel="stylesheet">

 {{ result }}

<button type="button" class="reset" ng-click="clear()">RESET</button>
<button type="button" class="next" ng-click="nextNum()">NEXT FIB</button>

My script file:

 var app = angular.module('fib', []);

 app.controller('nextFibCtrl', function($scope,){

 $scope.results = [0, 1];

 $scope.nextNum = function(){

     $scope.currentInt = $scope.results.length -1;

     $scope.nextInt = $scope.results[$scope.currentInt] +

     $scope.results[$scope.currentInt -1];

     $scope.results.push($scope.nextInt);

  }

      $scope.clear = function(){

      $scope.results = [0, 1];

  }

  });

Body:
The issue in your code are quotes, so instead of this:

<h2 ng-repeat="result in results track by $index" | "limitTo: 1"> {{ result }}
</h2>

Do this:

<h2 ng-repeat="result in results track by $index" | limitTo:1> {{ result }}
</h2>

But, considering that you want to display only one value, and you already have that value bound to the scope, just change the code to this:

<h2> {{ $scope.nextInt }} </h2>

I hope it helps


问:
Dynamic timer in rxjs
I am creating a slider with images and videos and am want to assign a certain amount of screen time for each type.

```<code>let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{"path":"http://localhost:8091/public/testvideo.mp4","type":"video"}]
Observable.timer(0, 3000)
                            .map(e => {
                                console.log(e); return data[e % data.length];
                            })
                            .subscribe(item => {
                                this.activeItem = item;
                            });
</code>```

I am able to set a generic time for all the slides using the code above but am unable to do set separate values for each of the items in the array.

Here is what I actually want to achieve
1) Iterate through the array from 0 to the last index once it has completed iterating infinitely
2) To be able to set a time when the next iteration takes place based on the type property inside each object.

Right now only 1) is satisfiable.

答:
The trick would be to use concatMap. It will create from each item an immediate observable with the item followed by a delay of an empty Observable. After that delay the observable completes, and the next one will be concatenated. This will be repeated infinitely with the repeat() operator.</p>

```<code>let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{"path":"http://localhost:8091/public/testvideo.mp4","type":"video"}];

const delayByMediaType = {image: 1000, video: 5000};

Observable.from(data)
    .concatMap(media =>
        Observable.of(media).concat(Observable.empty().delay(delayByMediaType[media.type]))
    )
    .repeat()
    .do(console.log)
    .subscribe(item => this.activeItem = item);
</code>```

Title: Dynamic timer in rxjs

Body:
I am creating a slider with images and videos and am want to assign a certain amount of screen time for each type.

let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{"path":"http://localhost:8091/public/testvideo.mp4","type":"video"}]
Observable.timer(0, 3000)
                            .map(e => {
                                console.log(e); return data[e % data.length];
                            })
                            .subscribe(item => {
                                this.activeItem = item;
                            });

I am able to set a generic time for all the slides using the code above but am unable to do set separate values for each of the items in the array.

Here is what I actually want to achieve
1) Iterate through the array from 0 to the last index once it has completed iterating infinitely
2) To be able to set a time when the next iteration takes place based on the type property inside each object.

Right now only 1) is satisfiable.

Body:
The trick would be to use concatMap. It will create from each item an immediate observable with the item followed by a delay of an empty Observable. After that delay the observable completes, and the next one will be concatenated. This will be repeated infinitely with the repeat() operator.

let data =  [{"path":"http://localhost:8091/public/testimg.jpg","type":"image"},{"path":"http://localhost:8091/public/testvideo.mp4","type":"video"}];

const delayByMediaType = {image: 1000, video: 5000};

Observable.from(data)
    .concatMap(media =>
        Observable.of(media).concat(Observable.empty().delay(delayByMediaType[media.type]))
    )
    .repeat()
    .do(console.log)
    .subscribe(item => this.activeItem = item);


问:
Struggling to correctly implement a custom rails controller method
I am attempting to implement a controller method where one account sends a sum of money to another account. The code in accnts_controller is as follows:

```<code>def donate(amt, client)
    if creator?
      raise 'Only Patron accounts can donate'
    else
      @client = Accnt.find(client)
      @client.balance += amt
      @accnt.balance -= amt
      @client.save
      @accnt.save
    end
  end
</code>```

(note: In my controller, I have a before action which sets up the @accnt object)

To do this, I have written the following custom route:

```<code>patch 'accnts/:id/donate' => 'accnts#donate'
</code>```

I have been having a couple of problems in implementing this method, but far and away the largest is that I do not know how to write a cURL request which can pass values to the amt and client arguments. I almost exclusively use cURL to test the efficacy of my back end, as the program I am in did not teach us how to use rails views. How can I go about writing a curl request to test my method?

EDIT: my full controller code. This was generated with a scaffold and has been slightly modified

```<code>class AccntsController < OpenReadController
  before_action :set_accnt, only: %i[show update donate destroy]
  # GET /accnts
  def index
    @accnts = Accnt.all
    render json: @accnts
  end
  # GET /accnts/1
  def show
    render json: @accnt
  end
  # POST /accnts
  def create
    if current_user.accnt
      raise 'Already has an account'
    else
      @accnt = Accnt.new(accnt_params)
      @accnt.user = current_user
      if @accnt.save
        render json: @accnt, status: :created
      else
        render json: @accnt.errors, status: :unprocessable_entity
      end
      # render json: @accnt, status: :created, location: @accnt if @accnt.save
    end
  end
  # PATCH/PUT /accnts/1
  def update
    if @accnt.update(accnt_params)
      render json: @accnt
    else
      render json: @accnt.errors, status: :unprocessable_entity
    end
  end
  # amt is the amount to be sent from the patron to the client, client is the client ID
  def donate(amt, client)
    # furthermore, I cannot say for certain whether this method of passing parameters is viable in rails
    if creator?
      raise 'Only Patron accounts can donate'
    else
      # Very easily could be logical errors here
      @client = Accnt.find(client)
      @client.balance += amt
      @accnt.balance -= amt
      @client.save
      @accnt.save
    end
  end
  # DELETE /accnts/1
  def destroy
    @accnt.destroy
  end
  private
    # Use callbacks to share common setup or constraints between actions.
    # To be used as a before method to determine whether or not the account in
    # question is a creator account
    def creator?
      creator
    end
    def set_accnt
      @accnt = Accnt.find(params[:id])
    end
    # Only allow a trusted parameter "white list" through.
    def accnt_params
      params.require(:accnt).permit(:user_id, :user_name, :balance, :creator, :content_type, :content_list)
    end
end
</code>```

As for the Curl request, I haven't really written it out beyond this:

```<code>API="http://localhost:4741"
URL_PATH="/accnts"
curl "${API}${URL_PATH}/${ID}/donate" \
  --include \
  --request PATCH \
  --header "Content-Type: application/json" \
  --header "Authorization: Token token=$TOKEN" \
  --data
echo
</code>```

答:
The following is the working method code and curl request n my controller:

```<code>def donate
  if @accnt.creator
    raise 'Only Patron accounts can donate'
  else
    client = params[:client_id]
    amt = params[:amt]
    # Very easily could be logical errors here
    @client = Accnt.find(client)
    @client.balance += amt
    @accnt.balance -= amt
    @client.save
    @accnt.save
  end
end
</code>```

And my (hideously hardcoded) cURL request:

```<code>API="http://localhost:4741"
URL_PATH="/accnts"
ID="2"
TOKEN="BAhJIiU2ZDA2MGI4YzZkZjFkMmRkYTBkMWI3ZmRjMmRiMTZlYgY6BkVG--e55aee8e39c0cdd0bf944fa66661f06930037ba1"
curl "${API}${URL_PATH}/${ID}/donate" \
  --include \
  --request PATCH \
  --header "Content-Type: application/json" \
  --header "Authorization: Token token=$TOKEN" \
  --data '{
    "client_id": 1,
    "amt": 10.0
  }'
echo
</code>```

Body:
I am attempting to implement a controller method where one account sends a sum of money to another account. The code in accnts_controller is as follows:

def donate(amt, client)
    if creator?
      raise 'Only Patron accounts can donate'
    else
      @client = Accnt.find(client)
      @client.balance += amt
      @accnt.balance -= amt
      @client.save
      @accnt.save
    end
  end

(note: In my controller, I have a before action which sets up the @accnt object)

To do this, I have written the following custom route:

patch 'accnts/:id/donate' => 'accnts#donate'

I have been having a couple of problems in implementing this method, but far and away the largest is that I do not know how to write a cURL request which can pass values to the amt and client arguments. I almost exclusively use cURL to test the efficacy of my back end, as the program I am in did not teach us how to use rails views. How can I go about writing a curl request to test my method?

EDIT: my full controller code. This was generated with a scaffold and has been slightly modified

class AccntsController < OpenReadController
  before_action :set_accnt, only: %i[show update donate destroy]
  # GET /accnts
  def index
    @accnts = Accnt.all
    render json: @accnts
  end
  # GET /accnts/1
  def show
    render json: @accnt
  end
  # POST /accnts
  def create
    if current_user.accnt
      raise 'Already has an account'
    else
      @accnt = Accnt.new(accnt_params)
      @accnt.user = current_user
      if @accnt.save
        render json: @accnt, status: :created
      else
        render json: @accnt.errors, status: :unprocessable_entity
      end
      # render json: @accnt, status: :created, location: @accnt if @accnt.save
    end
  end
  # PATCH/PUT /accnts/1
  def update
    if @accnt.update(accnt_params)
      render json: @accnt
    else
      render json: @accnt.errors, status: :unprocessable_entity
    end
  end
  # amt is the amount to be sent from the patron to the client, client is the client ID
  def donate(amt, client)
    # furthermore, I cannot say for certain whether this method of passing parameters is viable in rails
    if creator?
      raise 'Only Patron accounts can donate'
    else
      # Very easily could be logical errors here
      @client = Accnt.find(client)
      @client.balance += amt
      @accnt.balance -= amt
      @client.save
      @accnt.save
    end
  end
  # DELETE /accnts/1
  def destroy
    @accnt.destroy
  end
  private
    # Use callbacks to share common setup or constraints between actions.
    # To be used as a before method to determine whether or not the account in
    # question is a creator account
    def creator?
      creator
    end
    def set_accnt
      @accnt = Accnt.find(params[:id])
    end
    # Only allow a trusted parameter "white list" through.
    def accnt_params
      params.require(:accnt).permit(:user_id, :user_name, :balance, :creator, :content_type, :content_list)
    end
end

As for the Curl request, I haven't really written it out beyond this:

API="http://localhost:4741"
URL_PATH="/accnts"
curl "${API}${URL_PATH}/${ID}/donate" \
  --include \
  --request PATCH \
  --header "Content-Type: application/json" \
  --header "Authorization: Token token=$TOKEN" \
  --data
echo

Body:
The following is the working method code and curl request n my controller:

def donate
  if @accnt.creator
    raise 'Only Patron accounts can donate'
  else
    client = params[:client_id]
    amt = params[:amt]
    # Very easily could be logical errors here
    @client = Accnt.find(client)
    @client.balance += amt
    @accnt.balance -= amt
    @client.save
    @accnt.save
  end
end

And my (hideously hardcoded) cURL request:

API="http://localhost:4741"
URL_PATH="/accnts"
ID="2"
TOKEN="BAhJIiU2ZDA2MGI4YzZkZjFkMmRkYTBkMWI3ZmRjMmRiMTZlYgY6BkVG--e55aee8e39c0cdd0bf944fa66661f06930037ba1"
curl "${API}${URL_PATH}/${ID}/donate" \
  --include \
  --request PATCH \
  --header "Content-Type: application/json" \
  --header "Authorization: Token token=$TOKEN" \
  --data '{
    "client_id": 1,
    "amt": 10.0
  }'
echo


问:
Return type annotation for calling an object's methods
How can I write a return type annotation for a function that takes an object, calls all of its methods, and returns a new object with the original keys mapped to the methods' return values?</p>

```<code>function callMethods<T>(obj: T) {
    const objResults = {};
    Object.keys(obj).forEach((prop) => objResults[prop] = obj[prop]({}));

    return objResults;
}

type MethodArgs = any // some complex object

console.log(callMethods({
    a: (_args: MethodArgs): number => 1,
    b: (_args: MethodArgs): string => "one",
    c: (_args: MethodArgs): number[] => [1]
}));
// => {a: 1, b: "one", c: [1]}
// This object's type should be {a: number, b: string, c: number[]}
</code>```

答:
Right now there is no way of properly retrieving the return type of a method call and as such my solution is only partial. However there is a proposal in the works and you can read more about it here.

The best you could is at least get some more typing out of the thing you have now.

One thing you can do is use mapped types in order to retrieve the keys from T and use them as keys in the return value.

function callMethods<T>(obj: T) {
    return Object.keys(obj).reduce((previous, current) => {
        previous[current] = obj[current]({});
        return previous;
    }, {} as {[P in keyof T]: any});
}
```

<p>Because the return type of the methods can't be determined the value type of properties of the returned object is going to be any. </p>

<p>If the return types are finite you could define them as a type and use them (it's not perfect but it might be better).</p>

<pre class="lang-js prettyprint-override"><code>type ReturnTypes = number | string | number[];

function callMethods<T>(obj: T) {
    return Object.keys(obj).reduce((previous, current) => {
        previous[current] = obj[current]({});
        return previous;
    }, {} as {[P in keyof T]: ReturnTypes});
}
</code>```

If both the return types and the type of the object being passed in is known you could pass those as external parameters too, so you make a more generic function.

type ReturnTypes = number | string | number[];
interface Methods {
    a: (args: any) => number,
    b: (args: any) => string,
    c: (args: any) => number[],

}

function callMethods<T, V>(obj: T) {
    return Object.keys(obj).reduce((previous, current) => {
        previous[current] = obj[current]({});
        return previous;
    }, {} as {[P in keyof T]: V});
}

let result = callMethods<Methods, ReturnTypes>({
    a: (_args): number => 1,
    b: (_args): string => "one",
    c: (_args): number[] => [1]
});
```

While this isn't the perfect solution I hope it helps you.

Note: please forgive the rewrite of the method, it seemed cleaner to use reduce.

Body:
How can I write a return type annotation for a function that takes an object, calls all of its methods, and returns a new object with the original keys mapped to the methods' return values?

function callMethods<T>(obj: T) {
    const objResults = {};
    Object.keys(obj).forEach((prop) => objResults[prop] = obj[prop]({}));

    return objResults;
}

type MethodArgs = any // some complex object

console.log(callMethods({
    a: (_args: MethodArgs): number => 1,
    b: (_args: MethodArgs): string => "one",
    c: (_args: MethodArgs): number[] => [1]
}));
// => {a: 1, b: "one", c: [1]}
// This object's type should be {a: number, b: string, c: number[]}

Body:
Right now there is no way of properly retrieving the return type of a method call and as such my solution is only partial. However there is a proposal in the works and you can read more about it here.

The best you could is at least get some more typing out of the thing you have now.

One thing you can do is use mapped types in order to retrieve the keys from T and use them as keys in the return value.

function callMethods<T>(obj: T) {
    return Object.keys(obj).reduce((previous, current) => {
        previous[current] = obj[current]({});
        return previous;
    }, {} as {[P in keyof T]: any});
}

Because the return type of the methods can't be determined the value type of properties of the returned object is going to be any.

If the return types are finite you could define them as a type and use them (it's not perfect but it might be better).

type ReturnTypes = number | string | number[];

function callMethods<T>(obj: T) {
    return Object.keys(obj).reduce((previous, current) => {
        previous[current] = obj[current]({});
        return previous;
    }, {} as {[P in keyof T]: ReturnTypes});
}

If both the return types and the type of the object being passed in is known you could pass those as external parameters too, so you make a more generic function.

type ReturnTypes = number | string | number[];
interface Methods {
    a: (args: any) => number,
    b: (args: any) => string,
    c: (args: any) => number[],

}

function callMethods<T, V>(obj: T) {
    return Object.keys(obj).reduce((previous, current) => {
        previous[current] = obj[current]({});
        return previous;
    }, {} as {[P in keyof T]: V});
}

let result = callMethods<Methods, ReturnTypes>({
    a: (_args): number => 1,
    b: (_args): string => "one",
    c: (_args): number[] => [1]
});

While this isn't the perfect solution I hope it helps you.

Note: please forgive the rewrite of the method, it seemed cleaner to use reduce.


问:
Why variables start out with random values in C
I think this is wrong, it should start as NULL and not with a random value. In the case that you have a pointer with a random memory address as its default value it could be a very dangerous thing, no?</p>

答:
It was a design choice made many ears ago, probably for efficiency reasons.

Statically allocated variables (globals and statics) are initialized to 0 if there's no explicit initialization - this could be justified even taking efficiency into account becuase it only occurs once. I'd guess the thinking was that for automatic variables (locals) that are allocated each time a scope is entered, implicit initialization was considered something that might cost too much and therefore should be left to the programmer's responsibility.

If C were being designed today, I wouldn't be surprised if that design decision were changed - especially since compilers are intelligent enough today to be able to optimize away an initialization that gets overwritten before any other use (or potential use).

However, there are so many C compiler toolchains that follow the spec of not initializing automatically, it would be foolish for a compiler to perform implicit initialization to a 'useful' value (like 0 or NULL).  That would just encourage people targeting that tool chain to write code that didn't work correctly on other tool chains.

However, compilers can initialize local variables, and they often do. It's just that they initialize the locals to a values that's not generally useful (especially, that doesn't set a pointer to the null pointer). That kind of initialization isn't useful in writing your programming logic against, and it's not intended for that.  It's intended to cause deterministic and reproducible errors so that if you erroneously use values that have been set by implicit initialization, you'll be able to find it easily in test/debug.

Usually this compiler behavior is turned on only for debug builds; I could see an argument being made for turning it on in release builds as well - particular if the release build can still optimize it away when the compiler can prove that the implicit initialized value is never used.

ContentLicense: CC BY-SA 2.5


问:
Unable To connect two clients to same session in Tokbox
I am trying to add a video streaming service using tokbox.

But the users are not able to connect to each other. I followed the tutorial provided by them. Here are my codes. For testing purpose I am saving the session id on a file currently.

Client One:

```<code>$opentok    =   new OpenTok($apiKey, $apiSecret);
$session    =   $opentok->createSession();
$sessionId  =   $session->getSessionId();
$token      =   $opentok->generateToken($sessionId);

$file = fopen("session.txt","w+");
fwrite($file, $sessionId);
fclose($file);
?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>OpenTok</title>
</head>
<body>

    <h2>Hello, World!</h2>
    <div id="publisher"></div>
    <div id="subscribers"></div>

</body>
</html>

<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
<script>

    var apiKey = '<?php echo $apiKey; ?>';
    var sessionId = '<?php echo $sessionId; ?>';
    var token = '<?php echo $token; ?>';

    // Initialize an OpenTok Session object.
    var session = OT.initSession(sessionId);

    // Initialize a Publisher, and place it into the 'publisher' DOM element.
    var publisher = OT.initPublisher(apiKey, 'publisher');

    session.on('streamCreated', function(event) {
      // Called when another client publishes a stream.
      // Subscribe to the stream that caused this event.
      session.subscribe(event.stream, 'subscribers', { insertMode: 'append' });
    });

    // Connect to the session using your OpenTok API key and the client's token for the session
    session.connect(apiKey, token, function(error) {
      if (error) {
        console.error(error);
      } else {
        // Publish a stream, using the Publisher we initialzed earlier.
        // This triggers a streamCreated event on other clients.
        session.publish(publisher);
      }
    });

</script>
</code>```

client 2:

```<code>$opentok    =   new OpenTok($apiKey, $apiSecret);
    $myfile     =   fopen("session.txt", "r") or die("Unable to open file!");

    $sessionId  =   fgets($myfile);
    fclose($myfile);

    $token      =   $opentok->generateToken($sessionId);

?>

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <title>OpenTok Test</title>
</head>
<body>

    <h2>Hello, World!</h2>
    <div id="publisher"></div>
    <div id="subscribers"></div>

</body>
</html>

<script src="https://static.opentok.com/v2/js/opentok.min.js"></script>
<script>

    var apiKey = '<?php echo $apiKey; ?>';
    var sessionId = '<?php echo $sessionId; ?>';
    var token = '<?php echo $token; ?>';

    // Initialize an OpenTok Session object.
    var session = OT.initSession(sessionId);

    // Initialize a Publisher, and place it into the 'publisher' DOM element.
    var publisher = OT.initPublisher(apiKey, 'publisher');

    session.on('streamCreated', function(event) {
      // Called when another client publishes a stream.
      // Subscribe to the stream that caused this event.
      session.subscribe(event.stream, 'subscribers', { insertMode: 'append' });
    });

    // Connect to the session using your OpenTok API key and the client's token for the session
    session.connect(apiKey, token, function(error) {
      if (error) {
        console.error(error);
      } else {
        // Publish a stream, using the Publisher we initialzed earlier.
        // This triggers a streamCreated event on other clients.
        session.publish(publisher);
      }
    });

</script>
</code>```

I checked using chorme-dev-tools and found that the session id is same for both the user. But only the publisher screen is displayed on each user.

What am I doing Wrong? And how Should I correct it?

答:
It looks like you got this from the OpenTok PHP SDK sample page. Unfortunately this is using the old syntax so I'll update it ASAP, sorry about that.

The old syntax should still probably work but just in case you should change your initSession function to:

```<code>var session = OT.initSession(apiKey, sessionId);
</code>```

Your initPublisher function should be:

```<code>OT.initPublisher('publisher');
</code>```

And your session.connect function should be:

```<code>session.connect(token, function(error) {
</code>```

You can find references to the up-to-date syntax in the OpenTok JS SDK Reference.

Also, you should really listen for errors when subscribing and publishing.

To do that you need to add a callback to your session.subscribe function:

```<code>session.subscribe(event.stream, 'subscribers', {
  insertMode: 'append'
}, function(error) {
  if (error) {
    console.error('Failed to subscribe', error);
  }
});
</code>```

And also to your session.publish function:

```<code>session.publish(publisher, function(error) {
  if (error) {
    console.error('Failed to publish', error);
  }
});
</code>```

You can also use the OT.setLogLevel function to display extra logs to help debug the problem. Place this before your initSession call:

```<code>OT.setLogLevel(OT.DEBUG);
</code>```

There are a lot of logs there but it should give you a better idea of what's going on. Remember you should not set the log level to DEBUG in production.

Body:
I am trying to add a video streaming service using tokbox.

But the users are not able to connect to each other. I followed the tutorial provided by them. Here are my codes. For testing purpose I am saving the session id on a file currently.

Client One:

$opentok    =   new OpenTok($apiKey, $apiSecret);
$session    =   $opentok->createSession();
$sessionId  =   $session->getSessionId();
$token      =   $opentok->generateToken($sessionId);

$file = fopen("session.txt","w+");
fwrite($file, $sessionId);
fclose($file);
?>

<!doctype html>

    <meta charset="utf-8" />
    <title>OpenTok</title>

Hello, World!

client 2:

$opentok    =   new OpenTok($apiKey, $apiSecret);
    $myfile     =   fopen("session.txt", "r") or die("Unable to open file!");

    $sessionId  =   fgets($myfile);
    fclose($myfile);

    $token      =   $opentok->generateToken($sessionId);

?>

<!doctype html>

    <meta charset="utf-8" />
    <title>OpenTok Test</title>

Hello, World!

I checked using chorme-dev-tools and found that the session id is same for both the user. But only the publisher screen is displayed on each user.

What am I doing Wrong? And how Should I correct it?

Body:
It looks like you got this from the OpenTok PHP SDK sample page. Unfortunately this is using the old syntax so I'll update it ASAP, sorry about that.

The old syntax should still probably work but just in case you should change your initSession function to:

var session = OT.initSession(apiKey, sessionId);

Your initPublisher function should be:

OT.initPublisher('publisher');

And your session.connect function should be:

session.connect(token, function(error) {

You can find references to the up-to-date syntax in the OpenTok JS SDK Reference.

Also, you should really listen for errors when subscribing and publishing.

To do that you need to add a callback to your session.subscribe function:

session.subscribe(event.stream, 'subscribers', {
  insertMode: 'append'
}, function(error) {
  if (error) {
    console.error('Failed to subscribe', error);
  }
});

And also to your session.publish function:

session.publish(publisher, function(error) {
  if (error) {
    console.error('Failed to publish', error);
  }
});

You can also use the OT.setLogLevel function to display extra logs to help debug the problem. Place this before your initSession call:

OT.setLogLevel(OT.DEBUG);

There are a lot of logs there but it should give you a better idea of what's going on. Remember you should not set the log level to DEBUG in production.


问:
C# Discord Bot: How can I check if a user has said a specific phrase?
So I'm trying to create a bot that responds to a certain line of text in my discord server. I want to check if my friend says "no u" (he says that a lot, he has the mentality of a five year old) and I want my bot to respond to this statement. I'm still relatively new to C# and have looked desperately everywhere for this answer. If you can help, that would be greatly appreciated!  </p>

答:
This should do the job :</p>

```<code>using System;
using Discord;

class Program
{
    static public DiscordClient client;

    static void Main(string[] args)
    {
        client = new DiscordClient(input =>
        {
            input.LogLevel = LogSeverity.Info;
        });
        client.MessageReceived += Client_MessageReceived;
        client.ExecuteAndWait(async () =>
        {
            await client.Connect("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", TokenType.Bot);
        });
    }

    static async private void Client_MessageReceived(object sender, MessageEventArgs e)
    {
        if (e.Message.Text == "no u")
            await e.Channel.SendMessage("You have the mentality of a five year old");
    }
}
</code>```

Body:
This should do the job :

using System;
using Discord;

class Program
{
    static public DiscordClient client;

    static void Main(string[] args)
    {
        client = new DiscordClient(input =>
        {
            input.LogLevel = LogSeverity.Info;
        });
        client.MessageReceived += Client_MessageReceived;
        client.ExecuteAndWait(async () =>
        {
            await client.Connect("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", TokenType.Bot);
        });
    }

    static async private void Client_MessageReceived(object sender, MessageEventArgs e)
    {
        if (e.Message.Text == "no u")
            await e.Channel.SendMessage("You have the mentality of a five year old");
    }
}


问:
d3-geomap Cannot read property 'type' of undefined
I'm trying to use d3-geomap to visualize regions that have been recently established to administer the delivery of children's mental health services in Ontario, Canada. I've converted a publicly available shapefile of the these administrative regions to a topojson format file and I've aligned estimates of numbers of 0 - 18 years olds across these regions for 2014 - 2041.
My webpage at
http://cartoserve.com/maps/ontario/cymhsas_population/cymhsas_pop_2014.html is meant to display the estimated population for 2014, but throws the following error: "topojson.js:59 Uncaught TypeError: Cannot read property 'type' of undefined". I hate to admit how much time I've spent figuring out this problem! Any help is much appreciated.</p>

答:
Make sure you are loading components in following order

d3.geomap.dependencies.min.js

d3.geomap.min.js


问:
Cannot get javascript innerHtml to work on WebView
I am using a WebView with a javaScript interface.  All I want to do is change the inner html of a span if some checkboxes are ticked.

Below is a snippet of a String I have in strings.xml.  The form will call this function onSubmit and should not continue if it does not pass.  The problem is that I can't get the innerHtml working (is returns true everytime).

This works

```<code><script type=\"text/javascript\" language=\"javascript\">
    function pass() {
        return javaInterface.checkboxPass();
        /*
        if(passed) {
            //change the instructions
            document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
        }

        return passed;
        */
    }
</script>
</code>```

This returns true everytime

```<code><script type=\"text/javascript\" language=\"javascript\">
    function pass() {
        var passed= javaInterface.checkboxPass();

        if(passed) {
            //change the instructions
            document.getElementById(\"txtInstructions\").innerHTML = \'Loading Website...\';
        }

        return passed;

    }
</script>
</code>```

This is the span in the body of the document

```<code><span id=\"txtInstructions\">%1$s</span>
</code>```

What am I doing wrong?

答: I can't tell why the code doesn't behave like you want it to, but I can tell that you are trying to do this in a way too complicated fashion. Storing your JavaScript and HTML in an XML file seems like a genuine bad idea. I guess it is legal JavaScript, but naming a variable the same as it's parent function just seems wrong, in general you shouldn't use such scope subtleties, it's good for nothing but obfuscation.</p>

Body:
I am using a WebView with a javaScript interface.  All I want to do is change the inner html of a span if some checkboxes are ticked.

Below is a snippet of a String I have in strings.xml.  The form will call this function onSubmit and should not continue if it does not pass.  The problem is that I can't get the innerHtml working (is returns true everytime).

This works

This returns true everytime

This is the span in the body of the document

%1$s

What am I doing wrong?


问:
Find a character in a list of words
I am trying to find a specific character in a list of words and then print all the words that match. for example, I have a list of 6 words. I would like to find a way to select all the words with a ('.') (fullstop) in them and transfer them to another list.

Example:

```<code>List ['alpha', 'bravo', 'charlie.', 'delta', 'echo']
</code>```

I would like it to find Charlie and its position in the list

I mostly just need the if statement for it
Thanks in advance!

This is what I have so far

```<code>sent = str(input('enter sentance '))
words = sent.split()
print (words)
</code>```

答:
The usual way to know if a character is in a string in python is "in"

```<code>'.' in "charlie."
</code>```

that will return True.

To know the position of an element in a list you can iterate using enumerate(list) and will return a pair of (index,value).

To get a list of the index and the strings who have '.' character you can do something like this:

```<code>[(pos, word) for pos, word in enumerate(list) if '.' in word]
</code>```

Title: Find a character in a list of words

Body:
I am trying to find a specific character in a list of words and then print all the words that match. for example, I have a list of 6 words. I would like to find a way to select all the words with a ('.') (fullstop) in them and transfer them to another list.

Example:

List ['alpha', 'bravo', 'charlie.', 'delta', 'echo']

I would like it to find Charlie and its position in the list

I mostly just need the if statement for it
Thanks in advance!

This is what I have so far

sent = str(input('enter sentance '))
words = sent.split()
print (words)

Body:
The usual way to know if a character is in a string in python is "in"

'.' in "charlie."

that will return True.

To know the position of an element in a list you can iterate using enumerate(list) and will return a pair of (index,value).

To get a list of the index and the strings who have '.' character you can do something like this:

[(pos, word) for pos, word in enumerate(list) if '.' in word]


问:
Ksh, better way to ssh and run multiple commands
What is nice way to ssh and run multiple commands in korn shell ? I came across related question  and top answer works for me but I specify /bin/bash/ in this and running it over korn shell.

Is it ok to run below list of commands (copied from answer of referenced question) or there can be better way for ksh ?

```<code>ssh otherhost /bin/bash << EOF
  ls some_folder;
  ./someaction.sh 'some params'
  pwd
  ./some_other_action 'other params'
EOF
</code>```

答:
Yes, that works. But if later commands can do bad things if prior commands failed you had better stop the chain if prior commands fail.

One simple way is to chain the commands together with &&

```  A && B && { C || true $? } && D```

Or,

```  A &&
  B &&
  { C || true $? } &&
  D```

The trick on C allows that command to fail but keep the chain going... grep often needs this to continue if nothing matches.  The argument of $? on true does nothing, unless running under set -x, then it will trace the error condition of C.

Body:
What is nice way to ssh and run multiple commands in korn shell ? I came across related question  and top answer works for me but I specify /bin/bash/ in this and running it over korn shell.

Is it ok to run below list of commands (copied from answer of referenced question) or there can be better way for ksh ?

ssh otherhost /bin/bash << EOF
  ls some_folder;
  ./someaction.sh 'some params'
  pwd
  ./some_other_action 'other params'
EOF

Body:
Yes, that works. But if later commands can do bad things if prior commands failed you had better stop the chain if prior commands fail.

One simple way is to chain the commands together with &&

  A && B && { C || true $? } && D

Or,

  A &&
  B &&
  { C || true $? } &&
  D

The trick on C allows that command to fail but keep the chain going... grep often needs this to continue if nothing matches.  The argument of $? on true does nothing, unless running under set -x, then it will trace the error condition of C.


问:
How to use partial templates with map in StringTemplate?
I've got a map of city names => distance-from-origin.

I'd like to use a partial with this map, and create something like so:

```<code><ul>
<li>city1: distance1</li>
<li>city2: distance2</li>
<li>city3: distance3</li>
</ul>
</code>```

What is the canonical way to do this with StringTemplate?

Thanks.

Body:
I've got a map of city names => distance-from-origin.

I'd like to use a partial with this map, and create something like so:

city1: distance1

city2: distance2

city3: distance3

What is the canonical way to do this with StringTemplate?

Thanks.

Body:
<ul>
$amap.keys:{k | <li>$k$: $amap.(k)$</li>}$
</ul>


问:
Virtualenv with only Python3
I have two different Ubuntu VMs first 14.04 second 16.04. On the first one when I create virtualenv with pyhton3 for some reason python27 is also gets installed

```<code>user@ubuntu:~/venv$ virtualenv  --python=python3 --no-site-packages py3-venv
Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /home/user/venv/py3-venv/bin/python3
Also creating executable in /home/user/venv/py3-venv/bin/python
Installing setuptools, pip, wheel...done.
user@ubuntu:~/venv$ source py3-venv/bin/activate
(py3-venv) user@ubuntu:~/venv$ python -V
Python 2.7.12
</code>```

Same thing done on the second VM works as intended

```<code>user@my-box:~/venv$ virtualenv -p /usr/bin/python3 py3-venv
Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /home/user/venv/py3-venv/bin/python3
Also creating executable in /home/user/venv/py3-venv/bin/python
Installing setuptools, pip, wheel...done.
user@my-box:~/venv$ source py3-venv/bin/activate
(py3-venv) user@my-box:~/venv$ which python
/home/user/venv/py3-venv/bin/python
(py3-venv) user@my-box:~/venv$ python -V
Python 3.5.2
</code>```

I need the virtualenv to run python3 even though I type python command. Any ideas how to do it?

[UPDATE]

This is the strangest thing I have ever seen

```<code>(py3-venv) user@ubuntu:~/venv$ which python
/home/user/venv/py3-venv/bin/python
(py3-venv) user@ubuntu:~/venv$ python -V
Python 2.7.12
(py3-venv) user@ubuntu:~/venv$ ./py3-venv/bin/python -V
Python 3.4.3
</code>```

[UPDATE 2]

I am completely lost... Even strace python command points to the correct file

```<code>(py3-venv) user@ubuntu:~/venv$ strace python
execve("/home/user/venv/py3-venv/bin/python", ["python"], [/* 24 vars */]) = 0
brk(0)                                  = 0x204f000
</code>```

[UPDATE 3]

If I remove everything other than /home/user/venv/py3-venv/bin from the PATH python command fails to execute... Please help!!

```<code>(py3-venv) user@ubuntu:~$ export PATH=/home/user/venv/py3-venv/bin
(py3-venv) user@ubuntu:~$ echo $PATH
/home/user/venv/py3-venv/bin
(py3-venv) user@ubuntu:~$ python -V
Command 'python2.7' is available in the following places
 * /usr/bin/python2.7
 * /usr/local/bin/python2.7
The command could not be located because '/usr/bin:/usr/local/bin' is not included in the PATH environment variable.
python2.7: command not found
</code>```

答:
I agree with the point about the virtual env.  You can do some other things:

Firstly I remove the python alias (from the other answer) in .bashrc

Then I create a Python 3 virtual environment:

```<code>$ mkdir venv
[vagrant@localhost ~]$ cd venv
[vagrant@localhost venv]$ virtualenv -p python3 python3_virtualenv
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local'
New python executable in /home/vagrant/venv/python3_virtualenv /bin/python3
Also creating executable in /home/vagrant/venv/python3_virtualenv/bin/python
Installing setuptools, pip, wheel...done.
[vagrant@localhost venv]$ source ~/venv/python3_virtualenv/bin/activate
(python3_virtualenv) [vagrant@localhost venv]$
</code>```

Python 3 has been successfully installed as a virtualenv.

You can add the following line to your .bash_profile:

source ~/venv/python3_virtualenv/bin/activate

I will now log out, and then log in again:

```<code>$ vagrant ssh
Last login: Sat Jun  3 00:01:21 2017 from 10.0.2.2
(python3_virtualenv) [vagrant@localhost ~]$ python
Python 3.5.0 (default, Jun  2 2017, 18:10:55)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
</code>```

The source ~/venv/python3_virtualenv/bin/activate command has been run automatically, and when I type python, Python 3.5.0 is found.

The second option is to create a python symbolic link to python 3:

The second option is to add a python symbolic link in /usr/local/bin.  This will overide the python (in the /usr/bin directory).

I installed Python 3 manually in the /usr/local/bin directory.

Python 2 is in /usr/bin directory:

```<code>$ vagrant ssh
Last login: Sat Jun  3 00:39:12 2017 from 10.0.2.2

[vagrant@localhost ~]$ which python3
/usr/local/bin/python3

[vagrant@localhost ~]$ which python2
/usr/bin/python2
[vagrant@localhost ~]$ cd /usr/local/bin/
</code>```

I create my symbolic link:

```<code>[vagrant@localhost bin]$ sudo ln -s python3 ./python
</code>```

I log out:

```<code>[vagrant@localhost bin]$ exit
logout
Connection to 127.0.0.1 closed.
</code>```

I log in again:

```<code>rhubarb:scratch milesd$ vagrant ssh
Last login: Sat Jun  3 00:41:11 2017 from 10.0.2.2
</code>```

The python in /usr/local/bin is now "picked up in the path first":

```<code>[vagrant@localhost ~]$ python
Python 3.5.0 (default, Jun  2 2017, 18:10:55)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
[vagrant@localhost ~]$
</code>```

Title: Virtualenv with only Python3

Body:
I have two different Ubuntu VMs first 14.04 second 16.04. On the first one when I create virtualenv with pyhton3 for some reason python27 is also gets installed

user@ubuntu:~/venv$ virtualenv  --python=python3 --no-site-packages py3-venv
Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /home/user/venv/py3-venv/bin/python3
Also creating executable in /home/user/venv/py3-venv/bin/python
Installing setuptools, pip, wheel...done.
user@ubuntu:~/venv$ source py3-venv/bin/activate
(py3-venv) user@ubuntu:~/venv$ python -V
Python 2.7.12

Same thing done on the second VM works as intended

user@my-box:~/venv$ virtualenv -p /usr/bin/python3 py3-venv
Already using interpreter /usr/bin/python3
Using base prefix '/usr'
New python executable in /home/user/venv/py3-venv/bin/python3
Also creating executable in /home/user/venv/py3-venv/bin/python
Installing setuptools, pip, wheel...done.
user@my-box:~/venv$ source py3-venv/bin/activate
(py3-venv) user@my-box:~/venv$ which python
/home/user/venv/py3-venv/bin/python
(py3-venv) user@my-box:~/venv$ python -V
Python 3.5.2

I need the virtualenv to run python3 even though I type python command. Any ideas how to do it?

[UPDATE]

This is the strangest thing I have ever seen

(py3-venv) user@ubuntu:~/venv$ which python
/home/user/venv/py3-venv/bin/python
(py3-venv) user@ubuntu:~/venv$ python -V
Python 2.7.12
(py3-venv) user@ubuntu:~/venv$ ./py3-venv/bin/python -V
Python 3.4.3

[UPDATE 2]

I am completely lost... Even strace python command points to the correct file

(py3-venv) user@ubuntu:~/venv$ strace python
execve("/home/user/venv/py3-venv/bin/python", ["python"], [/* 24 vars */]) = 0
brk(0)                                  = 0x204f000

[UPDATE 3]

If I remove everything other than /home/user/venv/py3-venv/bin from the PATH python command fails to execute... Please help!!

(py3-venv) user@ubuntu:~$ export PATH=/home/user/venv/py3-venv/bin
(py3-venv) user@ubuntu:~$ echo $PATH
/home/user/venv/py3-venv/bin
(py3-venv) user@ubuntu:~$ python -V
Command 'python2.7' is available in the following places
 * /usr/bin/python2.7
 * /usr/local/bin/python2.7
The command could not be located because '/usr/bin:/usr/local/bin' is not included in the PATH environment variable.
python2.7: command not found

Body:
I agree with the point about the virtual env.  You can do some other things:

Firstly I remove the python alias (from the other answer) in .bashrc

Then I create a Python 3 virtual environment:

$ mkdir venv
[vagrant@localhost ~]$ cd venv
[vagrant@localhost venv]$ virtualenv -p python3 python3_virtualenv
Running virtualenv with interpreter /usr/local/bin/python3
Using base prefix '/usr/local'
New python executable in /home/vagrant/venv/python3_virtualenv /bin/python3
Also creating executable in /home/vagrant/venv/python3_virtualenv/bin/python
Installing setuptools, pip, wheel...done.
[vagrant@localhost venv]$ source ~/venv/python3_virtualenv/bin/activate
(python3_virtualenv) [vagrant@localhost venv]$

Python 3 has been successfully installed as a virtualenv.

You can add the following line to your .bash_profile:

source ~/venv/python3_virtualenv/bin/activate

I will now log out, and then log in again:

$ vagrant ssh
Last login: Sat Jun  3 00:01:21 2017 from 10.0.2.2
(python3_virtualenv) [vagrant@localhost ~]$ python
Python 3.5.0 (default, Jun  2 2017, 18:10:55)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>

The source ~/venv/python3_virtualenv/bin/activate command has been run automatically, and when I type python, Python 3.5.0 is found.

The second option is to create a python symbolic link to python 3:

The second option is to add a python symbolic link in /usr/local/bin.  This will overide the python (in the /usr/bin directory).

I installed Python 3 manually in the /usr/local/bin directory.

Python 2 is in /usr/bin directory:

$ vagrant ssh
Last login: Sat Jun  3 00:39:12 2017 from 10.0.2.2

[vagrant@localhost ~]$ which python3
/usr/local/bin/python3

[vagrant@localhost ~]$ which python2
/usr/bin/python2
[vagrant@localhost ~]$ cd /usr/local/bin/

I create my symbolic link:

[vagrant@localhost bin]$ sudo ln -s python3 ./python

I log out:

[vagrant@localhost bin]$ exit
logout
Connection to 127.0.0.1 closed.

I log in again:

rhubarb:scratch milesd$ vagrant ssh
Last login: Sat Jun  3 00:41:11 2017 from 10.0.2.2

The python in /usr/local/bin is now "picked up in the path first":

[vagrant@localhost ~]$ python
Python 3.5.0 (default, Jun  2 2017, 18:10:55)
[GCC 4.8.5 20150623 (Red Hat 4.8.5-11)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
[vagrant@localhost ~]$


问:
Parsing JSON into a object
I'm trying to parse this JSON using gson:

```<code>{"hvs1":{"16191":[["TestFile3","C",["A"]],["TestFile3","-",["1G","1A"]]],"16193":[["TestFile3","C",["G"]]]},"hvs2":{"25":[["TestFile3","-",["1A"]]]},"outros":{"16423":[["TestFile3","A",["T"]]]}}
</code>```

Into this object

```<code>public class Results {

private String regiaoAfetada;
private String posicaoReferencia;
private String nomeDoArquivo;
private String baseAlteradaReferencia;
private List<String> mutacaoEncontrada;

//get and set

}
</code>```

And my test class to try to achive this, but I'm getting a error.

```<code>public class JsonTeste {

  public static void main(String[] args) {

        Gson gson = new Gson();

        try (Reader reader = new FileReader("foobar.json")) {

        Type type = new TypeToken<TreeMap<String, TreeMap>>() {
        }.getType();

        TreeMap<String, TreeMap<String, List<List<List<String>>>>> map = gson.fromJson(reader, type);

        List<Results> listaMutacoes = new ArrayList<Results>();

        for (Entry<String, TreeMap<String, List<List<List<String>>>>> regioesMap : map.entrySet()) {

            TreeMap<String, List<List<List<String>>>> regiaoUm = regioesMap.getValue();

            for (Entry<String, List<List<List<String>>>> regiaoUmResult : regiaoUm.entrySet()) {

                List<List<List<String>>> resultados = regiaoUmResult.getValue();

                for (List<List<String>> list : resultados) {

                    Results resultado = new Results();
                    resultado.setRegiaoAfetada(regioesMap.getKey());
                    resultado.setPosicaoReferencia(regiaoUmResult.getKey());
                    resultado.setNomeDoArquivo(list.get(0).toString());
                    resultado.setBaseAlteradaReferencia(list.get(1).toString());
                    resultado.setMutacaoEncontrada(list.get(2));
                    listaMutacoes.add(resultado);
                }
            }
        }

        } catch (IOException e) {
        e.printStackTrace();
    }

}
}
</code>```

The problem is when I try to parse this part

```<code> [
         "TestFile3",
         "-",
         [
           "1G",
           "1A"
         ]
       ]
</code>```

Because I have two Strings and a Array inside, so the problem Is when I try to place "TestFile3" into setNomeDoArquivo, but even if I comment this line, i get the same error in the second line.

resultado.setNomeDoArquivo(list.get(0).toString());
                        resultado.setBaseAlteradaReferencia(list.get(1).toString());

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List

Can you guys help me?

答:
The List resultados is of List<string> or List<List<String>>.When you get the item of resultados it can be one of them. So to generalized declare it as List<List<Object>>

Try The below Code :

```<code>Gson gson = new Gson();
try (Reader reader = new FileReader("foobar.json")) {
    Type type = new TypeToken<TreeMap<String, TreeMap>>() {
    }.getType();

    TreeMap<String, TreeMap<String, List<List<Object>>>> map = gson.fromJson(reader, type);

    List<Results> listaMutacoes = new ArrayList<>();

    for (Map.Entry<String, TreeMap<String, List<List<Object>>>> regioesMap : map.entrySet()) {

        TreeMap<String, List<List<Object>>> regiaoUm = regioesMap.getValue();

        for (Map.Entry<String, List<List<Object>>> regiaoUmResult : regiaoUm.entrySet()) {

            List<List<Object>> resultados = regiaoUmResult.getValue();

            for (List<Object> list : resultados) {

                System.out.println(list);

                Results resultado = new Results();
                resultado.setRegiaoAfetada(regioesMap.getKey());
                resultado.setPosicaoReferencia(regiaoUmResult.getKey());
                resultado.setNomeDoArquivo((String) list.get(0));
                resultado.setBaseAlteradaReferencia((String) list.get(1));
                resultado.setMutacaoEncontrada((List<String>) list.get(2));
                listaMutacoes.add(resultado);
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}
</code>```

Title: Parsing JSON into a object

Body:
I'm trying to parse this JSON using gson:

{"hvs1":{"16191":[["TestFile3","C",["A"]],["TestFile3","-",["1G","1A"]]],"16193":[["TestFile3","C",["G"]]]},"hvs2":{"25":[["TestFile3","-",["1A"]]]},"outros":{"16423":[["TestFile3","A",["T"]]]}}

Into this object

public class Results {

private String regiaoAfetada;
private String posicaoReferencia;
private String nomeDoArquivo;
private String baseAlteradaReferencia;
private List<String> mutacaoEncontrada;

//get and set

}

And my test class to try to achive this, but I'm getting a error.

public class JsonTeste {

  public static void main(String[] args) {

        Gson gson = new Gson();

        try (Reader reader = new FileReader("foobar.json")) {

        Type type = new TypeToken<TreeMap<String, TreeMap>>() {
        }.getType();

        TreeMap<String, TreeMap<String, List<List<List<String>>>>> map = gson.fromJson(reader, type);

        List<Results> listaMutacoes = new ArrayList<Results>();

        for (Entry<String, TreeMap<String, List<List<List<String>>>>> regioesMap : map.entrySet()) {

            TreeMap<String, List<List<List<String>>>> regiaoUm = regioesMap.getValue();

            for (Entry<String, List<List<List<String>>>> regiaoUmResult : regiaoUm.entrySet()) {

                List<List<List<String>>> resultados = regiaoUmResult.getValue();

                for (List<List<String>> list : resultados) {

                    Results resultado = new Results();
                    resultado.setRegiaoAfetada(regioesMap.getKey());
                    resultado.setPosicaoReferencia(regiaoUmResult.getKey());
                    resultado.setNomeDoArquivo(list.get(0).toString());
                    resultado.setBaseAlteradaReferencia(list.get(1).toString());
                    resultado.setMutacaoEncontrada(list.get(2));
                    listaMutacoes.add(resultado);
                }
            }
        }

        } catch (IOException e) {
        e.printStackTrace();
    }

}
}

The problem is when I try to parse this part

 [
         "TestFile3",
         "-",
         [
           "1G",
           "1A"
         ]
       ]

Because I have two Strings and a Array inside, so the problem Is when I try to place "TestFile3" into setNomeDoArquivo, but even if I comment this line, i get the same error in the second line.

resultado.setNomeDoArquivo(list.get(0).toString());
                        resultado.setBaseAlteradaReferencia(list.get(1).toString());

java.lang.ClassCastException: java.lang.String cannot be cast to java.util.List

Can you guys help me?

Body:
The List resultados is of List<string> or List<List<String>>.When you get the item of resultados it can be one of them. So to generalized declare it as List<List<Object>>

Try The below Code :

Gson gson = new Gson();
try (Reader reader = new FileReader("foobar.json")) {
    Type type = new TypeToken<TreeMap<String, TreeMap>>() {
    }.getType();

    TreeMap<String, TreeMap<String, List<List<Object>>>> map = gson.fromJson(reader, type);

    List<Results> listaMutacoes = new ArrayList<>();

    for (Map.Entry<String, TreeMap<String, List<List<Object>>>> regioesMap : map.entrySet()) {

        TreeMap<String, List<List<Object>>> regiaoUm = regioesMap.getValue();

        for (Map.Entry<String, List<List<Object>>> regiaoUmResult : regiaoUm.entrySet()) {

            List<List<Object>> resultados = regiaoUmResult.getValue();

            for (List<Object> list : resultados) {

                System.out.println(list);

                Results resultado = new Results();
                resultado.setRegiaoAfetada(regioesMap.getKey());
                resultado.setPosicaoReferencia(regiaoUmResult.getKey());
                resultado.setNomeDoArquivo((String) list.get(0));
                resultado.setBaseAlteradaReferencia((String) list.get(1));
                resultado.setMutacaoEncontrada((List<String>) list.get(2));
                listaMutacoes.add(resultado);
            }
        }
    }
} catch (Exception e) {
    e.printStackTrace();
}


问:
Why do one of these two variables print in opposite order into the file?
Here are the variables:

```<code>int z = 0x12345678;
char zz[] = { 0x12, 0x34, 0x56, 0x78 };
</code>```

I print them into file using:

```<code>ofstream myfile;
myfile.open("myfile.txt", ios::out | ios::binary);
myfile.write((const char*)&z, sizeof(z));
myfile.write((const char*)&zz, sizeof(zz));
myfile.close();
</code>```

The file contains this when seen in hex editor:

```<code>78 56 34 12 12 34 56 78
</code>```

Why does the order reverse? What is the workaround to make both behave same way? I would prefer that the int prints in the same order like I type it in as the char does.

I am having the same issue at another place, I wrote a function that prints binary for an input value. It takes parameter as const char*. I cast the int z'saddress as const char* and can call the function, I can pass address of zz as well. The function masks each bit and to see if it is 0 or 1 and prints it to the screen. Since the int and char are not interpreted the same way, the function works with char but not with int.

答:
Cause you are running your code on a little endian machine, hence the int is stored in memory as 78 - 56 - 34 -12.
As you are writing the sequence of byte you are writing on disk the 4 bytes of the int as they are in memory. Hence the int has a specular rappresentation compared to the 4 bytes array.

The point is: until you write and read the same type of data on the same machine (so you are not dealing with Big Endian and Little Endian problem) I don't see the point of find a solution in order to have two 12345678 sequence written on disk.

Body:
Here are the variables:

int z = 0x12345678;
char zz[] = { 0x12, 0x34, 0x56, 0x78 };

I print them into file using:

ofstream myfile;
myfile.open("myfile.txt", ios::out | ios::binary);
myfile.write((const char*)&z, sizeof(z));
myfile.write((const char*)&zz, sizeof(zz));
myfile.close();

The file contains this when seen in hex editor:

78 56 34 12 12 34 56 78

Why does the order reverse? What is the workaround to make both behave same way? I would prefer that the int prints in the same order like I type it in as the char does.

I am having the same issue at another place, I wrote a function that prints binary for an input value. It takes parameter as const char*. I cast the int z'saddress as const char* and can call the function, I can pass address of zz as well. The function masks each bit and to see if it is 0 or 1 and prints it to the screen. Since the int and char are not interpreted the same way, the function works with char but not with int.


问:
Design-Time Errors in the Windows Forms Designer
I have this classes on the same namespace:

```<code>public partial class BaseForm : Form
{
    bool isNew = false;

    public BaseForm() {}

    public BaseForm(bool isNew)
    {
       InitializeComponent();

       this.isNew = isNew;
    }
    .
    .
    .
}

public partial class BitSetForm : BaseForm
{

    public BitSetForm(bool isNew) : base(isNew)
    {
        InitializeComponent();
    }

    new private void InitializeComponent()
    {
        .
        .
        .
    }
}
</code>```

1) And I got this warning: Could not find type "..BaseForm," Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built using the setting for your current platform or Any CPU.

2) Design-Time Errors in the Windows Forms Designer appears and hiding the design pane of the "BitSetForm" win-form.

What does this mean? What can I do to make the design pane of the "BitSetForm" win-form display again?

答:
Well a couple things...

You need to build your application before the designer can instantiate your base class. This can be very difficult if your subclass form has a bunch of errors.

The designer can only instantiate a class that has a default parameterless constructor. So that means your base class's BaseForm(bool isNew) will never be called by the designer. Which means InitializeComponent will not either. You should move InitializeComponent to the parameterless constructor and have the second constructor call the first.

InitializeComponent is private by default. You should not change its visibility to protected and since it's private, no new modifier is needed.

InitializeComponent should never be chained that way to the base class. It should only be called by the constructor.

Given all those issues, I would highly recommend either giving up on Windows Forms inheritance or at least moving your base class into a separate assembly. I've tried it many times and it's more trouble than it's worth.

The key thing to remember is that when you're viewing a form in the designer, the designer is not creating an instance of the form you see - it's creating an instance of the base class. At runtime that is obviously not the case. So it's very common to see different runtime/design time behavior.

Body:
I have this classes on the same namespace:

public partial class BaseForm : Form
{
    bool isNew = false;

    public BaseForm() {}

    public BaseForm(bool isNew)
    {
       InitializeComponent();

       this.isNew = isNew;
    }
    .
    .
    .
}

public partial class BitSetForm : BaseForm
{

    public BitSetForm(bool isNew) : base(isNew)
    {
        InitializeComponent();
    }

    new private void InitializeComponent()
    {
        .
        .
        .
    }
}

1) And I got this warning: Could not find type "..BaseForm," Please make sure that the assembly that contains this type is referenced. If this type is a part of your development project, make sure that the project has been successfully built using the setting for your current platform or Any CPU.

2) Design-Time Errors in the Windows Forms Designer appears and hiding the design pane of the "BitSetForm" win-form.

What does this mean? What can I do to make the design pane of the "BitSetForm" win-form display again?


问:
IdentityServer client example to remember QueryString parameters after redirect
When unauthenticated user opens URL of secure page on the client web site, he/she redirects to IdentifyServer for login and after successful login returns to the main page of the client(when using default implementation of client/IdentityServer).

Question on github RedirectUris with callback params does not work  explains that it is a client responsibility to remember QueryString and has the recommendation:

If you need to maintain state across the redirects, then issue a
  cookie client side or pass data via the official state param. You
  generally want to use the state parameter as a pointer to locally
  persisted data - e.g. a cookie. Create a cookie with a random name -
  store whatever needs to be stored there - round trip the cookie name
  as the state parameter. Just putting data on state has the issue that
  someone could potentially modify the values on the way back.

The question Identity server 3 MVC client state parameter has similar recommendation:

Store state in your app about the redirect path you want after login.
  After IdSvr logs your user in and redirect back to your one well-known
  callback URI you then read that state to know where to send the user.
  IOW, keep track of that in store state in your app about the redirect
  path you want after login. If you put it in the ProtocolMessage.State
  , then be aware that someone can tamper with it. If you protect the
  state (sign/encrypt), then it's ok. It might be easier/safer to keep
  that state in your app.

As it is a very typical scenario, I hope that someone has an example of such implementation. Can anyone share the sample code/give a reference to some article?

More info about my particular scenario:

My client is web forms site with implementation similar to IdentityServer3.Samples WebFormsClient.

1.User opens https://mydomain/mypage?querystringparams

2.In Web.config I have

```<code>  <authorization>
           <deny users="?" />
    </authorization>
</code>```

3.In client Startup.cs the relevant setting

```<code>new OpenIdConnectAuthenticationOptions
{
   Authority = "http://localhost:5000/",//IdentityServer4 Host
   RedirectUri ="https://mydomain/"
}
</code>```

4.On IdentityServer the relevant settings

```<code>new Client
{
     RedirectUris = { "https://mydomain/" , "http://mydomain/" }
}
</code>```

After login user redirected to https://mydomain/ , but needs to be redirected to https://mydomain/mypage?querystringparams

答:
I haven't looked into WebFormsClient. But if you could use OpenIdConnectAuthentication Owin middleware (used in OwinClient example) redirection should happen automatically. If OWIN middleware is not supported you can handle it manually. Have a look at https://github.com/IdentityServer/IdentityServer3.Samples/tree/master/source/Clients/MvcCodeFlowClientManual sample. There you can take control of the state parameter and handle redirection yourself.

e.g:
In AccountController/SignIn() you can get redirectUri from the query string and add that to the state parameter sent to identity server's authorization endpoint.

Then in AccountController/SignInCallback() you can retrieve the state parameter and redirect the user to the URL that he entered.

With OwinAuthentication middleware this should be handled automatically.

Body:
When unauthenticated user opens URL of secure page on the client web site, he/she redirects to IdentifyServer for login and after successful login returns to the main page of the client(when using default implementation of client/IdentityServer).

Question on github RedirectUris with callback params does not work  explains that it is a client responsibility to remember QueryString and has the recommendation:

If you need to maintain state across the redirects, then issue a
  cookie client side or pass data via the official state param. You
  generally want to use the state parameter as a pointer to locally
  persisted data - e.g. a cookie. Create a cookie with a random name -
  store whatever needs to be stored there - round trip the cookie name
  as the state parameter. Just putting data on state has the issue that
  someone could potentially modify the values on the way back.

The question Identity server 3 MVC client state parameter has similar recommendation:

Store state in your app about the redirect path you want after login.
  After IdSvr logs your user in and redirect back to your one well-known
  callback URI you then read that state to know where to send the user.
  IOW, keep track of that in store state in your app about the redirect
  path you want after login. If you put it in the ProtocolMessage.State
  , then be aware that someone can tamper with it. If you protect the
  state (sign/encrypt), then it's ok. It might be easier/safer to keep
  that state in your app.

As it is a very typical scenario, I hope that someone has an example of such implementation. Can anyone share the sample code/give a reference to some article?

More info about my particular scenario:

My client is web forms site with implementation similar to IdentityServer3.Samples WebFormsClient.

1.User opens https://mydomain/mypage?querystringparams

2.In Web.config I have

  <authorization>
           <deny users="?" />
    </authorization>

3.In client Startup.cs the relevant setting

new OpenIdConnectAuthenticationOptions
{
   Authority = "http://localhost:5000/",//IdentityServer4 Host
   RedirectUri ="https://mydomain/"
}

4.On IdentityServer the relevant settings

new Client
{
     RedirectUris = { "https://mydomain/" , "http://mydomain/" }
}

After login user redirected to https://mydomain/ , but needs to be redirected to https://mydomain/mypage?querystringparams


问:
Accessing UISegmentedControl @IBOoutlet from another class
I have Table View Controller, intended to serve as a settings page, that contains a UISegmentedControl with 3 segments:

```<code>class SettingsView: UITableViewController {

@IBOutlet weak var ButtonSelection: UISegmentedControl!

//Index 0 is default selection (first)

override func viewDidLoad() {
    super.viewDidLoad()
    // some code
}
</code>```

Separately, I have a Navigation View Controller that controls 3 different UIViewControllers with corresponding Storyboard IDs ("first", "second", and "third").

I'm trying to prepare the Navigation View Controller to present the appropriate View Controller based on UISegmentedControl selection. However, I keep getting "fatal error: unexpectedly found nil while unwrapping an Optional value" and not sure how to resolve.

This is what I have tried:

```<code>class NavViewController: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()

    if SettingsView().ButtonSelection.selectedSegmentIndex == 0 {

       print ("first segment is selected")

       let destinationController = storyboard?.instantiateViewController(withIdentifier: "first")

    else if SettingsView().ButtonSelection.selectedSegmentIndex == 1 {

       print ("second segment is selected")

       let destinationController = storyboard?.instantiateViewController(withIdentifier: "second")

    else if SettingsView().ButtonSelection.selectedSegmentIndex == 0 {

       print ("third segment is selected")

       let destinationController = storyboard?.instantiateViewController(withIdentifier: "third")
</code>```

Could anyone point me in the right direction, please? Thanks in advance!

答:
You have a couple of problems.

Problem 1: A UITableViewController is not set up to host anything but a table view. It's content view is locked to be a table view. If you want a table view that's managed by a UITableViewController and you want other content in the view controller, you need to make the UITableViewController a child of another view controller. The good news is that that is trivially easy using a container view and an embed segue.

Problem 2 is a "don't do that" problem. You should treat a view controller's views as private. Another view controller should not try to look at or change another view controller's segmented control. (It's bad design, and it also can lead to crashes like the one you describe because you can't be sure if the other view controller's views have been loaded yet.) Instead, you should add an integer property "selectedIndex" to the view controller that contains the segmented control, and use that to read/write the selected segment. (In OOP terms, you add a public interface to your view controller's "contract" that exposes the features you want to expose, and then add code that provides that interface.)

Body:
I have Table View Controller, intended to serve as a settings page, that contains a UISegmentedControl with 3 segments:

class SettingsView: UITableViewController {

@IBOutlet weak var ButtonSelection: UISegmentedControl!

//Index 0 is default selection (first)

override func viewDidLoad() {
    super.viewDidLoad()
    // some code
}

Separately, I have a Navigation View Controller that controls 3 different UIViewControllers with corresponding Storyboard IDs ("first", "second", and "third").

I'm trying to prepare the Navigation View Controller to present the appropriate View Controller based on UISegmentedControl selection. However, I keep getting "fatal error: unexpectedly found nil while unwrapping an Optional value" and not sure how to resolve.

This is what I have tried:

class NavViewController: UINavigationController {

override func viewDidLoad() {
    super.viewDidLoad()

    if SettingsView().ButtonSelection.selectedSegmentIndex == 0 {

       print ("first segment is selected")

       let destinationController = storyboard?.instantiateViewController(withIdentifier: "first")

    else if SettingsView().ButtonSelection.selectedSegmentIndex == 1 {

       print ("second segment is selected")

       let destinationController = storyboard?.instantiateViewController(withIdentifier: "second")

    else if SettingsView().ButtonSelection.selectedSegmentIndex == 0 {

       print ("third segment is selected")

       let destinationController = storyboard?.instantiateViewController(withIdentifier: "third")

Could anyone point me in the right direction, please? Thanks in advance!


问:
How to have this textbox display a different page in browser after the first time it's clicked (winforms C#)
I have a button on this Winforms app that when clicked, displays an HTML file in the browser module.

I need the button to display one file when it is clicked the first time and a different file any other time after that.

Here's the code that makes it open the first file:

```<code>private void button6_Click(object sender, EventArgs e)
        {
            string curDir = Directory.GetCurrentDirectory();
            this.webBrowser1.Url = new Uri(String.Format("file:///{0}/mail/index.html", curDir));
        }
</code>```

Currently it displays file:///{0}/mail/index.html every time it is clicked. I want it to display file:///{0}/mail/index2.html for the second and every other time it is clicked. How would I go about structuring this? is there an event that only responds to the first action on a piece of code? I've looked online for a while and can't seem to find anything specific to this problem.

答:
There is no event that only responds to the first action (you could theoretically create it yourself though). But it is much simpler to have just one Click event and inside it's event handler decide, which file to show - depending on  value of boolean variable that "remembers" if it is first button click or not. Something like this:

```<code>// Private filed of form that keeps track of whether button was already clicked before or not
private bool IsFirstButtonClick = true;

private void button6_Click(object sender, EventArgs e)
{
    string curDir = Directory.GetCurrentDirectory();

    // Display appropriate file depending on whether it is first time button click or not
    if(IsFirstButtonClick)
    {
        this.webBrowser1.Url = new Uri(String.Format("file:///{0}/mail/index.html", curDir));

        // Set flag so that next time button is clicked, we know it was alredy clicked (at least once) before
        IsFirstButtonClick = false;
    }
    else
        this.webBrowser1.Url = new Uri(String.Format("file:///{0}/mail/index2.html", curDir));
}
</code>```

Body:
I have a button on this Winforms app that when clicked, displays an HTML file in the browser module.

I need the button to display one file when it is clicked the first time and a different file any other time after that.

Here's the code that makes it open the first file:

private void button6_Click(object sender, EventArgs e)
        {
            string curDir = Directory.GetCurrentDirectory();
            this.webBrowser1.Url = new Uri(String.Format("file:///{0}/mail/index.html", curDir));
        }

Currently it displays file:///{0}/mail/index.html every time it is clicked. I want it to display file:///{0}/mail/index2.html for the second and every other time it is clicked. How would I go about structuring this? is there an event that only responds to the first action on a piece of code? I've looked online for a while and can't seem to find anything specific to this problem.

Body:
There is no event that only responds to the first action (you could theoretically create it yourself though). But it is much simpler to have just one Click event and inside it's event handler decide, which file to show - depending on  value of boolean variable that "remembers" if it is first button click or not. Something like this:

// Private filed of form that keeps track of whether button was already clicked before or not
private bool IsFirstButtonClick = true;

private void button6_Click(object sender, EventArgs e)
{
    string curDir = Directory.GetCurrentDirectory();

    // Display appropriate file depending on whether it is first time button click or not
    if(IsFirstButtonClick)
    {
        this.webBrowser1.Url = new Uri(String.Format("file:///{0}/mail/index.html", curDir));

        // Set flag so that next time button is clicked, we know it was alredy clicked (at least once) before
        IsFirstButtonClick = false;
    }
    else
        this.webBrowser1.Url = new Uri(String.Format("file:///{0}/mail/index2.html", curDir));
}


问:
Differences between hard real-time, soft real-time, and firm real-time?
I have read the definitions for the different notions of real-time, and the examples provided for hard and soft real-time systems make sense to me. But, there is no real explanation or example of a firm real-time system. According to the link above:

Firm: Infrequent deadline misses are tolerable, but may degrade the system's quality of service. The usefulness of a result is zero after its deadline.

Is there a clear distinction between firm real-time vs. hard or soft real-time, and is there a good example that illustrates that distinction?

In comments, Charles asked that I submit tag wikis for the new tags. The example of a "firm real-time system" I provided for the firm-real-time tag was a milk serving system. If the system delivers milk after its expiration time, then the milk is considered "not useful". One can tolerate eating cereal without milk, but the quality of the experience is degraded.

This is just the idea I formed in my head when I initially read the definition. I am looking for a much better example, and perhaps a better definition of firm real-time that will improve my notion of it.

答:
The definition has expanded over the years to the detriment of the term. What is now called "Hard" real-time is what used to be simply called real-time. So systems in which missing timing windows (rather than single-sided time deadlines) would result incorrect data or incorrect behavior should be consider real-time. Systems without that characteristic would be considered non-real-time.

That's not to say that time isn't of interest in non-real-time systems, it just means that timing requirements in such systems don't result in fundamentally incorrect results.


问:
error after using imshow() in mac
My code:

```<code>import cv2
import numpy
import matplotlib

img=cv2.imread('square1.png')
cv2.imshow('FRAME',img)
cv2.waitKey()
</code>```

Error message:

```<code>Traceback (most recent call last):
  File "/Users/tusharsharma/Desktop/image project/test1.py", line 5, in <module> cv2.imshow('FRAME',img)
cv2.error: /Users/travis/build/skvark/opencv-python/opencv/modules/highgui/src/window.cpp:583:
error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support.
If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config,
then re-run cmake or configure script in function cvShowImage
</code>```

OS is macOS Sierra. I had installed OpenCV using homebrew for Python 3.

答:
the main problem was with the configuration of build of OpenCv2 make sure you enter the correct part of your python libraries and Header files
for instance the following command will work for OpenCv for Python 3.6.1
cmake -D CMAKE_BUILD_TYPE=RELEASE \
 -D PYTHON3_EXECUTABLE=$(which python3) \
 -D PYTHON3_INCLUDE_DIR=$(python3 -c "from distutils.sysconfig import get_python_inc; print(get_python_inc())") \
 -D PYTHON3_LIBRARY=/Library/Frameworks/Python.framework/Versions/3.4/lib/python3.4/config-3.4m/libpython3.4.dylib \
 -D PYTHON3_LIBRARIES=/Library/Frameworks/Frameworks/Python.framework/Versions/3.4/bin \
 -D PYTHON3_INCLUDE_DIR=/Library/Frameworks1/Frameworks/Python.framework/Versions/3.4/Headers \
 -D PYTHON3_PACKAGES_PATH=$(python3 -c "from distutils.sysconfig import get_python_lib; print(get_python_lib())") \
 -D INSTALL_C_EXAMPLES=OFF -D INSTALL_PYTHON_EXAMPLES=ON \
 -D BUILD_EXAMPLES=ON \
 -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib/modules ..

Title: error after using imshow() in mac

Body:
My code:

import cv2
import numpy
import matplotlib

img=cv2.imread('square1.png')
cv2.imshow('FRAME',img)
cv2.waitKey()

Error message:

Traceback (most recent call last):
  File "/Users/tusharsharma/Desktop/image project/test1.py", line 5, in <module> cv2.imshow('FRAME',img)
cv2.error: /Users/travis/build/skvark/opencv-python/opencv/modules/highgui/src/window.cpp:583:
error: (-2) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Carbon support.
If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config,
then re-run cmake or configure script in function cvShowImage

OS is macOS Sierra. I had installed OpenCV using homebrew for Python 3.


答:
This is because of endianess (Please see https://en.wikipedia.org/wiki/Endianness ) . You should write endiness-independent code to avoid such issues.

Edit: IBM has a wonderful article on this https://www.ibm.com/developerworks/aix/library/au-endianc/index.html

Title: Why do one of these two variables print in opposite order into the file?


问:
Memory error with recursive function in MATLAB
I have the below recursive function in MATLAB but keep getting an "out of memory" error.

Should I be using use an iterative method instead? If so, how might I go about doing that?

```<code>function [Result] = Test(n)
    % Test(0) = 0
    if n > 0
        Result = 1+(31/45)*Test(n-1)+(1/5)*Test(n+2)+(1/9)*Test(n+5);
    else
        Result = 0;
    end
end
</code>```

This does not need to go to infinity but merely a sufficiently large n.

Body:
I have the below recursive function in MATLAB but keep getting an "out of memory" error.

Should I be using use an iterative method instead? If so, how might I go about doing that?

function [Result] = Test(n)
    % Test(0) = 0
    if n > 0
        Result = 1+(31/45)*Test(n-1)+(1/5)*Test(n+2)+(1/9)*Test(n+5);
    else
        Result = 0;
    end
end

This does not need to go to infinity but merely a sufficiently large n.

Body:
First of all you should rewrite the recursive function like the following:

T(n) = 1 + (31/45)*T(n-1) + (1/5)*T(n+2) + 1/9*T(n+5)
suppose: i = n + 5 => T(i-5) = 1 + (31/45)*T(i-4) + (1/5)*T(i-3) + 1/9*T(i)
=> T(i) = 9*T(i-5) - (31/5)*T(i-4) - (9/5)*T(i-3) - 9

So T(1) = T(2) = T(3) = -9, T(4) = 36/5. Therefore you can iterate like the following:

function Result = Test(n)
T = zeros(1,n);
T(1) = -9;
T(2) = -9;
T(3) = -9;
T(4) =  36/5;
T(5) = 63;
for i = 6 : n
    T(i) = 9*T(i-5) - (31/5)*T(i-4) - (9/5)*T(i-3) - 9;
end
Result = T(n);


问:
I have a h1, and a h3 that I can't vertically center in Foundation 6
I've tried to everything to vertically center my h1 and h3 tag in Foundation 6. I've tried the transform translate, flexbox, and tried multiple examples here on stack over flow, and nothing works. When I use absolute positioning to center the content the, the headings get in the way of the top-bar nav on smaller screens, id there anyway to fix this issue, and Could some give me a hand with this? The h1 tag, and the h3 tag are located in line 48, and 49 of my codepen.
Codepen link</p>

```<code><!doctype html>
<html class="no-js" lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">
  </head>
  <body>
    <div class="off-canvas-wrapper">
            <div class="off-canvas position-left" id="offCanvas" data-off-canvas data-transition="overlap">
                <!-- Close button -->
            <button class="close-button" aria-label="Close menu" type="button" data-close>
        <span aria-hidden="true">×</span>
            </button>
            <ul class="vertical menu">
              <li><a href="#">Home</a></li>
              <li><a href="#">About</a></li>
              <li><a href="#">References</a></li>
              <li><a href="#">Contact</a></li>
            </ul>
            </div><!-- off-canvas menu -->
            <div class="off-canvas-content" data-off-canvas-content>
            <!-- Your page content lives here -->
            <div class="hero-image">
                <div class="expanded header-intro row">
              <button type="button" class="button float-right show-for-medium" data-toggle="offCanvas">Menu</button><!-- Button to open off-canvas menu -->
              <div class="title-bar" data-responsive-toggle="menu" data-hide-for="medium"><!--top bar navigation -->
              <button class="menu-icon" type="button" data-toggle></button>
              <div class="title-bar-title">Menu</div>
              </div>
              <div class="top-bar show-for-small-only" id="menu">
                <div class="top-bar-left">
                <ul class="dropdown vertical menu" data-dropdown-menu>
                    <li class="menu-text">Foundation Framework</li>
                    <li><a href="#">Home</a></li>
                    <li><a href="#">About</a></li>
                    <li><a href="#">Reference</a></li>
                    <li><a href="#">About</a></li>
                </ul>
                </div>
              </div>
                </div>
                <div class="row">
            <div class="small-12 text-center columns">
              <h1>Foundation</h1> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
              <h3>Foundation For Sites</h3> <!-- CAN'T VERTICALLY CENTER THIS TAG -->
            </div>
                </div>
            </div><!-- Eno of hero-image section -->
            </div><!-- off-canvas-content-->
        </div><!-- off-canvas wrapper-->
    <script src="js/vendor/jquery.js"></script>
    <script src="js/vendor/what-input.js"></script>
    <script src="js/vendor/foundation.js"></script>
    <script src="js/app.js"></script>
  </body>
</html>
</code>```

答:
try this

```<code>h1 {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

}

h3 {

    margin: 0;
    position: absolute;
    top: 60%;
    left: 50%;
    transform: translate(-50%, -50%);

}
</code>```

Reference: w3schools

Body:
I've tried to everything to vertically center my h1 and h3 tag in Foundation 6. I've tried the transform translate, flexbox, and tried multiple examples here on stack over flow, and nothing works. When I use absolute positioning to center the content the, the headings get in the way of the top-bar nav on smaller screens, id there anyway to fix this issue, and Could some give me a hand with this? The h1 tag, and the h3 tag are located in line 48, and 49 of my codepen.
Codepen link

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Foundation for Sites</title>
    <link rel="stylesheet" href="css/foundation.css">
    <link rel="stylesheet" href="css/app.css">

            <button class="close-button" aria-label="Close menu" type="button" data-close>
        ×
            </button>

Home

About

References

Contact

              <button type="button" class="button float-right show-for-medium" data-toggle="offCanvas">Menu</button>

              <button class="menu-icon" type="button" data-toggle></button>

Menu

Foundation Framework

Home

About

Reference

About

Foundation

Foundation For Sites

Body:
try this

h1 {
    margin: 0;
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);

}

h3 {

    margin: 0;
    position: absolute;
    top: 60%;
    left: 50%;
    transform: translate(-50%, -50%);

}

Reference: w3schools


问:
Are global variables in C++ stored on the stack, heap or neither of them?
Initially I was pretty sure that the correct answer had to be "None of them", since global variables are stored in the data memory, but then I've found this book from Robert Lafore, called "Object Oriented Programming in C++" and it clearly states that, according to the C++ standard, global variables are stored on the heap. Now I'm pretty confused and can't really figure out what's the correct answer to the question that has been asked.

Why would global variables be stored on the heap? What am I missing?

EDIT: Link to the book - page 231

答:
Here is what the book says on page 205:

If you’re familiar with operating system architecture, you might be interested to know that local variables and function arguments are stored on the stack, while global and static variables are stored on the heap.

This is definitely an error in the book. First, one should discuss storage in terms of storage duration, the way C++ standard does: "stack" refers to automatic storage duration, while "heap" refers to dynamic storage duration. Both "stack" and "heap" are allocation strategies, commonly used to implement objects with their respective storage durations.

Global variables have static storage duration. They are stored in an area that is separate from both "heap" and "stack". Global constant objects are usually stored in "code" segment, while non-constant global objects are stored in the "data" segment.

ContentLicense: CC BY-SA 4.0