Should I change multiple text fields values via MySQL or is there any other preferable way?

Question: The site has a content type and this content type has two fields:

Text Field
Term Reference Field

There are thousands of nodes on this content type and I want to change some values (find/replace).
For example, I want to change all the "ABCD" strings with the "WXYZ" strings on the text fields in all the nodes.
Is it a good way to do this change via MySQL or is there any other preferable way? (Both text field change and taxonomy term replacement).
Note: I saw the Search and Replace Scanner module but it gives some errors I couldn't understand why. And it gives timeout error for a large amount of nodes.
Comment: The 'text field'-part of your question is clear to me, but is there anything in that term reference field that needs ay kind of updating? In other words: what's the relevance of that field in the context of this change-all operation that your question is about?
Comment: @Pierre.Vriens actually the important part of the question is the text-field part. I realised that there are other ways for finding and replacing the taxonomy term. Thanks and welcome :)
Comment: aha, that confirms what I was thinking of as a possible "additional answer" ... Hang on a little more to see it show up ...
Comment: The important thing for me is that: I will apply this find and replace multiple times for multiple find and replace values. So, if the "solution" can provide a simple option old_value and new_value then it would be easy. I tried the @Frank H.'s solution and it works good for SMALL AMAOUNT of nodes, but for thousands of nodes it doesn't work as expected (timeout errors etc). I "prepared" a custom module by using the BATCH API but it also gives some error and I will post it as another question.
Comment: Ok @herci ... it took a little time to prepare my answer, but now it's up to you to review it, and if you think it's worth doing so also "experiment with it" ... Curious for your feedback later on!
Comment: Hey @herci, with 4 answers to this question, is there really none of them you want to consider for marking as "accepted"? Also, it has been so long since you asked "new" questions ...
Answer: The Drupal way is to iterate over the nodes of interest and modify the fields. Here is a simple example that shows how you could make modifications in the Body field of the Article content type:
  $nodes = node_load_multiple(array(), array('type' => 'article'));
  foreach($nodes as $node) {
    // Only modify nodes that have something in the body field
    if (isset($node->body[$node->language][0]['value'])) {

      $text = $node->body[$node->language][0]['value'];
      $find = 'ABCD';
      $replace = 'WXYZ';
      $text = str_replace($find, $replace, $text);
      $node->body[$node->language][0]['value'] = $text;
      node_save($node);
    }
  }

One thing to note about doing it this way is the last-modified time of all your nodes will be updated. You may or may not want this. If you want to update the nodes without changing the timestamp, use this instead:
  $nodes = node_load_multiple(array(), array('type' => 'article'));
  foreach($nodes as $node) {
    // Only modify nodes that have something in the body field
    if (isset($node->body[$node->language][0]['value'])) {

      $text = $node->body[$node->language][0]['value'];
      $find = 'ABCD';
      $replace = 'WXYZ';
      $text = str_replace($find, $replace, $text);
      $node->body[$node->language][0]['value'] = $text;
      unset($node->created);
      unset($node->updated);
      field_attach_update('node', $node);
    }
  }

Edit: How to modify taxonomy terms
You could use the same approach to modify taxonomy terms, i.e. load the terms, iterate over them, and do a find/replace on each.
  $vocab = taxonomy_vocabulary_machine_name_load('my_vocabulary');
  $terms = entity_load('taxonomy_term', FALSE, array('vid' => $vocab->vid));

  foreach ($terms as $term) {
    $text = $term->name;
    $find = 'ABCD';
    $replace = 'WXYZ';
    $text = str_replace($find, $replace, $text);
    $term->name = $text;
    taxonomy_term_save($term);
  }

Depending on how expert you are with MySQL, you could try updating the database field directly and you might have success, but it's prone to error especially if your fields have revisions.
Comment: Thanks a lot for your answer. I will try the "Drupal way".
Comment: You're welcome. Updated my answer to also show how to modify taxonomy terms.
Comment: @herci The syntax error was caused by a typo in the line preceding the call to field_attach_update ("node-updated" should have read "node->updated". I have fixed it now.
Comment: The hook system in Drupal allows other modules to react to changes in data - lease of which, updating the last edit time, versioning, verification, and dozens more.  Even though doing it the drupal way is significant slower - it is the right thing to do.
Comment: @herci The 'Drupal way' (or at least, one Drupal way) to overcome timeout and memory errors is to use the [Batch API](https://www.drupal.org/node/180528). See also http://drupal.stackexchange.com/questions/57865/when-using-the-batch-api-should-i-create-an-operation-per-node
Comment: Thanks @FrankH. Interesting, I didn't see the typo :) Thanks also for the Batch API. I will check it and if I couldn't understand how it works I will try the method I mentioned on my last comment.
Comment: @herci Please see my answer which shows how to implement the Batch API in an update script.
Comment: The second one (without changing timestap) gives an error: `Parse error: syntax error, unexpected '-', expecting ',' or ')' in` for the line       `field_attach_update('node', $node);`. I'm executing this code in a custom node (PHP). The first piece of code one is working.
Comment: It gives timeout error because there are thousands of nodes. Is it a good way to add something like `if (($node->nid)<10000) {` to execute the code for every 10000 nodes then change the number to 20000, 30000 etc.
Answer: Step 1: Create a Rules Component
Have a look at this example of a Rules Component (in Rules export format):
{ "rules_search_and_replace_values_in_a_text_field" : {
    "LABEL" : "Search and replace values in a text field",
    "PLUGIN" : "rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules" ],
    "USES VARIABLES" : {
      "node" : { "label" : "Node", "type" : "node" },
      "old_value" : { "label" : "Old Value", "type" : "text" },
      "new_value" : { "label" : "New Value", "type" : "text" }
    },
    "IF" : [
      { "entity_has_field" : { "entity" : [ "node" ], "field" : "field_free_format_text" } },
      { "data_is" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[old-value:value]"
        }
      }
    ],
    "DO" : [
      { "data_set" : {
          "data" : [ "node:field-free-format-text" ],
          "value" : "[new-value:value]"
        }
      },
      { "drupal_message" : { "message" : "String \u0022[old-value:value]\u0022 was replaced to string \u0022[new-value:value]\u0022 in field \u0022field_free_format_text\u0022 for node with id \u0022[node:nid]\u0022 and title \u0022[node:title]\u0022." } }
    ]
  }
}

Some more details to further explain the above above example:

This Rules Component will be used in the subsequent step.
In my case I have a text field with machine name field_free_format_text.

Note that I also added the Rules Condition Entity has field to make that field available for further processing in this Rules Component. That's also what is mentioned in the Rules UI when you're adding a "data comparison" condition: somewhere it says "The data selector helps you drill down into the data available to Rules. To make entity fields appear in the data selector, you may have to use the condition 'entity has field' (or 'content is of type')". For a video tutorial that illustrates the importance of this Entity has field condition, refer to Data types and data selection, especially what is shown between about 13:30 and 17:30 in that video.
Note that I've not added a Rules condition here about selected content types, that's possibly an extra condition you might want to add also. But if the selection list field is only used for the content types you're interested in, then the Entity has field condition should be sufficient already.
If you want, just grab (copy) the exported rule above, change all occurrences of the machine name of that field to match the machine name of your field, and then you can simply import this Rules Component in your own environment.
After you did this, you can navigate to admin/config/workflow/rules/components in your own site, and then use the hyperlink "execute" to qa-test it in your own site. After you use that link, use the button that says Switch to direct input mode. Then you'll be able to enter some Node identifier and hit the Execute mode. Depending on the node id you selected (if it has that field, and if the Rules Condition is satisfied), your node will be updated.
After you're confident your rule works perfect for all variations of your nodes, move on to the next step below.
Here is an example of the (2) Drupal messages I got when executing this Rules component for a node with ID = 48, in which I changed the string "Pierre" to "Herci":

String "Pierre" was replaced to string "Herci" in field "field_free_format_text" for node with id "48" and title "Demo field_free_format_text replacement".
Component rule: Search and replace values in a text field has been executed.

Variation of the display of that message could be that you use Rules to create a (similar) log record ...
Attention: you always get the 2nd message. But the first one only shows up if you have an actual match ... and hence the update gets performed also.
Step 2: Let VBO to the bulk of the work
This step is pretty easy ... Just create an appropriate view of all your nodes to be processed, and transform it into a Views Bulk Operations view. The clue to what you want VBO to do as an operation is ... you guessed it: Execute the Rules Component from Step 1.
If you're not familiar with how to do so, have a look at the video about Using Rules components with VBO". If you want even more, then also watch the subsequent "Using Rules components with more than one parameter" video.
Of course there are multiple variations of the above approach, like processing by component type, narrowing down your Views output to only "a" specific value, etc. But that should be straight forward, and up to your own imagination.
Attention: to process many nodes at once is quite a challenge (memory requirements, etc). Therefor you might want to also watch the video about "More details about VBO settings" ... Before you are tempted to use VBO for processing them all at once ...
Step 3: Straight forward variations
There are dozens (hundreds?) of straight forward variations of this question that can also be solved using the above combination of VBO and Rules. To just mention 1 of them, have a look at my answer to "How to bulk delete selected content/nodes?" ...
The flexibility you get with this approach also illustrates the advantages of this one, as compared to direct MySql approach.
Happy VBO-ing while Rules-ing!
Comment: Thanks a lot for your "could be a book itself" answer. I think you love the Rules module and I will become familiar with it also. Your answers not only answer the questions but also give some very interesting aspects for solving problems. Thanks again.
Comment: Merci for the kudos, yes I "like" Rules ... even more: if you're familiar with "SAP", the programming there is done many times using "ABAP" as programming language ... To me "Rules" has become the ABAP-equivalent for Drupal ... combined with things like "Flag", "Group" (not "OG" !!!) and a few other modules I can get at least 95% of any site done ... with close to 0% of custom code ... That implies upgrading to new Drupal releases does not cause any custom coding pains either ...
Comment: @herci (FYI): A question like [How to answer questions about getting started with **Rules**?](http://drupal.stackexchange.com/questions/164463) seems like a possible followup-question about this one. I might soon start preparing my answer for it already ...
Answer: The real Drupal way of doing this is, writing an update script implementing hook_update_N(), which would find all the nodes with the text to be changed. Then update all the nodes in a batch (which prevents the timeouts).
A rough layout of the update script should look like as follows. Please read my comments in the code.
/**
 * Replaces all "ABCD" strings with "WXYZ" strings on text fields in all nodes.
 */
function mymodule_update_7100(&$sandbox) {
  // Set our $sandbox, which will stay persistent in multiple batch processes.
  if (!isset($sandbox['total'])) {
    // Find all nodes having 'ABCD' in a text field
    // Use your favorite method here, for the sake of this example I use EFQ.
    $query = new EntityFieldQuery();
    $query->entityCondition('entity_type', 'node');
    $query->propertyCondition('bundle', 'YOUR_CONTENT_TYPE');
    $query->fieldCondition('my_text_field', '%ABCD%', 'like');
    $result = $query->execute();

    // Put the node ids into the $sandbox
    $sandbox['nids'] = array_keys($result['node']);
    $sandbox['total'] = count($sandbox['nids']);
    // Set batch size to a number of nodes your server can process in a single
    // request. If you still get timeouts, try to reduce this number.
    $sandbox['batch_size'] = 10;
    $sandbox['current'] = 0;
  }
  else {
    // The sandbox is set, so we can process the nodes in batches. We load only
    // that much of nodes set in the $sandbox['batch_size']
    $offset = $sandbox['current'] * $sandbox['batch_size'];
    $current_nids = array_slice($sandbox['nids'], $offset, $sandbox['batch_size']);
    $nodes = node_load_multiple($current_nids);

    foreach ($nodes as $node) {
      // Change the text value here and save the node.
      // Again use your favorite method here. For the sake of this example, I
      // change the value directly on the $node object and save the $node.
      $text = $node->my_text_field['und'][0]['value'];
      $text = str_replace('ABCD', 'WXYZ', $text);
      $node->my_text_field['und'][0]['value'] = $text;
      node_save($node);
    }
  }

  // Check the progress and set $sandbox['#finished'] to 1 once all nodes are
  // processed.
  $progress = $sandbox['current'] * $sandbox['batch_size'] / $sandbox['total'];
  $sandbox['#finished'] = $progress > 1 ? 1 : $progress;
}

Put above script in an .install-file of a custom module. You should adjust the name of the function. Please see the documentation of hook_update_N() if you are not familiar with update scripts.
Then, you run the update.php or use drush command drush updb. This update script will be called as many time as all the nodes are processed which are set in the first part of the if statement. On the first call, it will just find the nodes and put the node ids in the $sandbox. On the consequent calls, it will load the nodes in batches of 10 and process them.
Comment: Thanks a lot for your detailed answer. I will try this and if I succeed I will try to improve it for some special case (match whole world, multiple words to change etc.)
Answer: IMO the fastest way to do this is trough a direct SQL query to your database, because you don't have to use any of the Drupal API functions (that can make calls to another functions) to solve this.
Remember that you must reindex your site again because you change some values in your nodes.
But if you want get the revisions updated also, this is not the way to do it.
Edit after @kiamlaluno comment:
Be aware that if you make the changes with a SQL query and if you have some Rules/Triggers/Validations/etc, then these changes can't be detected.
Comment: If you use a SQL query to change a field value, you don't allow Drupal core and third-party modules to detect that change. _Fast way_ doesn't mean _correct way_.
Comment: @herci Hooks are what allow other modules, including the ones part of Drupal core, to know something is going to be removed. Without them, modules cannot delete the data being invalidated by you altering nodes.
Comment: @kiamlaluno, could you please tell me what do you mean by "Drupal core couldn't detect that change". Most probably I will have to make this change through an SQL query because other methods didn't work me (timeouts, memory limits etc.). What happens if I change the values with that method? Thanks a lot.
Comment: Hımm, OK trying to understand the terminology :) If I change the value of a text field through SQL query, then re-index the whole site is that a problem? It's not important for me Drupal understand the change, revision etc. The only important thing is Drupal should see the latest value of it. Do you think it's OK? Thanks for your answers.
Comment: Even though this is "a" possible approach, I'd rather first ask the website owner "Do you want it **badly**?". However I can picture situations where this is technique is exactly what you want, such as when you want to mass update all sorts of things, but you don't want (eg) all sorts of eMails to go out to "subscribers" because of some update that nobody really cares to be informed about. Of course, that implies that if you're a huge enterprise, you'd also want to get approval from your auditors that there will NOT be any **audit trial" in the drupal loggings (to avoid being fired?).


