问:
How to change svn url in svnsync?
How can I change (relocate) a subversion url that I entered when creating a mirror repository using "svnsync init" (example from #https://whatever to svn://whatever)?

tried to run svnsync init again with new url but

```<code>svnsync init file:///<path_to_mirror> http:///<new_url>
svnsync: Destination repository is already synchronizing from 'http:///<old_url>'
</code>```

答:
The sync-from URL is stored as a revprop in the mirror repo. If on the machine with the mirror repository (my situation), use the svnlook tool to look and svnadmin to change:

```<code>user@q.r[~]$ svnlook pg --revprop -r0 /path/to/mirror/repo svn:sync-from-url
svn+ssh://svn.abc.com:1234/svn/foo
</code>```

You will see the URL of the repo to which your mirror is currently syncing. In the above example, the master repo URL ends with .../foo.  It may not have a newline at the end, so your shell prompt may follow. Now you need to get that into a file as svnadmin uses a file for input to change revprops.

```<code>user@q.r[~]$ svnlook pg --revprop -r0 /path/to/mirror/repo svn:sync-from-url > t.txt
</code>```

Now edit t.txt to change the URL to the master repo. This can cause a newline to appear at the end of t.txt and result in obscure/meaningless error messages from svnsync. So get rid of it:

```<code>user@q.r[~]$ cat t.txt | tr -d '\n' > t2.txt
</code>```

Note that we now have t2.txt which is the sanitized file. Then use svnadmin to change the revprop to the contents of the just-edited and sanitized file:

```<code>user@q.r[~]$ svnadmin setrevprop /path/to/mirror/repo -r0 svn:sync-from-url t2.txt
</code>```

Note that t2.txt is used not t.txt. Finally, check your changes:

```<code>user@q.r[~]$ svnlook pg --revprop -r0 /path/to/mirror/repo svn:sync-from-url
svn+ssh://svn.def.com:5678/svn/foo
</code>```

You should see your new repo URL immediately followed by the shell prompt, with no newline. In the above example the URL ends in foo and is immediately followed by the shell prompt user@q.r[~]$.

Title: How to change svn url in svnsync?

Body:
How can I change (relocate) a subversion url that I entered when creating a mirror repository using "svnsync init" (example from #https://whatever to svn://whatever)?

tried to run svnsync init again with new url but

svnsync init file:///<path_to_mirror> http:///<new_url>
svnsync: Destination repository is already synchronizing from 'http:///<old_url>'

Body:
The sync-from URL is stored as a revprop in the mirror repo. If on the machine with the mirror repository (my situation), use the svnlook tool to look and svnadmin to change:

user@q.r[~]$ svnlook pg --revprop -r0 /path/to/mirror/repo svn:sync-from-url
svn+ssh://svn.abc.com:1234/svn/foo

You will see the URL of the repo to which your mirror is currently syncing. In the above example, the master repo URL ends with .../foo.  It may not have a newline at the end, so your shell prompt may follow. Now you need to get that into a file as svnadmin uses a file for input to change revprops.

user@q.r[~]$ svnlook pg --revprop -r0 /path/to/mirror/repo svn:sync-from-url > t.txt

Now edit t.txt to change the URL to the master repo. This can cause a newline to appear at the end of t.txt and result in obscure/meaningless error messages from svnsync. So get rid of it:

user@q.r[~]$ cat t.txt | tr -d '\n' > t2.txt

Note that we now have t2.txt which is the sanitized file. Then use svnadmin to change the revprop to the contents of the just-edited and sanitized file:

user@q.r[~]$ svnadmin setrevprop /path/to/mirror/repo -r0 svn:sync-from-url t2.txt

Note that t2.txt is used not t.txt. Finally, check your changes:

user@q.r[~]$ svnlook pg --revprop -r0 /path/to/mirror/repo svn:sync-from-url
svn+ssh://svn.def.com:5678/svn/foo

You should see your new repo URL immediately followed by the shell prompt, with no newline. In the above example the URL ends in foo and is immediately followed by the shell prompt user@q.r[~]$.


来源: stackexchange

问:
Python 3 local variable not used
I'm writing a Tic Tac Toe AI and have a problem with a function that I want to define. It can be simplified to something like:

```<code>z = True
X = 1
y = 2

def place(X,y):
    if z = True:
        if X == 1:
            x = y
</code>```

(please note, I made some of my x'es capital just to make it easier to differentiate them for this post). The problem here is that I need to assign the value of y to X, but  in the "x=y" statement, I'm given an error that x is a local variable not used, like if the x in that IF statement is local only to that IF statement, and is not connected.

A test with it showed that after the function was run, the X was unchanged, and printed the old value. No error is given in the function before that, only the one marked as x is local. What can I do to fix this so that x and X actually share values?

I have tried making go through other variables, but that didn't work. I have tried to use the global function on a value to lead it through, but that didn't work either.

答:
Your 'x' is local since it is first defined locally. Define it globally and mark it global. That is,</p>

```<code>z = True
X = 1
x = None
y = 2

def place(X,y):
    global x
    if z = True:
        if X == 1:
            x = y
</code>```

ContentLicense: CC BY-SA 4.0

Title: Python 3 local variable not used

Body:
I'm writing a Tic Tac Toe AI and have a problem with a function that I want to define. It can be simplified to something like:

z = True
X = 1
y = 2

def place(X,y):
    if z = True:
        if X == 1:
            x = y

(please note, I made some of my x'es capital just to make it easier to differentiate them for this post). The problem here is that I need to assign the value of y to X, but  in the "x=y" statement, I'm given an error that x is a local variable not used, like if the x in that IF statement is local only to that IF statement, and is not connected.

A test with it showed that after the function was run, the X was unchanged, and printed the old value. No error is given in the function before that, only the one marked as x is local. What can I do to fix this so that x and X actually share values?

I have tried making go through other variables, but that didn't work. I have tried to use the global function on a value to lead it through, but that didn't work either.

Body:
Your 'x' is local since it is first defined locally. Define it globally and mark it global. That is,

z = True
X = 1
x = None
y = 2

def place(X,y):
    global x
    if z = True:
        if X == 1:
            x = y

ContentLicense: CC BY-SA 3.0


问:
simultaneously exec multiple shell_exec() commands?
Hi so i am wondering if somebody can offer me a solution..

I have multiple instances of a php script i would like to run at once, I can semi achieve this using shell_exec() and not waiting for a response apart from the pid. This works wonderfully. However when doing this with the method below it works well for 100 or so executes but I need it to execute around 1000 times and it is taking too long to loop around the foreach and execute 1 by one.

Example:

```<code> $items = $array(daatabase entries);

   foreach($items as $i){
    $pid = shell_exec("execute the process.php");
   }
</code>```

Now assuming there are < 100 this will take around 1 second or so to exec which is OK however i need to run loads of these and this will take 10-20 seconds.

Is there any way of sending the commands in bulk rather than 1 at a time?

Thanks

答:
Something like pthreads perhaps?

https://www.sitepoint.com/parallel-programming-pthreads-php-fundamentals/
(The most recent result I could find)

Body:
Hi so i am wondering if somebody can offer me a solution..

I have multiple instances of a php script i would like to run at once, I can semi achieve this using shell_exec() and not waiting for a response apart from the pid. This works wonderfully. However when doing this with the method below it works well for 100 or so executes but I need it to execute around 1000 times and it is taking too long to loop around the foreach and execute 1 by one.

Example:

 $items = $array(daatabase entries);

   foreach($items as $i){
    $pid = shell_exec("execute the process.php");
   }

Now assuming there are < 100 this will take around 1 second or so to exec which is OK however i need to run loads of these and this will take 10-20 seconds.

Is there any way of sending the commands in bulk rather than 1 at a time?

Thanks


问:
foreach htmlelement in ng-content
I wanna create a kind of container component that modifies all (parent) tags listed in ng-content.

For example all tags within this container shall be wrapped within within a bootstrap-row to define responiveness.

Is this possible. Something like

```<code>            <ng-content *ngFor="let tag of tags"
              <row>{{tag}}<row>
            </ng-content>
</code>```

答:
update Angular 5

ngOutletContext was renamed to ngTemplateOutletContext

See also https://github.com/angular/angular/blob/master/CHANGELOG.md#500-beta5-2017-08-29

original

<ng-content *ngFor="..." is pointless. It would create tags.length number of <ng-content> elements where only the first one ever takes effect.

You can achieve something like that using <template> and ngForTemplate or ngTemplateOutlet

See als

Angular2 child component as data

How to repeat a piece of HTML multiple times without ngFor and without another @Component

Title: foreach htmlelement in ng-content

Body:
I wanna create a kind of container component that modifies all (parent) tags listed in ng-content.

For example all tags within this container shall be wrapped within within a bootstrap-row to define responiveness.

Is this possible. Something like

            <ng-content *ngFor="let tag of tags"
              <row>{{tag}}<row>
            </ng-content>


答:
If you want to access global variables from inside a function you should use the keyword global so the function knows where to find this variables.

```<code>z = True
X = 1
y = 2

def place(X,y):
    global z, X, y
    if z = True:
        if X == 1:
            x = y
</code>```

Title: Python 3 local variable not used

Body:
If you want to access global variables from inside a function you should use the keyword global so the function knows where to find this variables.

z = True
X = 1
y = 2

def place(X,y):
    global z, X, y
    if z = True:
        if X == 1:
            x = y


问:
Using Retrofit in Android
I have an android app that has 3 activities :

A login activity

A tasks acivity where all tasks pertaining to a user are displayed (Populated using an Array Adapter)

A task_details activity which results from clicking a task on the list

I have to consume REST Apis. The research I have done so far directs me to use Retrofit. I checked how to use it and found out that :

Set the base URL in the Main Activity (Mine is  the Login Activity)

I need to create a API class and define my functions using annotations.

Use the class Rest Adapter in the Activity and define Callbacks.

Had my app been a single activity app, I would have crunched everything in my MainActivity.java but I don't know how and where to put all the code from steps 1,2,3 for use in my 3 activities.Could you please help by telling how to use Retrofit in my app. Thanks a lot.

Specifically, I need network calls to :
1. Login the user
2. Get all the tasks of the user.
And for both I would be using a given REST api.

```<code>*********************************************
          Calling Api USing Retrofit
*********************************************
**Dependancies** :-
      implementation 'com.android.support:recyclerview-v7:27.1.1'
        implementation 'com.squareup.picasso:picasso:2.5.2'
        implementation 'com.android.support:cardview-v7:27.1.1'
    enter code here
**Model**
use the Pozo class

**Api Call**
 -> getLogin()    // use the method

  //API call for Login
    private void getLogin()
    {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams requestParams = new RequestParams();
        requestParams.put("email_id", edit_email.getText().toString());
        requestParams.put("password", edit_password.getText().toString());
        Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
        Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
        client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                ShowProgress();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                Hideprogress();

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("", "Login RESPONSE-" + response);
                Login login = new Gson().fromJson(String.valueOf(response), Login.class);
                edit_email.setText("");
                edit_password.setText("");
                if (login.getStatus().equals("true")) {
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                    MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
                            MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
                    mdToast.show();
                    Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());

                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
                    hideKeyboard(SignInActivity.this);
                    Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                } else {
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                    MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
                            MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
                    mdToast.show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("", throwable.getMessage());
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
                        MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
                mdToast.show();
            }
        });
    }
</code>```

答: Beginners find it little intimidating to learn retrofit. I have prepared a tutorial which will simplify the learning curve. See Retrofit android tutorial for more information.</p>

Title: Using Retrofit in Android

Body:
I have an android app that has 3 activities :

A login activity

A tasks acivity where all tasks pertaining to a user are displayed (Populated using an Array Adapter)

A task_details activity which results from clicking a task on the list

I have to consume REST Apis. The research I have done so far directs me to use Retrofit. I checked how to use it and found out that :

Set the base URL in the Main Activity (Mine is  the Login Activity)

I need to create a API class and define my functions using annotations.

Use the class Rest Adapter in the Activity and define Callbacks.

Had my app been a single activity app, I would have crunched everything in my MainActivity.java but I don't know how and where to put all the code from steps 1,2,3 for use in my 3 activities.Could you please help by telling how to use Retrofit in my app. Thanks a lot.

Specifically, I need network calls to :
1. Login the user
2. Get all the tasks of the user.
And for both I would be using a given REST api.

*********************************************
          Calling Api USing Retrofit
*********************************************
**Dependancies** :-
      implementation 'com.android.support:recyclerview-v7:27.1.1'
        implementation 'com.squareup.picasso:picasso:2.5.2'
        implementation 'com.android.support:cardview-v7:27.1.1'
    enter code here
**Model**
use the Pozo class

**Api Call**
 -> getLogin()    // use the method

  //API call for Login
    private void getLogin()
    {
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
        AsyncHttpClient client = new AsyncHttpClient();
        RequestParams requestParams = new RequestParams();
        requestParams.put("email_id", edit_email.getText().toString());
        requestParams.put("password", edit_password.getText().toString());
        Log.e("", "LOGIN URL==>" + Urls.LOGIN + requestParams);
        Log.d("device_token", "Device_ Token" + FirebaseInstanceId.getInstance().getToken());
        client.post(Urls.LOGIN, requestParams, new JsonHttpResponseHandler() {
            @Override
            public void onStart() {
                super.onStart();
                ShowProgress();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                Hideprogress();

            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONObject response) {
                super.onSuccess(statusCode, headers, response);
                Log.e("", "Login RESPONSE-" + response);
                Login login = new Gson().fromJson(String.valueOf(response), Login.class);
                edit_email.setText("");
                edit_password.setText("");
                if (login.getStatus().equals("true")) {
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                    MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("User Login Successfully!"),
                            MDToast.LENGTH_SHORT, MDToast.TYPE_SUCCESS);
                    mdToast.show();
                    Utils.WriteSharePrefrence(SignInActivity.this, Util_Main.Constant.EMAIL, login.getData().getEmailId());
                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERID, login.getData().getId());

                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.USERNAME, login.getData().getFirstName());
                    Utils.WriteSharePrefrence(SignInActivity.this, Constant.PROFILE, login.getData().getProfileImage());
                    hideKeyboard(SignInActivity.this);
                    Intent intent = new Intent(SignInActivity.this, DashboardActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    startActivity(intent);
                    finish();
                } else {
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                    MDToast mdToast = MDToast.makeText(SignInActivity.this, String.valueOf("Login Denied"),
                            MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
                    mdToast.show();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                super.onFailure(statusCode, headers, responseString, throwable);
                Log.e("", throwable.getMessage());
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE);
                MDToast mdToast = MDToast.makeText(SignInActivity.this, "Something went wrong",
                        MDToast.LENGTH_SHORT, MDToast.TYPE_ERROR);
                mdToast.show();
            }
        });
    }


问:
How to Call Javascript method from a javascript file in the Iframe of aspx page?
I have an aspx page where I have a parent page xyz.aspx page where one js file(abc.js) mentioned in the  tag. I need to call a method written in abc.js in child aspx page on load based on some condition. I would like to know how to call this function in child aspx page under document.ready()/window.onload.

I tried using parent.methodname() under script tag but it didnt work.
Here is the code how it looks like:

```<code><script type="text/javascript">
    function getParameterByName(name) {
        name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
        var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        results = regex.exec(location.search);
        return results === null ? "" :         decodeURIComponent(results[1].replace(/\+/g, " "));
    }

    $(window).load(function () {
        var flgInsidePresentation = getParameterByName("flgInsidePresentation");
        if (flgInsidePresentation) { parent.updateButtons(null, 2, 1); }
    });

</script>
</code>```

If I write only Parent in my console i get the parent page(xyz.aspx) where the js file is mentioned under  tag.

PS: I have to call updateButtons method from deck.navigation.js file from my child.aspx page

```<code>(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);
</code>```

Please let me know if there is any other way. Thanks for the help in advance.

答:
The problem is that your updateButtons function is in a private scope.
Looks like you are building a jQuery plugin so the easiest way to solve this is to add the window to the scope and attach the function to that

```<code>(function($, window, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  window.updateButtons = function(event, from, to) {
    //your code
  };
 })(jQuery, window);
</code>```

Then call the function in your iframe

```<code>window.parent.updateButtons()
</code>```

Body:
I have an aspx page where I have a parent page xyz.aspx page where one js file(abc.js) mentioned in the  tag. I need to call a method written in abc.js in child aspx page on load based on some condition. I would like to know how to call this function in child aspx page under document.ready()/window.onload.

I tried using parent.methodname() under script tag but it didnt work.
Here is the code how it looks like:

If I write only Parent in my console i get the parent page(xyz.aspx) where the js file is mentioned under  tag.

PS: I have to call updateButtons method from deck.navigation.js file from my child.aspx page

(function($, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  var updateButtons = function(event, from, to) {
    var options = $.deck('getOptions');
    var lastIndex = $.deck('getSlides').length - 1;
    var $prevSlide = $.deck('getSlide', to - 1);
    var $nextSlide = $.deck('getSlide', to + 1);
    var hrefBase = window.location.href.replace(/#.*/, '');
    var prevId = $prevSlide ? $prevSlide.attr('id') : undefined;
    var nextId = $nextSlide ? $nextSlide.attr('id') : undefined;
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);

    $prevButton.toggleClass(options.classes.navDisabled, to === 0);
    $prevButton.attr('aria-disabled', to === 0);
    $prevButton.attr('href', hrefBase + '#' + (prevId ? prevId : ''));
    $nextButton.toggleClass(options.classes.navDisabled, to === lastIndex);
    $nextButton.attr('aria-disabled', to === lastIndex);
    $nextButton.attr('href', hrefBase + '#' + (nextId ? nextId : ''));
  };

  /*
  Extends defaults/options.

  options.classes.navDisabled
    This class is added to a navigation link when that action is disabled.
    It is added to the previous link when on the first slide, and to the
    next link when on the last slide.

  options.selectors.nextLink
    The elements that match this selector will move the deck to the next
    slide when clicked.

  options.selectors.previousLink
    The elements that match this selector will move to deck to the previous
    slide when clicked.
  */
  $.extend(true, $.deck.defaults, {
    classes: {
      navDisabled: 'deck-nav-disabled'
    },

    selectors: {
      nextLink: '.deck-next-link',
      previousLink: '.deck-prev-link'
    }
  });

  $document.bind('deck.init', function() {
    var options = $.deck('getOptions');
    var slides = $.deck('getSlides');
    var $current = $.deck('getSlide');
    var $prevButton = $(options.selectors.previousLink);
    var $nextButton = $(options.selectors.nextLink);
    var index;

    // Setup prev/next link events
    $prevButton.unbind('click.decknavigation');
    $prevButton.bind('click.decknavigation', function(event) {
      $.deck('prev');
      event.preventDefault();
    });

    $nextButton.unbind('click.decknavigation');
    $nextButton.bind('click.decknavigation', function(event) {
      $.deck('next');
      event.preventDefault();
    });

    // Find where we started in the deck and set initial states
    $.each(slides, function(i, $slide) {
      if ($slide === $current) {
        index = i;
        return false;
      }
    });
    updateButtons(null, index, index);
  });

  $document.bind('deck.change', updateButtons);
})(jQuery);

Please let me know if there is any other way. Thanks for the help in advance.

Body:
The problem is that your updateButtons function is in a private scope.
Looks like you are building a jQuery plugin so the easiest way to solve this is to add the window to the scope and attach the function to that

(function($, window, undefined) {
  var $document = $(document);

  /* Updates link hrefs, and disabled states if last/first slide */
  window.updateButtons = function(event, from, to) {
    //your code
  };
 })(jQuery, window);

Then call the function in your iframe

window.parent.updateButtons()


问:
Protobuf-net performance questions

Is there a noticeable performance overhead in serializing a property marked as a DynamicType (outputs NetObjectProxy)?

Would compiling the RuntimeTypeModel to a dll perform better than in memory compilation through RuntimeTypeModel.Compile()?

Is there any advantage to calling RuntimeTypeModel.Compile() manually?

答:
1: you'd have to test with your own data, but it is certainly much less efficient - more space on the wire, and a lot more things to do (type resolution, etc) - plus it can't just JIT everything to a nice simple path

2: not in my findings; it does reduce startup time a little, but the key driver for this feature was to allow AOT (although true AOT requires the separate cross-platform targeting thing, which is a little awkward). I'm waiting on "Roslyn code generators" (https://github.com/dotnet/roslyn/blob/master/docs/features/generators.md) for improved AOT support in the future.

3: in some scenarios - yes; for example, you're setting up a service/server, and you want everything ready to go before the first traffic comes in, then again - this can spend time now to avoid a slight delay later; but: by default it compiles on-demand anyway

Title: Protobuf-net performance questions


问:
Is XHTML really Xtensible?
Is there any way (server- or client-side) that I can actually extend HTML to include new tags?  For example, it would be cool if I could write something like a schema fragment that defined a blogpost, which contains a postname, a postauthor, a posttime, and a postcontent, and thereafter refer to blogpost in my HTML rather than resorting to the basic HTML div and p tags.

答:
For the general web developer, no.  You'd need to write your own DTD to have your own tags, and even then, it really will not benefit you semantically for anything other than your own sanity.

Also, some browsers ahem IE will not know how to handle your custom tags, and you'll have to resort to JavaScript to teach it.  Not really recommended...

ContentLicense: CC BY-SA 2.5

Title: Is XHTML really Xtensible?


问:
All com.google.android.gms libraries must use the exact same version

Images

Exception

All com.google.android.gms libraries must use the exact same version specification (mixing versions can lead to runtime crashes). Found versions 9.8.0, 10.2.0. Examples include com.google.android.gms:play-services-appindexing:9.8.0 and com.google.android.gms:play-services-base:10.2.0

I am mixing versions 9.8.0 and 10.2.0.

Lastest versions

com.google.android.gms:play-services-fitness: 10.2.0

com.google.android.gms:play-services-appindexing: 9.8.0

Issue

I must use com.google.android.gms:play-services-fitness:10.2.0 because it includes that latest update that I need.

However, there is no 10.2.0 version of com.google.android.gms:play-services-appindexing, 9.8.0 is the latest one.

Question

So, I can't downgrade fitness because I need the latest version, but there is no version for appindexing that matches it.

What do I do in this case?

答:
App Indexing moved to the Firebase bundle.  A lot is moving there and if you don't use Firebase I'd recommend migrating & checking it out.  It certainly seems to be the future of where this is all heading.

More info on how to migrate the AppIndexing element can be found here


问:
Is there any open api for IndianRailway
I am working on an app based on railway which requires to get the info of a train or of that railway station.I want an open API for that app which gives the results of PNR status, Live Station, etc..

Can anyone suggest one good API for that?

答:
Have you checked http://api.erail.in/ ?

```<code>Sample call : http://api.erail.in/stations/?key=API_KEY
</code>```

Json output

```<code>{
    "status" : "OK",
    "result" : [
                    {
                        "code" : "NDLS",
                        "name" : "New Delhi"
                    },
                    {
                        "code" : "BCT",
                        "name" : "Mumbai Central"
                    },
                    ....
                ]
}
</code>```

How to Get eRail API
First and foremost, app developers will need to get an API key which    Allows you to monitor your application’s API usage in the API console

Enables per-key instead of per-IP-address quota limits.

Ensures that eRail.in can contact you about your application if necessary.

The eRail.in Indian Railways API uses an API key to identify your application. API keys are managed through the eRail.in APIs console. To create your key:

Please send a request to info@erail.in

Upon approval you will be provided with the API key

Once the service has been activated, you can make HTTP request to the API.

Title: Is there any open api for IndianRailway

Body:
Have you checked http://api.erail.in/ ?

Sample call : http://api.erail.in/stations/?key=API_KEY

Json output

{
    "status" : "OK",
    "result" : [
                    {
                        "code" : "NDLS",
                        "name" : "New Delhi"
                    },
                    {
                        "code" : "BCT",
                        "name" : "Mumbai Central"
                    },
                    ....
                ]
}

How to Get eRail API
First and foremost, app developers will need to get an API key which    Allows you to monitor your application’s API usage in the API console

Enables per-key instead of per-IP-address quota limits.

Ensures that eRail.in can contact you about your application if necessary.

The eRail.in Indian Railways API uses an API key to identify your application. API keys are managed through the eRail.in APIs console. To create your key:

Please send a request to info@erail.in

Upon approval you will be provided with the API key

Once the service has been activated, you can make HTTP request to the API.


问:
Selecting siblings of parent of $(this) element
I need to update the id of all li that are siblings of the parent of the $(this) element by dynamically counting the present li that belong to the same "family" every time one is removed.

Note that there's more than one ul.customFieldUl on the page and more than one li.customFieldLi in each.

$('.customFieldUl').on('click', '.remove-button', function() {
  var field = $(this).parents('li.customFieldLi');
  if (field.length) {
    field.remove();

    // PROBLEMATIC SELECTOR BELOW:
    $(this).parent().siblings().each(function(i) {
      var id = i + 1;

      $(this).prop('id', 'field_' + id);
      $(this).find('label#top_title').html('Custom Field #: ' + id + ' »');
    });
  }
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="customFieldUl">
  <li class="customFieldLi">
    <label id="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label id="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
</ul></code>```

答:
The issue you have is that you're removing the element then trying to select elements based on it. This won't work as the element no longer exists. To fix this, get the related elements first, then perform the removal.

Note that you can simplify the code by using the index parameter provided by each(). Also, you've repeated the top_title id. You should make that a class. Try this:

$('.customFieldUl').on('click', '.remove-button', function() {
  var $button = $(this);
  var $ul = $button.closest('.customFieldUl');

  $button.closest('.customFieldLi').remove();
  $ul.find('.customFieldLi').each(function(i) {
    $(this).prop('id', 'field_' + i);
    $(this).find('label.top_title').html('Custom Field #: ' + i + ' »');
  })
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
</ul></code>```

It's also worth noting that changing id attributes dynamically is not a good idea. They are meant to be immutable.

Body:
I need to update the id of all li that are siblings of the parent of the $(this) element by dynamically counting the present li that belong to the same "family" every time one is removed.

Note that there's more than one ul.customFieldUl on the page and more than one li.customFieldLi in each.

$('.customFieldUl').on('click', '.remove-button', function() {
  var field = $(this).parents('li.customFieldLi');
  if (field.length) {
    field.remove();

    // PROBLEMATIC SELECTOR BELOW:
    $(this).parent().siblings().each(function(i) {
      var id = i + 1;

      $(this).prop('id', 'field_' + id);
      $(this).find('label#top_title').html('Custom Field #: ' + id + ' »');
    });
  }
});

    Additional Field

Remove

    Additional Field

Remove

Body:
The issue you have is that you're removing the element then trying to select elements based on it. This won't work as the element no longer exists. To fix this, get the related elements first, then perform the removal.

Note that you can simplify the code by using the index parameter provided by each(). Also, you've repeated the top_title id. You should make that a class. Try this:

$('.customFieldUl').on('click', '.remove-button', function() {
  var $button = $(this);
  var $ul = $button.closest('.customFieldUl');

  $button.closest('.customFieldLi').remove();
  $ul.find('.customFieldLi').each(function(i) {
    $(this).prop('id', 'field_' + i);
    $(this).find('label.top_title').html('Custom Field #: <b>' + i + '</b> &raquo;');
  })
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<ul class="customFieldUl">
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
  <li class="customFieldLi">
    <label class="top_title">Additional Field</label>
    <div class="additionalFieldForm"></div>
    <div class="remove-button">Remove</div>
  </li>
</ul>

It's also worth noting that changing id attributes dynamically is not a good idea. They are meant to be immutable.


问:
Hudson Perforce plugin - how can I automatically update versions without repeatedly triggering a build
I'm trying to get continuous integration working using Hudson, Maven & Perforce (with an scm poll used to trigger each build)

One of the requirements is to automatically update POM snapshot version numbers following each successful build.

This is trivial using the Maven release plugin, but the act of checking in the newly versioned POMs triggers another build - which continues ad infinitum.

Is there any way of checking in version updates without triggering another build? There doesn't seem to be any way of excluding specific user checkins, specific changelists, or specific files when the scm poll makes the decision to rebuild.

This seems like a basic requirement - been doing it for years using Cruise Control / Ant / Perforce,

Cheers,

Mark

答:
What is "POM"?

You can have Hudson "Create or Update Label in Perforce" (see near the bottom of your project's configuration.) You could use that along with the BUILD_NUMBER environment variable that Hudson provides, giving you unique build numbers and stamped P4 labels of said build.


问:
PyQt QTableWidget - restoring doubleclick behavior after subclassing
I have a QTableView that I need to be able to drag and move in a QGraphicsScene. I am accomplishing this by subclassing the QTableWidget like this:

```<code>def mouseMoveEvent(self, event):
    newPos = self.mapToGlobal(event.pos())
    self.move(newPos)
</code>```

However this seems to overwrite the ability to doubleclick a cell to edit it's text. Is there an easy way to get that back?

Here's a complete sample, the second row is uneditable:

```<code>import sys
from PyQt4 import QtGui, QtCore

class PicNode(QtGui.QTableWidget):
    def __init__(self):
        super(PicNode, self).__init__()
        picWidth = 480
        picHeight = 240

        self.setFixedSize(picWidth,picHeight+105)
        self.setRowCount(2)
        self.setColumnCount(1)
        self.setColumnWidth(0, picWidth)
        self.setRowHeight(0,picHeight)
        self.setRowHeight(1, 100)
        self.horizontalHeader().hide()
        self.verticalHeader().hide()

        img = QtGui.QPixmap("MV17_Pix BoxR.jpg")
        pic = QtGui.QLabel()
        pic.setPixmap(img.scaled(picWidth,picHeight))
        self.setCellWidget(0,0,pic)
        self.setItem(0,1,QtGui.QTableWidgetItem("some caption data goes here"))

        self.mouseOffset = 0

    def mousePressEvent(self, event):
        # capture the click position on the widget so that when we move it, we offset it by
        # that much
        self.mouseOffset = self.mapFrom(self, event.pos())
        if event.button() != QtCore.Qt.LeftButton:
            event.ignore()
            return

    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            newPos = self.mapToGlobal(event.pos())
            self.move(newPos - self.mouseOffset)

class NodeGraph(QtGui.QGraphicsView):
    def __init__(self, parent):
        super(NodeGraph, self).__init__(parent)
        self._zoom = 0
        self._scene = QtGui.QGraphicsScene(self)
        self._node = PicNode()
        #QtGui.QGraphicsProxyWidget(self._scene.addWidget(self._node))
        self._scene.addWidget(self._node)
        self.setScene(self._scene)
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30)))
        self.setFrameShape(QtGui.QFrame.NoFrame)
        self.setRenderHint(QtGui.QPainter.Antialiasing)
        self.setDragMode(QtGui.QGraphicsView.RubberBandDrag)

class NodeGraphApp(QtGui.QDialog):
    def __init__(self):
        super(NodeGraphApp, self).__init__()
        self.initUI()

    def initUI(self):
        self.viewer = NodeGraph(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.viewer)

        self.setWindowTitle("Nodegraph test")

def main():
    app = QtGui.QApplication(sys.argv)
    ex = NodeGraphApp()
    ex.show()
    sys.exit(app.exec_())

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

答:
The problem isn't with mouseMoveEvent, it's with mousePressEvent. Try calling the superclass method before doing your own:

```<code>class PicNode(QTableWidget):
    def __init__(self, parent=None):
        super(PicNode, self).__init__(parent)

    def mousePressEvent(self, event):
        super(PicNode,self).mousePressEvent(event)
        # your stuff here
</code>```

Body:
I have a QTableView that I need to be able to drag and move in a QGraphicsScene. I am accomplishing this by subclassing the QTableWidget like this:

def mouseMoveEvent(self, event):
    newPos = self.mapToGlobal(event.pos())
    self.move(newPos)

However this seems to overwrite the ability to doubleclick a cell to edit it's text. Is there an easy way to get that back?

Here's a complete sample, the second row is uneditable:

import sys
from PyQt4 import QtGui, QtCore

class PicNode(QtGui.QTableWidget):
    def __init__(self):
        super(PicNode, self).__init__()
        picWidth = 480
        picHeight = 240

        self.setFixedSize(picWidth,picHeight+105)
        self.setRowCount(2)
        self.setColumnCount(1)
        self.setColumnWidth(0, picWidth)
        self.setRowHeight(0,picHeight)
        self.setRowHeight(1, 100)
        self.horizontalHeader().hide()
        self.verticalHeader().hide()

        img = QtGui.QPixmap("MV17_Pix BoxR.jpg")
        pic = QtGui.QLabel()
        pic.setPixmap(img.scaled(picWidth,picHeight))
        self.setCellWidget(0,0,pic)
        self.setItem(0,1,QtGui.QTableWidgetItem("some caption data goes here"))

        self.mouseOffset = 0

    def mousePressEvent(self, event):
        # capture the click position on the widget so that when we move it, we offset it by
        # that much
        self.mouseOffset = self.mapFrom(self, event.pos())
        if event.button() != QtCore.Qt.LeftButton:
            event.ignore()
            return

    def mouseMoveEvent(self, event):
        if event.buttons() == QtCore.Qt.LeftButton:
            newPos = self.mapToGlobal(event.pos())
            self.move(newPos - self.mouseOffset)

class NodeGraph(QtGui.QGraphicsView):
    def __init__(self, parent):
        super(NodeGraph, self).__init__(parent)
        self._zoom = 0
        self._scene = QtGui.QGraphicsScene(self)
        self._node = PicNode()
        #QtGui.QGraphicsProxyWidget(self._scene.addWidget(self._node))
        self._scene.addWidget(self._node)
        self.setScene(self._scene)
        self.setTransformationAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.setResizeAnchor(QtGui.QGraphicsView.AnchorUnderMouse)
        self.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
        self.setBackgroundBrush(QtGui.QBrush(QtGui.QColor(30, 30, 30)))
        self.setFrameShape(QtGui.QFrame.NoFrame)
        self.setRenderHint(QtGui.QPainter.Antialiasing)
        self.setDragMode(QtGui.QGraphicsView.RubberBandDrag)

class NodeGraphApp(QtGui.QDialog):
    def __init__(self):
        super(NodeGraphApp, self).__init__()
        self.initUI()

    def initUI(self):
        self.viewer = NodeGraph(self)
        layout = QtGui.QVBoxLayout(self)
        layout.addWidget(self.viewer)

        self.setWindowTitle("Nodegraph test")

def main():
    app = QtGui.QApplication(sys.argv)
    ex = NodeGraphApp()
    ex.show()
    sys.exit(app.exec_())

if __name__ == '__main__':
    main()

Body:
The problem isn't with mouseMoveEvent, it's with mousePressEvent. Try calling the superclass method before doing your own:

class PicNode(QTableWidget):
    def __init__(self, parent=None):
        super(PicNode, self).__init__(parent)

    def mousePressEvent(self, event):
        super(PicNode,self).mousePressEvent(event)
        # your stuff here


问:
Send an email from Google Sheets after a change to one column
I have a simple google sheet collecting data.   We use the sheet to follow up events.  I want to send an email based on a change to a cell (column W) which will always be the same column. The email is always to the same person in the business.

I have got to the point of being able to make a change to ANY cell in the sheet and the first email is sent.  But I cannot figure out how to lock it down to only look at one column.

Ideally the event will leave a footprint so I wanted to add a comment in the cell.   It is working also.

What I need - how do I limit the script to only look at column W???    Thank you.

The columns also pull through tot he email fine.

```<code>function onEdit(event)
{
  var ss = event.source.getActiveSheet();
  var r = event.source.getActiveRange();
  r.setComment("Email Sent To Warrens: " + (new Date()));
}
function CustomEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A2:W13");
var UserData = range.getValues();
var text = 'm******n@gmail.com';
for (i in UserData) {
var row = UserData[i];
var Title = row[6];
var SURNAME = row[7];
var EmailAddress = row[9];
var Rentalagreementnumber = row[3];
var Startofhiredate = row[4];
var Invoicereason = row[5];
var Amountdue = row [2];
var Rentallocation = row [8];
MailApp.sendEmail(text, "a***@*****.co.uk", "SUBJECT", "EMAIL TEXT");
}
}
</code>```

答:
Get the range from the event object, then use the function range#getA1Notation() to check which column was edited. </p>

```<code>function onEdit(event)
{
  var range = event.range;
  if(range.getA1Notation().charAt(0) === 'W'){
      sendEmail();
      range.setComment("Email Sent To Warrens: " + (new Date()));
  }
}
</code>```

Body:
I have a simple google sheet collecting data.   We use the sheet to follow up events.  I want to send an email based on a change to a cell (column W) which will always be the same column. The email is always to the same person in the business.

I have got to the point of being able to make a change to ANY cell in the sheet and the first email is sent.  But I cannot figure out how to lock it down to only look at one column.

Ideally the event will leave a footprint so I wanted to add a comment in the cell.   It is working also.

What I need - how do I limit the script to only look at column W???    Thank you.

The columns also pull through tot he email fine.

function onEdit(event)
{
  var ss = event.source.getActiveSheet();
  var r = event.source.getActiveRange();
  r.setComment("Email Sent To Warrens: " + (new Date()));
}
function CustomEmail() {
var sheet = SpreadsheetApp.getActiveSheet();
var range = sheet.getRange("A2:W13");
var UserData = range.getValues();
var text = 'm******n@gmail.com';
for (i in UserData) {
var row = UserData[i];
var Title = row[6];
var SURNAME = row[7];
var EmailAddress = row[9];
var Rentalagreementnumber = row[3];
var Startofhiredate = row[4];
var Invoicereason = row[5];
var Amountdue = row [2];
var Rentallocation = row [8];
MailApp.sendEmail(text, "a***@*****.co.uk", "SUBJECT", "EMAIL TEXT");
}
}

Body:
Get the range from the event object, then use the function range#getA1Notation() to check which column was edited.

function onEdit(event)
{
  var range = event.range;
  if(range.getA1Notation().charAt(0) === 'W'){
      sendEmail();
      range.setComment("Email Sent To Warrens: " + (new Date()));
  }
}


答:
The problem can be fixed with variable-precision arithmetic:

```<code>>> expr = vpa(expression)
expr =
-5949.2156936801140978790460880789*(x - 2.0)^2
</code>```

Convert it to a function

```<code>>> func =
  function_handle with value:
    @(x)(x-2.0).^2.*-5.949215693680114e3
</code>```

Then evaluate it

```<code>>> func(1)
ans =
  -5.9492e+03
</code>```

Title: How to avoid loss of accuracy when converting symbolic expressions to functions?

Body:
tl;dr: I observe a complete loss of accuracy when converting a symbolic expression to a function handle with matlabFunction. I wonder if there are ways to improve the conversion in order to avoid the loss of accuracy.

I have a symbolic variable x for which 1 <= x && x <= 2 holds true:

syms x real
assumeAlso(1 <= x & x <= 2);

I have many computer-generated, lengthy symbolic expression in that variable. One of them looks like this:

expression = ( ...
  1015424780204960143215273323910078528628754663952913658657288835138029704791686717561885487746105223164496264397062144000 ...
  *( ...
     60345244216851610523130575942127473698515638085026410114070496399315754724985170479034760688327679099512793302302720*2^(1/2) ...
   - 85341062796188128379389251264141456937242003828816791711306294886439805159655912635773490018204138847163921224639041 ...
   )*(x - 2)^2 ...
) ...
/31504288346872372712061562812941419427167561153216213605146864117586323331155800294021400857537041202039565879856190821729945216935526707438840242294801134287960934949194864204307116208568439380511702602881;

Edit: You have to construct it with (pasting the above will make expression a constant 0)

expression = sym('(1015424780204960143215273323910078528628754663952913658657288835138029704791686717561885487746105223164496264397062144000*(60345244216851610523130575942127473698515638085026410114070496399315754724985170479034760688327679099512793302302720*2^(1/2) - 85341062796188128379389251264141456937242003828816791711306294886439805159655912635773490018204138847163921224639041)*(x - 2)^2)/31504288346872372712061562812941419427167561153216213605146864117586323331155800294021400857537041202039565879856190821729945216935526707438840242294801134287960934949194864204307116208568439380511702602881');

Calling double(subs(expression, x, 1)) evaluates this expression to approximately -5.9492e+03 without any problems, which actually is the correct value. However, the evaluation takes far too long and is a huge (or rather tiny?) bottleneck in my application. That’s why I intend to convert the expression to an anonymous function that operates on doubles and is much faster, like so:

evaluator = matlabFunction(expression, 'Vars', x);

The result being

@(x) (sqrt(2.0).*6.034524421685161e115-8.534106279618813e115) ...
.*(x-2.0).^2.*3.223131940086397e-86

I had much success with this approach in the past. Unfortunately in this case, evaluator(x) evaluates to 0 for any value of x, because the first row is exactly zero. Obviously, this has to do with the limited number of significant digits for doubles.

Are there ways to work around this? Can I tell MATLAB to consider the range of x so that it can find a better representation of the constants?

Body:
The problem can be fixed with variable-precision arithmetic:

>> expr = vpa(expression)
expr =
-5949.2156936801140978790460880789*(x - 2.0)^2

Convert it to a function

>> func =
  function_handle with value:
    @(x)(x-2.0).^2.*-5.949215693680114e3

Then evaluate it

>> func(1)
ans =
  -5.9492e+03


问:
Dynamic method name inside a class?
I'd like to, when instantiating a class to be able to pass to it a name that will be used for prefixing a method name in that class, so far I have this

```<code><?php
if ( ! class_exists( 'My_Class' ) ) {
    /**
     * Creates filter method
     *
     * @since  1.0.0
     */
    class My_Class {

        /**
         * Prefix for method names
         *
         * @var string $name Name of the filter prefix.
         */
        private $name;

        /**
         * Version.
         *
         * @var string
         */
        private $version = '1.0.0';

        /**
         * Initialize the class and set its properties.
         *
         * @since 1.0.0
         * @param string $name    The name for the method prefix.
         * @param string $version The version of this plugin.
         */
        public function __construct( $name, $version ) {
            $this->name = $name;
            $this->version = $version;
            add_filter( 'my_filter_name', $name . '_my_folder' );
        }

        /**
         * Function for filtering folder array
         *
         * Each plugin has to set its own array of paths and url.
         *
         * @param  array $import_array Array with folder values.
         * @return array               Modified array with folder values.
         */
        public function $name . _my_folder() {
            $import_array[$this->name]['folder']     = plugin_dir_path( __FILE__ ) . 'includes/layout';
            $import_array[$this->name]['folder_url'] = plugin_dir_url( __FILE__ ) . 'includes/layout';
            return $import_array;
        }

    }
}
</code>```

The idea is that I'd just call it like

```<code>$first_object = new My_Class( 'first' );
$second_object = new My_Class( 'second' );
</code>```

This is so that I can use this in multiple same plugins, with different names, depending on the type of the plugin.

The obvious problem is function $name . _my_folder().

I read something about __call() magic method but I'm not sure if this can be used in this case, or how to apply it.

Can this be done?

答:
I'm not an expert, but I think that you have to specific the default version in the constructor... I'm not sure, but you can try it.</p>

```<code>    public function __construct( $name, $version="1.0.0" ) {
        $this->name = $name;
        $this->version = $version;
        add_filter( 'my_filter_name', $name . '_my_folder' );
    }
</code>```

Title: Dynamic method name inside a class?

Body:
I'd like to, when instantiating a class to be able to pass to it a name that will be used for prefixing a method name in that class, so far I have this

<?php
if ( ! class_exists( 'My_Class' ) ) {
    /**
     * Creates filter method
     *
     * @since  1.0.0
     */
    class My_Class {

        /**
         * Prefix for method names
         *
         * @var string $name Name of the filter prefix.
         */
        private $name;

        /**
         * Version.
         *
         * @var string
         */
        private $version = '1.0.0';

        /**
         * Initialize the class and set its properties.
         *
         * @since 1.0.0
         * @param string $name    The name for the method prefix.
         * @param string $version The version of this plugin.
         */
        public function __construct( $name, $version ) {
            $this->name = $name;
            $this->version = $version;
            add_filter( 'my_filter_name', $name . '_my_folder' );
        }

        /**
         * Function for filtering folder array
         *
         * Each plugin has to set its own array of paths and url.
         *
         * @param  array $import_array Array with folder values.
         * @return array               Modified array with folder values.
         */
        public function $name . _my_folder() {
            $import_array[$this->name]['folder']     = plugin_dir_path( __FILE__ ) . 'includes/layout';
            $import_array[$this->name]['folder_url'] = plugin_dir_url( __FILE__ ) . 'includes/layout';
            return $import_array;
        }

    }
}

The idea is that I'd just call it like

$first_object = new My_Class( 'first' );
$second_object = new My_Class( 'second' );

This is so that I can use this in multiple same plugins, with different names, depending on the type of the plugin.

The obvious problem is function $name . _my_folder().

I read something about __call() magic method but I'm not sure if this can be used in this case, or how to apply it.

Can this be done?

Body:
I'm not an expert, but I think that you have to specific the default version in the constructor... I'm not sure, but you can try it.

    public function __construct( $name, $version="1.0.0" ) {
        $this->name = $name;
        $this->version = $version;
        add_filter( 'my_filter_name', $name . '_my_folder' );
    }


问:
Regex optional and depending on older optional
I currently have this regex:

```<code>/^\+\(?([0-9]{1,4})\)?$/g
</code>```

Now, I can use the following formats:

```<code>+31
+(31)
+(31
+31)
</code>```

However, I want to modify it so only with both parentheses it'll work, not just with one. So +(31 and +31) won't work anymore. How can I manage to get it?

答:
Create an alternation group to match digits inside parentheses or with no parentheses:

```<code>^\+(?:\([0-9]{1,4}\)|[0-9]{1,4})$
</code>```

See regex demo

Details:

^ - start of string anchor

\+ - a literal +

(?:\([0-9]{1,4}\)|[0-9]{1,4}) - one of the two alternatives:

\([0-9]{1,4}\) - 1 to 4 digits enclosed with literal ( and )

| - or

[0-9]{1,4} - 1 to 4 digits

$ - end of string anchor

Body:
I currently have this regex:

/^\+\(?([0-9]{1,4})\)?$/g

Now, I can use the following formats:

+31
+(31)
+(31
+31)

However, I want to modify it so only with both parentheses it'll work, not just with one. So +(31 and +31) won't work anymore. How can I manage to get it?

Body:
Create an alternation group to match digits inside parentheses or with no parentheses:

^\+(?:\([0-9]{1,4}\)|[0-9]{1,4})$

See regex demo

Details:

^ - start of string anchor

\+ - a literal +

(?:\([0-9]{1,4}\)|[0-9]{1,4}) - one of the two alternatives:

\([0-9]{1,4}\) - 1 to 4 digits enclosed with literal ( and )

| - or

[0-9]{1,4} - 1 to 4 digits

$ - end of string anchor


问:
How to use Lua table inside redis.call?
Getting an error in Redis while executing a Lua script in Redis. My confusion is how to use Redis array reply in making second redis.call. My use case is bulk deletion of Sorted Set members.

```<code>127.0.0.1:6380> eval "local list = redis.call('zrevrange','test', 50, -1) return redis.call('zrem', 'test', list)" 0
(error) ERR Error running script (call to f_aa5dddbbb039b576aba5f46a99a268339ca2e9d5): @user_script:1: @user_script: 1: Lua redis() command arguments must be strings or integers
</code>```

How to accomplish this?

答:
Use Lua's unpack - i.e.:

```<code>local list = redis.call('zrevrange','test', 50, -1) return
redis.call('zrem', 'test', unpack(list))
</code>```

However, to perform a bulk delete from a Sorted Set based on a range, simply use ZREMRANGEBYRANK:

```<code>ZREMRANGEBYRANK test 0 -50
</code>```

Title: How to use Lua table inside redis.call?

Body:
Getting an error in Redis while executing a Lua script in Redis. My confusion is how to use Redis array reply in making second redis.call. My use case is bulk deletion of Sorted Set members.

127.0.0.1:6380> eval "local list = redis.call('zrevrange','test', 50, -1) return redis.call('zrem', 'test', list)" 0
(error) ERR Error running script (call to f_aa5dddbbb039b576aba5f46a99a268339ca2e9d5): @user_script:1: @user_script: 1: Lua redis() command arguments must be strings or integers

How to accomplish this?

Body:
Use Lua's unpack - i.e.:

local list = redis.call('zrevrange','test', 50, -1) return
redis.call('zrem', 'test', unpack(list))

However, to perform a bulk delete from a Sorted Set based on a range, simply use ZREMRANGEBYRANK:

ZREMRANGEBYRANK test 0 -50


问:
python list comprehension not working as expected
I am new to list comprehension in python . I am tying to convert a for-if statement to list comprehension but it is not working as expected:

```<code>a = ['Done', 'add dns addRec test 11.11.11.11']
record = "addRec"
</code>```

Normal python code:

```<code>list_new = []
for member in a:
  if record and "addRec" in member:
    list_new.append(member)
    print(list_new)
</code>```

My list comprehension:

```<code>list_new = [list_new.append(member) for member in a if record and "addRec" in member]
</code>```

list_new is returning as a empty list.

It should return :

```<code>['add dns addRec test 11.11.11.11']
</code>```

答:
The comperhension already return a list, so I think that the list_new.append(member) is redundant.

I reproduced your code without the "record" and without the append part. It seems to be working:

```<code>a = ['Done', 'add dns addRec test 11.11.11.11']
list_new = []
for member in a:
  if "addRec" in member:
    list_new.append(member)
    print(list_new)
assert ['add dns addRec test 11.11.11.11'] == list_new

#comperhension
list_new = [member for member in a if "addRec" in member]
print list_new
assert ['add dns addRec test 11.11.11.11'] == list_new
</code>```

EDIT (adding "record" after question edit):

```<code>a = ['Done', 'add dns addRec test 11.11.11.11']
record = "addRec"

list_new = []
for member in a:
  if record and "addRec" in member:
    list_new.append(member)
    print(list_new)
assert ['add dns addRec test 11.11.11.11'] == list_new

#comperhension
list_new = [member for member in a if record and "addRec" in member]
print list_new
assert ['add dns addRec test 11.11.11.11'] == list_new
</code>```

Body:
I am new to list comprehension in python . I am tying to convert a for-if statement to list comprehension but it is not working as expected:

a = ['Done', 'add dns addRec test 11.11.11.11']
record = "addRec"

Normal python code:

list_new = []
for member in a:
  if record and "addRec" in member:
    list_new.append(member)
    print(list_new)

My list comprehension:

list_new = [list_new.append(member) for member in a if record and "addRec" in member]

list_new is returning as a empty list.

It should return :

['add dns addRec test 11.11.11.11']

Body:
The comperhension already return a list, so I think that the list_new.append(member) is redundant.

I reproduced your code without the "record" and without the append part. It seems to be working:

a = ['Done', 'add dns addRec test 11.11.11.11']
list_new = []
for member in a:
  if "addRec" in member:
    list_new.append(member)
    print(list_new)
assert ['add dns addRec test 11.11.11.11'] == list_new

#comperhension
list_new = [member for member in a if "addRec" in member]
print list_new
assert ['add dns addRec test 11.11.11.11'] == list_new

EDIT (adding "record" after question edit):

a = ['Done', 'add dns addRec test 11.11.11.11']
record = "addRec"

list_new = []
for member in a:
  if record and "addRec" in member:
    list_new.append(member)
    print(list_new)
assert ['add dns addRec test 11.11.11.11'] == list_new

#comperhension
list_new = [member for member in a if record and "addRec" in member]
print list_new
assert ['add dns addRec test 11.11.11.11'] == list_new


问:
Python 3 local variable not used
I'm writing a Tic Tac Toe AI and have a problem with a function that I want to define. It can be simplified to something like:

```<code>z = True
X = 1
y = 2

def place(X,y):
    if z = True:
        if X == 1:
            x = y
</code>```

(please note, I made some of my x'es capital just to make it easier to differentiate them for this post). The problem here is that I need to assign the value of y to X, but  in the "x=y" statement, I'm given an error that x is a local variable not used, like if the x in that IF statement is local only to that IF statement, and is not connected.

A test with it showed that after the function was run, the X was unchanged, and printed the old value. No error is given in the function before that, only the one marked as x is local. What can I do to fix this so that x and X actually share values?

I have tried making go through other variables, but that didn't work. I have tried to use the global function on a value to lead it through, but that didn't work either.

答:
You have a typo here:

```<code>if z = True:
</code>```

It should be

```<code>if z == True:
</code>```

Title: Python 3 local variable not used

Body:
I'm writing a Tic Tac Toe AI and have a problem with a function that I want to define. It can be simplified to something like:

z = True
X = 1
y = 2

def place(X,y):
    if z = True:
        if X == 1:
            x = y

(please note, I made some of my x'es capital just to make it easier to differentiate them for this post). The problem here is that I need to assign the value of y to X, but  in the "x=y" statement, I'm given an error that x is a local variable not used, like if the x in that IF statement is local only to that IF statement, and is not connected.

A test with it showed that after the function was run, the X was unchanged, and printed the old value. No error is given in the function before that, only the one marked as x is local. What can I do to fix this so that x and X actually share values?

I have tried making go through other variables, but that didn't work. I have tried to use the global function on a value to lead it through, but that didn't work either.

Body:
You have a typo here:

if z = True:

It should be

if z == True:


问:
What are my options for optimizing this Spring/Hibernate page?
I have a page that touches a lot of data in the database. It displays a lot of data, and also does a fair amount of calculations on it, which would be a really massive hassle to do inside of a group by query, or in a stored procedure. It's just so much easier when you have your domain model.

Anyway, as a result, Hibernate ends up making TONS of queries as it pulls out all of the data. It doesn't really matter if I get the data eagerly or lazily... all the queries tally up to about ~600-700ms.

The individual queries are very fast. They are not even 1 ms. But as you can see, this page makes a lot of queries for a table that lists of the results of a training course for 58 students:

```<code>0 ms  JDBC SELECT (MODULE)
0 ms  JDBC SELECT (TASK)
0 ms  JDBC SELECT (USER_ACCOUNT) // student #1
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (USER_ACCOUNT)
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (USER_ACCOUNT)
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)

0 ms  JDBC SELECT (USER_ACCOUNT) // student #2
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_FILL_IN_THE_BLANK_ANSWER)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_FILL_IN_THE_BLANK_ANSWER)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)

0 ms  JDBC SELECT (USER_ACCOUNT) // student #3
....
0 ms  JDBC SELECT (USER_ACCOUNT) // student #58
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
</code>```

It is going to be very common that 30-60 students take a course, so 600-700ms is going to kill the server.

To give an idea as to the complexity, here's the 1-M relationships:

Module(1)->Task->Question->Keyword

ActiveModule(1)->ActiveTask->ActiveQuestion->QuestionResult->Keyword, LanguageKeyword

Also, there are other 1-M links too:

Module->ActiveModule

Task->ActiveTask

Question->ActiveQuestion

Basically, this is a really complex graph of data.

What are my options? The server this application is running on only has 1 GB of RAM, so caching the individual objects is pretty much out of the question. I don't know if getting Hibernate to issue less queries would even make much difference. There are just so many.

The schema for this app is very tree-like, and it's deep and complex. Unfortunately, all of this data is needed. The trees are basically all or nothing.

答: Use a view.  That should optimize your joins and reduce the number of individual queries you have to do.</p>

Body:
I have a page that touches a lot of data in the database. It displays a lot of data, and also does a fair amount of calculations on it, which would be a really massive hassle to do inside of a group by query, or in a stored procedure. It's just so much easier when you have your domain model.

Anyway, as a result, Hibernate ends up making TONS of queries as it pulls out all of the data. It doesn't really matter if I get the data eagerly or lazily... all the queries tally up to about ~600-700ms.

The individual queries are very fast. They are not even 1 ms. But as you can see, this page makes a lot of queries for a table that lists of the results of a training course for 58 students:

0 ms  JDBC SELECT (MODULE)
0 ms  JDBC SELECT (TASK)
0 ms  JDBC SELECT (USER_ACCOUNT) // student #1
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (USER_ACCOUNT)
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (USER_ACCOUNT)
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)

0 ms  JDBC SELECT (USER_ACCOUNT) // student #2
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (QUESTION)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (KEYWORD)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_FILL_IN_THE_BLANK_ANSWER)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_FILL_IN_THE_BLANK_ANSWER)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)

0 ms  JDBC SELECT (USER_ACCOUNT) // student #3
....
0 ms  JDBC SELECT (USER_ACCOUNT) // student #58
0 ms  JDBC SELECT (ACTIVE_TASK)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (ACTIVE_QUESTION)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_LANGUAGE_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)
0 ms  JDBC SELECT (QUESTION_RESULT_TO_KEYWORD)

It is going to be very common that 30-60 students take a course, so 600-700ms is going to kill the server.

To give an idea as to the complexity, here's the 1-M relationships:

Module(1)->Task->Question->Keyword

ActiveModule(1)->ActiveTask->ActiveQuestion->QuestionResult->Keyword, LanguageKeyword

Also, there are other 1-M links too:

Module->ActiveModule

Task->ActiveTask

Question->ActiveQuestion

Basically, this is a really complex graph of data.

What are my options? The server this application is running on only has 1 GB of RAM, so caching the individual objects is pretty much out of the question. I don't know if getting Hibernate to issue less queries would even make much difference. There are just so many.

The schema for this app is very tree-like, and it's deep and complex. Unfortunately, all of this data is needed. The trees are basically all or nothing.


问:
How to ask if I have saved my text document before closing the jframe
I'm developing a text editor and I need to check whether I have saved chances typed (even a space) in my Text Area.

If I have typed even a space, the dialog should pop and ask me to save the text before closing the application.

I need to define all the keys in a single way without checking all the keyboards keys are pressed or not... This is my code:

```<code> private void isAnyKeyWasPressed() {
    jTextPane1.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            if (e.getKeyChar()==e.VK_0 || e.getKeyChar()==e.VK_1) {//need to define all the keyboard keys without defining one by one like this
                //my dialog box goes here
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyReleased(KeyEvent e) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });
}
</code>```

答:
You do not want to listen for key events.

Instead, you want to track a "unsaved property" within the class that wraps around your different components. Any time the user makes any change to the editor (more specifically to the underlying model object); you set that property to true.

Every time the user saves, you turn the property to false.

And whenever the user tells the application to shutdown, you check that property, and if it is true - you ask the user if he wants to save.

Do not get into a mode where "one action" directly triggers another one.

Edit: just to make that clear - with property I mean that you add a field to your class, very much like the isModified that the other answer already suggests.

Body:
I'm developing a text editor and I need to check whether I have saved chances typed (even a space) in my Text Area.

If I have typed even a space, the dialog should pop and ask me to save the text before closing the application.

I need to define all the keys in a single way without checking all the keyboards keys are pressed or not... This is my code:

 private void isAnyKeyWasPressed() {
    jTextPane1.addKeyListener(new KeyListener() {

        @Override
        public void keyTyped(KeyEvent e) {
            if (e.getKeyChar()==e.VK_0 || e.getKeyChar()==e.VK_1) {//need to define all the keyboard keys without defining one by one like this
                //my dialog box goes here
            }
        }

        @Override
        public void keyPressed(KeyEvent e) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }

        @Override
        public void keyReleased(KeyEvent e) {
            throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
        }
    });
}


问:
SQLException: Access denied for user 'whatever'@'localhost'
Credentials are correct, database name is correct, MySQL users are set correctly and have all the privileges, I have entries for 'username'@'%' as well as 'username'@'localhost', I can connect to this user via commandline correctly, as well as through mysql workbench. In other words, everything works as it should and is set as it should be, except my java app is unable to connect.

I did about 3 clean uninstalls and installs of MySQL, with restarts, without restarts, tried to login through app as root (with pass) which didn't work, tried to login through app as user with no password (same error), etc.

Also, a PHP website running on localhost using precisely the same login works perfectly.

I've been checking and re-checking and trying all of this for the past 3 days, I went through all the related SO questions, all the blogs and docs I could find, all of it.

```<code>try {
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  conn = DriverManager.getConnection("jdbc:mysql://localhost/correctDBname", "correctUsername", "correctPassword");
} catch(ClassNotFoundException | SQLException ex) {
  Logger.getLogger(SqlConnection.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
}
</code>```

MySQL driver name precisely as it appears in NetBeans' "Libraries" section in project: MySQL JDBC Driver - mysql-connector-java-5.1.23-bin.jar

Full text of the exception:

```<code>java.sql.SQLException: Access denied for user 'strada'@'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:925)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1704)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1250)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2465)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2498)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2283)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:822)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at eu.storemedia.stradaserver.engine.SqlConnection.<init>(SqlConnection.java:23)
at eu.storemedia.stradaserver.engine.StradaServer.<init>(StradaServer.java:51)
at eu.storemedia.stradaserver.Home.<clinit>(Home.java:31)
</code>```

答:
...turns out reading credentials from .txt file might be dangerous, and omitting this fact from the question in the name of simplifying it was a mistake.

if I use hardcoded credentials, login works. If I use credentials read from incorrectly created .txt file, the error occurs. If I use credentials read from correctly created .txt file (utf-8 with no BOM), login works.

I've rewritten the file I'm reading the credentials from to be correct, so I can't find out any specifics, but basically it contained some invisible character (possibly BOM) that was making the credentials invalid.

Body:
Credentials are correct, database name is correct, MySQL users are set correctly and have all the privileges, I have entries for 'username'@'%' as well as 'username'@'localhost', I can connect to this user via commandline correctly, as well as through mysql workbench. In other words, everything works as it should and is set as it should be, except my java app is unable to connect.

I did about 3 clean uninstalls and installs of MySQL, with restarts, without restarts, tried to login through app as root (with pass) which didn't work, tried to login through app as user with no password (same error), etc.

Also, a PHP website running on localhost using precisely the same login works perfectly.

I've been checking and re-checking and trying all of this for the past 3 days, I went through all the related SO questions, all the blogs and docs I could find, all of it.

try {
  Class.forName("com.mysql.jdbc.Driver").newInstance();
  conn = DriverManager.getConnection("jdbc:mysql://localhost/correctDBname", "correctUsername", "correctPassword");
} catch(ClassNotFoundException | SQLException ex) {
  Logger.getLogger(SqlConnection.class.getName()).log(Level.SEVERE, ex.getMessage(), ex);
}

MySQL driver name precisely as it appears in NetBeans' "Libraries" section in project: MySQL JDBC Driver - mysql-connector-java-5.1.23-bin.jar

Full text of the exception:

java.sql.SQLException: Access denied for user 'strada'@'localhost' (using password: YES)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1074)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4120)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4052)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:925)
at com.mysql.jdbc.MysqlIO.proceedHandshakeWithPluggableAuthentication(MysqlIO.java:1704)
at com.mysql.jdbc.MysqlIO.doHandshake(MysqlIO.java:1250)
at com.mysql.jdbc.ConnectionImpl.coreConnect(ConnectionImpl.java:2465)
at com.mysql.jdbc.ConnectionImpl.connectOneTryOnly(ConnectionImpl.java:2498)
at com.mysql.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:2283)
at com.mysql.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:822)
at com.mysql.jdbc.JDBC4Connection.<init>(JDBC4Connection.java:47)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at com.mysql.jdbc.Util.handleNewInstance(Util.java:411)
at com.mysql.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:404)
at com.mysql.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:317)
at java.sql.DriverManager.getConnection(DriverManager.java:664)
at java.sql.DriverManager.getConnection(DriverManager.java:247)
at eu.storemedia.stradaserver.engine.SqlConnection.<init>(SqlConnection.java:23)
at eu.storemedia.stradaserver.engine.StradaServer.<init>(StradaServer.java:51)
at eu.storemedia.stradaserver.Home.<clinit>(Home.java:31)


问:
How to set value in odata of radiobuttons like inputfield
I am creating a form now. In a line I need only answer with yes or no. the Code now looks like this

<Input value="{appointments>flag}"
 id="flag"
 placeholder="set a flag in true or false"/>```
</div>
</div>
</p>

<p>and i need radiobuttons with yes or no. I have tried to write radiobutton, but it does not work</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code><Label text="Billable" />
<VBox binding="{appointments>flag}">
 <RadioButton  text="true"/>
 <RadioButton  text="false"/>
</VBox></code>```

the value property an the RadioButton is not allowed. How can i set the value from radioButton to the {appointments>flag} in ODatamodel like inputfield as above?

答:
You should try using data binding the control with the model.

```<code><RadioButtonGroup columns="3" width="500px" selectedIndex="{/flag}" buttons="{/buttons}"  select="radioSelectionHandler">
            <buttons>
                <RadioButton  text="{label}"/>
            </buttons>
        </RadioButtonGroup>
</code>```

You controller can be something like this

```<code>onInit: function() {
    var radioButtons = {
        "buttons":[
                      {
                          "key" : "true",
                          "label" : "True"
                      },
                      {
                          "key" : "false",
                          "label" : "False"
                      }
                  ] ,

    }

    this.getView().setModel(new  sap.ui.model.json.JSONModel(radioButtons));
},

radioSelectionHandler : function(event){
    var flag = this.getView().getModel().oData.flag;
    sap.m.MessageToast.show(this.getView().getModel().oData.buttons[flag].key);
}
</code>```

I added the key property which you use in if else check in controller rather than using the display text.
Hope this helps!

Body:
I am creating a form now. In a line I need only answer with yes or no. the Code now looks like this

<Input value="{appointments>flag}"
 id="flag"
 placeholder="set a flag in true or false"/>

and i need radiobuttons with yes or no. I have tried to write radiobutton, but it does not work

<VBox binding="{appointments>flag}">
 <RadioButton  text="true"/>
 <RadioButton  text="false"/>
</VBox>

the value property an the RadioButton is not allowed. How can i set the value from radioButton to the {appointments>flag} in ODatamodel like inputfield as above?

Body:
You should try using data binding the control with the model.

<RadioButtonGroup columns="3" width="500px" selectedIndex="{/flag}" buttons="{/buttons}"  select="radioSelectionHandler">
            <buttons>
                <RadioButton  text="{label}"/>
            </buttons>
        </RadioButtonGroup>

You controller can be something like this

onInit: function() {
    var radioButtons = {
        "buttons":[
                      {
                          "key" : "true",
                          "label" : "True"
                      },
                      {
                          "key" : "false",
                          "label" : "False"
                      }
                  ] ,

    }

    this.getView().setModel(new  sap.ui.model.json.JSONModel(radioButtons));
},

radioSelectionHandler : function(event){
    var flag = this.getView().getModel().oData.flag;
    sap.m.MessageToast.show(this.getView().getModel().oData.buttons[flag].key);
}

I added the key property which you use in if else check in controller rather than using the display text.
Hope this helps!