conditional formatting UI

Question: The app I'm working on is a calculator basically. What i want to do is to is set up something so that on the results screen if the answers all = 60 or higher a big green check (an image I'll place in) appears and some text above or below that says you passes. If not I want a red X to appear that says you fail.
I know this should be simple I just don't know where to look to get the answers. If someone could point me in the right direction with a link or something so i can read up on this that would great. because i have tried looking but i just don't know what to look for to be honest.
Comment: Does the user enter numbers in the fields?
Comment: yes the user enters numbers into the text field. Calculations are done on those numbers that are entered. and then a score comes up on the results screen and that is where i want the green check or red x to pop up
Answer: So you basically just need to get the text from the UITextField as an integer like so:
int sumOfFields += [[myUITextField text] intValue];

You would do that for all of your fields. Then you need to check if it's greater than or equal to 60 or not:
if (sumOfFields >= 60) {
    [self setValidationUI:TRUE];
}
else {
    [self setValidationUI:FALSE];
}

Where setValidationUI is a method that takes a boolean value that determines wether it should show the big green checkmark or a bit red X like so:
-(void)setValidationUI:(BOOL)isValid {
    if (isValid) {
        [resultsImage setImage:[UIImage imageNamed:@"checkmark.png"]];
        [resultsTextField setText:@"You Passed!"];
    }
    else {
        [resultsImage setImage:[UIImage imageNamed:@"BigUglyRedX.png"]];
        [resultsTextField setText:@"You Fail..."];
    }
}

header file
- (void)setValidationUI:(bool)isValid;

@property (nonatomic, retain) IBOutlet UIImageView *resultsImage;
@property (nonatomic, retain) IBOutlet UILabel *resultsLabel;

Comment: @Shaun: I've updated my code with a function like I was talking about. Does it all make sense now?
Comment: Yes, you need to put the method name `-(void)setValidationUI:(BOOL)isValid;` in the header, and the whole method in the m file. And then replace `resultsImage` and `resultsTextField` with the names you gave to those views in Interface Builder.
Comment: You need them named in Interface Builder. Then you need to add properties to the view that uses them: `@property (nonatomic, retain) UIImageView *myImageView;` Of course use your name for the views instead of 'myImageView'.
Comment: Ok i understand taking the text that will show up in my labels on the results screen and setting them to an integer. Then have the if / else statement to check if it is >= 60. But the "setValidationUI" how does that display a green check or red x? if i am going to be importing those 2 images into my project. how does "setValidationUI" call those images to be displayed and where would it display them?
Comment: Yes i think so. So the -(void) would go in my app delegate.h & .m ?? and then what ever image placeholder and textfeild or label i have setup on my results screen i link them that method in IB?
Comment: ok Thanks ill try n see what i can put together.. ill let you know how it works out
Comment: I put everything in but in the method it says use of undeclared identifier "resultsImage" and "resultsLabel" ? i named them in IB. Am i suppose to do soemthing else?
Comment: @Free Thanks.. I had to add an IBOutlet to the property and connect them in IB for it to work. But everything else was spot on.. Thanks again for your help :)

conditional formatting UI


How to display image using jquery

Question: How can I display the image in the following div id="image" using jQuery
HTML:

Images

jquery:
 $(document).ready(function(){
            var id = window.location.search.substring(1);
            id = id.replace('id=','');
            var url = "http://localhost/schoollife/services/author_chapter.php?a=image&id="+id;
            //alert(url);
            $.ajax({
               url:url,
               success:function(result){
                  var obj = $.parseJSON(result);
                  var table = "
";
                  for (var i = 0; i < obj.length; i++) {

                     table += "
"
                     table += "	";

                     table += "
";
                     table +="

";
                  }
                  table += "
";
                  $("#image").html(table);

                }
              });
            })

Thanks in advance.
Comment: use `` tag... i think the src in your script is not correct.. thus image is not displayed
Comment: `'http://img/"+obj[i].image_file_name+"` I think this should be without `http`, like `'/img/"+obj[i].image_file_name+"` or `img/"+obj[i].image_file_name+"`
Comment: What is not working? What is the PHP code you are using?
Comment: nothing is wrong with the above code, check your link that you pass in `SRC`
Comment: can you send me any link how to display image using jquery
Comment: Are you trying to call up a PHP file from localhost?
Answer: You rather rely on $.getJSON as it makes your code saying what you want to achieve with $.ajax - retrieving JSON-formatted data from a remote source. And check your server side code if it provides a valid JSON. Here is a working example:
$( document ).ready(function(){
      var url = "./author-chapter.json";
      $.getJSON( url, function( data ){
            var out = "
";
            $.each( data, function( i, row ) {
               out += "
";
               out += "	";
               out += "
";
               out +="

";
            });
            out += "
";
            $("#image").html( out );
      });
  });

Controller (author-chapter.json)
[
  {"image_file_name": "./slides/sample_fussen.jpg"},
  {"image_file_name": "./slides/sample_keukenhof.jpg"}
]

P.S. If you want to control exceptional behavior - just go with deferred methods - .done, .fail instead of the callback

How to display image using jquery


Not able to run AndroidViewClient

Question: I am get the all the Id's of the current screen without using the Source.
https://stackoverflow.com/questions/23333936/android-get-id-of-the-each-widget-in-the-screen-without-source
So I am using Androidviewclient
Have followed below steps
1) Downloaded the Androidviewclient-master.zip
2) unzipped and edited the dump file in the AndroidViewClient-master\AndroidViewClient\tools for the souce location
3) Set the Environment variable ANDROID_VIEW_CLIENT_HOME and PYTHONPATH
4) When i execute as below in cmd
C:\Users\Lahir\Desktop\Automation\adt-bundle-windows-x86_64-20131030\adt-bundle-windows-x86_64-20131030\sdk\tools>monkeyrunner.bat C:\AndroidViewClient-master\AndroidViewClient\tools\dump.py
Getting Error as below:-
Can't open specified script file
Usage: monkeyrunner [options] SCRIPT_FILE
-s      MonkeyServer IP Address.
-p      MonkeyServer TCP Port.
-v      MonkeyServer Logging level (ALL, FINEST, FINER, FINE, CONFIG, INFO, WARNING, SEVERE, OFF)
And also instead of dump.py if i run as dump as below
C:\Users\Lahir\Desktop\Automation\adt-bundle-windows-x86_64-20131030\adt-bundle-windows-x86_64-20131030\sdk\tools>monkeyrunner.bat C:\AndroidViewClient-master\AndroidViewClient\tools\dump
I am getting the following Error
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] Script terminated due to an exception
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]Traceback (most recent call last):
  File "C:\AndroidViewClient-master\AndroidViewClient\tools\dump", line 129, in
    vc = ViewClient(*ViewClient.connectToDeviceOrExit(**kwargs1), **kwargs2)
  File "C:\AndroidViewClient-master\AndroidViewClient\src\com\dtmilano\android\viewclient.py", line 1435, in connectToDeviceOrExit
    ViewClient.setAlarm(timeout+5)
  File "C:\AndroidViewClient-master\AndroidViewClient\src\com\dtmilano\android\viewclient.py", line 1395, in setAlarm
    signal.alarm(timeout)
  File "C:\Users\Lahir\Desktop\Automation\adt-bundle-windows-x86_64-20131030\adt-bundle-windows-x86_64-20131030\sdk\tools\lib\jython-standalone-2.5.3.jar\Lib\signal.py", line 222, in alarm
NotImplementedError: alarm not implemented on this platform
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyException.doRaise(PyException.java:219)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.Py.makeException(Py.java:1239)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.Py.makeException(Py.java:1243)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.Py.makeException(Py.java:1247)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at signal$py.alarm$14(C:\Users\Lahir\Desktop\Automation\adt-bundle-windows-x86_64-20131030\adt-bundle-windows-x86_64-20131030\sdk\tools\lib\jython-standalone-2.5.3.jar\Lib\s
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at signal$py.call_function(C:\Users\Lahir\Desktop\Automation\adt-bundle-windows-x86_64-20131030\adt-bundle-windows-x86_64-20131030\sdk\tools\lib\jython-standalone-2.5.3.jar\
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyTableCode.call(PyTableCode.java:165)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyBaseCode.call(PyBaseCode.java:134)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyFunction.call(PyFunction.java:317)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at com.dtmilano.android.viewclient$py.setAlarm$71(C:\AndroidViewClient-master\AndroidViewClient\src\com\dtmilano\android\viewclient.py:1395)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at com.dtmilano.android.viewclient$py.call_function(C:\AndroidViewClient-master\AndroidViewClient\src\com\dtmilano\android\viewclient.py)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyTableCode.call(PyTableCode.java:165)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyBaseCode.call(PyBaseCode.java:134)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyFunction.call(PyFunction.java:317)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at com.dtmilano.android.viewclient$py.connectToDeviceOrExit$72(C:\AndroidViewClient-master\AndroidViewClient\src\com\dtmilano\android\viewclient.py:1463)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at com.dtmilano.android.viewclient$py.call_function(C:\AndroidViewClient-master\AndroidViewClient\src\com\dtmilano\android\viewclient.py)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyTableCode.call(PyTableCode.java:165)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyBaseCode.call(PyBaseCode.java:301)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyFunction.function___call__(PyFunction.java:376)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyFunction.call(PyFunction.java:371)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyFunction.call(PyFunction.java:366)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyObject._callextra(PyObject.java:527)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.pycode._pyx0.f$0(C:\AndroidViewClient-master\AndroidViewClient\tools\dump:131)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.pycode._pyx0.call_function(C:\AndroidViewClient-master\AndroidViewClient\tools\dump)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyTableCode.call(PyTableCode.java:165)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.PyCode.call(PyCode.java:18)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.Py.runCode(Py.java:1275)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.core.builtin.execfile_flags(builtin.java:522)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at org.python.util.PythonInterpreter.execfile(PythonInterpreter.java:225)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at com.android.monkeyrunner.ScriptRunner.run(ScriptRunner.java:116)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at com.android.monkeyrunner.MonkeyRunnerStarter.run(MonkeyRunnerStarter.java:77)
140509 17:19:12.884:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]       at com.android.monkeyrunner.MonkeyRunnerStarter.main(MonkeyRunnerStarter.java:189)
Don't know how to get it? Need help please guide me.
Answer: I'm assuming you downloaded the latest version from github (.i.e. AndroidViewClient 5.4.7).
In such case, you don't need monkeyrunner, just python.
I think
python C:\AndroidViewClient-master\AndroidViewClient\tools\dump.py

should work (sorry, I'm guessing as I don't use Windows).
You could also give easy_install a try and keep AndroidViewClient up-to-date automatically.
Check How to use Python's "easy_install" on Windows ... it's not so easy for some hints.
Comment: Have already installed easy_install. About the version i have downloaded https://github.com/dtmilano/AndroidViewClient. In dump file  verion shows as __version__ = '5.4.5'.
Comment: Hi Thank you its running as you said rather than monkeyrunner using only python i am able to get. Thank you :).                       But one issue after running i am getting the following output C:\Python27>python C:\AndroidViewClient-master\AndroidViewClient\tools\dump
            android.widget.TextView  Hello ALLLL
            android.widget.Button com.example.pageindicator:id/gotoSurface Go to Surface