How do I open the Gradle tasks window in Intellij?

Question: This is probably a very silly question, but I cannot find the gradle tasks window, like with compile, clean, build, instrument etc.
Can anyone help me? Thanks
Answer: View -> Tool Windows -> Gradle
Answer: In my case the Gradle window was not in the Tool Windosws menu because the project was not linked with Gradle yet. IntelliJ eventually detected that the Gradle files in the project and suggested to link it.
After that (as mentioned by @RaGe) the Gradle window could be surfaced using:
View -> Tool Windows -> Gradle


Sorting comments from newest to oldest

Question: How should I configure Drupal 8 to sort comments from newest to oldest, similarly to what the Comment Goodness module does in Drupal 7?
Comment: Find some clue: \Drupal\Core\Entity\EntityViewBuilder::viewMultiple but still didn't know how to order
Answer: As CommentStorage::loadThread adds comment_filter tag to its query, you may use hook_query_TAG_alter hook to change comments order:
/**
 * Implements hook_query_TAG_alter() for comment_filter tag.
 *
 * @see CommentStorage::loadThread().
 */
function mymodule_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {
  // Change comment order to DESC for 'comment' field.
  if ($query->getMetaData('field_name') == 'comment') {
    /** @var \Drupal\Core\Database\Query\SelectInterface $query */
    $order_by = &$query->getOrderBy();
    // 'c.cid' is for flat comment lists.
    if (isset($order_by['c.cid']) && $order_by['c.cid'] == 'ASC') {
      $order_by['c.cid'] = 'DESC';
    }
    // 'torder' is for threated comment lists.
    if (isset($order_by['torder']) && $order_by['torder'] == 'ASC') {
      $order_by['torder'] = 'DESC';
    }
  }
}

Comment: @seb your solution works for threaded commens. For flat comment lists works mine. I updated my answer. Thank you!
Comment: Thank you @Stanislav Agapov

I had to modify your code. For me works this one:

```if ($query->getMetaData('field_name') == 'comment') {
        /** @var \Drupal\Core\Database\Query\SelectInterface $query */
        $order_by = &$query->getOrderBy();
        if (isset($order_by['torder']) && $order_by['torder'] == 'ASC') {
            $order_by['torder'] = 'DESC';
        }
    }```
Comment: your solution for threaded comments is not going to sort properly, making latest replies visually appear above parent comments.

@echo's approach with unsetting `toroder` and sorting by `thread` worked
Answer: Assuming your comment field's machine name is field_comments, put this code into a module to get descending comments. I was having trouble with threaded comments, but this works since it alters the query by the c.thread database column instead of just 'torder'
/**
 * Implements hook_query_TAG_alter() for comment_filter tag.
 *
 * @see CommentStorage::loadThread().
 */
function MYMODULE_query_comment_filter_alter(Drupal\Core\Database\Query\AlterableInterface $query) {

  // Change comment order to DESC for 'comment' field.
  if ($query->getMetaData('field_name') == 'field_comments') {

    $order_by = &$query->getOrderBy();
    $expressions = &$query->getExpressions();
    // Sorting for threaded comments.
    if (isset($order_by['torder']) && $order_by['torder'] == 'ASC') {
      // Get rid of the expressions that prepare the threads for ASC ordering.
      unset($expressions['torder']);
      unset($order_by['torder']);
      // Simply order by the thread field.
      $order_by['c.thread'] = 'DESC';
    }

  }

}

Comment: This is the properly working solution for threaded comments. Thank you
Answer: You could create a comments view and sort them there.
Answer: For Drupal 8 you can use the next module: Comments order.
Link: https://www.drupal.org/project/comments_order

This module provides to change comments order (sorting functionality)
  in Drupal 8. You can pick comment order (newest first or oldest first)
  per node type, editing your comment type field on the "Manage fields"
  tab (node type administration page).
Not only in flat, but also in threaded display! If you use threaded
  display, you can pick how will able to sort children comments.
  Examples below.
Answer: core/modules/comment/src/CommentStorage.php line 302. I think the only way is hack the core! & only for FLAT module.
    if ($mode == CommentManagerInterface::COMMENT_MODE_FLAT) {
  $query->orderBy('c.cid', 'DESC');
}
else {
  // See comment above. Analysis reveals that this doesn't cost too
  // much. It scales much much better than having the whole comment
  // structure.
  $query->addExpression('SUBSTRING(c.thread, 1, (LENGTH(c.thread) - 1))', 'torder');
  $query->orderBy('torder', 'ASC');
}

Comment: There is no need to hack core when an entity definition can be altered.

Sorting comments from newest to oldest


Server with GC, CA, WSUS replication passed tombstone period

Question: To cut a long story short, we have inadvertently ended up with a Windows Server 2003 DC that has now passed the 60 day tombstone period for replication. As well as a DC it is also a Global Catalogue, our only Certification Authority and runs Windows Server Update Services.
The server has been turned back on after the tombstone period, however I have checked all of our other DC's and they all have strict replication consistency enabled. So we shouldn't have had any lingering objects copied to our other DC's. I have now turned off the problem server while we figure out what to do next.
I have done a little research and will continue looking, but so far I have read that fixing it is risky and we are much better off removing the DC from the domain and rebuilding it (We are waiting to upgrade this sever to a supported OS anyway, but don't currently have a spare compatible server). It appears that WSUS can just be installed on a new server and we would just need to point our clients to it. But I've no idea where we stand with the CA.
So my questions are:

What do I need to do to safely remove the server from our domain?
What do I need to do to replace the CA with a new one?
Can I just install WSUS on a different server and point our clients to it, or is there something else which needs to be done to remove the old one?
What do I need to do to remove the global catalogue on from this server? (It is NOT the only GC in the domain)
Are there any questions I should be asking, but have missed?
Answer:
What do I need to do to safely remove the server from our domain?

You have to delete the active directory object and clean-up metadata.
If you have domain controller running Windows 2008R2 or above, the second (metadata) is done automatically.
More info : https://technet.microsoft.com/en-us/library/Cc816907%28v=WS.10%29.aspx

What do I need to do to replace the CA with a new one?

This is the most trickiest part, but since you do have access to the server, there's no major obstacle.
You will find various procedure on Microsoft Web sites, for example here or maybe preferably this one

Can I just install WSUS on a different server and point our clients to it, or is there something else which needs to be done to remove the old one?

Yes, no trick here, just change your GPO to point to the new server.

What do I need to do to remove the global catalogue on from this server? (It is NOT the only GC in the domain)

This is part of the first point.

Are there any questions I should be asking, but have missed?

None I think about right now.
Answer: Firstly  CA
backup and move the CA complete guide here Migrating CA from 2003 to 2012 but the high level steps are as follows
1) Backup current CA
This can be done by accessing the CA console and using the Backup option, ensure you backup the private key along with the database and logs, when asked)
2) Backup CA Registry Settings
Export the following key HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\CertSvc
3) Uninstall CA Service from Windows Server 2003
From inside control panel, add remove programs windows components
4) Clean up CA information in the domain.
Using sites and services remove references to failed ca ms support page
5) Install Windows Server 2012 R2 Certificate Services
Use the roles wizard to do this, include web enrolment role
6) Configure AD CS
Select AD CS from the installed roles and select configure, select enterprise CA, ROOT CA, and importantly use existing Private Key (These are on various secreens) Import the private key from the backup created earlier
7) Restore the CA
The same steps as backup but restore, restore private ca, database and log when prompted
8) Restore the registry info
Import the registry backup from above
9) Reissue Certificate Templates
 certificate templates list click on the appropriate certificate template

Secondly WSUS
This can be moved or can be clean installed. The main thing here is to update your Group Policies with the new server information Technet Guide

Thirdly Domain controller
If you still need this server to be a domain controller you need to do the following.
1) Turn the server back on while disconnected from the network and run dcpromo /forceremoval
2) Seize any FSMO roles this server had onto another server MS Support Page
3) Do a metadata cleanup from active domain controller Technet on Meta Data Cleanup
4) Delete all DNS entries relating to the original server
5) Rename server (Not strictly required, but if you miss anything on the cleanup this will save you problems with old references)
6) Promote back to DC
Comment: Thanks. As the server needs to be kept offline until it has been removed from the domain, will the uninstallation of the CA work as expected? I.e. Doesn't it need to remove anything from Active Directory? Because it will obviously remove everything on itself, but won't replicate to our other servers.
Comment: @Daniel Good point, I've updated step 4. Which isn't part of the full guide but has separate steps
Answer: One question you should ask yourself is why TSL is 60 days.  It has been 180 days since Windows Server 2003 SP1/Windows Server 2003 R2 SP2 (about eight years).  You should change that to 180 days.  This episode is one reason why Microsoft increased this to 180 days.  Another reason is any AD backup older than TSL is invalidated.
Determine the tombstone lifetime for the forest
https://technet.microsoft.com/en-us/library/cc784932%28v=ws.10%29.aspx
AD DS: The resultant backup lifetime in this forest should be equal to or greater than 180 days
https://technet.microsoft.com/en-us/library/dd723674%28v=ws.10%29.aspx
Comment: Thanks, I will look into changing that. This domain was originally created with Server 2000 or NT I believe. Maybe that's why the TSL is set to 60 days.


I have created a quiz, ammending code I have found on the web, but I am having a slight issue

Question: I have ammended this code, to create a quiz that a user answers questions by checking a radio button.
var totalScore = 0;
var numAnswer = 0;

//an array with objects that hold the questions
var allQuestions = [{question: ["Q1: Who was the Top Goalscorer in the 1998 World Cup?"],
                    choices: ["Ronaldo", "Davor Sukor", "Zinedine Zindane", "Thierry Henry"],
                    correctAnswer:1},

    {question: ["Q2: Where was the 1998 World Cup Final Held?"],
     choices: ["Parc des Princes", "Stade Velodrome", "Stade de France", "Stade de Gerland"],
    correctAnswer:2},

    {question: ["Q3: What was the score in the 1998 World Cup Final?"],
    choices: ["2-0", "2-1", "3-0", "3-1"],
    correctAnswer:2},

    {question: ["Q4: Who won the 2002 World cup?"],
    choices: ["France", "Holland", "Brazil", "Germany"],
    correctAnswer:2},

    {question: ["Q5: Who was the Top Goalscorer in the 2002 World Cup?"],
    choices: ["Vieri", "Ronaldo", "Klose", "Ballack"],
    correctAnswer:1}];

//create the questions created by the array, first unselecting all radiobuttons
function createQuestions() {

    for (var i = 0; i < 4; i++) {
        document.getElementById("answer" + i).checked = false;
    }
    var quizQuestion = document.getElementById("questions");
    quizQuestion.innerHTML = allQuestions[this.numAnswer].question[0];
    createOptions();
}

//change the innerHTML of the label by calling it's ID
function createOptions() {
    for (var o = 0; o <= allQuestions[0].choices[o].length; o++) {
        document.getElementById("a" + o).innerHTML = allQuestions[this.numAnswer].choices[o];
    }
}

//create an HTMLcollection using document.forms and check selected radiobutton and
//corresponding value.
function checkAnswers() {
    var methods = document.forms.radioAnswers.elements.choice;

    if (this.numAnswer < 4) {
        for (var i = 0; i < methods.length; i++) {
            if (methods[i].checked) {
                answer = methods[i].value;

            }
        }
        //check if answer is correct answer.
        if (parseInt(answer) === allQuestions[this.numAnswer].correctAnswer) {
            this.totalScore += 1;

        }
        this.numAnswer += 1;
        createQuestions();
    } else {

        showScore();
    }
}

function showScore() {
    var printTotalscore = document.getElementById("questions");
    printTotalscore.innerHTML = "Your total score is: " + this.totalScore;
    var removeRadio = document.getElementById("questions_form").style.display="none";
    var removeButton = document.getElementById("next").style.display="none";
}

window.onload = createQuestions();

I have gone through the code and I understand that it is using a series of for loops to create the questions, create the HTML for the question answers and finally keeping track of the number of questions.
On the last question the score is not updating properly, like it does for the other questions, I think its something to do with the final for loop but I've debugged it as much as I can but I still can't see how to fix it.
this line if (this.numAnswer < 4) is where I think the problem lies, as after the final loop it is going straight to the function showScore(), I could be wrong, but if I change the loop to (this.numAnswer <= 4) the final question needs to be selected again, and then the score is correct.
Can some one help me solve this please?
Here is the codepen to maybe make it easier: http://codepen.io/Addiosamigo/pen/fFHly
Thanks
Answer: The issue appears to be the if statement as you correctly identified.  The code behaves this way due to the fact that on the last answer you do not check for it's vadility/update scores.
You need to alter the code to ensure the score checking is carried out even on the last question.  As the score checking needs to be carried out always, the simplest solution might be to move the if statement to cover only the logic of showing next question of the result.
for (var i = 0; i < methods.length; i++) {
    if (methods[i].checked) {
        answer = methods[i].value;
    }
}
//check if answer is correct answer.
if (parseInt(answer) === allQuestions[this.numAnswer].correctAnswer) {
    this.totalScore += 1;
}

// Move the if statement to here
if (this.numAnswer < 4) {
    this.numAnswer += 1;
    createQuestions();
} else {

    showScore();
}

This can be seen in action at - http://codepen.io/anon/pen/ezgtD.  The code also removes some magic numbers.
Comment: to add dynamically answers without changing the if statement all the time, you can improve the code by changing the if to `if (this.numAnswer < allQuestions.length) {}`
Comment: @jan holmes, is this statement controlling the last question number? if numAnswer is less than all questions, add score, if not this is the end of questions, move onto showscore function?
Comment: @kami, I tried your codepen but the last question is not working. I should of known that there was a way of telling the program when the last question is!
Comment: @Addioioi Corrected the issue.
Comment: thanks for taking your time to help me, what was the issue by the way?
Comment: @Addioioi The codepen on the last answer did not validate the if statement correctly.  It required a -1 to the index check.


Dúvida com checkbox value true e checked

Question: Eu tenho um formulário e para atualizar eu tenho esse trecho de código.
Não consigo entender o que ele quer dizer. Tipo, se o aluno não está ativo no sistema ele coloca como value="true"?
Senão ele também coloca como value="true" mas o checked="checked". O que isso quer dizer?
    <%if(aluno.getAtivo() == false){ %>
        <input type="checkbox" id="ativo" name="ativo" value="true"/>

    <%}else { %>
        <input type="checkbox" id="ativo" name="ativo" value="true" checked="checked"/>

    <%} %>
    <input type="submit" value="Atualizar">

Segue página jsp completa:
<%@page import="DAO.AlunoDAO"%>
<%@page import="MODEL.Aluno"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Atualizando aluno</title>

<% Aluno aluno = new AlunoDAO().find(Integer.parseInt(request.getParameter("id")));%>

<form action="alunoCONTROLLER" method="get">
    <input type="hidden" name="operacao" value="atualizar">
    <input type="hidden" name="id" value="<%=aluno.getId()%>">

    Nome:
    <input type="text" id="nome" name="nome" value="<%=aluno.getNome()%>"/>

    Telefone:
    <input type="text" id="telefone" name="telefone" value="<%=aluno.getTelefone() %>"/>

    E-mail:
    <input type="text" id="email" name="email" value="<%=aluno.getEmail()%>" />

    Endereço:
    <input type="text" id="endereco" name="endereco" value="<%=aluno.getEndereco() %>"/>

    Matricula
    <input type="text" id="matricula" name="matricula" value="<%=aluno.getMatricula() %>"/>

    Idade
    <input type="text" id="idade" name="idade" value="<%=aluno.getIdade() %>"/>

    Ativo:

    <%if(aluno.getAtivo() == false){ %>
        <input type="checkbox" id="ativo" name="ativo" value="true"/>

    <%}else { %>
        <input type="checkbox" id="ativo" name="ativo" value="true" checked="checked"/>

    <%} %>
    <input type="submit" value="Atualizar">
</form>

Answer: Sua dúvida tem relação com HTML e não com JSP.
Não confunda value=true com checked.
Embora possa ser confuso, o atributo value não está definindo se o checkbox está marcado ou não na interface com usuário. Este atributo é utilizado para definir o que será recebido no servidor quando uma requisição HTTP POST for feita (obviamente o servidor só recebe se o checkbox estiver marcado).
O atributo que controla o estado do checkbox na interface com o usuário é o checked. Existem duas maneiras de utilizá-lo:
<input type="checkbox" id="ativo" name="ativo" value="true" checked="checked"/>

ou
<input type="checkbox" id="ativo" name="ativo" value="true" checked/>

Portanto, o código que você postou está correto. Quando aluno.getAtivo() == true, você renderiza um checkbox com o atributo checked e value=true. Quando aluno.getAtivo() == false, você renderiza o checkbox sem o atributo checked, mas com value também igual true. Isso é feito, pois se o usuário clicar no checkbox e enviar, será recebido true no servidor, o que é coerente com o seu problema.
Veja outro  exemplo abaixo para entender melhor.
<form action="form_demonstracao" method="get">
  <input type="checkbox" name="veiculo" value="Bicicleta"> Eu tenho uma bicicleta

  <input type="checkbox" name="veiculo" value="Carro" checked> Eu tenho um carro

  <input type="submit" value="Submit">
</form>

Se o form acima for submetido da maneira que está, o servidor receberá o seguinte:
veiculo=Carro

Caso o checkbox bicicleta seja marcado, então o seguinte será recebido:
veiculo=Carro&veiculo=Bicicleta

Comment: Olá @AlineGonzaga. Não entendi. Eu apenas disse que sua dúvida é de HTML puramente, não tem relação com JSP. Pelo que li da sua pergunta, você está com duvida no significado dos atributos de um input checkbox.
Comment: @AlineGonzaga, meu objetivo principal foi mostrar pra você que o valor do atributo value não tem relação com o estado do checkbox (marcado ou desmarcado). O value pode ser o que você quiser. Pode ser inclusive o valor de um atributo de um objeto Java. No seu caso, como você está falando de Aluno ativo, o true é o mais correto. No exemplo que postei, true já não serve, pois estamos falando de carro.
Comment: AHHHHHHHHHHHHHHH Agora entendi. Até que enfim...
Comment: Mas a página se chama atualizar.jsp Não entendi por quê não posso chaamr de jsp...
Comment: Não entendi isso: veiculo=Carro&veiculo=Bicicleta
Comment: Não seria: veiculo=Bicicleta?
Comment: veiculo=Bicicleta é o que foi recebido do lado do servidor. Só é recebido se o checkbox estiver marcado. Note que no primeiro exemplo, apenas o checkbox carro está marcado, então recebe apenas veiculo=Carro. Depois eu comento que o checkbox Bicicleta foi marcado, então é recebeido do lado do servidor veiculo=Carro&veiculo=Bicicleta, pois os dois checkboxes estão marcados. Quando eu falo do lado do servidor, pode ser PHP, JAVA, C#, qualquer linguagem WEB.
Comment: Esse Bicicleta é um atributo de alguma classe em java?
Comment: @AlineGonzaga, então melhor não marcar a resposta como correta. Eu coloquei a tag HTML e certamente vai encontrar alguém que vai te dar uma outra explicação. Isso é importante no SOpt. Muitas vezes o conhecimento está em várias respostas.
Comment: Não, vou estudar o que tu escreveu depois direito. Valeu a juda.
Comment: No caso ali do seu exemplo então os dois estariam marcados?
Comment: No exemplo, apenas um está marcado, o Carro, pois ele tem o atributo checked. Note que desse jeito, o servidor recebe apenas veiculo=Carro. Logo depois eu cito que cliquei na Bicicleta. Como agora os dois estão marcados, então o servidor recebe veiculo=Carro&veiculo=Bicicleta.


How to validate k-means result

Question: I'm doing anomaly detection on unsupervised data using k-means I got a result but I don't know how to validate my clustering result.
by plotting I can see my anomalies but how should I validate that clustering is accurate.
in supervised learning, we use cross-validation like this any method or technique for unsupervised means.
Answer: You can still use any CV method for this, as you should know the expected result for your training / validating data. Supervised just means the algorithm knows what the answer should be, and unsupervised it doesn't.
If you don't know what the answer should be then you have no way of telling if it is right or wrong yourself

How to validate k-means result


multicast tcpdump and subscriptions

Question: From the multicast howto:

IP_ADD_MEMBERSHIP.
Recall that you need to tell the kernel which multicast groups you are interested
      in. If no process is interested in a group, packets destined to it that arrive to
      the host are discarded.

If you don't do that, you won't see those packets with tcpdump.

Is it possible to subscribe to all multicast traffic so I can do a tcpdump for all existing traffic? I would think IGMP doesn't allow this, so probably not.. but maybe you can configure a switch to still send all multicast traffic. Is that possible?
Is it possible to do subscription (for a specific IP) with a command line tool? (note: I know how to do this in C.. but would prefer to use an existing tool and not compile a separate program for this)
Answer: It depends on your multicast infrastructure: For instance, you could have many multicast routers, and various rules set on your switches (making subscriptions static, or dynamic, or even banned on certain ports/nodes).
But, if you want to subscribe to a multicast group... Just subscribe.  Send an IGMP JOIN packet across some infrastructure, which obviously has IGMP snooping enabled.  You can generate an IGMP packet with a variety of tools.
Taking a step to a higher level, use iperf to subscribe to any multicast group.  If your network infrastructure isn't too complex, and if you are "allowed" to subscribe to any multicast group, then use the following:
iperf -s -u -B 188.8.131.52 Where 18.104.22.168 is your multicast group address.
tcpdump simultaneously to get a detailed report.
Note that I believe iperf only supports IGMP v1 and v2.  If you want to craft an IGMP v3 JOIN packet, it shouldn't be too hard to write a program, as you stated.  But there would be a lot more tools out there that would probably do the same.
Comment: "You can generate an IGMP packet with a variety of tools.". What are these tools? I obviously don't want to manually assemble a packet.. `iperf` looks nice. What else can you use?
Comment: Also, as I said, if possible, I want to get all available multicast traffic. There are a lot of traffic and I don't know all the addresses.
Comment: Other tools like the large count of packet generation tools, where you [craft the packet with a nice front end](http://packeth.sourceforge.net/#screenshots) for instance.  iperf would serve much better, but doesn't support IGMP v3 (I don't think).  You can't just "get all multicast traffic."  That's the exact opposite purpose of multicast.  What you're asking for now sounds like more of a job for port mirroring/spanning on a switch trunk port/point, where you know the multicast traffic traverses.  Sniff at the target port, filtering for multicast packets, and you've got your answer.
Comment: And, by the way, you might be able to leverage the API your apps are using to send and receive multicast to compile a membership list in a centralized location that you could, in turn, subscribe to at the higher level (other than physical, layer 2 as the suggestion to mirror traffic).
Comment: .. so I set up the switch so it forwards all the multicast traffic.. now it arrives at my linux box, where the kernel will drop all those packets because apps haven't subscribed for the specific multicast addresses.. or have I misunderstood something?
Comment: [Promiscuous mode](http://www.tcpdump.org/faq.html#q7) should allow tcpdump to see all packets that arrive at the interface. I think you've gotten too deep in your analysis on how to do this.  [Stop pondering theory and test some actions.](http://blog.serverfault.com/post/eating-our-vegetables/)
Comment: I tested `iperf`, I cannot specify which interface to use so it sends the multicast joins on the wrong physical interface (no, I don't want to set up a route table entry for that)... couldn't test the rest, as usual, I'm waiting for the netadms :/
Comment: You can't send a packet to a place without a route to that place.  Since your multicast group is "living" on infrastructure interconnected to your server via, say eth4, the network stack would need to know where to send the packet with the IGMP JOIN.  Otherwise, you can't join the multicast group.  It's quite clear you're a super human sysadmin; but it seems that you're perspective is very complex.  This is simple networking concept.  You must add a route for your network stack to know where to route a packet.  Otherwise, it will send it to the router who's the designated pathway to 0.0.0.0.
Comment: O'rly? search for IP_ADD_MEMBERSHIP. here is one good source: http://tldp.org/HOWTO/Multicast-HOWTO-6.html (it was in my question BTW)
Comment: Sorry I'm not a developer.  Maybe you would be better served inquiring on stackoverflow or programmers.stackexchange.com.  I didn't realize you were re-writing the network stack or concerned with relying on your own API to interface directly with it.  I strongly suggest that you just add the route statement and see what happens.  Seems reasonable?
Comment: *sigh*.. it's not re-writing. it's pretty natural that you can select the interface for (in/out) multicast traffic, as it is valid address on multiple interfaces. note: thanks for you help!
Comment: If you need a very specific feature set, and you do appear to be quite comfortable, maybe write your own (JOINer)?  It seems like a reasonable feat given your knowledge.  When I needed an IGMP v2 all-hosts querier written, the dev chose to use python to craft the packet and send it out, relying on the available py modules.  It wasn't complex or difficult.  iperf isn't the tool, but look into many more packet crafting tools.  And, as I said, a port mirror/span may be an option if you don't know what the groups are.  This will definitely have the traffic arrive to the wire....
Comment: Obviously, this is a very interesting issue to me, so please post an response if you figure something.
Comment: Looks like I've finally come across a similar questions to yours with [ntop and ipt_NETFLOW](https://sourceforge.net/tracker/?func=detail&aid=3464029&group_id=232613&atid=1088104).  I am now curious if you were looking to build something similar to that of [the PF_RING project](http://www.ntop.org/products/pf_ring/).
Comment: And your solution is to patch the kernel, or, much more easily, create a bridge between a dummy NIC and the real NIC, place the real NIC into promisc mode.  See: http://ipt-netflow.git.sourceforge.net/git/gitweb.cgi?p=ipt-netflow/ipt-netflow;a=blob;f=README.promisc
Comment: hmm... http://www.computerworlduk.com/news/security/3333956/intrusion-detection-offered-as-cloud-package-by-metaflows/?olo=rss
Answer: The linked-to page of the multicast HOWTO doesn't say anything about tcpdump.
Tcpdump uses libpcap to capture network packets and, on Ethernet, libpcap supports both:

promiscuous mode, in which the network adapter delivers to the host every packet it sees, regardless of the destination address, and the network stack delivers every packet passing the filter to the capture mechanism, and
non-promiscuous mode, in which the network adapter delivers to the host unicast packets, broadcast packets, and multicast packets it's configured to deliver, and the network stack delivers all of those packets that pass the capture filter to the capture mechanism.

Tcpdump default to requesting promiscuous mode; in that mode, you'll even see unicast packets not sent to your host (as long as you're not on a switched network or are on a switched network but are plugged into a "mirror" port that gets all traffic).
If you pass tcpdump the -p flag, it will request non-promiscuous mode, in which case you'll only see the packets that your machine "should" get; in that case, if no process has registered an interest in a particular multicast group, you won't see packets sent to that group's multicast address, but, in that case, that's not a bug, that's a feature, as your machine isn't doing anything with those packets.
So if you want to see all packets (unicast packets to all hosts, multicast packets to all multicast addresses, and broadcast packets), run tcpdump (or Wireshark or whatever) in promiscuous mode and, if you're on a switched network, run on a "mirror port" or "SPAN port" or whatever the switch vendor calls it (if it supports "mirror ports").
See the Wireshark Wiki page on Ethernet packet capture for a lot of details on promiscuous mode and switched networks; the information on that page applies to all packet sniffers, including tcpdump, not just to Wireshark.

multicast tcpdump and subscriptions


Como anunciar IP de servidor na rede?

Question: Estou desenvolvendo uma aplicação composta por um servidor feito em NodeJS que deve fornecer dados em JSON para os clientes, no caso um aplicativo para Android, tudo funcionando em rede interna.
Já consegui fazer todo o processo de comunicação e tudo funciona da forma esperada, porém estou definindo o IP e porta do servidor de forma fixa tanto no servidor quanto no cliente (por exemplo 192.168.1.15:3300).
Gostaria de saber se existe uma forma de anunciar o IP do servidor na rede já que este pode mudar em algum momento, como por exemplo nos jogos online, onde é mostrado uma lista com servidores ligados.
Já pensei em fazer um escaneamento da porta do meu servidor em toda a rede, porém este processo pode se tornar lento, ainda mais que o cliente pode não ter muito poder de processamento.
Existe alguma forma mais rápida ou melhor para "anunciar"o IP do servidor na rede para que os clientes possam se conectar?
Comment: Não dá pra usar DNS? Simplificaria.
Comment: Não é possível fazer um loop sobre os IP's, imagina algo como 200 clientes conectados, agora imagina fazer um loop sobre os 200 IP's (se o servidor for o último é claro) feito por um Smartphone e isso sem considerar o Timeout. Fiz uns teste com 30 IPs e já levou mais de 1 minuto para descobrir o servidor. Talvez exista algum algorítimo melhor. Posso ter feito algo errado.
Comment: Olha se entendi o que você quer é que os clientes saibam qual o IP está distribuindo o JSON, não seria melhor fixa-lo? Eu não sei se entendi o que você necessita
Comment: No exemplo atual está fixo como comentado, porém pode ocorrer do servidor alterar o IP por algum motivo e não conseguir mais o IP fixado nos clientes. Preciso que o servidor de alguma forma conte em que IP está executando. Mas Obrigado pelo comentário de qualquer forma.
Comment: Entendi, se o IP é somente local acredito o rastreamento não seja lento, se você utilizar algo como `try { Socket socket = new Socket(); socket.connect(new InetSocketAddress(ip, 3300), timeout); socket.close(); return true; } catch (Exception ex) { return false;  }` e um loop
Answer: Pedro, de fato vasculhar a rede procurando pelo serviço/dispositivo é inviável, principalmente se você não pode usar algo como nmap (com algum binding para o nodejs) no dispositivo cliente.
A minha sugestão é que você não implemente nada na mão e utilize protocolos já conhecidos para esta finalidade, por exemplo o SSDP.

O protocolo simples de descoberta de serviços (SSDP) é um protocolo de rede do conjunto de protocolos da internet, para divulgação e descoberta de serviços de rede e presença de informação. Ele cumpre este objetivo sem assistência de mecanismos de configuração baseados em servidor, como o DHCP ou o DNS, e sem configurações estáticas. O SSDP é a base do protocolo de descoberta do Universal Plug and Play (UPnP).

O SSDP é um protocolo baseado em HTTPU que é uma extensão do HTTP 1.1 utilizando o UDP como camada de transporte.
O servidor anuncia o serviço disponível fazendo multicast IP para a porta 1900. O range de endereço multicast é 126.96.36.199 - 184.108.40.206. É utilizado o verbo HTTP NOTIFY para anunciar ou notificar a desativação de um serviço.
Para um cliente descobrir serviços disponíveis em uma rede é utilizado o verbo M-SEARCH e respostas para estes requests são devolvidos em unicast (comunicação um-a-um) para o mesmo endereço e porta que o originou.
Esclarecendo
Na arquitetura da sua aplicação ambos os clientes (smartphones) e o servidor vão escutar e emitir mensagens. Inicialmente, quando ninguém conhece ninguem pode haver duas situações:
1- O servidor acabou de entrar na rede, suponha que o seu servidor acabou de voltar de um reboot - ele então faz multicast para todos na rede, na porta 1900 com UDP, enviando um verbo NOTIFY, com todas as informações necessárias da sua localização na rede (ip e porta). Os clientes (smartphones) que já estão escutando na porta 1900 recebem o request e a partir daí usam esta informação como bem entenderem.
2- Um novo cliente acabou de entrar na rede e quer descobrir o servidor. Ele então envia um multicast para a porta 1900, com o verbo M-SEARCH. O servidor recebe esta requisição e retorna a requisição para o mesmo endereço e porta originários, o cliente recebe o retorno e faz o que bem entender com a informação.
Porque usar tudo isso?
Para você não ter a necessidade de criar o seu próprio protocolo de descoberta de serviços e não perder tempo desenvolvendo bibliotecas que já lidam com isso. O node já tem módulos que abstraem esse tipo de problema e aposto que existem bibliotecas para os smartphones que também já o fazem.
Como implementar tudo isso?
1- Você implementa tudo na mão, ou
2- Você pode usar o módulo super-ssdp que é super simples e tem uma API minúscula:
var ssdp = require('super-ssdp'),
    ip = require('ip'),
    porta = (Math.random() * 10000).toFixed(0), // Porta fake. Coloque aqui a porta do seu serviço principal
    peer = ssdp.createPeer({
        name: 'suaAplicação',
        url: 'http://' + ip.address() + ':' + porta
    });

peer.start();

peer.on('found', function(endereco) {
    console.log('Serviço encontrado!', endereco);
});

Para testar o código acima você precisa fazer o seguinte; npm install super-ssdp ip e então node app.js (ou o nome do arquivo que você preferir). Agora abra outro terminal (para simular um outro dispositivo) e rode o último comando novamente. Preferencialmente teste em outro computador conectado a rede.
Mais Testes
Vamos testar que qualquer cliente, smartphone no seu caso, é capaz de encontrar o servidor.
Em uma aba de terminal rode o código acima, em outra rode este
var dgram = require('dgram'),
    ip = require('ip');

//0- Este é o nosso request HTTPU
var msearch = new Buffer(
    'M-SEARCH * HTTP/1.1\r\n' +
    'HOST:188.8.131.52:1900\r\n' +
    'MAN:\"ssdp:discover\"\r\n' +
    'ST:ssdp:all\r\n' +
    'MX:3\r\n' +
    '\r\n'
);

//1- Criamos um socket para enviar o M-SEARCH e escutar a resposta
var client = dgram.createSocket('udp4');

//2- Este socket escuta numa porta que o proprio SO vai designar,
//   e em todos os endereços, não apenas localhost
client.bind(function() {
    client.on('message', function(msg, rinfo) {
        //3- Aqui trataremos a reposta
        if(rinfo.address !== ip.address()) {
            //4- Só estamos interessados em mensagens vindas do localhost.
            //   Se você não colocar este `if` você vai receber varias mensagens
            //   do seu roteador, por exemplo!
            return;
        }

        //5- Imprimimos a resposta que contem o IP e porta do servidor.
        //   O ideal aqui seria fazer um parse da resposta.
        console.log(msg.toString());
    });

    //6- Enviamos o M-SEARCH para todo mundo, repare a porta e o endereço multicast
    client.send(msearch, 0, msearch.length, 1900, '126.96.36.199', function() {
        console.log('M-SEARCH enviado...');
    });
});

No código acima implementamos na mão o código de um cliente SSDP, que é justamente o que a biblioteca para Android ou iOS deve fazer para você.
Nós até poderíamos implementar outro teste em que o o servidor 2 envia um NOTIFY para o servidor1 mas a biblioteca super-ssdp não implementou o handler para NOTIFY então não tem como testar. Na verdade essa biblioteca não é consolidada, o único like que ela tem no GitHub é o meu kkk - você provavelmente vai querer encontrar algo mais testado e consolidado, as vezes algo até fora do node mesmo e aí você só cria os bindings.
O seu problema (ou não) será encontrar uma biblioteca que implemente o SSDP na linguagem/plataforma dos smartphones.
Answer: Como é rede interna acho que o mais simples seria o servidor soltar um pacote UDP broadcast (ou multicast) a intervalos regulares "anunciando" sua existência.
Talvez esses links ajudem:

http://nodejs.org/api/dgram.html
https://stackoverflow.com/questions/14130560/nodejs-udp-multicast-how-to
https://gist.github.com/ciaranj/9056285
Comment: Uma alternativa para diminuir o tráfego, apesar de UDP ser compacto por natureza, seria o cliente mandar um broadcast ao conectar e o servidor responder só quando solicitado, se a quantidade de clientes não for gigantesca.
Comment: Vou dar uma olhada, de cara posso falar que talvez Broadcast cause problemas. Vou fazer um protótipo com MultiCast e ver se apresenta um resultado bom.

Como anunciar IP de servidor na rede?


Generalized Linear model with python, using categorical data to explain continuous variable

Question: I'm trying to model Mean Opinion Scores (MOS) about image quality, based on an image data base. The data base has 3000 images, it has 25 original images, 24 distortions of each one and 5 levels of distortion for each distortion type (25*24*5 = 3000). The MOS is a real number between 0 and 9.
The MOS distribution doesn't seem to be normal since according to its histogram it is not symmetric.
I think a Beta distribution would be fine, since it is negative skew. Do you agree with me? What other distribution could be used?
What confuses me is that the explanatory variables are categorical,
Image: it is a number in the range 1, 2, ... up to 25
Distortion: it is a number in the range 1, 2, ... up to 24
Level: it is a number in the range 1, 2, ... up to 5
I'm not sure how to work with categorical variables in a General Linear Model.
I don't know what link function use and why neither.
I wrote this code in python to fit the model:
<code># the data were previously loaded in a numpy array called data_array

X = np.empty((3000, 3))

X[:,0] = data_array[:, 0].astype(int) # image
X[:,1] = data_array[:, 1].astype(int) # distortion
X[:,2] = data_array[:, 2].astype(int) # level

mos = data_array[:, 3] # mos

X = sm.add_constant(X, prepend=False) # it appends a column of 1's

model = sm.GLM(mos, X, family=sm.families.Gamma())

results = model.fit()

print(results.summary())
</code>
I used a Gamma distribution because Beta distribution is not available in Python... do you know how to get a Beta distribution from another distribution?... or maybe I should try with R not Python...
Any kind of help is welcome.
Thanks you very much!
Best regards
Lucy
Comment: Using categorical variables to explain the response is very common in multivariate regression. What exactly are you not getting? Is your question specifically about categorical variables in GLMs? Or just in regressions in general? (Also, I believe you mean Generaliz*ed* Linear Model, not General Linear Model, which is not the same thing.)
Comment: I want to know if I can make a GLM in python using a beta distribution and how would be the code? how do I indicate to the software that the variables are categorical?
Answer: Regarding your issue with categorical variables:
I guess it's not such a big deal to add categorical var into regression if your categorical variable is ordered (so that you can say that the increase variable means something). I've never worked with something like that, but I think with "distortion" it should work.
Once categories are something like "levels" and they cannot be ordered, I think it will make more sense to split this variable into the set of dummies (leaving one category as a baseline).
Comment: Actually the 1 to 24 distortions are not ordered, they could be in any order and it would be the same, they are 24 totally different types of distortions. The levels from 1 to 5 are ordered,  for example distortion 15 with level 4 is more contaminated than distortion 15 with level 2.


How do I scroll to end of page using the requests-html library?

Question: I need to scrape the data but the entire data only generated when I scroll.
if I scrape before I scroll only some of the data is scraped not all.
from requests_html import AsyncHTMLSession

link="https://www.daraz.com.np/catalog/?q={}"
asession = AsyncHTMLSession()
async def get_daraz():
    r = await asession.get(link.format("mouse"))
    await r.html.arender()
    return r.html
results = asession.run(get_daraz)

items_div=results[0].xpath('//*[@id="root"]/div/div[2]/div[1]/div/div[1]/div[2]/div')

for item in items_div:
    print(item.xpath('//div/div/div[1]/div/a/img',first=True))

the above gives images of only first three.
Answer: You could check out the pyautogui library to scroll the web page. Selenium works too, but is blocked by many websites.
pyautogui.moveTo(200,200) # move mouse to a blank spot on the screen. (x, y) coordinates.
pyautogui.click(200,200) # click spot on screen at the coordinates of your choice.
pyautogui.scroll(100) # you could use a higher number to scroll more to load the whole page.

Comment: but this needs the chrome to be open , im webscraping with no browserwindow .how do i use this technique on an html? i have no idea.


The Following Setups were Not Matched, WPF MVVM Unit Testing with Moq

Question: I am writing a unit test in WPF with Moq to test whether or not a user clicked the "Yes" button on a YesNoCancel MessageBox when they are closing the window.  In my CloseCommand I have in my ViewModel gives the following message when the user is closing the window:
var result = _messageSvc.Show(
    "Do you want to save changes?",
    "Save Changes",
    Services.MessageBoxButton.YesNoCancel,
    Services.MessageBoxIcon.Question,
    Services.MessageBoxResult.Yes);

My _messageSvc is a private instance inside of a custom Messaging service to display messageboxes.  Here is the code for the service:
public interface IMessageSvc
{
    void Show(string message);
    MessageBoxResult Show(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon, MessageBoxResult defaultResult = 0);
}

public class MessageSvc : IMessageSvc
{
    public void Show(string message)
    {
        MessageBox.Show(message);
    }

    public MessageBoxResult Show(string message, string caption, MessageBoxButton buttons, MessageBoxIcon icon, MessageBoxResult defaultResult)
    {
        return (MessageBoxResult)MessageBox.Show(message, caption, (System.Windows.MessageBoxButton)buttons, (System.Windows.MessageBoxImage)icon, (System.Windows.MessageBoxResult)defaultResult);
    }
}

Note: MessageBoxButton, MessageBoxIcon, and MessageBoxResult are enumerations I made in the same file to mimic what .NET provides out of the box.  I am not showing them here for sake of readability
My unit test is:
[TestMethod]
public void ShouldAskToSaveOnCloseRespondYesTest()
{
    // Mock and setup initial user data
    var u= new User
    {
        UserId = 1,
        UserName = "FirstName LastName",
        FavoriteColor = "Blue"
    };
    mainViewModel.UserInfo= new UserInfoDtoWrapper(u);

    // assert the data has not changed yet
    Assert.IsFalse(mainViewModel.UserInfo.IsChanged);

    // change the user data
    mainViewModel.UserInfo.UserName= "LastName FirstName";

    // assert the data has changed
    Assert.IsTrue(mainViewModel.UserInfo.IsChanged);

    // execute window closing
    mainViewModel.CloseCommand.Execute(new object());

    // verify messagebox shows and the 'Yes' button is clicked
    // this will then save the changes made to the user instance
    var messageBox = new Mock<IMessageSvc>();
    messageBox.Setup(x => x.Show(It.Is<string>(y => y == "Do you want to save changes?"),
        It.Is<string>(y => y == "Save Changes"),
        It.Is<MessageBoxButton>(y => y == MessageBoxButton.YesNoCancel),
        It.Is<MessageBoxIcon>(y => y == MessageBoxIcon.Question),
        It.Is<MessageBoxResult>(y => y == MessageBoxResult.Yes)))
        .Returns(MessageBoxResult.Yes);

    messageBox.Verify();
}

The error comes on the messageBox.Verify() line, but from what I can see I am doing it correctly.  I need to get the return value of the messagebox to continue testing what happens after the user clicks the "Yes" button, so I did not want to use Verify with a Linq query inside, instead I need to capture the result.
Thanks
Comment: "The error comes on the messageBox.Verify() line" - What error?
Comment: ShouldAskToSaveOnCloseRespondYesTest threw exception: Moq.MockVerificationException: The following setups were not matched: IMessageSvc x=> x.Show(It.Is(y => y == "Do you want to save changes?"), It.Is(y => y == "Save Changes") . . .
Comment: Where's the rest of the code between Setup and Verify? Currently no test is performed.
Comment: I guess that's where my question is.  I need to verify the messagebox is shown.  Should I then just call "MessageBox.Show" or show the messageBox object I created above?
Answer: This won't work. You have 2 issues in your test code:

You first fire the CloseCommand (which is assumed to call the IMessageSvc.Show method), and only then setup a mock for that service.
You setup a new mock for a service but don't use it.

To correct these errors:

Change the order such that it is a correct 'arrange' - 'act' - 'assert' order
Inject your mocked service in the view model using dependency injection

Here is an example:
class MainViewModel
{
    private readonly IMessageSvc _messageSvc;

    public MainViewModel(IMessageSvc svc)
    {
        this._messageSvc = svc;
    }
}

[TestMethod]
public void ShouldAskToSaveOnCloseRespondYesTest()
{
    // Arrange
    var messageBox = new Mock<IMessageSvc>();
    messageBox.Setup(x => x.Show(It.Is<string>(y => y == "Do you want to save changes?"),
        It.Is<string>(y => y == "Save Changes"),
        It.Is<MessageBoxButton>(y => y == MessageBoxButton.YesNoCancel),
        It.Is<MessageBoxIcon>(y => y == MessageBoxIcon.Question),
        It.Is<MessageBoxResult>(y => y == MessageBoxResult.Yes)))
        .Returns(MessageBoxResult.Yes)
        .Verifiable();

    var mainViewModel = new MainViewModel(messageBox.Object);

    // Act
    mainViewModel.CloseCommand.Execute(new object());

    // Assert
    messageBox.Verify();
}

Comment: I am adding the message service object to the view model constructor on the unit test class initialization so it is being injected from there.  Within the unit test method however, after arranging my code to how you showed I am still getting the same error.
Comment: @J-man, no, you haven't arranged your code as I suggested. You're creating a new mock for your service in your test method. Exactly this mocked service has to be provided to the view model. You have to either create your view model in the test method (as I proposed) or setup your service mock in the class initialization where the view model is created.
Comment: You are correct @dymanoid, I mistakenly was setting up a new mocked instance of my messaging service, when I already has access to the class scoped messageSvc object which is injected in the initialize method of the unit test class.  So I should have been setting up the `messageSvc.Setup(...)` instead of what I was doing `var messageBox = new Mock(); messageBox.Setup(...)`.  No wonder it could not find the correct setup, you are correct in that the SAME object needs to be injected into the VM, I was mistakenly trying to inject a new one.  Thanks!!  I'll mark yours as the answer.
Answer: Currently you are setting up your mocked method after testing the code that would call it. Re-arrange your test into the AAA (Arrange, Act, Assert) pattern like so:
var messageBox = new Mock<IMessageSvc>();
messageBox.Setup(x => x.Show(It.Is<string>(y => y == "Do you want to save changes?"),
    It.Is<string>(y => y == "Save Changes"),
    It.Is<MessageBoxButton>(y => y == MessageBoxButton.YesNoCancel),
    It.Is<MessageBoxIcon>(y => y == MessageBoxIcon.Question),
    It.Is<MessageBoxResult>(y => y == MessageBoxResult.Yes)))
    .Returns(MessageBoxResult.Yes);

mainViewModel.CloseCommand.Execute(new object());

messageBox.Verify(x => x.Show(It.Is<string>(y => y == "Do you want to save changes?"),
    It.Is<string>(y => y == "Save Changes"),
    It.Is<MessageBoxButton>(y => y == MessageBoxButton.YesNoCancel),
    It.Is<MessageBoxIcon>(y => y == MessageBoxIcon.Question),
    It.Is<MessageBoxResult>(y => y == MessageBoxResult.Yes)));

Comment: I tried this before, error that is being returned in this situation is `Expected Invocation on the Mock once, but was 0 times` with `messageBox.Verify(x => x.Show(
                It.Is(y => y == "Do you want to save changes?"),
                It.Is(y => y == "Save Changes"),
                It.Is(y => y == MessageBoxButton.YesNoCancel),
                It.Is(y => y == MessageBoxIcon.Question),
                It.Is(y => y == MessageBoxResult.Yes)), Times.Once);`
Comment: I have my IMessageService injected into the ViewModel and initialized in the Unit Test class, so when I run `_messageSvc.Verify(x =>
            x.Show(It.Is(y => y == "Do you want to save changes?"),
            It.Is(y => y == "Save Changes"),
            It.Is(y => y == MessageBoxButton.YesNoCancel),
            It.Is(y => y == MessageBoxIcon.Question),
            It.Is(y => y == MessageBoxResult.Yes)), Times.Once);` it works, but I need to setup the messagebox to get the return value


Click to hide/show hree level navigation with jQuery

Question: I have a basic HTML menu with three levels:

On load, I would like for only the top level nav items to show. When a user clicks on a link, they will see the sub-menu. For, that I have:
$('ul li a').click(function() {
    $(this).next('.sub-menu').toggle();
});

That works just fine.

$('ul li a').click(function() {
  $(this).next('.sub-menu').toggle();
});

1

2

2.1

2.2

2.3

3

3.1

3.2

3.2.1

3.2.2

3.2.3

3.3

3.4

4

4.1

4.2

4.3

5

The problem is that the sub-menus do not hide unless you click them again (toggle).
I would like for only one navigation item and it's sub menus to be showing at one time.
What I need is for every sub-menu that is not a child of the top level nav item that was clicked on to be hidden.
Answer: To start out showing only the top level menu, use this CSS:
ul ul {
  display: none;
}

To show only the appropriate submenu, see the comments below:
$('ul li a').click(function() {
  $('ul ul').hide();                  //hide all ul children
  $(this).parents('ul').show();       //show all ul ancestors of the clicked anchor
  $(this).next('.sub-menu').toggle(); //toggle its submenu
});

Snippet:

$('ul li a').click(function() {
  $('ul ul').hide();                  //hide all ul children
  $(this).parents('ul').show();       //show all ul ancestors of the clicked anchor
  $(this).next('.sub-menu').toggle(); //toggle its submenu
});
ul ul {
  display: none;
}

Test 1

Test 2

Test 2a

Test 2b

Test 2c

Test 3

Test 3a

Test 3b

Test 3b 1

Test 3b 2

Test 3b 3

Test 3c

Test 3d

Test 4

Test 4a

Test 4b

Test 4c

Test 5

Comment: Yes, that is it. Thank you so much.


Qual a diferença de utilizar return e print nesta função recursiva que calcula a soma de números?

Question: Fiz uma função simples em Python para me dar a soma dos números de n até 0:
def retorna(n, zero, soma):
    if n <= zero:
        soma += n
        return soma
        retorna(n+1, zero, soma)
ret = retorna(1, 5, 0)
print(ret)

O resultado da função, como está é 1. Mas se eu colocar print (soma) no lugar de return soma (e chamar a função sem print), ela me dá:
1, 3, 6, 10, 15.

Por que isso acontece? Eu queria conseguir exibir apenas o último resultado, 15, no caso.
Podem me ajudar e me dar mais algum exemplo para eu entender?
Comment: O objetivo é praticar a recursividade ? Porque isto seria muito mais facil e faria muito mais sentido de forma iterativa.
Comment: Quase, o objetivo é aprender recursividade.
Comment: @IagoPaschoal Alguma das respostas resolveu sua dúvida? Acha que pode aceitar uma delas? Veja o [tour] como fazer isso, se ainda não o fez. Você ajudaria a comunidade identificando qual foi a melhor solução para você. Pode aceitar apenas uma delas. Mas pode votar em qualquer pergunta ou resposta que achar útil no site todo (quando tiver pontuação suficiente).
Answer: Primeiro: este código funciona melhor iterativamente e não recursiva. Deixe para aprender recursão com problemas que precisam ser recursivos e aprenda melhor.
Um erro básico é que não está retornando o resultado da recursão, está só chamando a função e jogando fora seu resultado. E ainda está fazendo isso condicionalmente já que está dentro do if, não pode, ele deve executar todas as vezes, exceto a última.
O código poderia ter nome de variável mais significativo para saber do que se trata. A soma de n parece uma linha sem sentido ali, deveria ter a soma na função recursiva.
Exceto na última vez o retorno deve ser sempre o próprio resultado da função, toda recursão é assim.
def retorna(valor, limite, soma):
    if valor > limite:
        return soma
    return retorna(valor + 1, limite, soma + valor)
print(retorna(1, 5, 0))

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Comment: Obrigado.
Mais uma coisa, se puder... Não entendi o critério de parada. Por que ele não fica em looping infinito? já que está para sempre retornar o "retorna(valor + 1, limite, soma + valor" ???
Comment: @IagoPaschoal você não viu que tem um `if`? Ali define a parada. Leu a parte `Exceto na última vez`?
Comment: Vi o if. Ele não sai do if e depois cai no "return retorna(valor........)"???
Comment: @IagoPaschoal você entende o que é um `if`? E o que é um `return`?
Comment: Até o momento, achava que sim.
O if faz parte da estrutura condicional. Se uma comparação depois do if for verdadeira, então o que está aninhado dentro do if é executado. Caso contrŕtio, o que está aninhado dentro do if não é executado.

O return retorna algum valor para a função. (mas creio não estar ainda muito claro o conceito de return na minha cabeça).

A pergunta continua... e se puder recomendar algo sobre o return, agradeço.
Comment: É, o `return` encerra a função e nada mais é executado nela.
Comment: Uou, agora entendi. O return além de retornar um valor, funciona como break. Só mais uma coisa. Qual é a diferença entre chamar a função com ""return retorna(valor + 1, limite, soma + valor)"" ou sem o return, apenas assim ""retorna(valor + 1, limite, soma + valor)""?
Comment: EU ach oque você precisa aprender de maneira estruturada, tem um monte de pequenos detalhes que fazem toda diferença. Aprender por demanda não costuma dar certo, cria a ilusão que está aprendendo. Programar é entender tudo o que está acontecendo, não ter uma visão por cima. A primeira estão retornando o valor da função chamada, a segunda não está.
Comment: Valeu. E por onde eu aprendo a maneira estruturada?
Comment: Livros e cursos de primeira linha.
Answer: Se a função deve retornar a soma de um conjunto de inteiros, podemos definir matematicamente o problema. Consideremos que o intervalo seja definido por a e b: [a, b], sendo b maior ou igual a a. Assim, temos:

Esta expressão pode ser expandida como:

E é trivial perceber que pode ser reescrita como:

Que é nada mais que a forma recursiva da função de soma. Mas isso não pode ser infinito, caso contrário seu programa irá rodar eternamente. Precisamos de uma situação em que a escrita recursiva possa ser simplificada, gerando o que chamamos de condição de parada.
Para este exemplo, podemos analisar a situação quando o intervalo [a, b] chega no caso particular em que a é igual a b, ficando:

Isto é, quando a = b, sabemos que a soma será apenas b.
Assim, podemos definir a nossa função somar, que recebe os valores a e b:
def somar(a, b):
    return a + somar(a+1, b) if a < b else b

Assim, como esperado, ao fazermos somar(1, 5) teremos o resultado 15.


SQLite vs Couchbase Lite for Xamarin app

Question: Our company is creating an enterprise app using Xamarin that will be deployed on Windows 10, iOS, and Android devices.
Our developers only have experience with relational databases and we like the more structured nature of SQL, so our plan is to go with SQLite. Are there any reasons we should consider Couchbase Lite instead?
Answer: This is a very subjective question and here are some subjective reasons why you might consider it:

Couchbase Mobile allows you to use Sync Gateway to sync data from the device to other devices (and to a Couchbase Server if you want)
You don't have to worry as much about your schema changing between versions of your app
It's easier to store complex hierarchy (i.e. you don't have to use multiple tables and foreign keys as much)

For more p̶r̶o̶p̶a̶g̶a̶n̶d̶a̶ information, check out the Couchbase Mobile Developer Portal.
Comment: That lines up with what I've read, thanks for the answer. We already have a sync process built and have a simple db so will probably stick with SQLite. Thanks!


Subspaces of normal spaces aren't always normal

Question: An exercise I'm working on asks to identify the error in the below proof.
(False) Statement: Prove that normality is hereditary.
Proof.
Suppose $X$ is normal with $Y \subset X$. Let $E$, $F$ be closed in $X$ with $E \cap F = \varnothing$. Then
$$G = E \cap Y \hspace{1cm} H = F \cap Y$$
are closed in $Y$. Since $X$ is normal, there exist $X$-open sets, $U$ and $V$ so that
$$E \subset U \hspace{0.5cm} F \subset V \hspace{0.5cm} U \cap V = \varnothing$$
Then $U \cap Y$ and $V \cap Y$ are open in $X$. Moreover,
$$G \subset U \cap Y \hspace{1cm} H \subset V \cap Y$$
and so $Y$ is normal. Thus, normality is hereditary.

I cannot see the error with the proof given here. Any advice on what goes wrong?
Comment: When you say "Since $X$ is normal, there exist . . ." don't you need $E\cap F=\varnothing$?
Comment: @bof yes I edited it. It's fixed now
Comment: Why do you think your Statement is wrong?
Comment: @miracle173 this is a Q&A site. I Q'd, now you A. If I thought I knew why the statement was wrong, I wouldn't be on this site.
Comment: @cheesefoot no, I see now that the exercise said the statement ist wrong. I missed this, when I read the question
Answer: Normality is only preserved bij closed subspaces. To see this, let $(X,\mathcal{T})$ be a normal topological space and let $Y \subseteq X$ be closed, where $(Y,\mathcal{T}|_Y)$ is equipped with the subspace topology.
Let $A,B \subseteq Y$ be closed in $Y$, then they are also closed in $X$. Hence open sets $U,V \subseteq X$ exist such that $A \subseteq U$, $B \subseteq V$ and $U \cap V = \emptyset$. But then $U \cap Y$ and $V \cap Y$ are open sets in $Y$ still containing $A$ and $B$ respectively, and of course $(U \cap Y)\cap(V \cap Y) = \emptyset$. So $(Y,\mathcal{T}|_Y)$ is normal.
The fact that this does NOT carry over to open sets, can easily be disproved by a counterexample.
Let $X = \{a,b,c,d\}$ and $\mathcal{T} = \{ \emptyset,\{d\},\{b,d\},\{c,d\},\{b,c,d\},X\}$. Then $(X,\mathcal{T})$ is a topology, and because it has no pair of disjoint non-empty closed subsets, it is ny default normal. Consider $Y = \{b,c,d\}$ however (and mark that this is an open subset of $X$).Then $\mathcal{T}|_Y = \{\emptyset,\{d\},\{b,d\},\{c,d\},Y\}$ in which $\{b\}$ and $\{c\}$ are disjoint closed sets in $(Y,\mathcal{T}|_Y)$ that cannot be separated by disjoint open sets in $(Y,\mathcal{T}|_Y)$. Hence $(Y,\mathcal{T}|_Y)$ is not normal.
Answer: I think the error is in the beginning when you pick G and H. As I read this, you are considering some arbitrary closed subsets of $X$, say $E$ and $F$ where $E\cap F=\emptyset$ and then considering $G=E\cap Y$ and $H=F\cap Y$. Note, that in order to show that $Y$ is normal, you must consider arbitrary closed sets $G$ and $H$ in $Y$ such that $G\cap H=\emptyset$. Then, we can say that there are closed sets $E$ and $F$ in $X$ such that $G=E\cap Y$ and $H=F\cap Y$, but this does not imply that $E\cap F=\emptyset$. The fact that $E\cap F=\emptyset$ is key to your argument here, and I believe is the flaw.


Unable to connect to Sql server 2016 express

Question: I have two sql server installed in my machine. The 2016 one shows SQL Server(MSSQLSERVER) name and 2014 one SQLEXPRESS respectively.
When I log in from sql server management studio using this hostname\SQLEXPRESS I get loggged into 2014 instance
but when I try to access 2016 version using this hostname\MSSQLSERVER It gives me below error:

a network-related or instance-specific error 26.The server was not
  found or was not accessible.

In sevice.msc i can see both SQLEXPRESS and MSSQLSERVER up and running.
Comment: MSSQLSERVER being the default instance, you can simply access it with
Comment: Is The Browser server for sql running properly And Also check the Name Pipe is Enable or Not
Comment: @dean is correct. Just connect to `hostname`
Answer: Run SQL Server Configuration Manager
Expand SQL Server Network Configuration
You should see Protocols for MSSQLServer and Protocols for SQLEXPRESS
Check that the protocols you wish to use are enabled for each instance
If using TCP/IP - Select TCP/IP in the right pane
Right Click and select Properties
Select the IP Addresses tab
Scroll Down to IPAll and change the dynamic ports to 0 (Zero)
You need to do this for both instances
Restart the SQL Server Services


Drawing Circle with OpenGL

Question: I'm trying to draw simple circle with C++/OpenGl
my code is:
#include <GL/glut.h>
#include <math.h>

void Draw() {
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 1.0, 1.0);

    glBegin(GL_QUADS);
      glColor3f (0.0, 0.0, 0.0);

      glVertex3f (0.1, 0.1, 0.0);
      glVertex3f (0.9, 0.1, 0.0);
      glVertex3f (0.9, 0.9, 0.0);
      glVertex3f (0.1, 0.9, 0.0);

    glEnd();

    glFlush();
}

void DrawCircle(float cx, float cy, float r, int num_segments)
{
    glBegin(GL_LINE_LOOP);
    for(int ii = 0; ii < num_segments; ii++)
    {
        float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle

        float x = r * cosf(theta);//calculate the x component
        float y = r * sinf(theta);//calculate the y component

        glVertex2f(x + cx, y + cy);//output vertex

    }
    glEnd();
}

void Initialize() {
    glClearColor(1.0, 1.0, 1.0, 0.0);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(0.0, 1.0, 0.0, 1.0, -1.0, 1.0);
}

int main(int iArgc, char** cppArgv) {
    glutInit(&iArgc, cppArgv);
    glutInitDisplayMode(GLUT_SINGLE | GLUT_RGB);
    glutInitWindowSize(950, 500);
    glutInitWindowPosition(200, 200);
    glutCreateWindow("Universum");
    Initialize();
    glutDisplayFunc(Draw);
    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f(1.0, 1.0, 1.0);
    DrawCircle(0.5, 0.5, 0.2, 5);

    glutMainLoop();
    return 0;

}

I'm beginner with OpenGL and now i'm starting to learn,
Can someone please explain me why i don't get the circle (i only see the black box).
Answer: It looks like immediately after you draw the circle, you go into the main glut loop, where you've set the Draw() function to draw every time through the loop. So it's probably drawing the circle, then erasing it immediately and drawing the square. You should probably either make DrawCircle() your glutDisplayFunc(), or call DrawCircle() from Draw().
Comment: To get a filled circle you could change GL_LINE_LOOP to GL_TRIANGLE_FAN.
Comment: Ty! calling DrawCircle() from Draw() - it worked!

btw is there a method to make the circle filled with color?
Comment: As mentioned above, use `GL_TRIANGLE_FAN`, but note that you'll need to put the first point in the center of the circle.
Comment: @user1118321: A vertex in the center isn't actually needed, since the shape is convex.
Answer: #include <Windows.h>
#include <GL/glu.h>
#include <GL/glut.h>
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define window_width  1080
#define window_height 720
void drawFilledSun(){
    //static float angle;
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
    glTranslatef(0, 0, -10);
    int i, x, y;
    double radius = 0.30;
    //glColor3ub(253, 184, 19);
    glColor3ub(255, 0, 0);
    double twicePi = 2.0 * 3.142;
    x = 0, y = 0;
    glBegin(GL_TRIANGLE_FAN); //BEGIN CIRCLE
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= 20; i++)   {
        glVertex2f (
            (x + (radius * cos(i * twicePi / 20))), (y + (radius * sin(i * twicePi / 20)))
            );
    }
    glEnd(); //END
}
void DrawCircle(float cx, float cy, float r, int num_segments) {
    glBegin(GL_LINE_LOOP);
    for (int ii = 0; ii < num_segments; ii++)   {
        float theta = 2.0f * 3.1415926f * float(ii) / float(num_segments);//get the current angle
        float x = r * cosf(theta);//calculate the x component
        float y = r * sinf(theta);//calculate the y component
        glVertex2f(x + cx, y + cy);//output vertex
    }
    glEnd();
}
void main_loop_function() {
    int c;
    drawFilledSun();
    DrawCircle(0, 0, 0.7, 100);
    glutSwapBuffers();
    c = getchar();
}
void GL_Setup(int width, int height) {
    glViewport(0, 0, width, height);
    glMatrixMode(GL_PROJECTION);
    glEnable(GL_DEPTH_TEST);
    gluPerspective(45, (float)width / height, .1, 100);
    glMatrixMode(GL_MODELVIEW);
}
int main(int argc, char** argv) {
    glutInit(&argc, argv);
    glutInitWindowSize(window_width, window_height);
    glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE);
    glutCreateWindow("GLUT Example!!!");
    glutIdleFunc(main_loop_function);
    GL_Setup(window_width, window_height);
    glutMainLoop();
}