My doubt why i am not able to get the id for the Textview?? will i get the id for the Testview also
Comment: Ask another SO question to keep this organized
Comment: @dtmilano There is an AndroidViewClient 5.4.7??? All I can see on github is 5.1.1.
Comment: @dtmilano Oh wow. All I can find by just searching around is the older versions. But I upgraded with easy_install and now I got the 7.0.2. Is there a hangout where everyone talks about the latest stuff and has latest examples or some API? I assume github is outdated now?
Comment: Latest info about **AndroidViewClient/culebra** can be found at http://dtmilano.blogspot.com/
Comment: @dtmilano this is a dumb question but what does dump.py actually do? When do you use it? (I read the docs on your main site and still don't get it)
Comment: dumps the content of the screen. See it as a *logical* screenshot.

Not able to run AndroidViewClient


Playing video from a container

Question: I am trying to play a video from a URL. I am passing the video URL but the problem I have now is that I passed the video container into a UIView because I just want it to play in the container. now the video does not play.
 func setup() {
    playervc.view.frame = vidContainer.bounds
    self.addChild(playervc)
    vidContainer.addSubview(playervc.view)
    playervc.didMove(toParent: self)
    playervc.player?.play()
  }

extension ProfileVC: AVPlayerViewControllerDelegate {
    private func videoPlayer(url: String) {
        let videoURL = URL(string: url)
        player = AVPlayer(url: videoURL!)
        playervc = AVPlayerViewController()
        playervc.delegate = self
        playervc.player = player
    }
}

Comment: If it works outside of that view container, id assume it something to do with the layout not your code. Id double check there isn't something blocking the video in the ViewController
Comment: I can't understood these lines.  `self.addChild(playervc)
    vidContainer.addSubview(playervc.view)
    playervc.didMove(toParent: self)`. What is `self.addChild(playervc)` where you adding your **playervc** etc...
Answer:
playervc.videoPlayer(url: "Some Video URL")

call this function in setup()
func setup(){

   //This should be call in this function
   playervc.videoPlayer(url: "Some Video URL")

   playervc.view.frame = vidContainer.bounds
   self.addChild(playervc)
   vidContainer.addSubview(playervc.view)
   playervc.didMove(toParent: self)
   playervc.player?.play()

}

Playing video from a container


Why do mathematicians use $\oplus$ instead of $+$?

Question: What is the historical reason for using $\oplus$ instead of $+$ to denote operations that are generally thought of as addition? Similarly, why is $\otimes$ used instead of $\times$ (or just $\cdot$) to denote operations generally thought of as multiplication?
Comment: So you won't confuse them with $+$ and $\times$?
Comment: The symbol $\oplus$ is not synonymous with $+$. ${}\qquad{}$
Comment: In general, $\otimes$ and $\oplus$ are not user for such things. They are rather used for operations on algebraic objects such as rings, groups, algebras and modules.
Comment: @nathey: Sometimes we do overload those symbols. Other times it is important to make a distinction. This is not a mysterious issue, it is a simple question of people writing in a way that communicates their meaning.
Comment: @nathey: They did.  Then they come up with some different operations on algebraic objects that were also analogous to addition and multiplication, and needed new symbols to distinguish them.
Comment: The question is why did mathematicians of old not overload $+$ and $\times$ to algebraic objects as well?
Comment: @PedroTamaroff: Let me kow if I missunderstood you: Aren't these operations satisfying all on addition and multiplication as well? Regard the category of vector spaces for simplicity. That itself can be endowed with addition and multiplication taking its objects as elements. These will satisfy up to isomorphism all properties expected on addition and multiplication from associativity, commutativity up to distributivity. Especially zero will be the trivial space and one the field itself.
Comment: @EricWofsey: Do you have an example at hand?
Answer: If $A$ and $B$ are modules over a ring, their direct product $A \times B$ and their tensor product $A \otimes B$ are different things, so it would be unhelpful to use the same notation for them.
Answer: These symbols have different meanings in different contexts. For instance, if we are talking about vector spaces then saying $V=U+W$ is different from $V=U\oplus W$
Comment: Oh yeah, at least one case where $+$ and $\oplus$ coexist.
Comment: I'm assuming that was meant to be condescending. Can you give me an instance you speak of where $\oplus$ is used for something "generally thought of as addition"?
Comment: $\oplus$ isn't used anywhere for addition, but the question is why shouldn't it be? The answer is because of places where the two clash like this.
Answer: Besides customary uses, I've seen it used to emphathize the differences of two types of addition, for example: $(\alpha \oplus \beta)A+B$.
The $\oplus$ refers to regular scalar addition, and the $+$ refers to matrix addition.


Not able to stop Azure SQL MI

Question: I am trying to stop one of our SQL MI but it gives below error
Long running operation failed with status 'Failed'. Additional Info:'You cannot stop the instance that has running operation on an instance or on one or more of its databases. Please wait for ongoing operation to finish or cancel ongoing operation, then try again.'
when tried to find ongoing operation using Get-AzSqlInstanceOperation it returns nothing.
I checked in sys.dm_operation_status  and can see 2 operations are CANCEL_IN_PROGRESS state for last 3 days and seems like it's stuck. tried all options but no luck.
Any idea how I can restart my MI forcefully ?
Thanks
tried Azure portal and Powershell both and it didn't work.
looking for some next level of help
Comment: I removed the  tag since this isn't related to the ISO/ANSI SQL _language_. Instead you can add a tag for the dbms used.
Comment: According to [this](https://learn.microsoft.com/en-us/answers/questions/1339338/how-to-do-a-forced-restart-on-a-sql-managed-instan), there is no option to force a restart of an Azure SQL Managed Instance. You must wait until the cancel operation is completed.
Answer: Stop and Start an Azure SQL Managed Instance is still in preview. It is not possible to restart sql managed instance forcebly.
There is only a User-Initiated Failover, which does not guarantee a SQL MI Instance restart.
<code>$ResourceGroup = 'enter resource group of your MI'
$ManagedInstanceName = 'enter MI name'
Invoke-AzSqlInstanceFailover -ResourceGroupName $ResourceGroup -Name $ManagedInstanceName

</code>
For more information you can refer this

Not able to stop Azure SQL MI


Download a folder to the FileSystemStorage

Question: In an app, I need to download html pages (along with css, images and js files) from server to the FileSystemStorage and then display it on device. With Util.downloadUrlToFile I can download the files individually but is there any way to download the entire folder to device?
Answer: No, since there is no such concept of a directory in HTTP. You can download a file but you won't know there are other files next to it. One of the things apps do is parse the HTML/CSS to find other referenced files and download them. That's a HUGE pain.
Another option is to zip or tar the files together and unzip them locally.


Taxonomy tags are not saved - Field API - Drupal 7

Question: I am creating a new content type and I want to add a Tags field. I created a  vocabulary and a taxonomy_term_reference, field  but this field is giving this notice every time I try to add content and click save:

Notice: Undefined index: tid in taxonomy_field_is_empty() (line 1562 of /var/www/html/drupal/modules/taxonomy/taxonomy.module).

This is the code I am using.
news.install
function news_install() {
  node_types_rebuild();
  $types = node_type_get_types();
  // Add the body field to the node type
  node_add_body_field($types['news']);

  // Load the instance definition for our content type's body
  $body_instance = field_info_instance('node', 'body', 'news');
  // Configure the body field
  $body_instance['type'] = 'text_summary_or_trimmed';
  // Save our changes to the body field instance.
  field_update_instance($body_instance);
  // Create all the fields we are adding to our content type.
  foreach (_news_installed_fields() as $field) {
    field_create_field($field);
  }

  // Create all the instances for our fields.
  foreach (_news_installed_instances() as $instance) {
    $instance['entity_type'] = 'node';
    $instance['bundle'] = 'news';
    $instance['required'] = True;
    field_create_instance($instance);
  }

  // Create vocabulary for tags
  $news_tags_vocab = (object) array(
    'name' => 'Tags vocabulary',
    'description' => 'This vocabulary is used for the tags field',
    'machine_name' => 'news_tags_vocab',
    );

  taxonomy_vocabulary_save($news_tags_vocab);
}

function _news_installed_fields() {
  $t = get_t();
  return array(
    'news_title' => array(
      'field_name' => 'news_title',
      'label' => $t('Title'),
      'type' => 'text',
      ),
    'news_image' => array(
      'field_name' => 'news_image',
      'label' => $t('Image'),
      'type' => 'image',
    ),
    'news_tags' => array(
      'field_name' => 'news_tags',
      'label' => $t('Add Tags'),
      'type' => 'taxonomy_term_reference',
      'settings' => array(
        'allowed_values' => array(
          array(
            'vocabulary' => 'news_tags_vocab',
            'parent' => 0,
            ),
          ),
        ),
      ),
    ),
  );
}

/**
 * Return a structured array defining the field instances associated with this content type.
 */
function _news_installed_instances() {
  $t = get_t();
  return array(
    'news_title' => array(
      'field_name' => 'news_title',
      'type' => 'text',
      'label' => $t('The heading of the news topic'),
      'widget' => array(
        'type' => 'text_textfield',
      ),
      'display' => array(
        'news_display_option' => array(
          'label' => $t('The heading of the news topic (display option)'),
          'type' => 'text',
          ),
        ),
      ),
      'news_image' => array(
        'field_name' => 'news_image',
        'type' => 'image',
        'label' => $t('Add Image'),
      ),
      'news_tags' => array(
        'field_name' => 'news_tags',
        'type' => 'taxonomy_term_reference',
        'label' => $t('Add Tags'),
        'widget' => array(
          'type' => 'taxonomy_autocomplete'
        ),
        'display' => array(
          'default' => array('type' => 'hidden'),
          'teaser' => array('type' => 'hidden')
        ),
      ),
    )
  );
}

/**
 * Implements hook_uninstall().
 */
function news_uninstall() {
  // Delete the taxonomy with its terms
  $vocab = taxonomy_vocabulary_machine_name_load('news_tags_vocab');
  taxonomy_vocabulary_delete($vocab->vid);

  // Gather all the example content that might have been created while this
  // module was enabled.
  $sql = 'SELECT nid FROM {node} n WHERE n.type = :type';
  $result = db_query($sql, array(':type' => 'news'));
  $nids = array();
  foreach ($result as $row) {
    $nids[] = $row->nid;
  }

  // Delete all the nodes at once
  node_delete_multiple($nids);
  // Loop over each of the fields defined by this module and delete
  // all instances of the field, their data, and the field itself.
  foreach (array_keys(_news_installed_fields()) as $field) {
    field_delete_field($field);
  }
  // Loop over any remaining field instances attached to the news
  // content type (such as the body field) and delete them individually.
  $instances = field_info_instances('node', 'news');
  foreach ($instances as $instance_name => $instance) {
    field_delete_instance($instance);
  }
  // Delete our content type
  node_type_delete('news');
  // Purge all field infromation
  field_purge_batch(1000);
}

What's wrong in my code, and how can I fix it?
Answer: The solution for this problem is to implement Hook_form()
So, the following code must be added into news.module file.
function news_form($node, $form_state){
  return node_content_form($node, $form_state);
}

Tricky but easy :)


How to dynamically add codepen embed and ensure it is rendered?

Question: Desired Behaviour
Show embedded codepen in an environment where registered users can edit page content.
There may be more than one codepen added to a page.
Actual Behaviour
When adding a pen to the DOM, the pen does not display, only a link to the pen is displayed.
Steps To Reproduce
Note: the steps below are just to demonstrate the logic that would take place in my own environment, ie a registered user editing content on a website.
01)  Go to this randomly selected pen
02)  Click on the Embed link at the bottom right of the page
03)  Copy contents from the HTML (recommended) tab
04)  Go to https://blog.codepen.io/documentation/features/embedded-pens
05)  Open Chrome developer tools, and replace a paragraph element with the embed code
06)  The pen will not be displayed, only a link like:
See the Pen [pen_name] by [pen_author] on CodePen

Question
What additional steps do I need to make to ensure the codepen is rendered?
Given that the format of the embed code is:

    See the Pen
            Clip Clop Clippity Clop by Steve Gardner (@ste-vg)
        on CodePen.

it does seem a bit presumptuous to expect the script will just do its job when pasted in the page.
If that is the case, how do I dynamically add the contents (including the script tag) and ensure it is executed?
EDIT
I just came across this answer from 2010, which suggests this format:
$.getScript("https://static.codepen.io/assets/embed/ei.js", function(){
    console.log("running new js!");
});

and when I run that in Chrome dev tools, after pasting the embed code in the DOM, the pen is rendered.

Is there anything wrong with this approach?
Why doesn't pasting the embed code in the DOM 'just work'?
Is the script file referenced in the embed code unique to the pen?
Or could you just add the script to your page once and it would handle all embedded pens (both existing and those dynamically added)?

I tried adding this to :

and having it there doesn't seem to parse existing or dynamically added embed code.
They still just display the message:
See the Pen [pen_name] by [pen_author] on CodePen

EDIT AGAIN
With script referenced in , I tried calling this after dynamically adding the HTML to the DOM:
__CPEmbed()

And it renders the codepens!
I'm not sure if it is a legitimate way to do it, but I came across __CPEmbed at the end of the article here:
https://blog.codepen.io/documentation/prefill-embeds
Answer: I see you've figured it out! Yes, __CPEmbed() is the official API for triggering the iframe insertion. You can even feed it a specific selector if there are certain embeds you want to target: __CPEmbed('.my-codepen-embed')
It's triggered by default when the document.readyState !== 'loading', but you can call it at any time. Multiple calls should not affect already converted embeds.
I couldn't find this in our regular Embed documentation anymore, so I'm making a note to update that.
Thanks!
Comment: @user1063287 There was a temporary issue with the CodePen embed script ( ei.js ) that has since been fixed. It should work as expected now.
Comment: hello - has this changed at all, i *just* started getting the error `Uncaught ReferenceError: __CPEmbed is not defined` when calling `__CPEmbed();` - it was working yesterday I think, and it is possible i changed something elsewhere in a recent coding frenzy and that is causing it, but just thought i'd ask, thanks.  script is linked to in template html page:  ``
Comment: specifically, the error is:  `Uncaught ReferenceError: __CPEmbed is not defined at Object.success (common.js:1945) at fire (jquery.js:3291) at Object.fireWith [as resolveWith] (jquery.js:3421) at done (jquery.js:9533) at XMLHttpRequest.eval (jquery.js:9785)`
Comment: thank you @shshaw - i can confirm this error message is no longer displaying, thank you.


How Do I Count Note Durations In These Bars?

Question: I am learning a piece at the moment which is in 4/4, however some bars look like they should be 12/8, and I am confused about the mixing of notation of sometimes triplets sometimes not. Here is the section in question:

Consider bar 48. The right hand is an easily interpretable 4/4. But the bass staff is confusing. Ignoring the whole note in the extra voice, the first things we see are a quarter note rest, then a quarter note, and then two eight notes beamed together. Okay, that's 3 quarters used up of our 4 in 4/4. But there's still some eight note triples (another quarter), followed by three more eight notes.
So counting the left hand in 4/4 makes no sense. But, if we ignore the triplet of the third beat, then counting the left hand in 12/8 does make sense (albeit with bad beaming). But then the right and left hands don't match up in time properly. What am I missing here? To play this I've counted both staves as 12/8 (while playing the right hand notes as if they are dotted), but I am not certain how accurate I am being (and the original piece is very fast, so I can't figure it out by ear).
Then take bar 50. Right hand looks like a 12/8 (not paying attention to meter at the moment), left hand looks like a 4/4. Is the rule "because triplets are notated in one staff, if there's vertical alignment with quarter notes of the other staff, then it implies triplets in the other staff"? Or am I missing something else?
Comment: Hey neat, what piece is your excerpt from?
Comment: @Alan Just from looking at it, my guess was that everything was supposed to be triplets and it's just a bad engraving. After listening to it, that's definitely the case. Just go write little 3's above everything in the left hand and it should make sense again.

Also, this is an unofficial transcription, which explains the poor engraving. I'm betting the actual book has it written more clearly.
Comment: @Dekkadeci Neat? **Neat?!**
Comment: Yeah. What **is** it?
Comment: "The original piece is very fast, so I can't figure it out by ear", yes you can. Tap out the beat to the recording and sing whichever line you're struggling with. Once you can do that -- you don't need to sing particularly well or even in tune -- you can do the same thing at a slower rate.
Comment: I reckon it's very poorly written. Actually - what is it. Peter's idea is good, but with no identification, that's nigh on impossible. 'Cos it's pretty well unplayable as it stands. And it doesn't stand well. I'd even upvote the question with that information!
Comment: Thanks for the answers (and reassurances that I am not going mad!) The piece is from the video game FFXV. Originally a piano/violin/vocal piece called Somnus by Yoko Shimomura, this piano version is called Dreaming of the Dawn and was arranged by a Japanese composer who works for the game's developers, called Sachiko Miyano. Here is the piece, with sheet music: https://www.youtube.com/watch?v=fjKD2llwi_A&ab_channel=Tobik. (2:35 is where this section comes in) It's worth noting that every FF game has a piano collections album, and usually the transcription quality is excellent.
Comment: @PeterSmith, 100% whenever I can't figure out sheet music I slow the piece down and tap out by ear. As I mentioned, when I tap it out, I hear it as a 12/8. That's what my ear is telling me... this question is me saying "agh, I think I am right but someone help me be certain!"
Answer: The first (and second) bar are odd.  It would add up if the first two items in the LH - the rest and the chord, were 8ths rather than quarters.  A misprint, or just rule-breaking?  Did the composer want a 5/4 bar? Or maybe he wants a half-bar triplet, as in bar 50.  I suspect the latter.  But we shouldn't have to guess.  BAD composer!
Apart from that bar, it seems to be just sloppy inclusion of triplet numbers.  Sometimes he's put them in, sometimes we have to infer them. But it's pretty clear where they need to go to make everything add up.  (Maybe the first 'big' triplet would be clearer as a 6:4 rather than a 3:2?   But you get the idea.)

What's the piece?   A transcription by a talented but slightly ignorant musician perhaps?
Comment: dv'd due to the middle paragraphh.
Comment: For a second I was wondering what LH meant. Left Hand?
Comment: It's not clear at all in bars 48 and 49. Please enlighten us with your solution.
Answer: This is 4/4 time with triple 8th and triple quarter notes, but the triple sign is lacking in the first 2 bars shown on the beat 4 (with the triple 8th rest) and it should be notated also in the r.h. in the next measure (analogous to the l.h.)
Bad lay out, unclear notation. But there's no doubt about the intention to me. The placement of the note heads is correct and tells everything.
Comment: The layout's OK.  He's just left out some '3' markings.
Answer: You don't count note durations in these bars. The way they're written makes them uncountable.
Whether it's written in 4/4 or 12/8 doesn't make a lot of difference - were it written properly. Of course it will sound like 12/8 in parts - that's what the triplets do. But that's not the problem. It sounds a little (to me) at the point in question that there's a lot of rubato being exploited - which could be (if so) written into the dots so much more clearly. It's my guess that that's what's going on, but the writer just stuck extra beats in instead. Or that's what the computer writing mechanism felt was the best way to portray it.
Comment: There are surely no extra beats, just saloppe  or incorrect notation.
Comment: Keep saying it - please explain dvs - it's really positive and good for development.
Comment: An over-complicated analysis I think!   The note spacing strongly suggests that all we need to correct this is a few '3' markings.
Comment: @LaurencePayne - the second half of bars 48 and 49 will work - how would you propose to triplify the first half of each?
Comment: Triplet over the first half of the bar, as in bar 50.  Three quarter notes in the time of two.  No matter that one's a rest and one's subdivided, the triplet still works.
Comment: @LaurencePayne - fair enough. I missed that. Tried to retract dv, not allowed to. Damned 'rules'. Still stand by my first paragraph - 'as written...'
Comment: @Tim If you WANT to retract the dv, I've just made a small edit to my answer, so you should be able to!   Yes, rules are sometimes applied too pedantically round here :-)
Answer: Maybe (just maybe) the intended interpretation is for LH's middle voice to play an eigth triplet while LH's upper voice plays four normal eigths (one of them being a rest). Meaning that E4 should be played slightly sooner and shorter than the corresponding E3 below.
This would explain why the eigth rest is placed above the staff, in line with LH's upper voice, instead of right in the middle like the quarter rest.
(If that was indeed the intention, I agree that it is bad notation.)


How can I display only list[i] from the function?

Question: I have rewritten this code below and in the main function I am calling the push_front function like this:  push_front( &link[i], rollnumber, src, dst, gentime );
My question is how can I display only link[i], for example link[1]?
 int push_front( Node **head, int rollnumber, int src, int dst, double gentime )
{
    Node *new_node = malloc( sizeof( Node ) );
    int success = new_node != NULL;

    if ( success )
    {
        new_node->rollnumber=rollnumber;
        new_node->src = src;
        new_node->dst=dst;
        new_node->gentime=gentime;
        new_node->next = *head;
        *head = new_node;
    }

    return success;
}

void output( Node **head )
{
    for( Node *current =*head; current != NULL; current = current->next )
    {
        //printf( "%d %d %d %0.1f ",current->rollnumber, current->src, current->dst, current->gentime );
        printf("Roll Number:%2d\t",current->rollnumber);
        printf("src:%2d\t", current->src);
        printf("dest:%2d\t", current->dst);
        printf("gentime:%0.1f\n", current->gentime);
    }
    printf( "%s\n", "NULL" );
}

void display( Node **set, size_t n )
{
    for ( size_t i = 0; i <= n; i++ )
    {
        output( set++ );
        putchar( '\n' );
    }
}

The output I am getting when I display all the lists is down below:
Roll Number: 6  src: 1  dest:10 gentime:64.1
Roll Number: 5  src: 1  dest: 4 gentime:51.5
Roll Number: 4  src: 1  dest:17 gentime:38.0
Roll Number: 3  src: 1  dest:20 gentime:25.9
Roll Number: 2  src: 1  dest:15 gentime:13.9
Roll Number: 1  src: 1  dest: 3 gentime:1.6
NULL

Roll Number: 6  src: 2  dest:17 gentime:64.8
Roll Number: 5  src: 2  dest: 6 gentime:52.6
Roll Number: 4  src: 2  dest: 5 gentime:39.5
Roll Number: 3  src: 2  dest:20 gentime:26.0
Roll Number: 2  src: 2  dest:19 gentime:14.0
Roll Number: 1  src: 2  dest: 4 gentime:1.9
NULL

...and etc. for all the variables : src
The list[i] is based on the variable: src. So, how can I only print for only src: 1?
Comment: Because of the structure of lists, each node is connected via pointer to the next node, (from head to tail if non-circular) thus they are accessed differently than arrays (eg. array of struct.). The next node then would not be represented by `list[i]`, rather `list = list->next` .
Comment: @ryyker isn't it possible to display only first link from the function I already have?
Comment: Not as is.   The output function will have problems with `for( Node *current =*head; current != NULL; current = current->next )`.  For one, the center expression should check `current->next != NULL` rather than `current!= NULL`.  But then the third expression will also error out when the assignment is made using an uninitialized pointer value `current->next` .  If you want to print only members of head node, then pass head pointer as an argument into a function that simply takes a node pointer, and output the member values
Comment: See edit in answer for example of very simple method to output members of one node.  (without error checking, which you should add if plan to use.)
Comment: in one comment you've used the phrase  'first link', in another you've used 'one list'.  In your original post  'list[i]' is used.  ('list[i]' is array notation, not typically used when working with lists.) If I'm not mistaken they all seem to suggest the same thing.  I.e. that you want to output _one node of a list_.  If that is correct then the most recent edit in my post shows how to do that.  If not please clarify your question.  Keep in mind a 'list' is a collection of  pointers called 'nodes'.  Each node points to one instance of the data contained as well as another node(s).
Comment: If indeed your intent is to output the entire list, then the first part of my post ('display(...)') Illustrates that.
Comment: @ryyker you are right! It was my fault and I just edited my actual question above. I meant to say, that I want to display only link[1], as it is in the push_front function as arguement: push_front( &link[i], rollnumber, src, dst, gentime );.  Thank you for your help!
Answer: Modify your prototype to pass the list.  Because you are not changing anything, it does not need to be a pointer to pointer.  Then traverse the list until the  condition meets the criteria:
In pseudo code:   (Assuming you have a Node *next member...)
void display( Node *set, size_t n )//you do not need size of list here
{                                  //but you can use n to indicate node to output
    Node *temp = set;

    if(temp->src == n)//check head node
    {
        output(temp)
        return;
    }
    while(temp->next)//check all remaining nodes in list
    {
        temp = temp->next;
        if(temp->src == n)
        {
            output(temp)
            return;
        }
    }
    ...

EDIT  to address question in comments about outputting a single node.  Once list is created, output() can be called from anywhere that has visibility of the list.
void output( Node *h )//
{
    printf("Roll Number:%2d\t",h->rollnumber);
    printf("src:%2d\t", h->src);
    printf("dest:%2d\t", h->dst);
    printf("gentime:%0.1f\n", h->gentime);
}

For example, In an example main()
int main(void)
{
    Node *head = malloc(sizeof(*head));
    memset(head, 0, sizeof *head); //initialize
    push_front(&head, 1, 10, 100, 1.0); //first node
    push_front(&head, 2, 20, 200, 2.0); //first node
    push_front(&head, 3, 30, 200, 2.0);//first node,
    output(head); //outputs 1st node
    head = head->next;//points to 2nd node
    output(head); //outputs 2nd node
    head = head->next;//points to third node
    output(head); //outputs 3rd node.
    ...

Note that because your code used a push_front method, each new node is placed at the beginning of the list, making each new addition the first node.
As mentioned in comment, this would need to be bolstered with error checking before use in a real application.
Aside, do not forget to include some free() statements in your code to prevent memory leaks.
Comment: thank you for your time, but still can't figure out how to achive displaying only one list
Comment: After your edit I have not understand how can I display a specific head I want, for example not the first but the third one as first.
Comment: After the third 'push_front()' in the example above you have the head node.. Traverse two nodes to the third one by setting 'head = head->next' twice. Now head is pointing to the third node. Pass it to output.
Comment: @wajaap - see edited last example.


Using matrix operations to wrap arrays

Question: I'm coding with Maple and I need an efficient way to wrap arrays of numbers to different dimensions.  For example, let $A$ be the 3x5 matrix listing the numbers 1-15 in order, and $B$ be the 5x3 matrix of the same numbers.  Is there an easy way to relate these two matrices in terms of matrix algebra?
Comment: I think you're looking for a function or operator that will be called reshape
Comment: Do you want to vectorize the matrices? https://en.wikipedia.org/wiki/Vectorization_%28mathematics%29
Answer: Leaving aside the question of relating the matrices using matrix algebra, if you simply want to reshape the matrix of values in Maple you have a couple of options:
In the ArrayTools package, you can use the Reshape command to copy the original data to a new matrix with the specified shape. The Alias command can also provide a different view (shape) of the data and does not create a copy of the underlying data, however if you do change the underlying data, this may have some adverse effects. Note that neither of these commands change the underlying order of the elements. Here's an example:
<code>data := Array(seq([1..15]));
A := ArrayTools:-Reshape(data, [3,5]);
B := ArrayTools:-Reshape(data, [5,3]);
</code>

Using matrix operations to wrap arrays


Distribution of difference of two random variables with chi-squared distribution

Question: Supose that we have two random variables $X \sim \chi_k^2$ and $Y \sim \chi_k^2$, with the same degrees of freedom.
A chi-squared distribution cannot have zero degrees of freedom, so what would be the distribution of $X - Y$ ?
Comment: [From Maths stack exchange](https://math.stackexchange.com/questions/85249/distribution-of-difference-of-chi-squared-variables)
Comment: The technique at https://stats.stackexchange.com/questions/72479/generic-sum-of-gamma-random-variables/72486#72486 will work because chi-squared variables are scaled gamma variables.
Comment: Even assuming $X$ and $Y$ to be independent, there is no result that states that difference of two independent chi-squared variables is also a chi-square variable.
Answer: This is not a chi-squared density, $X-Y$ will have support on $(-\infty, +\infty)$.
If the two variables are independent, it has mean 0 and variance $4k$.
If $k$ is large, its density is well approximated a normal variable with 0 mean and $4k$ variance. In the general case, its MGF has a closed form:
$$E(\exp(t(X-Y))) = (1-4t^2)^{-k/2}$$
If the 2 variables have dependence, the nature of that dependence needs to be explicited.
Comment: This MGF can be inverted (by sight if you have ever considered the MGF of the Student t distribution) to give the density function in terms of the Bessel $K$ function, $$f_{X-Y}(x)=\frac{2^{\frac{1}{2}-k } \left| x\right| ^{\frac{k -1}{2}} K_{\frac{k -1}{2}}\left(\frac{\left| x\right| }{2}\right)}{\Gamma \left(\frac{k }{2}\right)}.$$
Comment: @whuber When $k=2m$ is even, a partial fraction expansion of $(1-4t^2)^{-m}$ into a sum of fractions with denominators $(1-2t)^{-j}, j = 1,2, \ldots, m$ and $(1+2t)^{-j}, j = 1, 2, \ldots, m$ is possible and so we can deduce that the pdf of $X-Y$ is proportional to a mixture of $\chi_j^2$ pdfs, $j = 1, 2, \ldots, m$ as stated in my answer here.  No Bessel K functions need be invoked here.
Comment: @Dilip Thank you for clarifying that point.  I presented the Bessel function solution because it is (a) immediate and (b) completely general -- but it's nice to have the simplification in special cases.
Answer: Since $X$ and $Y$ can also be considered to be Gamma random variables with (order, rate) parameters $\left(\frac k2, \frac 12\right)$, then, as Sebapi points out, $X-Y$ has support $(-\infty,\infty)$.  Furthermore, if $X$ and $Y$ are assumed to be independent, then the pdf of $X-Y$ is also symmetric about $0$ and has mean zero.
For independent $X$ and $Y$, the pdf of their difference $X-Y$ is the cross-correlation of the pdfs of $X$ and $Y$ (not the convolution of the pdfs as happens for the sum $X+Y$) and in this case, since the pdfs are identical, the cross-correlation is actually an autocorrelation and so the pdf of $X-Y$ is symmetric about $0$ as claimed.  Furthermore, for the case here of $X$ and $Y$ being Gamma random variables, an explicit form can be deduced from this answer of mine here on stats.SE.
When $k$ is an odd number, then, as noted in my answer cited above, it is possible to write the pdf $f_{X-Y}(z)$ of $X-Y$ in terms of polynomial, exponential, and Bessel functions of  $z$.  However when $k$ is an even number, then for $z \geq 0$, $f_{X-Y}(z)$  is proportional to a mixture of Gamma pdfs with (order, rate) parameters $\Gamma\left(1, \frac 12\right), \Gamma\left(2, \frac 12\right), \ldots, \Gamma\left(\frac k2, \frac 12\right)$ pdfs (equivalently, $\chi_2^2, \chi_4^2, \ldots, \chi_{k}^2$ pdfs) and of course, since $f_{X-Y}(z)$ is an even function of $z$, the same curve "flipped over" is the pdf curve on the negative axis.
Those worried that Gamma pdfs have value $0$ at the origin whereas autocorrelation functions have a maximum at the origin and so something is awry in the above claims should relax. A $\chi_2^2$ pdf is an exponential pdf which has nonzero value (or a limiting value that is nonzero at the origin for those whose exponential random variables take on values only on the positive real line) and so that mixture pdf is indeed nonzero at the origin, and because of the weights in the mixture, indeed a maximum at the origin.
Answer: Using the following links and parameter correspondence between the characteristic function(chf) of difference of $\Gamma(\alpha,\nu_{\Gamma})$ and $VG(\sigma,\nu)$ symm. variance gamma rvs we can obtain density of $X-Y$ indirectly, alternative to the method of chf inversion,
\begin{equation}
\phi_{VG}(u,\sigma,\nu)=\left(\frac{1}{1+\frac{\nu u^{2}\sigma^{2}}{2}}\right)^{\frac{1}{\nu}}
\end{equation}
\begin{equation}
\phi_{\Gamma}(u,\alpha,\nu_{G})=\left(\frac{1}{1+\nu_{\Gamma}^{2}}\right)^{\alpha}
\end{equation}
\begin{equation}
\sigma=\nu_{G}\sqrt{2\alpha}\\
\nu=\frac{1}{\alpha}
\end{equation}
and the fact that $\chi^{2}(k)\sim\Gamma(\frac{k}{2},2)$, we can see that final density will be almost the same as @whuber's formula above with minor differences.
\begin{equation}
f_{X-Y}=\frac{2^{-k}|x|^{\frac{k-1}{2}}K_{k-\frac{1}{2}}\left(\frac{|x|}{2} \right)}{\sqrt{\pi}\Gamma\left(\frac{k}{2}\right)}
\end{equation}
Following MC experiments with 2 and 10 df and 100K simulations respectively, provides a good match.


Retrieve SQS Messages-available/Message-in-flight using Node.js Aws-sdk

Question: I need to get the number of SQS messages available and messages in flight using aws-sdk with javascript.
Can someone please give me some kind of reference or code snippet?
I need metadata for this SQS. I can send Messages and read it but need this info to conclude if there is high load on my infrastructure
Answer: You can make use of GetQueueAttributes. As per your requirements, fetching only ApproximateNumberOfMessages, ApproximateNumberOfMessagesNotVisible, ApproximateNumberOfMessagesDelayed should suffice. You can read more about these parameters here.
Sample code to get you moving:

var params = {
  QueueUrl: '<sqs_queue>',
  AttributeNames: [
    ApproximateNumberOfMessages,
    ApproximateNumberOfMessagesNotVisible,
    ApproximateNumberOfMessagesDelayed
  ]
};
sqs.getQueueAttributes(params, function(err, data) {
  if (err) console.log(err, err.stack);
  else     console.log(data);
});


Multiple vCPUs or multiple identical VMs, which is better?

Question: I am looking to upgrade one of our servers, an 8 core server running VMware Server 2. The VMs it runs are mostly web, file, and email servers; specifically, it runs three webservers, 2 email/file servers, and a few Jabber/XMPP Servers.
When we originally set this machine up, we had the two web servers configured with two vCPUs. We had some very serious performance issues. At the time we were only running 3 VMs with a total of 5 vCPUs. We were also running VMware Server 1 and a RAID1. We have now upgraded to a RAID10 and I would never consider anything less! :-)
The new server will have VMware ESXi on it instead of VMware Server. We are looking at either another 8-core machine with faster processors, or a 16- or 32-core server. I want to make sure that I avoid the issues we had before.
Because I had such issues with multiple vCPUs before, my plan was to replace the primary web server VM with multiple identical webserver VMs (2 - 4), each with a single vCPU, serving content from an NFS share, and place these in a load-balanced configuration. SO I would basically be replacing one VM with at least 4: 2 small webserver VMs, a file server VM, and a load balancing VM. My plan here being twofold: First, I can avoid any multiple vCPU isuses I saw before, and secondly, I can spawn new web server VMs to handle increased load.
Note that I understand I am not getting all the benefits of the load balancing because I still have a single point of failure.
Is this a good plan, or is it unnecessary? Can VMware ESXi handle multiple vCPUs better than VMware Server 1 could over three years ago? Which will perform better, a single large webserver VM with 2 - 4 vCPUs, or 4 VMs with a single vCPU, in a load-balanced configuration?
Comment: @Vick, where does it recommend that? isn't that old news?
Comment: @Chopper3 - Top of page 8 - http://www.vmware.com/pdf/exchange_best_practices.pdf  (yes it is exchange specific, but it was published in 2010.)
Comment: @Chopper3♦, There's a lot of talking on the web about this topic, dozens of pages of white papers and discussions which come with the conclusion I stated. Look for "recommended vcpu per vm" in google. There's a lot of material about it.
Comment: As you probably aware, VMware suggests using 1vCPU per VM, unless you have a software that will actually not only benefit but can actually utilize multiple CPUs.
Comment: That's exactly what I wanted to know @Vick. As far as I could tell, the docs that said that were years old.
Comment: Thanks guys, I really didn't think that was still a valid recommendation but I guess I'm wrong, thanks again.
Answer: Can VMware ESXi handle multiple vCPUs better than VMware Server 1 could over three years ago?
Yes, they're totally seperate product lines, and ESXi can handle multiple vCPUs very well. I'm running a 5 node vmware farm right now with a mix of machines on each box, each with 1, 2 and in some cases 4 processors as needed and it works very well indeed.
Which will perform better, a single large webserver VM with 2 - 4 vCPUs, or 4 VMs with a single vCPU, in a load-balanced configuration?
That's less of a VMWare question and more of a application/website testing question. VMWare (or any other modern bare metal virtual machine) can do either way - there might be a cost to having lots of vCPUs attached to one guest but this might be offset by the resource costs of having multiple guests running and by performance issues (or improvements, for that matter) your web application might realise from a more distributed approach.
On that last issue, its really a matter of testing and architectural preferences rather than the one true way, but my general feeling is that if you can distribute the application over more than one virtual machine easily, its better to build a few smaller virtual machines than one big one. Gives you more flexibility and helps performance in the long run as you can move things about if you have to. In other words, scaling outwards rather than upwards
With physical machines I think we think of scaling upwards, putting as much into one OS "instance" as possible to get the most out of the cost of the licence and of the hardware, but with virtual machines those equations change a bit - if you can get more than one virtual OS instance for the price of a licence then this might change the way your server infrastructure is designed.
edit
http://blog.peacon.co.uk/understanding-the-vcpu/ is an article Iain mentioned while discussing this question in chat that explains in some detail why its important to think about vCPU allocation when creating your VMs.
Comment: Definitely its something to be tested.  But VMware still recommends single vCPUs over more, as the hypervisor must schedule two simultaneous free cpus instead of one to schedule for the VM.  That creates more overhead.
Comment: Agreed on the vCPU count.  Recent ESX/ESXi versions have gotten much more scalable, the vCPU per physical core limit has gone up from 8 (in 3.5) to 25 (in 4.1).  Not that it's wise to hit the limit (the core you're splitting 25 different ways is still just one core).  If your CPU resources aren't in contention, then it can definitely be worthwhile to have extra compute resources available to VMs under heavier load.
Comment: Just revisiting this question, a year after we made the switch. **VMWare ESXi is indeed running many VMs with multiple vCPUs with no issues whatsoever**. We did go with a 32-core host and have multiple VMs with 2 and 4 vCPUs each, all running great. The improved performance of ESXi over VMWare Server blew me away. No issues with ESXi at all, it's working great.
Comment: @Steven - absolutely agree, its a balancing act, I think. You have to balance any requirement for raw power against a loss of flexibility if you're going to put a lot of guests on the host.
Answer: I can tackle this question in a number of ways, but I'll start of with horizontal vs. vertical scaling.
Horizonal scaling

Pros

Can scale very large
Can scale across hosts (ie a vmware cluster)
Fault tolerant
Low/No downtime during maintenance

Cons

More overhead from VM OSes and Load Balancers
More maintenance/management (eg patching, SSL certs)
More website version management across web servers
Additional testing and development may be required for web site behind load balancer
Licensing?

Vertical Scaling

Pros

Scales easier (just add another vCPU or two, or more memory)
Only one web server to manage, license, etc.

Cons

Downtime during maintenance/upgrades
Scaling too big can cause performance issues in a VM.
Doesn't truly scale.

So, both have their goods and bads, and I am a big fan of horizontal scaling, but here's what I'd recommend to you:

Scale vertically to a certain point (I'll get to that certain point in a minute).
Do your homework on what it is going to cost time and money wise to get going horizontally.
Give yourself plenty of time to test your horizontal scaling solution.
When you've reached the point where it's time to scale horizontally, you can ramp back down your vertically scaled server, make some clones, throw them behind your already configured load balancer, and watch it rock and roll.

Okay, so what is that certain vertical scaling point?
It depends on your hardware.
VMware has done a lot to vCPU scheduling since ESX 2.x, and there is more room to grow vertically. How much really depends on the CPUs you get.
Sizing VMs for performance nowadays requires understanding of NUMA (Non-Uniform Memory Access. Basically, you don't want a VM to be bigger than your CPUs NUMA node. Here are some links to help guide you in that area:
http://frankdenneman.nl/2010/02/sizing-vms-and-numa-nodes/
http://frankdenneman.nl/2010/09/esx-4-1-numa-scheduling/
http://frankdenneman.nl/2011/01/amd-magny-cours-and-esx/
I guess I'll wrap it up by saying that CPU has never been too much of an issue for me, unless you are oversubscribing CPU on your host. Instead, memory is normally the culprit. Ballooning/swapping memory os a very noticeable performance issue.
Good luck!


Find the minimum value of $\frac{1}{x - y} + \frac{1}{y - z} + \frac{1}{x - z}$ for real numbers $x > y > z$ given $(x - y)(y - z)(x - z) = 17$.

Question: I've tried using AM-GM inequality:
$$
\frac1{x-y}+\frac1{y-z}+\frac1{x-z}\ge3\sqrt[3]{\frac1{(x-y)(y-z)(x-z)}}
$$
Which gives us
$$
\frac1{x-y}+\frac1{y-z}+\frac1{x-z}\ge\frac3{\sqrt[3]{17}}
$$
By plugging in the value.

I thought I was done. However, the equality holds if and only if $\frac1{x-y}=\frac1{y-z}=\frac1{x-z}$
This never happens because $x > y > z$. The inequality turns out to be strict.
Therefore, the minimum value is  greater than $\frac3{\sqrt[3]{17}}$
Can someone provide a way to do this? Thanks.
Comment: You might find it easier to let $a=x-y$, $b=y-z$ both positive, find $a$ in terms of $b$, then find $b$ which maximises the expression and thus the maximum of the expression.  You may have to solve a cubic equation on the way.
Answer: Since $x > y > z$, It seems natural to me to write
$$x - z > y - z > 0$$
hence let $$a = y-z, \quad b = x-y, \quad a+b = x-z.$$
Then we wish to minimize
$$f(a,b) = \frac{1}{a} + \frac{1}{b} + \frac{1}{a+b}$$
subject to the constraints $$ab(a+b) = 17, \quad a, b > 0.$$
So $$f(a,b) = \frac{a(a+b) + b(a+b) + ab}{ab(a+b)} = \frac{a^2 + b^2 + 3ab}{17}.$$
Can you now minimize $f(a,b)$ subject to the above constraints?
Hint:

  Write $$a^2 + b^2 + 3ab = (a^2 + 2ab + b^2) + ab = (a+b)^2 + ab = (a+b)^2 + \frac{17}{a+b}.$$  Now let $c = a+b$, so that $$f(a,b) = \frac{c^2}{17} + \frac{1}{c}$$ and minimize with respect to $c > 0$.
Answer: Let $x-y=a$ and $y-z=b$.
Thus, $x-z=a+b$, the condition gives $ab(a+b)=17$ and we need to find a minimal value of $$\frac{1}{a}+\frac{1}{b}+\frac{1}{a+b},$$ which for $$a=b=\sqrt[3]{\frac{17}{2}}$$ gives a value $\frac{5}{\sqrt[3]{68}}.$
We'll prove that it's a minimal value.
Indeed, after homogenization we need to prove that:
$$\frac{1}{a}+\frac{1}{b}+\frac{1}{a+b}\geq\frac{5}{\sqrt[3]{4(a+b)ab}}.$$
Now, let $a+b=2\sqrt{ab}x^3.$
Thus, by AM-GM $x\geq1$ and we need to prove that:
$$2x^3+\frac{1}{2x^3}\geq\frac{5}{2x}$$ or $$4x^6+1\geq5x^2,$$ which is true by AM-GM:
$$4x^6+1\geq5\sqrt[5]{\left(x^6\right)^4\cdot1}\geq5x^2.$$
Answer: Let's solve the problem using the method of Lagrange multipliers. With $x-y=a>0$ and $y-z=b>0$ (hence $x-z=a+b$), we want to minimize
$$
f(a,b)=\frac{1}{a}+\frac{1}{b}+\frac{1}{a+b} \tag{1}
$$
subject to the constraint
$$
ab(a+b)=17. \tag{2}
$$
To solve this problem, let's find the stationary points of
$$
g(a,b,\lambda)=f(a,b)+\lambda[ab(a+b)-17], \tag{3}
$$
which are given by the solutions to the system of equations
\begin{align}
\frac{\partial g}{\partial a}=0&\implies -\frac{1}{a^2}-\frac{1}{(a+b)^2}+\lambda(2ab+b^2)=0, \tag{4a} \\
\frac{\partial g}{\partial b}=0&\implies -\frac{1}{b^2}-\frac{1}{(a+b)^2}+\lambda(a^2+2ab)=0, \tag{4b} \\
\end{align}
and $\frac{\partial g}{\partial \lambda}=0$, which is equivalent to the constraint $(2)$.
Subtracting $(4\text{b})$ from $(4\text{a})$ we obtain
$$
-\frac{1}{a^2}+\frac{1}{b^2}+\lambda(b^2-a^2)=0 \implies
(b^2-a^2)\left(\lambda-\frac{1}{a^2b^2}\right)=0
$$
$$
\implies b^2=a^2\quad\text{or}\quad \lambda=\frac{1}{a^2b^2}. \tag{5}
$$
Let's examine these two possibilities:

$b^2=a^2$ implies $b=a$ (since $a$ and $b$ are both positive). Inserting this in $(2)$ and solving for $a$ we find $a=\sqrt[3]{\frac{17}{2}}$. The corresponding value of $f$ is
$$
f(a,a)=\frac{5}{2a}=\frac{5}{2}\sqrt[3]{\frac{2}{17}}=\frac{5}{\sqrt[3]{64}}, \tag{6}
$$
which agrees with the result found by Michael Rozenberg.
Plugging $\lambda=\frac{1}{a^2b^2}$ into Eq. $(4\text{a})$ and simplifying, we obtain
$$
-\frac{1}{(a+b)^2}+\frac{2}{ab}=0. \tag{7}
$$
Using Eq. $(2)$, we may rewrite $(7)$ as
$$
-\frac{1}{(a+b)^2}+\frac{2(a+b)}{17}=0, \tag{8}
$$
which is equivalent to the solution presented by heropup$^{(*)}$. Solving $(8)$ we find $a+b=\sqrt[3]{\frac{17}{2}}$; Eqs. $(2)$ and $(1)$ then yield $ab=\sqrt[3]{2\cdot 17^2}$ and
$$
f(a,b)=\frac{a+b}{ab}+\frac{1}{a+b}=\frac{\sqrt[3]{\frac{17}{2}}}{\sqrt[3]{2\cdot 17^2}}+\sqrt[3]{\frac{2}{17}}=\frac{3}{2}\sqrt[3]{\frac{2}{17}}. \tag{9}
$$

The result $(9)$ is smaller than the result $(6)$, but is it the minimum value of $(1)$ for real numbers $a,b>0$? The answer is no. To show why, let $c:=\sqrt[3]{\frac{17}{2}}$; then, according to the results presented after Eq. $(8)$, $a+b=c$ and $ab=2c^2$, which imply that $a$ and $b$ are solutions to the equation
$$
t^2-ct+2c^2=0. \tag{10}
$$
However, the solutions to $(10)$ are complex:
$$
t=\frac{c\pm\sqrt{c^2-8c^2}}{2}=\frac{(1\pm i\sqrt{7})c}{2}. \tag{11}
$$
We conclude that the correct solution to the problem is the one presented by Michael Rozenberg.

$^{(*)}$ Minimize $f(a,b) = \frac{c^2}{17} + \frac{1}{c}$ with respect to $c=a+b$, that is, $\frac{\partial f}{\partial c}=\frac{2c}{17}-\frac{1}{c^2}=0$.
Comment: But, Rosenberg found $\frac5{\sqrt[3]{68}}$.
Comment: @BobDobbs, that's what I said --- see Eq. $(6)$.


Hyper-V snapshots – unable to start VM

Question: I restarted my Host server after shutting down three guest VMs. After I restarted the machine I tried to start the VMs and got an error stating the the VM failed to start.
SERVERNAME failed to start.
Attachment 'avhd file path' is read only. Please provide read/write access to the attachment. Error: 'General access denied error'
SERVENAME failed to start. (virtual machine ID 17292200-wd22-dd22-d23-dddddd2222)
The issue seems to be with the disk space. The VHD file for this VM is 128 GB and there are two AVHD files of 58 and 75 GB. Whereas the total disk space on this drive (E) is 280 GB - the free space is only around 23 GB. I understand that the error is caused by the unavailability of the required disk space.
Unfortunately, I cannot increase the disk space on this drive. However I have another drive (D) that has 400 GB of free space. I exported this VM to D drive and then tried to add the copied AVHD files but it gives me a similar error.
I am running Windows Server 2008 R2 Datacenter.
Any help is appreciated.
Comment: Are you sure the file permissions are correct?
Comment: How did you export the files?  Via the UI? Or did you just copy them?
Comment: Chris - The file permissions are correct. I have used this method to assign permissions to the avhd files.

http://support.microsoft.com/kb/2249906

Steven - I exported the files through the Hyper-V Manager.
Comment: And the snapshots did not export with the VM image?  They should have exported to a Snapshots folder in the export process.
Comment: The snapshots did export and an AVHD file of the same size was created on the other drive. However the snapshots folder is empty, the AVHD file is in the same folder as the VHD file.
Comment: I have tried creating a new VM and then tried to merge the existing AVHD and VHD files according to this article:

http://www.networkfoo.org/server-infrastructure/recovering-your-virtual-machine-how-manually-merge-hyper-v-snapshots-back-one-

But I still get the same error:

'UATNEW': Attachment 'C:\Test UAT VM\UAT\UAT\Virtual Hard Disks\UAT_ED224380-XXX-4FD8-YYYY-D751A270835C.vhd' is read only. Please provide read/write access to add the attachment. Error: 'General access denied error' (7864368). (Virtual machine ID D31639AE-ZZZZ-CCCC-ACB6-564959991701)
Comment: did you try to import the exported machine as it stood?  Or did you go right into the steps from that article?
Answer: Based on the scenario and the discussion in the comments, I would attempt to import the exported VM as Hyper-V exported it.  You may need to adjust the location of files in the .exp file.
You will want to delete the previous machine's configuration from Hyper-V before importing the VM, if you want to keep the same VM ID.  If you don't care, you can re-import the VM with a new ID.

Hyper-V snapshots – unable to start VM


Calculating HTML input using JavaScript

Question: Hi I am trying to calculate the percentage using the input from the HTML input
let timeSpend = document.querySelector(".time_spend")

var fSubject = (50/timeSpend)*100;
var sSubject = (25/timeSpend)*100;
var tSubject = (25/timeSpend)*100;
window.alert(fSubject);

This is my HTML input that I have the type of number but I don't know why it still not working
<input
          type="number"
          id="text-box"
          class="time_spend"
          placeholder="How much time do you have?"
        />

Comment: Elements have a value property
Comment: To get the *value* of the element, you need to use its `.value` property (or `.valueAsNumber` in your case if you like). ([More here](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement).) Right now you're trying to use the element itself in the calculation, not its value. Also be sure to do the calculation in response to an event (such as a button click or a change to the input), not right away, since if you do it right away you'll be getting the starting value of the input, not the value you enter later.
Comment: And you need to get the value whenever the input is changed - not at loading time -> `.addEventListener("input",...)` ...
Answer: When you want to get a value out of an input, you should use .value on the element. And when you want do to this should still be decided, do you want it on a submit or a button click. This is an example using a button.

<!DOCTYPE html>

    <input type="number" id="text-box" class="time_spend" placeholder="How much time do you have?" />
    <button onclick="buttonClicked()">test</button>

Answer: Here's how you can do it if you want the percentages to be recalculated when you change the value in the input.
I'm outputting the percentages in the html here just as an example

const timeSpendInput = document.querySelector(".time_spend")
const fSubjectSpan = document.querySelector("#fSubject");
const sSubjectSpan = document.querySelector("#sSubject");
const tSubjectSpan = document.querySelector("#tSubject");

timeSpendInput.addEventListener("change", () => {
  const timeSpend = timeSpendInput.value;
  const fSubject = (50/timeSpend)*100;
  const sSubject = (25/timeSpend)*100;
  const tSubject = (25/timeSpend)*100;

  fSubjectSpan.innerHTML = fSubject;
  sSubjectSpan.innerHTML = sSubject;
  tSubjectSpan.innerHTML = tSubject;

})
<input
          type="number"
          id="text-box"
          class="time_spend"
          placeholder="How much time do you have?"
        />

fSubject:

sSubject:

tSubject:

Calculating HTML input using JavaScript


What is the proper way to hash passwords in modern objective c?

Question: Can anyone provide information on the proper way to hash passwords using objective c (ios 6+)? I'm looking for examples and can't find anything clear out there.
Comment: Check [MD5](http://stackoverflow.com/questions/7632145/how-do-i-create-a-hash-of-a-file-on-ios) [SHA](http://stackoverflow.com/questions/9454620/how-to-sha-hash-in-cocoa-ios)
Comment: I love the way people down-vote questions just because they're duplicates. If I had found that in my searching, do you really think I'd have asked for help??
Comment: Please check these tutorials too. [1](http://www.raywenderlich.com/6475/basic-security-in-ios-5-tutorial-part-1),[2](http://maniacdev.com/2010/09/tutorial-how-to-calculate-md5-or-sha-hash-of-file-efficiently),[3](http://en.wikipedia.org/wiki/MD5),[4](https://developer.apple.com/library/ios/documentation/System/Conceptual/ManPages_iPhoneOS/man3/Common%20Crypto.3cc.html#//apple_ref/doc/man/3cc/CommonCrypto),[5](http://en.wikipedia.org/wiki/SHA-1)
Comment: Good stuff Midhun - thanks! I'm still hoping to find a nice clear tutorial, but don't think there's one out there yet. I think I can use the SHA function though.
Answer: I would avoid doing your own hashing and store them in the Keychain for security.
UPDATE
There are probably many ways to do this, but the way I have sent info securely over the net is to simply use the https protocol. See this question, answer and discussion.
As an aside, why even do this at all? The OAuth protocol has been invented for this purpose, and is fairly easy to setup.
Comment: But don't you think storing a hashed password in the keychain would provide even better security? Defense in depth...
Comment: I know nothing about your app, but unless you are dealing with bank records, medical records or govt secrets, I would bet that the encryption Apple has on the keychain is probably good enough.
Comment: I probably should have mentioned that I'll be sending them to a web service.
Comment: coneybeare, can you guide me to a good tutorial for setting up oauth for this purpose? I have researched it, but still don't fully understand it yet.


Give attribute to wordpress post titles

Question: I am working on a Wordpress site where multiple posts are to be displayed in a single page. The title of each post is displayed with h2 tags. Now I want to be able to give each of these an id (html id attribute), preferably of my choice so I can link to them (use as anchor).
Link to my page is
https://www.risingidiots.com/photoshop-opening/
Comment: This isn't a complete question - you need to post relevant code
Answer: If you wanted to add id in h2 tag you need to change the code in page-blog.php file.
there is two way to add the id.
if you wanted to add different id for each post as you want then you can just add custom field in each and every post.
then edit file and add the custom field value in h2 tag as ID.
as below.
<?php
   $post_id = get_post_meta( get_the_ID(), 'post_id', true );
?>
<h2 id="<?php echo $post_id; ?>"><a href="<?php the_permalink(); ?>" title="Read more"><?php the_title(); ?>

another way is you just use post id as id for h2 tag.
Comment: Thank you @Nirav Patel, I do not know what file to edit.
Answer: That's how I did it :)
First of all in my case what I had to modify was a plug-in- file not a theme file.

<h2 class="entry-title"
 id="<?php echo $title2; ?>"><a href="<?php the_permalink(); ?>"><?php the_title(); ?>

What I have done here is to use the title itself as an ID

Give attribute to wordpress post titles


Unusual renewal of subscription products

Question: Marketing wants to sell a subscription product at a discounted price of 5 septims a year for 3 years, and then return it to its regular price of 10 septims after that.
In discussion the idea came up to:

Generate 3 new products (SUB_Y1, SUB_Y2, and SUB_Y3 in addition to the existing SUB product)
Set up the renewals notifications for the first 3 products to encourage users to renew
Direct them only to the next product in the series
Offer them the regular product after the first 3 cheap years

However, I know my marketing department; if I do this, they will want more, and by the end of the year I will have 25 different series, each of which having 2 to 5 steps in the process. My /admin/store/products/view will be a nightmare to behold.
Is there a cleaner way of handling this that will not use up much of the 25 minutes actual coding time I am alotted each week?
Comment: The possible solution I just realized... which may or may not work depending on the complexity of the mod:

I am going to look at extending the "After first recurring expiration" functionality... so "After THIRD recurring expiration" then it would redirect to the regular product.

This may be biting off more than I can chew... but its where I'm going at the moment.
Comment: Ok realized after the fact that the "first expiration" code is part of a custom module... which is likely derived from another module that I'll contrib my changes with if I get that far.
Comment: Really Kiamlaluno? Bored much? You changed the Title from Title Case to sentence case... the title... sigh.
Answer: I've not used UC Recurring Payments and Subscriptions before properly, but if each payment is a fully fledged order then I imagine you could use Conditional Actions to look at the date compared to the initial purchase date and give a discount if that is within the three years. The coding effort is then just creating a new condition using hook_ca_condition() which is not hard, and then after that setting up the pricing rules in the CA interface.
Comment: Clever... that may work if my current course of action explodes in my face.
Answer: Ultimately I altered the custom module with a toggle to extend the "different price after first month" to 1,3,6, or 12 months, and attach that to the product.  Given that the module was outdated custom variant of a Ubercart mod in the first place, there was nothing to contrib to.  Solution worked very well though, if anyone bumps into it.


How to get a list from all work items from a specific board in TFS API without ID?

Question: I'm using TFS and I would like to get all work items from a specific board. This is how I'm getting the board atm: https://myTFSLink.com/tfs/TPC/ProjectName/MY-BOARD-NAME/_apis/work/boards?api-version=5.1
But nothing about stories/workItems are present in this API request. I know I can get all workItemsRevisions using
GET https://dev.azure.com/{organization}/{project}/_apis/wit/reporting/workitemrevisions?api-version=5.0

but I don't know how I can target this to a specific board :(
I also know that I can get multiple workItems by ID with
GET https://dev.azure.com/fabrikam/_apis/wit/workitems?ids=297,299,300&$expand=all&api-version=5.1

but the ideal would be get all workItems from a specific board as I said in the beginning. Is there any way to do it?
Answer: A specific board is corresponding to a Team/Area Path, so you can try to query the work items By Wiql. For example,
POST https://dev.azure.com/{organization}/{project}/{team}/_apis/wit/wiql?api-version=5.1

Request Body:

{
  "query": "Select [System.Id], [System.Title], [System.State] From WorkItems Where [System.WorkItemType] = 'PRODUCT BACKLOG ITEM' AND [Area Path] = 'TestCase\\Team1' order by [System.CreatedDate] desc"
}


Como armazenar dados enviadas de uma API em uma variável no IONIC 4?

Question: Eu tenho uma função no ionic que recebe da API um array e mostra os dados recebido
public info;

  async showinfo() {
    await this.authService.getInfo().subscribe(
      data=>{
        this.info = data;
        console.log(data);
        for(let i=0; i<data.length; i++){
          this.info[i];
        }
    },
    error=>{
      console.log(error);
    });

    console.log(this.info); //aparece undefined
 }

Quando eu dou um console.log() dentro do subscribe eu consigo ver o valor que eu recebo da API porém se eu tento ver o valor fora dele, ele não mostra o dado.
Como eu faço para ver fora do subscribe o valor da variável??
Answer: Isso ocorre porque você está realizando uma operação assíncrona. O código fora do subscribe é executado antes, por isso o undefined na saída do console.
Uma solução seria criar um método para manipular a variável info e chamá-lo dentro da inscrição do Observable. Desta forma, a manipulação ocorre após atribuição de algum valor para info
Exemplo:
public info;

async showinfo() {
 await this.authService.getInfo().subscribe(
  data => {
   this.info = data;
   console.log(data);
   for (let i = 0; i < data.length; i++) {
    this.info[i];
   }
   handleInfo();
  },
  error => {
   console.log(error);
  });
}

handleInfo() { // realiza a manipulação de info
 console.log(this.info);
}

Comment: muito obrigado!!!!


bloco Try e except

Question: Necessito realizar este programa:
Reescrever seu programa de pagamento usando try e except para
que o programa trate entradas não numérica amigavelmente imprimindo uma
mensagem e saindo do programa. A seguir mostra duas execucões do programa:
Digite as Horas: 20
Digite a Taxa: nove
Erro, por favor, informe entrada numérica
Digite as Horas: quarenta
Erro, por favor, informe entrada numérica

O
meu código é o seguinte:
numero_horas=input("Digite o numero de horas:")
valor_hora=input("Digite o valor hora:")
print("Erro, digite numeros")
valor_total=int(numero_horas*valor_hora)
print("Valor total", valor_total)
try:
    valor=int(valor_total)
    print("Valor de Pagamento é:", valor)
except:
    print("Inicie programa novamente")

Só que dá este erro :
valor_total=int(numero_horas*valor_hora)
TypeError: can't multiply sequence by non-int of type 'str'

como poderei resolver este problema?
Comment: Você está multiplicando duas strings; precisa converter para int antes.
Comment: Possível duplicata de [Aceitar somente numéricos no input](https://pt.stackoverflow.com/questions/244764/aceitar-somente-num%c3%a9ricos-no-input)
Answer: Sergio o problema é que voce está setando as variáveis como INT depois da multiplicação, esse erro quer dizer que você está multiplicando strings, por isso o problema.
tente desse forma:
numero_horas=input("Digite o numero de horas:")
valor_hora=input("Digite o valor hora:")
try:
    #print("Erro, digite numeros")
    valor_total=int(numero_horas)*int(valor_hora)
    print("Valor total", valor_total)
    valor=int(valor_total)
    print("Valor de Pagamento é:", valor)
except ValueError:
    print("Inicie programa novamente")

Comment: Obrigado pela ajuda, resolveu o que queria,valeu
Answer: O input retorna string. Assim sendo, antes de fazer contas com os retornos você deve convertê-los.
Além disso, você fala que o exemplo é de duas execuções do programa, assim, entende-se que ao receber um entrada não numérica o programa, além de apresentar a mensagem de erro, é interrompido (sys.exit).
Como o mesmo tratamento é dado para dois inputs, é melhor criar uma função (int_or_exit) para evitar repetição de código.
import sys

def int_or_exit(int_string):
    try:
        int_valor = int(int_string)
    except ValueError:
        print("Erro, por favor, informe entrada numérica")
        sys.exit(1)
    return int_valor

input_numero_horas = input("Digite as Horas: ")
numero_horas = int_or_exit(input_numero_horas)

input_valor_hora = input("Digite a Taxa: ")
valor_hora = int_or_exit(input_valor_hora)

valor_total = numero_horas * valor_hora
print("Valor de Pagamento é:", valor_total)

Comment: Obrigado pela ajuda, resolveu o que queria,valeu

bloco Try e except


Passing form value into batch process

Question: I have a form that is used to trigger a bulk operation and add a node for each of the currently registered users on the site. This is all working well, but I'd like to pass form data from BulkAddForm.php to the batch operation in BulkAddNode.php
If is were to setup a variable called $year in BulkAddForm which contained form state. How would I then use it in a line like this...
'title' => 'Perf-plan-' . $year . '-' . $user->get('field_user_employeeid')->value,

BulkAddForm.php
<?php
 namespace Drupal\create_perf_plan_for_new_year\Form;
 use Drupal\Core\Form\FormBase;
 use Drupal\Core\Form\FormStateInterface;
/**
 * Class BulkAddForm.
 *
 * @package Drupal\create_perf_plan_for_new_year\Form
 */
class BulkAddForm extends FormBase {
  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'bulk_add_form';
  }
  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $form['perfPlanYear'] = array(
      '#type' => 'textfield',
      '#title' => 'Year Tag (1819 for instance)',
    );
    $form['bulk_add'] = array(
      '#type' => 'submit',
      '#value' => $this->t('Create new Performance Plans'),
    );
    return $form;
  }
  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $uids = \Drupal::entityQuery('user')
      //->condition('type', 'batch')
      ->sort('created', 'ASC')
      ->execute();
    $batch = array(
      'title' => t('Bulk Add happening within the Bulk Add Form file...'),
      'operations' => array(
        array(
          '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAdd',
          array($uids)
        ),
      ),
      'finished' => '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAddFinishedCallback',
    );
    batch_set($batch);
  }
}

BulkAddNode.php
<?php
namespace Drupal\create_perf_plan_for_new_year;
use Drupal\node\Entity\Node;
use Drupal\user\Entity\User;
use Drupal\Core\Url;

class BulkAddNode {

    public static function bulkAdd($uids, &$context){
    $message = 'Bulk add happening in functional file...';
    foreach ($uids as $uid) {
        $user = \Drupal\user\Entity\User::load($uid);
        \Drupal\node\Entity\Node::create([
            'type' => 'perf_plan',
            'title' => 'Perf-plan-' . '1718' . '-' . $user->get('field_user_employeeid')->value,
            'uid' => $user->id(),
            'field_employee_uid' => $user->id(),
            //'field_supervisor_uid' => $user->get('field_supervisor')->first()->getValue()['target_id'], //Brilliant means of getting entity reference UID from User. SM
            //'field_director_uid' => $user->get('field_director')->first()->getValue()['target_id'],
          ])->save();
    }
    $context['message'] = $message;
  }

function bulkAddFinishedCallback($success, $operations) {
    if ($success) {
      $message = 'Performance plan added.';
    }
    else {
      $message = t('Encountered an error during bulk performance plan creation.');
    }
    drupal_set_message($message);
  }
}

Answer: You can pass variables to the batch process by doing the following...
     $year = "2018";
     $batch = array(
          'title' => t('Bulk Add happening within the Bulk Add Form file...'),
          'operations' => array(
            array(
              '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAdd',
              array($uids, $year)
            ),
          ),
          'finished' => '\Drupal\create_perf_plan_for_new_year\BulkAddNode::bulkAddFinishedCallback',
        );

Year in this case can obviously be anything... a piece of $form_state for instance also works.
You could then change
public static function bulkAdd($uids, $year, &$context){
    $message = 'Bulk add happening in functional file...';
    foreach ($uids as $uid) {
        $user = \Drupal\user\Entity\User::load($uid);
        \Drupal\node\Entity\Node::create([
            'type' => 'perf_plan',
            'title' => 'Perf-plan-' . $year . '-' . $user->get('field_user_employeeid')->value,
            'uid' => $user->id(),
            'field_employee_uid' => $user->id(),
            //'field_supervisor_uid' => $user->get('field_supervisor')->first()->getValue()['target_id'], //Brilliant means of getting entity reference UID from User. SM
            //'field_director_uid' => $user->get('field_director')->first()->getValue()['target_id'],
          ])->save();
    }
    $context['message'] = $message;
  }

Hope this helps. It took me a while to figure out where in the batch array structure this needed to be placed. I didn't find the docs particularly helpful.

Passing form value into batch process


WPF set TextWrapping.Wrap global for multiline TextBox

Question: How can i set in WPF-Textboxes TextWrapping = TextWrapping.Wrap for all multiline textboxes (AcceptsReturn = true) in my application? Is their some thing possible with styles?
I found a way with reflection, but their must be more elegant ways.
Thank you!
Answer: You can create a default Style for TextBox, with a Trigger on the AcceptsReturn property:
<Application.Resources>

    </Style>
</Application.Resources>

Comment: You should have included that in your question.
Comment: Thank you for your fast answer, you set the property always to Wrap, not only if it is an multiline textbox.
Comment: You mean if AcceptsReturn is true?
Comment: Ok, found a solution thats working prettiy nice. If you add this to your answer i will accept it: `
`... Thank you


Rewrite url writing using htaccess to access in a folder from root

Question: I want to write a rewrite url to one of my sub folder from root.
 Ex : www.mydomain.com/subscriber.html
want to redirect to
www.mydomain.com/subscriber/index.php
I used following code in my magento root .htaccess file.
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^(.+)\.htm$ subscriber/$1.php [R,NC]

but it is not working.Any one can help me to short this issue?
Answer: you can rewrite url from admin panel as below:
Catalog => URL rewrite management
Comment: thank you.It was a customized folder for subscribers.what is the id path in custom rewrite page in admin panel.
Comment: id path will be your page id ex.subscriber.html and request path will be subscriber/index.php.
Answer: Try this one
Redirect 301 /subscriber.html /subscriber/index.php

Answer: Try this:
RewriteRule ^(.*)\.html$ $1/index.php [QSA,L]
Comment: how the redirect engine verify that this is want to go to specific folder? if we write like this?
Comment: Is this you want? www.aaa.com/xxx.html -> www.aaa.com/xxx/index.php
Answer: The following example could be helpful to use
RewriteRule ^(.+)\.html$ $1/index.php [R,NC]

if you have specific a page foo.html and folder foo that you want to redirect to, then the following example might be helpful
RewriteRule ^foo\.html$ foo/index.php


playing sdcard video on textureview

Question: I'm trying to play a video that I have on the sdcard of my device using Textureview, which according to the documentation, is the best solution to further transform the video, the problem is that when I put the path of an Internet video me working correctly , and when I put my route sdcard me the video is black, but the sound if it works, is very rare. I attached the code if you can help me, I've been searching like crazy but I find it can be happening, thanks in advance. regards
<code>public class tres extends Activity implements TextureView.SurfaceTextureListener {

private MediaPlayer mp;
private TextureView textureview;

private String Path = "video.mp4";

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tres);

textureview = (TextureView) findViewById(R.id.vista_video);
textureview.setSurfaceTextureListener(this);

}

@Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width,
int height) {
// TODO Auto-generated method stub

Surface s = new Surface(surface);

try {
mp= new MediaPlayer();
mp.setDataSource(Environment.getExternalStorageDir ectory()+"/" + Path);
mp.setSurface(s);
mp.prepare();

mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.start();

} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
</code>
}
Answer: im having exact the same issue.
current workarround is a running webserver app on the same device and setting the DataSource of my mediaPlayer instance to localhost.
but thats not the solution im hoping to find.

playing sdcard video on textureview


How do I drush vset a number with decimals?

Question:
drush vset latest_version 6.34a
latest_version was set to "6.34a"

So far so good.

drush vset latest_version 6.34
latest_version was set to 6.

Hmm...

drush vset latest_version '6.34'
latest_version was set to 6.
drush vset latest_version "6.34"
latest_version was set to 6.
Comment: What happens if you explicitly set the type to string?
Comment: Pretty sure this is a bug in `_drush_variable_format()`.  It uses is_numeric() instead of is int().  I would post in the issue queue.
Comment: @greg_1_anderson  That was quick :)  I was going to investigate this further when I got home from work, with the hopes of giving you a patch.
Comment: Wow, yeah that was quick. Not sure why assumed it wasn't a bug.
Answer: Turns out that calling Drush as follows does the trick.
<-- language: lang-bsh -->
<code>drush php-eval "variable_set('latest_version', '6.34');"
</code>
It also turns out that this is a bug, and that awesome greg_1_anderson fixed it within hours of me asking the question.


Django ModelMultipleChoiceField : Iterating through the data

Question: I am trying to display the data from a ModelMultipleChoiceField, and have tried to iterate for the objects, but I am getting funky results. Thanks for the help!
{{ chef.meal }}

Renders
[<Meal: Breakfast>, <Meal: Brunch>]

--
{% for i in chef.meal%} {{i}} {% endfor %}

Renders
[ < M e a l : B r e a k f a s t > , < M e a l : B r u n c h > ]

Here is the way I have the ModelMultipleChoiceField set up:
  meal = forms.ModelMultipleChoiceField(
        label=_("What is your best meal?"),
        queryset=Meal.objects.all(),
                                        required=True)

And the Meal model:
class Meal(models.Model):
  name = models.CharField(max_length=10)

  def __unicode__(self):
    return "%s" % self.name

HttpResponse:
  data = {"profile":profile,
          "chef":chef}
  return render_to_response(template_name,
                            data,
                            context_instance=RequestContext(request))

I am passing 'chef' through to the template, and then pulled the meals from the Chef object.
Comment: How are you sending your meal objects to your template? Post the HttpResponse line or render_to_response lin from your code.
Comment: Added that above. I am pulling meals from the Chef model
Comment: How are you generating the Chef form, using modelform or forms.Form?
Answer: You cannot use form fields inside a model. Instead make a foreign key from meal to Chef.
class Meal(models.Model):
    name = models.CharField(max_length=10)
    chef = models.ForeignKey(Chef)
    def __unicode__(self):
        return "%s" % self.name

Now inside the template use
{% for meal in chef.meal_set.all %}
     {{ meal }}
{% endfor %}

Ofcourse, instead of foreign field, there can be multiple-multiple relations between chef and meal models. Modify the code accordingly.
Comment: Ah Neo, I'm actually trying to display the data from the Chef object, not the form. I'm sorry for the confusion.
Comment: 'meal' is actually a form field and not an object. I'll repost the answer in that case.


ipconfig.exe is crashing when run from the windows (7) command prompt

Question: I am trying to use ipconfig, but everytime I enter the command in the windows command prompt, I get the crash dialog saying, "The IP configuration utility has stopped working", with the reason saying "APPCRASH". Is there anyway I can remedy this issue without a reimage of the OS?
Comment: capture a dmp with Procdump (http://channel9.msdn.com/Shows/Defrag-Tools/Defrag-Tools-9-ProcDump), open it in Windbg (part of the Windows SDK), fix the symbols (http://support.microsoft.com/kb/311503/en-us), now open the generated dmp with Windbg and run **!analyze -v**. Post the output here.
Comment: If you didn't mess with the executable, I would just reimage for peace of mind.
Answer: Do you suspect that you have malware?  Are other command line utilities working? Did you recently install something that may have modified the required libraries?  Try grabbing ipconfig.exe from a known working machine and replacing yours with that copy.  If that fixes it, and nothing else is funky, I'd move on, otherwise you may want to confirm it's not something malicious.


C# code behind not working after load() jQuery

Question: I have an update panel in aspx page.
Click on one of the button show a div from code behind, and load to that div element from another page
  ScriptManager.RegisterClientScriptBlock(this.Page, typeof(UpdatePanel), Guid.NewGuid().ToString(),
                        "UpsalePopup();  $('#MyDiv').load('PopUp/UpsaleAdv.aspx  #UpsaleAdvPanel');"
                        , true);

And its working perfect.
After user close that div (have only picture)
click on asp Button to do function on server side, go to '/UpsaleAdv.aspx' and show it as 404.
Is the load() function ruin my page ? how can I prevent it or solve it ?
Comment: is the error that it is going to `404` page ??
Comment: yes, but what i'm looking for is not the redirecting to this page (UpsaleAdv.aspx), I expected to get the code behind from the original aspx page (with the panel)
Comment: but in your code, you have passed url as `PopUp/UpsaleAdv.aspx`
Comment: tell me one thing, to which page it should get redirected ??
Comment: None! the original page is 'myaspx.aspx' on it I open div that load :$('#MyDiv').load('PopUp/UpsaleAdv.aspx  #UpsaleAdvPanel');" and i want to get the code behind of myaspx.aspx
Comment: I still didnt get you exactly what your error is and what exactly do you want. Can you explain it in more clearly
Comment: After close the div, clicking on asp Button in the myaspx.aspx page do NOT go the   btn_Click(object sender, EventArgs e) function in myaspx.aspx code behind. what he is doing: retirect to  '/UpsaleAdv.aspx' and show it as 404.
Answer: The page 'PopUp/UpsaleAdv.aspx' was an aspx page with <form> tag.
And after do this function:
$('#MyDiv').load('PopUp/UpsaleAdv.aspx  #UpsaleAdvPanel');"
it makes the current page (myaspa.aspx) to get the funcunality from PopUp/UpsaleAdv.aspx
And once I removed the <form> tag and replaced the page to inherit from master page all works perfect.


source code to transmit data using CAN protocol using C++

Question: I'm using a QT creator application. In my application I need to transmit and receive data's using CAN protocol using C++ source code.
I searched a lot on Google also, but I was not able to find the source code for this.
Comment: How are you connected to your CAN Bus?
Comment: This site is about asking specific programming problems or patterns, also showing you've tried something and are stuck in the process. Please read [this](http://stackoverflow.com/help/on-topic) to know what's on topic here.
Answer: Independent of language, first understand the CAN protocol (ie, formation of data packets), and the different layers used, and what is the underlying physical transport. Since this involves more than one system you should start with a reference implementation, like the Discovery board, or other boards referenced in http://liu.diva-portal.org/smash/get/diva2:822343/FULLTEXT01.pdf, or http://www.keil.com/forum/22051/can-bus-on-lpc2129/


Save pre-formatted column-view lists to .txt file - Python

Question: thanks for helping.
This python code format my lists into column-view style:
for ele1,ele2,ele3 in zip(I,a,F):
   print('{:<10}{:<10}{:<}'.format(ele1,ele2,ele3))

where I,a,F are previously done lists of the same size. The question is: How do I save this result into a .txt file?
Thanks.
Answer: Like this:
with open('file_name.txt', 'w') as filename:
    for ele1,ele2,ele3 in zip(I,a,F):
        print('{:<10}{:<10}{:<}'.format(ele1,ele2,ele3), file=filename)

Comment: You saved my life Sir. Thank you so much!