This is what I did. I hope this helps. Two types of circle are here. Filled and unfilled.
Answer: There is another way to draw a circle - draw it in fragment shader.
Create a quad:
float right = 0.5;
float bottom = -0.5;
float left = -0.5;
float top = 0.5;
float quad[20] = {
    //x, y, z, lx, ly
    right, bottom, 0, 1.0, -1.0,
    right, top, 0, 1.0, 1.0,
    left, top, 0, -1.0, 1.0,
    left, bottom, 0, -1.0, -1.0,
};

Bind VBO:
unsigned int glBuffer;
glGenBuffers(1, &glBuffer);
glBindBuffer(GL_ARRAY_BUFFER, glBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)*20, quad, GL_STATIC_DRAW);

and draw:
#define BUFFER_OFFSET(i) ((char *)NULL + (i))
glEnableVertexAttribArray(ATTRIB_VERTEX);
glEnableVertexAttribArray(ATTRIB_VALUE);
glVertexAttribPointer(ATTRIB_VERTEX , 3, GL_FLOAT, GL_FALSE, 20, 0);
glVertexAttribPointer(ATTRIB_VALUE , 2, GL_FLOAT, GL_FALSE, 20, BUFFER_OFFSET(12));
glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

Vertex shader
attribute vec2 value;
uniform mat4 viewMatrix;
uniform mat4 projectionMatrix;
varying vec2 val;
void main() {
    val = value;
    gl_Position = projectionMatrix*viewMatrix*vertex;
}

Fragment shader
varying vec2 val;
void main() {
    float R = 1.0;
    float R2 = 0.5;
    float dist = sqrt(dot(val,val));
    if (dist >= R || dist <= R2) {
        discard;
    }
    float sm = smoothstep(R,R-0.01,dist);
    float sm2 = smoothstep(R2,R2+0.01,dist);
    float alpha = sm*sm2;
    gl_FragColor = vec4(0.0, 0.0, 1.0, alpha);
}

Don't forget to enable alpha blending:
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA,GL_ONE_MINUS_SRC_ALPHA);

UPDATE: Read more
Comment: Some ideas: Instead of `sqrt(dot(val,val))` use the builtin `distance` function. Better yet, use `dot(val,val)` with adjusted `R` and `R2` values to save a `sqrt` operation. Replacing `discard` with setting alpha to 0 may or may not improve performance.
Answer:
We will find the value of X and Y from this image. We know, sinθ=vertical/hypotenuse and cosθ=base/hypotenuse from the image we can say X=base and Y=vertical. Now we can write X=hypotenuse * cosθ and Y=hypotenuse * sinθ.

Now look at this code

void display(){
float x,y;
glColor3f(1, 1, 0);
for(double i =0; i <= 360;){
    glBegin(GL_TRIANGLES);
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    i=i+.5;
    x=5*cos(i);
    y=5*sin(i);
    glVertex2d(x, y);
    glVertex2d(0, 0);
    glEnd();
    i=i+.5;
}
glEnd();

glutSwapBuffers();
}

Answer: glBegin(GL_POLYGON);                        // Middle circle
double radius = 0.2;
double ori_x = 0.0;                         // the origin or center of circle
double ori_y = 0.0;
for (int i = 0; i <= 300; i++) {
    double angle = 2 * PI * i / 300;
    double x = cos(angle) * radius;
    double y = sin(angle) * radius;
    glVertex2d(ori_x + x, ori_y + y);
}
glEnd();

Comment: While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value.
Comment: //I did this with the following code,
//but make sure you had imported the needed library
Answer: Here is a code to draw a fill elipse, you can use the same method but replacing de xcenter and y center with radius
void drawFilledelipse(GLfloat x, GLfloat y, GLfloat xcenter,GLfloat ycenter) {
    int i;
    int triangleAmount = 20; //# of triangles used to draw circle

    //GLfloat radius = 0.8f; //radius
    GLfloat twicePi = 2.0f * PI;

    glBegin(GL_TRIANGLE_FAN);
    glVertex2f(x, y); // center of circle
    for (i = 0; i <= triangleAmount; i++) {
        glVertex2f(
            x + ((xcenter+1)* cos(i * twicePi / triangleAmount)),
            y + ((ycenter-1)* sin(i * twicePi / triangleAmount))
        );
    }
    glEnd();
}

Answer: I have done it using the following code,
glBegin(GL.GL_LINE_LOOP);
     for(int i =0; i <= 300; i++){
         double angle = 2 * Math.PI * i / 300;
         double x = Math.cos(angle);
         double y = Math.sin(angle);
         gl.glVertex2d(x,y);
     }
glEnd();

Answer: glBegin(GL_POLYGON);
double x = 2;
double y = 2;
for (int i = 0; i <= 360; i++) {
    glVertex2d(x * sin(i), y * cos(i));
}
glEnd();

Comment: This answer is no different from the other answers present here. I am voting to close it.
Comment: downvoted this.  so many things wrong with this code.  cos is x/r, sin is y/r, so you got that backwards.  sin and cos take radian input.

Drawing Circle with OpenGL


How to use the language neutral url alias pattern in pathauto?

Question: I want to use the following patterns in pathauto:

myCT All languages: pattern1
myCT neutral language: pattern2
myCT EN language: pattern2

So that all neutral (UND) and EN nodes of myCT have pattern2 and all other languages have pattern1. I'm using the ALL languages pattern for all other, as I have many other languages that should have the same pattern and I do not want to repeat it.
I'm using entity translation module for myCT.
When I create a node and save it having the default language (UND) and automatic path alias, pattern1 is always generated. I have to re-edit the node to have it get the correct pattern (for UND/neutral language), pattern2.
First of all, the pathauto_pattern_load_by_entity function (pathauto.module file) is called before the node creation, so the language of the node is always UND during creation of a node.
Second, trying to debug the pathauto module I can see the following:
function pathauto_pattern_load_by_entity($entity, $bundle = '', $language = LANGUAGE_NONE) {
  $patterns = &drupal_static(__FUNCTION__, array());

  $pattern_id = "$entity:$bundle:$language";
  if (!isset($patterns[$pattern_id])) {
    $variables = array();
    if ($language != LANGUAGE_NONE) {
      $variables[] = "pathauto_{$entity}_{$bundle}_{$language}_pattern";
    }
    if ($bundle) {
      $variables[] = "pathauto_{$entity}_{$bundle}_pattern";
    }
    $variables[] = "pathauto_{$entity}_pattern";

    foreach ($variables as $variable) {
      if ($pattern = trim(variable_get($variable, ''))) {
        break;
      }
    }

    $patterns[$pattern_id] = $pattern;
  }

  return $patterns[$pattern_id];
}

So in the following lines it seems that it never takes into account the neutral language path.
if ($language != LANGUAGE_NONE) {
   $variables[] = "pathauto_{$entity}_{$bundle}_{$language}_pattern";
}

Shouldn't that if statement be removed? How is it possible to use the neutral language path otherwise?
Answer: You can use the Pathauto i18n module:

This module provides functionality to create aliases for each
  language. Also this module will be helpful, if you use field
  translation and you want show node on all language with paths,
  different from node/nid.
Answer: Good point, I was thinking the same too.
Rather then the line to be removed there should be a check for LANGUAGE_NONE to set a pattern in the variables array for "und"-language. Then if not set the language specific pattern in the array.
I opened an issue and posted a patch, please check out https://www.drupal.org/node/2438745
Comment: Thank you for the patch. I hope it get included in the next release of Pathauto.


Active = False ante de iniciar uma aplicação Delphi

Question: Sempre que trabalhamos no Datamodule no componente de conexão, ativamos para fazer testes e afins. Acontece que, se esquecermos de desativar quando compilamos, pode dar erro quando enviamos para o cliente devido ao IP ou usuário e senha serem diferentes no desenvolvimento e produção.
Eu utilizo o componente TZConnection da Zeos, mas acho que isso vale pra todos.
Gostaria de saber se tem como desativar o componente antes ou no onCreate do form. Já vi que no evento onCreate não adianta, pois ele ativa a conexão antes mesmo do onCreate.
Answer: Resolvi tratando no evento BeforeConnect do componente, ali eu seto todas as variaveis referente a conexao levando em conta se é Desenvolvimento ou Produção.
Answer: desde a faculdade aprendi a realizar esse tipo de procedimento no evento OnShow ao invés do OnCreate.
e outra dica que sempre utilizo é deixar um DataModule padrão no servidor salvo e outro para uso diario nas demais maquinas, ai quando vou compilar os fontes sempre acaba pegando o padrao, ai esse tipo de erro por esquecimento acaba não ocorrendo.
Comment: Então @Leonardo Maciel, eu resolvi tratando no BeforeConnect do componente, assim não importa se eu esquecer como Active, pois eu seto as configurações antes de ele conectar.


Hide comments and show them using views

Question: Am using views to display the comments below my node types in drupal 7.
The view works fine but i can't find a way to hide the regular drupal comments above the form.
How do i just display the comment form and the comments using views.
Answer: In node.tpl
<code>    hide($content['comments']);
</code>
This hides both the comment form and the comments.
To render the comment form alone use
<code>    print render($content['comments']['comment_form']);
</code>
Then you can create your view for them nice comments and display them below the form.

Hide comments and show them using views


SVN Redirect cycle

Question: so ive installed SVN on my centos 6.5,  version 1.6.11
and im trying to configure that in /var/www/html/svn/testrepo will be my repository,
so i found alot of guides in google and used all of them to try to do that,
here is my subversion.conf
LoadModule dav_svn_module     modules/mod_dav_svn.so
LoadModule authz_svn_module   modules/mod_authz_svn.so

#
# Example configuration to enable HTTP access for a directory
# containing Subversion repositories, "/var/www/svn".  Each repository
# must be both:
#
#   a) readable and writable by the 'apache' user, and
#
#   b) labelled with the 'httpd_sys_content_t' context if using
#   SELinux
#
#
# To create a new repository "http://localhost/repos/stuff" using
# this configuration, run as root:
#
#   # cd /var/www/svn
#   # svnadmin create stuff
#   # chown -R apache.apache stuff
#   # chcon -R -t httpd_sys_content_t stuff
#

<Location /unixmen1>
   DAV svn
   SVNParentPath /var/www/html/svn
# Require SSL connection for password protection.
# SSLRequireSSL

      AuthType Basic
      AuthName "Subversion repos"
      AuthUserFile /etc/svn-auth-users
      Require valid-user

</Location>

now i checked and i found out that /etc/svn-pass and /etc/svn-auth-users are the same ...
also i dont see svn folder in /var/ which is weird because it is shown in all of the guides,
i tried those guides :
http://www.if-not-true-then-false.com/2010/install-svn-subversion-server-on-fedora-centos-red-hat-rhel/
https://wiki.centos.org/HowTos/Subversion
just cant figure wht the hell ive done wrong ...
and by the way this is the first time i try to setup svn ...
EDIT:
now after i played with it for a bit i can access via browser the whole directory but i cant connect to the repo with tortoiseSVN i get an redirection cycle error
and the httpd/access log says :
 192.168.1.36 - - [19/Nov/2015:14:44:19 +0200] "OPTIONS /svn/unixmen1 HTTP/1.1" 301 319 "-" "SVN/1.9.2 (x64-microsoft-windows)
serf/1.3.8 TortoiseSVN-18.104.22.168806"

this was in the error log :
    [Thu Nov 19 14:40:38 2015] [notice] Apache/2.2.15 (Unix) DAV/2 SVN/1.6.11 configured -- resuming normal operations
[Thu Nov 19 14:44:04 2015] [notice] caught SIGTERM, shutting down
[Thu Nov 19 14:44:09 2015] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec)
[Thu Nov 19 14:44:09 2015] [notice] Digest: generating secret for digest authentication ...
[Thu Nov 19 14:44:09 2015] [notice] Digest: done
[Thu Nov 19 14:44:09 2015] [notice] Apache/2.2.15 (Unix) DAV/2 SVN/1.6.11 configured -- resuming normal operations

and i changed the subversion.conf file aswell (edited the file above)
the etc/svn-auth-users got 1 user in it but the svn doesnt even require credentials, just says that there's a redirection cycle for the URL :
192.168.1.14/svn/unixmen1
[root@SVN svn]# cd /var/www/html/svn/unixmen1/
[root@SVN unixmen1]# ls -als
total 36
4 drwxr-xr-x 7 apache apache 4096 Nov 19 12:43 .
4 drwxr-xr-x 3 root   root   4096 Nov 19 09:47 ..
4 drwxr-xr-x 2 apache apache 4096 Nov 19 09:47 conf
4 drwxr-sr-x 6 apache apache 4096 Nov 19 09:47 db
4 -r--r--r-- 1 apache apache    2 Nov 19 09:47 format
4 drwxr-xr-x 2 apache apache 4096 Nov 19 09:47 hooks
4 drwxr-xr-x 2 apache apache 4096 Nov 19 09:47 locks
4 drwxr-xr-x 2 root   root   4096 Nov 19 12:43 project1
4 -rw-r--r-- 1 apache apache  229 Nov 19 09:47 README.txt
[root@SVN unixmen1]#

would really appreciate if someone could help me.
Answer:
Show DocumentRoot for Apache's mainhost. I suppose, it's below /var/www/html/svn/ and it's big error
I see cd /var/www/html/svn/unixmen1/, i.e virtual path from <Location> exist as real physical path (and even inside DocumentRoot??? - see p.1) - this is giant NO-NO

Common rules (dirty short draft) for Apache-served SVN-repos

Repositories places at any location outside web-root
DAV-Location doesn't exist as real path inside DocumentRoot (unique name)
SVNParentPath used for serving family of repositories with common 1-st parent, SVNPath - for serving single repo

I.e, f.e.:

var/repos/Name1 ... var/repos/NameN are paths to repositories
var/www/html is DocumentRoot
URL for the repos have to be smth. like http://HOST/repositories/NameX

your configuration will be (relevant part)
# if mod_dav was compiled as a shared object (instead of statically linked)
LoadModule dav_module         modules/mod_dav.so
LoadModule
LoadModule
...
<Location /repositories>
   ...
   SVNParentPath /var/repos/
   ...
</Location>

SVN Redirect cycle