Using db_query and joins

Question: I am using Drupal 6 and trying to use db_query to delete rows from a table based on joins in order to untag a certain node of all tags of certain vocabulary.
This http://drupal.org/node/1079620 implies that delete doesn't work when using joins.
So I have a tried all the following forms of $queries:
<code>1) $query = "DELETE a FROM {term_node} a LEFT JOIN {term_data} b ON a.tid = b.tid WHERE a.nid = %d AND b.vid = %d";

2) $query = "DELETE a FROM {term_node} a, {term_data} b WHERE a.tid = b.tid AND a.nid = %d AND b.vid = %d";

3) $query = "DELETE FROM a USING {term_node} AS a, {term_data} AS b WHERE (a.tid = b.tid) AND a.nid = %d AND b.vid = %d";
</code>
Before running
<code>$result = db_query($query, $nid, $vid);
</code>
None of them deletes the rows from database. I have checked that $nid and $vid get the appropriate values and when I take of the curly brackets and run the query in phpMyAdmin it works like a charm.
I tried to perform simple query where there are no needs from joins. It didn't work either. But once again it works perfectly if I run the query in phpMyAdmin.
I started thinking could it be somehow related to the Drupal batch processing. The delete query not working gets executed when feeds module is performing a batch process (importing nodes to Drupal). So does Drupal during batch process somehow restrict access to tables or something? I didn't find anything in the mysql logs.
Comment: I think the first thing to do is find out what query's actually being executed on the db (MySQL?). (You can do this eg. with devel.module or by adding a temporary `dpm()` in `db_query()` or `_db_query()`.)
Answer: Some thing you can try doing is try printing the entire query string like,
<code>$query = "DELETE a FROM {term_node} a LEFT JOIN {term_data} b ON a.tid = b.tid WHERE a.nid = ".$nid." AND b.vid = ".$vid;
print $query; //printing the query
</code>
Notice that I have used the variables instead of place holders %d. This might not be relevant but has helped me many times while debugging queries.
On the link you mentioned http://drupal.org/node/1079620, have you tried #5 ? if not give that a try, it should work IMO.
Comment: I tried #5. It didn't help at this case.
Answer: A thing that has bitten me in the past is PHP's "I'm not a typed language until I am a typed language," so throwing a cast into the mix, eg,
<code>$result=db_query($query, (int) $nid, (int) $vid);
</code>
has solved some of these problems for me.
Comment: Didn't solve the problem in my case.
Comment: I updated my question.
Answer: I am curious on the other answers coming, and too lazy to go test this out in dummy d7 instance, I would consider not using left joins with the delete operation.
I think I would try using 2 queries instead of a join.  I just think it would be the next possible options short of using subqueries, but those don`t seem really well supported by D6 db_select anyhow.  So the simplest approach when confronted one can try to divide and conquer. Just use 2 queries, I would consider as an alluring alternate approach.
I'll post working  code example during the week-end if you really need one,  but it's basically a 10 liner maybe 15 max.
Good-day, happy coding

Using db_query and joins


Can't attach #ajax to altered form displayed in block

Question: I have a module that displays an existing signup form in a block.
function my_contact_block_view($delta = '') {
    switch ($delta) {

        // Newsletter signup block
        case 'newsletter_signup':
            $block = my_contact_get_emma_block();
            break;
    }
    return $block;
}

I make some minor alterations to the form. Some markup elements are removed from the form (this works), and I am attaching an #ajax property to the submit element (this doesn't seem to work):
function my_contact_get_emma_block(){
    $form = drupal_get_form('my_contact_emma_form');

    // get wrapping markup
    $header = variable_get('my_contact_emma_block_header', '');
    $footer = variable_get('my_contact_emma_block_footer', '');

    // unset some stuff
    unset($form['heading']);
    unset($form['copy']);
    unset($form['required_blurb']);
    unset($form['privacy_blurb']);

    // alter some stuff
    $form['fname']['#attributes']['placeholder'] = t('First');
    $form['lname']['#attributes']['placeholder'] = t('Last');
    $form['email']['#attributes']['placeholder'] = t('Email');

    // config to submit via ajax
    $form['submit']['#ajax'] = array(
    'callback' => 'my_contact_emma_form_ajax_submit',
    'wrapper' => 'brd-contact-emma-form',
    'method' => 'replace',
    'effect' => 'fade',
    );

    // render the form
    $form = drupal_render($form);
    $markup = $header . $form . $footer;

    // return renderable array for block
    return array(
        'subject' => t('Event Email Sign-Up?'),
        'content' => array(
            '#type' => 'markup',
            '#markup' => $markup,
        ),
    );
}

Unfortunately, it never hits my ajax submit function.  Instead the page submits to the normal submit routine (my_contact_emma_form_submit).
/**
 * Ajax callback function. (Never called)
 */
function my_contact_emma_form_ajax_submit($form, $form_state) {
  // Dummy/dumb validation for demo purpose.
  if (!empty($form_state['input']['email'])) {
    return 'Subscribed !';
  }
  else {
    return $form;
  }
}

What am I doing wrong?
Answer: drupal_get_form will return a builded form/ rendered form. i.e Your form has been already prepared based on the specification done in the form callback, like its finalized.
So making changes to the return values of drupal_get_form wont work.
If you want to alter any of the form then you should use any of the following hook

hook_form_alter
hook_form_FORM_ID_alter
Comment: Ok, I kind of thought that might be the case.  But why are other changes working (placeholders, markup elements, etc)?
Answer: The real problem here is that my whole approach was wrong.  I should not have been trying to bend the same form to serve multiple purposes.
If all I needed to do was minor alterations the display of the form (which were working above), I probably could have gotten away with it.  But when I tried to do things like change the submission method things got sticky. And when I realized that I wanted to show the user a different result for ajax submissions (a simple 'Ok!' instead of a whole confirmation page), things really broke down.
What prevented me from doing what I want is that there is no way to detect the difference between Form A submitted from a block and Form A submitted from a page.  Because I couldn't differentiate between them, I could not use hook_form_alter (or similar) to create 2 different use cases.
Ultimately, the solution was to basically duplicate the first form, make all the alterations in my original post in that form, and handle the ajax there as well.
Comment: You can detect the difference between Form A submitted from a block and Form A submitted from a page. You could call `drupal_get_form` with params. Like `$param1 = 'is_page';` or `$is_page = TRUE`. Then type `drupal_get_form('my_contact_emma_form', $param1, $param2);`. And then in form you can use them and set in values and whatever. `function my_contact_emma_form($form, &$form_state, $param1, $param2){...}`
Answer: Try using button instead of submit.
$form['submit']['#type'] = 'button';


Dependency in Use Case Diagrams

Question: I'm working on a high-level Use Case Diagram for a business system and want to express a relationship between 2 separate Use Cases, as follows:

Actor1 performs UseCase1
Actor2 performs UseCase2
But the results of UseCase2 are in someway affected by UseCase1.

Is it correct to represent this relationship as a dependency,
UseCase2 ---> UseCase1?
Answer: There is nothing in the norm about that, so it is not possible to understand the role of the dependency looking at your diagram.
It is very common for an UC to affect the system so to have consequences on other UCs execution, and we don't try to show that (look at How to draw a use case diagram when an actor can change the other actor's use cases?
Of course if you really want you can add a profile&stereotype for instance <<affect>> and use it for your dependency, with associated explanations. But if you start to do that you will have a lot the dependencies <<affect>> in your diagrams and they will be unreadable.
The right way is to not only do diagrams but also to add textual descriptions explaining the goal/effects of each UC (and of course actors) more possible pre/post conditions etc
Comment: Thank you, your answer and link helped. I have been labeling these dependency relationships in my actual diagrams but unsure if it was acceptable to make-up names for the relationships. I have been frequently writing <> but had not confirmed until now whether it was incorrect to do so.

Dependency in Use Case Diagrams


Proof using logic consequence. Is this correct?

Question: Try to proof this using the definition of logic consequence.
$\forall x(\alpha \rightarrow \beta), \forall x \alpha \models \forall x \beta$
Let's say that: $\Gamma = \alpha \rightarrow \beta$, by definition of logic consequence: for all interpretation $\mathfrak{I}\models\Gamma$ must then  $\mathfrak{I}\models\forall x \beta$.
Suppose any interpretation $\mathfrak{I}$ such that $\mathfrak{I}\models\Gamma$.
With this i have that $\mathfrak{I}$ satisfy this two cases:
1) $\mathfrak{I}\models\forall x(\alpha \rightarrow \beta)$
By definition of relation of satisfaction of "$\forall$":
for all a $\in$ A, $\mathfrak{I}[a/x]\models(\alpha \rightarrow \beta)$
By definition of relation of satisfaction of "$\rightarrow$":
for all a $\in$ A, if $\mathfrak{I}[a/x]\models\alpha$ then $\mathfrak{I}[a/x]\models\beta$
2) $\mathfrak{I}\models\forall x \alpha$.
By definition of relation of satisfaction of "$\forall$":
for all a $\in$ A, $\mathfrak{I}[a/x]\models\alpha$
So, since there is a interpretation that satisfy 1) and this interpretation also satisfy 2). By Modus Ponens(1 and 2) we have:
for all a $\in$ A, $\mathfrak{I}[a/x]\models \beta$.
By definition of relation of satisfaction of "$\forall$" we have:
$\mathfrak{I}\models\forall x \beta$.
This proof is correct?
Answer: Yes, your proof looks correct.


Issue with finally not appearing at the end of the code in console

Question: Is anyone so kind to advise how can I make .finally message: "End of promise" appear at the end of the code instead of at the beginning?

const posts = [
  { title: "Post One", body: "This is post one" },
  { title: "Post Two", body: "This is post two" },
];

function getPosts() {
  setTimeout(() => {
    posts.forEach((post) => {
      console.log(post.title, post.body);
    });
  }, 1000);
}

function createPostPromise(post) {
  return new Promise((resolve, reject) => {
    const error = false;
    if (!error) {
      setTimeout(() => {
        posts.push(post);
        resolve(true);
      });
    } else {
      reject("Error: Something went wrong");
    }
  }, 2000);
}

createPostPromise({ title: "Post Three", body: "This is post three" })
  .then(getPosts)
  .catch((err) => console.log(err))
  .finally(() => {
    console.log("End of promise");
  });
Comment: `setTimeout` is asynchronous
Comment: @RocketHazmat correction, `getPosts` is run after *the first* promise is resolved. It just queues a timer that fires in the future. But the function does run *before* all the promises settle and *before* the `.finally` callback executes.
Comment: `getPosts` does not return a promise so your code is pretty much the same as `getPosts(); console.log("End of promise");` since there is nothing to define how to wait for `getPosts` to finish. It just starts a timer and completes instantly. [You can turn it into a promise producing function](https://stackoverflow.com/questions/22707475/how-to-make-a-promise-from-settimeout), if you wish.
Comment: Your `getPosts` is ran via `.then()`.  This happens after all the promises are resolved.  `getPosts` has a `setTimeout` so that's scheduled to run in the future.  So, with `.then()` "done", it moves on to `.finally()`.  Eventually, in the future the `setTimeout` from `getPosts` is ran.
Comment: Thanks - I have converted getPosts so that it returned a Promise and now it works :)
Answer: The code does exactly what you tell it to do: getPosts sets a callback to log the posts in one second, then returns immediately. You probably meant getPosts to be an async function (= a function that returns a promise) that resolves after logging the posts:

const posts = [{
    title: "Post One",
    body: "This is post one"
  },
  {
    title: "Post Two",
    body: "This is post two"
  },
];

function getPosts() {
  return new Promise((resolve) => {
    setTimeout(() => {
      posts.forEach((post) => {
        console.log(post.title, post.body);
      });
      resolve();
    }, 1000);
  })
}

function createPostPromise(post) {
  return new Promise((resolve, reject) => {
    const error = false;
    if (!error) {
      setTimeout(() => {
        posts.push(post);
        resolve(true);
      });
    } else {
      reject("Error: Something went wrong");
    }
  }, 2000);
}

createPostPromise({
    title: "Post Three",
    body: "This is post three"
  })
  .then(getPosts)
  .catch((err) => console.log(err))
  .finally(() => {
    console.log("End of promise");
  });
Comment: Thats exactly what I have done after reading the first few comments.
Thanks a lot for confirming that my solution is correct.


Edit of page with captcha requires solving captcha?

Question: I just added a captcha to a page and it seems that the users with edit permission have to solve the captcha in order to edit/save the page. Is this normal behavior?  Is there a setting that will allow for editing w/o having to solve the captcha?
Answer: Making the assumption that you're using the CAPTCHA module there is a permission called Skip CAPTCHA you should configure for your editor's roles to skip it.


Can I make Pattern Password Screen Locker android app

Question: Has anyone got experience with developing an application to replace the default lock screen? I've been told it is not possible, however this application manages it.
Any tutorials or guidance you know of would be appreciated.
Comment: This is the best Android Pattern Locker code :        http://www.androidviews.net/2012/11/android-lock-pattern/
Comment: @Arshu link not found
Comment: @nida : Follow these links: https://github.com/coderkiss/AppLock

https://code.google.com/p/android-lockpattern/
Answer: 100% possible. Here are some links to get you started.
Android App and Pattern Lock Screen
Android Lock Screen Widget
Developing a custom lock screen
Answer: You can implement deviceAdminReciever to use device locks and all please have a look at this it explains everything about locks setting passwords.....
Update:
Use this library  Link
and Source Here..
Comment: That link is no good, android 2.2 is out of date. Plus it wasnt until recently you could use the pattern matching api's. Read what the link you posted says "Device Administration API currently only supports passwords for screen lock"
Comment: know check my answere
Answer: Try this one:
lockscreenswitchwidget
Comment: please expand your answere link only answeres are ussually down-voted


How to choose a guitar pedal power supply?

Question: I have a Boss BCB 30 pedal board with daisy chain. I have three pedals: TU2, CS3 and DD3. I was planning to pick up an universal power adapter I can use with it. I'm not that literate coming to electronics, so what should I look for when I pick a power adapter for this purpose?
Comment: I'm pretty sure Boss makes an adapter to power their pedals. Since you are happy with the Boss line, you might just continue down that road.
Comment: Yes, I know their Boss PSA adapter would be a safe pick, but that's not my question. :)
Comment: I made it a comment for that reason. Maybe if you mention why you aren't happy just getting the Boss adapter(s), it will make your question clearer. Without more information, it's tempting to recommend you simply look for a power adapter that will be compatible with your pedals. What else do you need?
Comment: I need an adapter to be used for several different purposes rather than buying 10 different adapters that is pricy because of brand.
Comment: Ok, that helps. So you want to be able to power other pedals in the future besides just the Boss ones you already have?
Comment: Yes, so what I'm asking for is simply what I should look for considering current etc.
Answer: It's best to have the pedals picked out and/or purchased before finding a power supply for them, because there are some strange power requirements out there and it's hard to know what you need until you have it. That said, there are some power supplies that give you options to change the settings for one or more outputs to give you some flexibility.
There are some (usually boutique) pedals for which there are no power supplies that can power them with just a straight connection. The MuFX Tru-Tron is just one example.
Power for a pedal needs to fit three criteria:

Whether the power is AC or DC must exactly match
The voltage must exactly match
The current provided by the power supply must be equal to or greater than the current needed by the pedal

The most common power requirement for a guitar pedal is almost certainly DC, 9V, and 100 mA or less. So, most power supplies either only supply that kind of power, or have most of the power outputs designed to supply that configuration.
One more thing you may very rarely have to be aware of is the polarity of the power needed by the pedal. As far as I know, the only pedals likely to have reversed polarity are those with germanium transistors (usually vintage style fuzz pedals). You can power those with either a polarity-reversed connection or with an isolated power output or dedicated supply.
When looking at a device that can power multiple pedals, some of them will have a dedicated amount of current for each power output, and others will have a total amount of current that they can handle for all the connected pedals. For the ones with individual current supplies, each supply must be enough for the pedal plugged into it. For the total current style, the sum of the current needs for all the connected pedals must be less than or equal to the total supply.
Beyond having the power requirements met, there are some extras that the more expensive power supplies may offer. Isolated outputs are nice for keeping pedals supplied correctly and allowing for reverse polarity pedals. Other add-ons include more outputs, unusual power options, accessory outlets, voltage sag (to simulate old batteries), mounting brackets for rack or pedalboard mounting, etc.
The information above is for the output of the power supply, to match the input(s) of the pedal(s) that will be connected to it. The input for a power supply should match the building's power outlets. Power supplies should either have a sticker on them or a page in their manual detailing the input and output parameters. Here is an example sticker:

Notice that the input is AC and the output is DC. Also note that it says "0.5A" instead of "500 mA", which are two different ways to say the same amount of current is available. The polarity is shown by the circles and lines right under the output line. The polarity diagram on this sticker indicates standard polarity, often called "tip negative". This power supply could supply at least five standard pedals that require standard polarity 9V DC power of 100 mA or less.
Comment: Thanks for a very informative answer. I thought I had followed these criterias on my setup (in my question), and got myself a 9v 1000mA AC power adapter with reversed polarity. But I only got it working when connect to only one pedal, but not all with daisy chain.
Comment: Are you trying to buy something different or figure out why the one you have is not working? If it works with one pedal then the **output** is certainly DC, even though the **input** is AC. Any power supply should have both input and output specifications. I'll add that to the answer.
Comment: I actually got a universal adapter that doesn't seem to work, which should work according to the information I've read about pedals. But unfortunately it don't work, so I got interested in what I may have overlooked. The adapter has IN: 100-240 V, 50/60 Hz, 0,3 A, and OUT: 9 volt 1000 mA, and reversed polarity. According to the PSA adapter, and information given, I cannot see why it won't work.
Comment: Most of the DC adapters I ever had to test were negative on the collar, so yeah, "check the polarity": good tip.
Comment: @janlindso It might have been better to have asked your specific question, since it seems now like you still don't have the information you wanted. I agree that the daisy chain cable may be the problem. You might check to see if it works with two pedals instead of one or three.
Comment: Note that polarity is only important for the OUTPUT when it's D.C.   A.C output cares less. If mixing pedals, some with neg. tip, some with pos. tip, it's necessary to ensure the 'reverse polarity' pedals have a rewired cable, the 'wrong way round', if you like.
Comment: I disagree strongly with "exactly match."   For AC vs DC, it's not really a "match" so much as AC will do BadThings to a non-protected DC circuit.  As to the input DC (or AC) voltage,  most circuits will run just fine over a wide range of inputs.   A 9-VDC rated item will probably function fine from 6 to 11 V input (although the upper end may shorten the lifetime a bit).    What matters most, since nearly all pedals/switches run on DC, is how well your supply filters all line noise from the 120VAC wall source.
Comment: @CarlWitthoft I was writing in a way to provide a basic guide to getting power that will definitely work for someone who describs themselves as not having a lot of understanding about electronics, not so much trying to make any firm statements about electrical consequences of different combinations of power supplies versus power needs. I wanted to write for the worst-case scenario, and since there are pedals that are less flexible about DC input voltage, I deliberately recommended matching that, rather than going into details - about which you are correct.
Comment: @ToddWilcox Your answer is the information I wanted, and that's why I just accepted it. Your answer made me understand what I wanted to know. But in the same time it didn't HELP me in that sense that my adapter don't work. I will check the daisy chain as mentioned here. If it still don't work, I might try to pick up a official Boss adapter, as I didn't intend to.
Comment: @janlindso I suggest with future questions, make it about the exact situation if that's what you want to resolve. In this case, if you had written "I have this adapter and it's not working, what am I doing wrong?" it would have been easier for us to actually address that issue instead of giving you general information about how power supplies work.
Comment: @ToddWilcox can you please [take a look](https://music.stackexchange.com/questions/75609/standard-effect-pedal-connector-size)?
Answer: You want an adapter that conforms to the wall plug in your country. In the US, that's 120V.
After that, a quick check indicates that Boss adapters output 9v (or 9.5v; makes sense since they are designed for 9v batteries) and I see photos of most of them supplying 200mA. I don't think most pedals draw anywhere close to 200mA (probably more like 10mA max; the CS-3 manual says 11mA for that one), and the power draw is straight additive so two would be 20mA etc.
The Boss website has one that can supply 9v at 500mA. So the BOSS-branded range off the shelf is going to be between 200mA and 500mA.
Most of the pedals I have actually held in my hand have had the specs on the bottom sticker.
The male-end connector is standardized for voltage as far as I know, so if it fits, and you can see the specs on the brick or in the manual, you ought to be fine. I have a very old one from Radio Shack which is switchable from 1.5v to 12v and has a swappable plug end for each voltage rating. I expect it was in the 5$ range.
So for US: INPUT: standard 120v AC 60Hz OUTPUT: 9.Xv DC 200mA-500mA
Comment: I suppose an easy way to test the cable is to simply take the one device that works and plug it into each connector in turn. If the single device works on each connector, then it probably is not a manufacturing defect.
Comment: Just tried a universal adapter with 9v, 1000 mA. Check for correct polarity. I worked for one pedal, but not all through daisy chain. And on one pedal it was more noisy than with battery. But shouldn't it in theory work?
Comment: I would suspect the daisy chain. If you have a voltmeter, you can test the connectors by switching the meter to the proper dc voltage range and then putting the positive probe inside the connector tube and touch the ground probe to the outer collar. Transformers are EM noisy, move it away/alter the angle, and try plugging it into the same power strip as your amplifier.
Comment: I'll see if I can borrow a voltmeter, but the daisy chain is completely unused from the package, so it should be OK.
Comment: There's no guarantee that each pedal won't feed some AC noise back onto the power line, so a pure daisy-chain cable may pass that noise around; or it could simply be acting as a ground-loop antenna.  I'd stick with supplies that have independent output ports.


How to migrate files together with additional fields

Question: In my Drupal 8.4 installation I use the module File Entity. In the module are defined a few additional fields: 'author', 'title', 'alt',... My migration works. The files are imported, but the additional fields are after the import empty.
The complete YML (modules\my_migration_module\config\install\migrate_plus.migration.files.yml) looks like:
langcode: en
status: true
id: files
migration_group: import_xml
label: 'Import the test XML file'
source:
  plugin: url
  data_fetcher_plugin: file
  urls: 'http://example.org/test.xml'
  data_parser_plugin: xml
  item_selector: /imports/files
  fields:
    -
      name: id
      label: ID
      selector: ./@id
    -
      name: title
      label: Title
      selector: ./@title
    -
      name: alt
      label: Alt
      selector: ./@alt
    -
      name: author
      label: Author
      selector: ./@author
    -
      name: filename
      label: Filename
      selector: ./@filename
    -
      name: uri
      label: URI
      selector: ./@uri
    -
      name: target
      label: Target
      selector: ./@target
  keys:
    - id
  ids:
    id:
      type: string
process:
  field_alt: alt
  field_title: title
  field_author: author
  filename: filename
  uri:
    plugin: download
    source:
      - uri
      - target
destination:
  plugin: 'entity:file'
  source_path_property: uri
  destination_path_property: target
template: null

E.g. for the field title I have tried:
field_title: title
title: title
field_title/field_title_value: title
field_title/field_title_value: title
field_title/field_title: title
file__field_titel/field_title_value: title
file__field_titel/field_title: title

I have found a solution for a similar problem in Drupal 7: How to migrate fields attached to files? I'm not sure, how can I implement this in Drupal 8.
Comment: Do you migrate files with additional fields from d7 to d8? Have you tried to implement a custom source plugin? There you can specify on prepareRow()   function some additional fields to migrate.
Comment: No, I import the files from XML.
Comment: Have you tried using `simple_xml` instead of `xml` as `data_parser_plugin`? I also had a some problems with a XML import that were solved by changing nothing execpt the data_parser_plugin
Comment: I have tried to change 'data_parser_plugin: xml' to 'data_parser_plugin: simple_xml'. But it did not helped. And I've got then the warning "Illegal string offset 'x-default' ContentEntityBase.php:949",
Comment: I have found the following issue. May be it is the reason, why the additional fields are not imported. See: https://www.drupal.org/project/drupal/issues/2822545
Answer: The YML code is correct. But there is an issue in Drupal core: https://www.drupal.org/project/drupal/issues/2822545
There is also a patch. I have tested the patch and it works:
https://www.drupal.org/files/issues/2822545-cannot_update_file_properties-6.patch
The patch can be installed with Composer:
{
    ...
    "require": {
        "cweagans/composer-patches": "~1.0",
        "drupal/core": "8.4.6",
        ...
    },
    ...
    "extra": {
        "patches": {
           "drupal/core": {
             "Solve the issue when migrating files with additional fields": "https://www.drupal.org/files/issues/2822545-cannot_update_file_properties-6.patch"
            }
        }
    }
}


Fazer uma consulta com pymongo filtrando por uma string ignorando letras maiusculas e minusculas

Question: Preciso fazer uma consulta em uma base de dados no MongoDB usando a biblioteca pymongo no python, a consulta que estou a fazer é a seguinte:
dbCliente.find({"nome": "carlos"})

Quero retornar o cliente cujo o nome seja exatamente "carlos" porém ignorando letras maiúsculas ou minusculas.
Como faço essa consulta usando pymongo?
Comment: Tenta com [regex](https://docs.mongodb.com/v2.2/reference/operator/query/regex/) :`dbCliente.find({"nome":{ $regex: 'carlos', $options: 'i' } })`
Answer: O caminho mais correto seria criar um índice que seja case insensitive
Criando a coleção
db.createCollection("nomes", { collation: { locale: 'pt_BR', strength: 2 } })

Criando índice
db.nomes.createIndex( { nome: 1} )

Inserindo nomes
db.nomes.insert( [ { nome: "Carlos" },
                   { nome: "CARLOS"},
                   { nome: "carlos"} ] )

Buscando
db.nomes.find( { nome: "carlos" } )

Nota: irá encontrar os três resultados
No seu caso, você poderá usar
dbCliente.find({"nome": "carlos"})

Answer: Uma outra maneira é utilizando o módulo re, que inclui opções para expressões regulares:
import re
dbCliente.find({"nome": re.compile("carlos", re.IGNORECASE))


Django: Passing Kwargs as form Values to generic CBV Form

Question: I have a form in which the value of the first field can be determined by the URL. ie: example.com/value/form in which value is the appropriate response to the first field on the form.
How can I pass this value to the form on the page?
class VarietyCreate(CreateView):
    template_name = "generic_create.html"
    model = Variety
    form_class = VarietyForm
    pk_url_kwarg = "pk"
    initial = {"product_group" : pk_url_kwarg}

    def get_success_url(self):
        return reverse("purchases:Variety Index", kwargs={'pk': self.kwargs.get('pk')})

What I have does not seem to work.
From my URLs:
url(r'^commodities/view/(?P<pk>[^\/]+)/create/$', views.VarietyCreate.as_view(), name='Variety Create'),

Answer: Found the answer based on this post.
class VarietyCreate(CreateView):
    template_name = "generic_create.html"
    model = Variety
    form_class = VarietyForm

    def get_initial(self):
        return {"product_group" : self.kwargs.get('pk')}

    def get_success_url(self):
        return reverse("purchases:Variety Index", kwargs={'pk': self.kwargs.get('pk')})


Spinner performclick() not working

Question: I want the spinner to open up by itself when I run the activity, so I'm using the performClick() method but it's showing this error:
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
What should I do?
Here is my code
public class FacilityComplaint extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
    private Spinner spinner1;

    private static final String[] suggestions = {"Select from suggestions", "Switch not working",
            "Switch faulty", "Switch light not working", "Switch handle faulty"};

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

        spinner1 = (Spinner) findViewById(R.id.spinner1);
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(FacilityComplaint.this,
                android.R.layout.simple_spinner_item, suggestions);

        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner1.setAdapter(adapter);
        spinner1.setOnItemSelectedListener(this);
        spinner1.performClick();
    }

    public void onItemSelected(AdapterView<?> parent, View v, int position, long id) {

        switch (position) {
            case 0:
                //do something
                break;

            case 1:
                //do something
                break;

            case 2:
                //do something
                break;

            case 3:
                //do something
                break;

            case 4:
                //do something
                break;
        }
    }

    public void onNothingSelected(AdapterView<?> parent) {

    }

}

Answer: For spinner you have don't need to implement "AdapterView.OnItemSelectedListener" Create like this .
spinner1 = (Spinner) findViewById(R.id. spinner1);
    ArrayAdapter adapter = ArrayAdapter.createFromResource(this,
            suggestions, android.R.layout.simple_spinner_item);
    adapter1.setDropDownViewResource(
            android.R.layout.simple_spinner_dropdown_item);
    spinner1.setAdapter(adapter);
    spinner1.performClick();

// Get selecte index or Suggestions
spinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView<?> parent, View view,
            int pos, long id) {
        String selectedSugg = suggestions[pos];
        Log.d("Suggestions ", selectedSugg);
    }

    @Override
    public void onNothingSelected(AdapterView<?> arg0) {

    }
});

Comment: i'm getting an error that ArrayAdapter.createFromResource expects Int as a second argument but 'suggestions' is of string type. What should I do?  Note that the spinner was working before, I only want it to open up by itself without the user clicking it, that was why i added the performClick() and then the error start showing. Thanks1

Spinner performclick() not working


Calculating summary statistics on a distribution of "day of year" data [R]

Question: Say I have a dataset that consists of 1,000 integers between 1 and 365 that represent days of the year a certain event happened. I am trying to figure out how I could calculate summary statistics of the distribution while respecting the fact that the data are cyclic (i.e. 1 and 365 are neighbors). I specifically want to calculate the median value and the values of at specific quantiles (.025 and .975).
Here is an example of a distribution I'd like to calculate these values for:

I can't quite figure out how to do this. I think I may need to do something like map the values to a circle, but this is not something I am familiar with (and R libraries like circular do not have much documentation that pertains to this sort of situation).
I am using R, so I would very much appreciate possible R code solutions!
EDIT
I am going to add a bit more information to make it clear why I want to do this.
For simplicity, say I am trying to model which day of the year kids  are happiest. I have happiness data, and I generate a model that estimates happiest doy. Now I want to know the uncertainty of this estimate.
These 1000 values are draws from a bootstrap that estimates the happiest doy for each bootstrap. I want to summarize this info using the median value and the 95% CI for this estimate.
I don't want to simply show the distribution, because say I am repeating this for 100 different countries and want to just show the median+CI in a table.
Comment: The fundamental question is: what do you hope a median or quantile would represent?  How do **you** define them for circular data?
Comment: I want to describe this distribution. In actuality, these values are akin to a bootstrap distribution of estimates of a day of the year at which a certain event happens. I want to be able to say what the average value across 1000 bootstraps is and what the CI is for that average value. Does that make sense?
Comment: Your graph already is a great description.  Generally, any statistical description focuses on a small number of salient or important properties of the dataset or its inferred data-generating process.  You have now changed the properties you refer to (from percentiles to an average), so it's worth asking for confirmation: what kind of "average value" do you seek?  One way to answer that would be to explain how you plan to interpret it (or how you intend your audience to interpret it).
Comment: I have a number of these distributions, and I want to be able to show how they differ at a glance (say in a table). For this purpose, I was thinking of showing median value and CI for each one.
Comment: Isn't a graphic *ideal* for "at a glance" assessment?
Comment: Yes, though as I said, there are many of these--too many to make a sort of stacked histogram. Either way, this is a tangent to the original question.
Comment: Research "small multiple."  It is an extremely effective solution.  As far as tangential goes, perhaps: but do you want a literal but likely meaningless or useless answer to the question your asked, or would you like to solve the problem that motivated it?
Answer: You specify more than summarizing a distribution: this is a distribution relative to the day the event happened.  You wish, then, to summarize the differences.  Although these are still circular data, they have a natural origin (0) and are signed.
This enables us to make sense of your original request.  When you sort the signed differences (lying between $-183$ and $+183$), the median is the middle value.  A nonparametric confidence interval can be found in the standard way using order statistics as described at https://stats.stackexchange.com/a/284970/919 and https://stats.stackexchange.com/a/160148/919.  BTW, these are not the same as the $1-\alpha/2$ and $\alpha/2$ quantiles of the distribution.

There's one tiny technical issue: what do you do when your bootstrap is diametrically opposite the reference value?  That is, it's exactly 183 days away (let's suppose this is even possible because perhaps you are considering leap years) and you need to represent it as a deviation of either $+183$ or $-183.$  I would suggest, even though this is ad hoc, splitting the difference and introducing both values into your dataset, each with weight $1/2.$
Why?

This is superior to just dropping such values, because it retains all the data, which will yield more accurate values for the confidence interval.

It implicitly supposes your error distribution is approximately symmetric.  Thus, the likelihood that this is a positive error equals the likelihood it is a negative error.

It's not really any more difficult to compute weighted quantiles and weighted order statistics: you just put the weights of your data in the same order as the data and compute cumulative sums.

If your bootstrap is producing a highly asymmetrical error distribution, then you would need to do something more sophisticated.  But in that case you likely need a more complicated summary of the results in the first place.

An alternative, which is fairly robust because these are circular data (thereby with bounded, compact support), is to use the square root of a circular variance.  Convert each of your $n$ deviations (a signed number of days) into an angle $\theta$ (divide by 365, 366, or 365.25 as appropriate, then multiply by $2\pi$), convert that to Cartesian coordinates $(x,y)=(\cos\theta, \sin\theta),$ compute their means $(\bar x,\bar y)$ separately for each coordinate, and convert that to an angle and back to a number of days.  This estimates the bias.
For the circular dispersion, set $R^2 = (\bar x)^2 + (\bar y)^2$ to be the squared length of that mean vector and report $\sqrt{-\log(R^2)},$ converted back to days.
To illustrate, and provide all details, here is R code to compute the circular mean and dispersion.  The function expects your data vector in theta and the length of your year (in any units you desire) in modulus.  It returns a vector of two values: the circular mean and circular dispersion.
summary.circular <- function(theta, modulus = 2 * pi) {
  angles <- theta / modulus * 2 * pi # Convert to angles
  xy <- cbind(cos(angles), sin(angles))         # Cartesian coordinates
  xy.bar <- colMeans(xy)
  R2 <- sum(xy.bar^2)
  c(Mean = atan2(xy.bar[2], xy.bar[1]) / (2 * pi) * modulus,
    Dispersion = sqrt(-log(R2)) / (2 * pi) * modulus)
}

As an example of how this works, let's generate some realistic looking data.  I have chosen a true date of January 30 (day of year is 30) and a bias of +5 days.
set.seed(17)
day.actual <- 30 # True date
bias <- 5
sigma <- 25      # Nominal dispersion (of the normal values used for data generation)
n <- 1e3         # Dataset size
U <- 183 * (runif(n) < 0.05) # Used to generate some outlying values
day.simulated <- round(day.actual + bias + rnorm(n, U, sigma)) %% 365
hist(day.simulated, breaks = seq(0, 365, length.out = 51),
     main = "Simulated Data", xlab = "Day of year")

Here is a summary of a thousand such values:

On this histogram I have drawn the circular mean as a red dashed line and the true reference date as a blue line, illustrating the use of summary.circular:
stats <- summary.circular(day.simulated, 365)
abline(v = stats[1], lwd = 2, col = "Red", lty = 3)

The value in stats for these data is
      Mean Dispersion
  35.33973   38.02667

Because the input data are in days, these statistics are in days, too.  Their bias is $35.33973 - 30 = 5.33973,$ differing from the intended value of $5$ only because of the random generation of these data.
Comment: This is fantastic! Thank you for the thorough explanation! I will put it to the test :)
Answer: You probably want statistics on when the observed events $E$ happened relative to a reference point $R$. If so, this can be calculated as:
((E-R+182.5) %% 365) - 182.5

where %% is the function known mathematically as $\text{mod}$. This formula produces a number of days between $-182$ and $+182$, negative for events up to half a year before $R$, and positive for events up to half a year after $R$. All the usual statistics can be calculated based on these differences.
It probably does not make sense to use the mean of your data as a reference point, precisely because means of circular statistics are not obvious.
A good possibility for a reference point could be:

a holiday
a solstice or equinox
the first day of a month
the first day of a hunting season
the mode of your data, calculated as  names(sort(-table(E)))[1].

Any of these can work for $R$, so long
as there are few events which are half a year from $R$, and so long as a phrase like "five days before $R$" will make intuitive sense.
EDIT
In the example above, you can:

Use the modal happiest day in each country as its reference point,

e.g.: Christmas.

Convert calendar days to signed integers using the first formula above,

e.g.: two days before Christmas or three days after Christmas.

Calculate statistics on those integers as usual,

e.g.: a mean of 4 days before Christmas and sd of 5 days.

Convert the statistics back to calendar days,

e.g.: a mean of December 21, and a standard deviation of 5 days.
Comment: Oh, that is a really interesting idea! The use of a reference point could be useful in ways that go beyond the scope of this question.

However, your last point would still be an issue--if there are points that are a half year from R.

In actuality, the distribution I have plotted in my post are draws from a bootstrap procedure that is trying to show the uncertainty of my doy estimate.  I am doing this procedure for many different types of events, and I want to be able to report them succinctly. Hence why I want to get the mean/median and a CI of these values. Some may hit the 1/2 year...
Comment: If, indeed, you are researching the uncertainty (variability) in an estimate of a circular variable, then you need to change your question, because the answer is to summarize that variability in a circular metric, and *not* just to describe the distribution of the results without reference to the estimand.
Comment: I tried to edit the question a bit to help. What I want to do is provide the mean/median of these bootstrap estimates of doy while also providing an estimate of the uncertainty.


How to integrate the Fusioncharts library with Drupal 7?

Question: I have been trying to integrate the Fusioncharts library with my Drupal 7 site.
Just to check if everything is working properly, I followed this documentation for creating a basic graph with data contained in Data.xml file; the entire documentation is here.
FYI, I need to use PHP as I am more comfortable with it.
I have extracted the downloaded folder into /sites/all/libraries/FusionChartsFree/; with changes in paths (nothing else); I have pasted the code in the given example into my Drupal 7 node with the php input filter enabled. I also have the libraries module installed.
<?php
  //We've included ../Includes/FusionCharts_Gen.php, which contains FusionCharts PHP Class
  //to help us easily embed the charts.
  $name = "FusionChartsFree";
  if ($path = libraries_get_path($name)) {
    include $path . '/Code/PHP/Includes/FusionCharts.php';
  }
?>

    <?php
      //You need to include the following JS file, if you intend to embed the chart using JavaScript.
      //When you make your own charts, make sure that the path to this JS file is correct. Else, you
      //would get JavaScript errors.

      include($path.'/Code/FusionCharts/FusionCharts.js');
    ?>

    <title>FusionCharts - Simple Column 3D Chart</title>

    <?php
      //Create the chart - Column 3D Chart with data from Data/Data.xml
      echo renderChart("/sites/all/libraries/FusionChartsFree/Code/FusionCharts/Column3D.swf", "/sites/all/libraries/FusionChartsFree/Code/PHP/BasicExample/Data/Data.xml", "", "myFirst", 600, 300, false, true);
   ?>

I get the below output. It is pretty long; hence, I have put then in part by part in these pictures.

(FYI, those Flash files that appear in the output, do not display anything if I click on them.)
Now, suppose I remove the below line from the code.
<?php
 include $path . '/Code/FusionCharts/FusionCharts.js';
?>

I get nothing. I mean only a text which reads "cahrt" in the below output.

My Question: How can I make Fusioncharts work in DRUPAL 7?
I am also having similar trouble with the pChart library too: Even pChart does not display anything, not even an error, or warning. Simply there is nothing in the node body.
Answer: There's a couple of problems in your code:

include($path.'/Code/PHP/Includes/FusionCharts.php'); you have to use ./ to include files.
include($path.'/Code/FusionCharts/FusionCharts.js'); you should use drupal_add_js() to include javascript in your code.
FusionCharts documentation seems a little old as Column3D.swf is now FCF_Column3D.swf

Here is a working example, I haven't used the librarie module but you should be able to adapt it easily. I put this code in a node with PHP filter activated.
<?php
$file = './sites/all/libraries/FusionChartsFree/Code/PHP/Includes/FusionCharts.php';
if (is_file($file)) {
  require_once $file;
}
drupal_add_js('sites/all/libraries/FusionChartsFree/Code/FusionCharts/FusionCharts.js');

//Create the chart - Column 3D Chart with data from Data/Data.xml
echo renderChart("/sites/all/libraries/FusionChartsFree/Code/FusionCharts/FCF_Column3D.swf", "/sites/all/libraries/FusionChartsFree/Code/PHP/BasicExample/Data/Data.xml", "", "myFirst", 600, 300, false, true);

?>

Comment: Thank you so much..!! But still I have small problem,  I get a flash player icon hwere I can click it load the graph. but when I click it, its empty..!
Comment: before I click,  http://oi44.tinypic.com/300s0i8.jpg    after I click, http://oi39.tinypic.com/33z7f5v.jpg
Comment: Also can you tell me how to do it in phpclass.of fusionchart..? I followed this documentation , made the necessary cahnges as u said (about the path and adding js) http://docs.fusioncharts.com/free/Contents/PHPClass_BasicExamples.html . But all I see is a text "chart" on my node.FYI, I tried both examples given on that page and got same results. Am getting too frustrated with this..:( So please help me.
Comment: This is rather strange, using the code as is works for me in chrome: http://i.imgur.com/UzWFx.png
For the PHPClass the only important thing is to get the `  $FC->setSwfPath("../../FusionCharts/");` path correctly.
Comment: I done everything properly..!! I have no idea what to do.. how can I create graphs now..?? I tried flot module but even that having problems,http://drupal.stackexchange.com/questions/23588/using-flot-with-drupal-7
Comment: Do u know any other way I can create graphs in D7..?? What's the solution to my problem now..??
Comment: Double check your paths to see if everything is in the right place. Try on a clean new Drupal 7 install.
Comment: there is nothing wrong with the paths, I checked..! Am gonna give another try on a new d7 install...
Comment: could there be some other module which is interfering with the working of fusioncharts..? or could there be some otherthings need to be installed for it to work..?? for eg., do I need swftools..? (its required for openflashchart, and fusioonchart is also a flash chart. but there is no d7 version of swftools yet.) Can you tell me what are th external modules you have installed, so that I can cross check and see if anything is wrong with one that I have installed..??
Comment: Hey, I tried with all other modules except core modules uninstalled and it still didn't work..!!
Answer: Finally, it worked. I don't know exactly what the problem is, but here is what I did.

I uninstalled all other modules related to charting
I downloaded FusionchartFree again
I sed the Libraries module
I checked with the following code, and it worked.
$name = "FusionChartsFree";
if ($path = libraries_get_path($name)) {
  include $path . '/Code/PHP/Includes/FusionCharts.php';
  drupal_add_js($path.'/Code/FusionCharts/FusionCharts.js');
}

// Create the chart - Column 3D Chart with data from Data/Data.xml

echo renderChart($path.'/Charts/FCF_Column3D.swf', $path.'/Code/PHP/BasicExample/Data/Data.xml', "", "myFirst", 600, 300, false, true);


PHP e MySQL: Banco de dados não atualiza

Question: Boa tarde a todos, eu estou fazendo uma tela para edição de informações pessoais.
O meu código para capturar os dados digitados é este:
<?php
require("../config/functions.php");
require("../classes/BDConnection.class.php");
require("../classes/Academico.class.php");
session_start();

$connection = new BDConnection();
$connection->Connect();
$con = $connection->getConnection();

$login = $_SESSION['usuario'];
$password = $_SESSION['senha'];

$email = ClearString($_POST['Email'], $con);

//VERIFICAR SE O NOVO EMAIL JÁ EXISTE NO SISTEMA, EXCETO O DO PRÓPRIO USUÁRIO QUE ESTÁ ALTERANDO
$result = mysqli_query($con, "SELECT email FROM academico WHERE email='".$email."' AND (login <> '".$login."' AND senha <>'".$password."');");
if(mysqli_num_rows($result) >= 1){
    echo "";
    die();
}

$user = new Academico();

//INFORMAÇÕES PESSOAIS
$user->setNome(ClearString($_POST['NomeCompleto'], $con));
$user->setDataNascimento( ClearString($_POST['DataNascimento'], $con));
$user->setTelefone( (!empty($_POST['TelFixo'])) ? ClearString($_POST['TelFixo'], $con) : null);
$user->setCelular(ClearString($_POST['TelCelular'], $con));

$user->setEmail($email);

$user->setCidade(ClearString($_POST['CidadeNatal'], $con));
$user->setEndereco(ClearString($_POST['Endereco'], $con));
$user->setBairro(ClearString($_POST['Bairro'], $con));

$user->setComentario( !empty($_POST['ComentarioAdicional']) ? ClearString($_POST['ComentarioAdicional'], $con) : null);

if($user->AtualizarDados($con)){
    echo "";
}else{
    die('
Erro ao atualizar dados.

'.mysqli_error($con));
}

?>

Os dados estão sendo capturados normalmente, eu testei todas as variáveis com echo, porém quando chamo o método AtualizarDados(), é retornada a mensagem de sucesso, entretanto os dados não estão sendo atualizados no BD.
método AtualizarDados():
function AtualizarDados($con){
        $result = mysqli_query($con, "UPDATE academico SET nome='".$this->nome."', email='".$this->email."', data_nascimento='".$this->dataNascimento."', endereco='".$this->dataNascimento."', cidade='".$this->cidade."', telefone='".$this->telefone."', celular='".$this->celular."', comentario='".$this->comentario."', bairro='".$this->comentario."' WHERE login='".$this->login."' AND senha='".$this->senha."';")  or die('ERRO: '.mysqli_error($con));

        if(!mysqli_error($con)){
            return true;
        }else{
            return false;
        }
    }

O que estou fazendo de errado?
Comment: É totalmente não recomendado receber os valores do POST diretamente na *query* sql. Você precisa tratar as entradas antes. Para isso existe o PDO ou no caso MySQLi. Dê uma olhada no *link* a seguir:
[Evitando SQL Inject](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) Uma maneira fácil de se trabalhar com o banco de dados é utilizar uma biblioteca chamada RedBeans: [http://www.redbeanphp.com/](http://www.redbeanphp.com/) Dê uma olhada na página oficial. Tem exemplos super fáceis de como utilizar.
Answer: function AtualizarDados($con){
$sql = "UPDATE academico SET nome='".$this->nome."', email='".$this->email."', data_nascimento='".$this->dataNascimento."', endereco='".$this->endereco."', cidade='".$this->cidade."', telefone='".$this->telefone."', celular='".$this->celular."', comentario='".$this->comentario."', bairro='".$this->comentario."' WHERE login='".$this->login."' AND senha='".$this->senha."'";

   if ($con->query($sql) === TRUE) {
       echo "Atualização feita com sucesso!";
   } else {
       echo "Error ao atualizar: " . $con->error;
   }
}

Tenta fazer isso. (CORRIGIDO)
Comment: continua com o mesmo problema, dá a mensagem de sucesso, mas quando eu verifico os dados no BD, eles não mudaram
Comment: Acho que achei!

data_nascimento='".$this->dataNascimento."', endereco='".$this->dataNascimento."' <<< Os valores estão repetidos
Comment: Muito obrigado pela ajuda!
Answer: Existe duas situações, se você quer saber se executou o comando ou se o comando afetou registros. No caso pra saber se ele alterou algum registro é com o affected_rows.
if($mysqli->affected_rows > 0){
    return true; // registros alterados
}else{
    return false; // não alterado
}

Comment: Os valores de login e senha estavam sendo passados como vazio, eu tinha esquecido de setar o objeto com esses atributos... Muito obrigado pela ajuda, sua dica me mostrou o erro. resolvido!
Comment: executei esse código, e está retornando false. Será problema é no BD ou a sintaxe SQL?
Comment: @RaphaelHenrique Da um `echo` na query que você está montando: `echo "UPDATE academico SET nome='".$this->nome."', email='".$this->email."', data_nascimento='".$this->dataNascimento."', endereco='".$this->dataNascimento."', cidade='".$this->cidade."', telefone='".$this->telefone."', celular='".$this->celular."', comentario='".$this->comentario."', bairro='".$this->comentario."' WHERE login='".$this->login."' AND senha='".$this->senha."';"`
Comment: Verifica o que está aparecendo e executa a mesma query direto no banco de dados pra ver o resultado.


Why is electric guitar passive acoustic performance still important?

Question: By passive acoustic performance, I mean the acoustic performance while the guitar is not plugged into an amplifier.
Nowadays, stompboxes, postproccessing applications, and other electronic audio processors are able to change the sound of electric guitar any way the player wants. So, why are some guitar players still choosing an electric guitar by its passive acoustic performance? Is there any sound characteristic of an electric guitar we can't postprocess?
Comment: @Tom I see this question as presupposing that the acoustic sound of a solid-body electric guitar is a good basis to judge the plugged in sound, which I think is true. So the question seems to be about whether we need to judge the acoustic sound at all if the plugged in sound can be so manipulated. My answer is essentially "because we don't always want to manipulate it that much, and even if we do we can't manipulate it to make it sound like a higher quality guitar sound that hasn't been manipulated."
Comment: I don't think any guitarist uses an electric guitar without plugging it into *something*.  You're asking on the premise that the guitar is not plugged in. Maybe a translation problem?
Comment: @Dekkadeci - of course they mean it - but is that relevant to this question? I may play unplugged to practise, but rarely do. Might as well use some apparatus - amp., pedal, looper, et al... and, for performance? No-one's going to hear it !
Comment: Personally, I've always found I want a Strat to sing on its own, without the amp. A Les Paul just doesn't seem to matter. [& everything in between] My best Strat was a '64; weighed nothing, sang like a bird. My worst is a Squier 50th Anniversary, weighs a ton, sounds like rubber bands on Plasticine, plugged or unplugged. [Of course, I could have bought 70 Squiers for the price of the real '64, both technically 'second hand']
Comment: @toddwilcox Oh, okay! I had the feeling that the clean sound (is without any coloured amplifier or pedals) so partly pickups response, was the initial intention of this question but reading it again I have to say that I feel your way now... Anyway you got my vote already ;)
Comment: This makes me wonder if things like sustain can actually be accurately processed afterward.. I don't really think so, and sustain can depend a lot on the guitar's physical behavior
Comment: @Tim - Wait, so when people say they play unplugged electric guitars, they don't literally mean it?
Comment: Maybe this question should be better read as "Is the bare sound produced by an electric guitar to the jack is important"? If that's the case @toddwilcox 's answer is very good!
Comment: @Kaddath The pickups and the setup make the most difference to sustain - hot passive pickups with a low action create more magnetic damping on the string and cut down on the sustain.  Active pickups (which use weaker magnets) and a higher action, to increase the distance to the magnets, let the string ring for longer.  Wood type and hardware matter to some degree, but pickups play a big role.  [Sustain science](https://www.cycfi.com/2013/11/sustain-myth-science/), and [Related Question](https://music.stackexchange.com/q/14019/26413).
Comment: Who does this?  I've never in my life seen or heard of a guitarist judging the quality of an electric guitar by its acoustic tone.  It must be plugged in.  In fact I've always been encouraged to (1) bring my guitar in when buying an amp, and (2) mimicking my set up at the store when trying out a new guitar.
Comment: i agree with @ToddWilcox and I do think its actually a good question. Ive been conditioned into listening for it before buying but I do think its a bit snake-oil. Only thing I can think that you could truly get out of it (speaking as a bass player) is if **sufficient** sustain exists naturally in its construction or if there are any dead spots on the neck. Neither of which can really be fixed by post-processing.
Answer: You can't make a bad guitar sound like a good guitar no matter what processing you have. You can completely change the sound to something where it's not possible to tell whether it's a good or bad guitar. Sometimes people want exactly that. I find that the very popular Mesa/Boogie Dual Rectifier amp makes every guitar sound identical.
But some styles of music and some guitarists call for hearing the actual tone of the guitar itself coming through the amp. John Mayer is a famous example of someone whose tone is often very bare and really shows how his fingers and guitar sound. For him and anyone like him, the acoustic and the mechanics properties of the guitar itself will have a big impact on the final tone that comes from the amp, because there is minimal processing being done.
If you want to hear the guitar, the best way is to not process the sound very much at all. Trying to make it sound like a guitar with processing is just going to make it sound like a processed guitar, at best.
Comment: @J... Making a good guitar and a bad guitar sound the same is completely different from making a bad guitar sound like it's a good guitar. Maybe that's what's confusing about my first paragraph. When a bad guitar and good guitar sound the same after processing, it's because the processing has removed all of the original sound of the guitar and all you hear is the sound almost "re-synthesized" - like the processing has removed all of the timbre of the guitar and only preserved the pitch and then imposed a new timbre on the note.
Comment: Your first paragraph seems to be a contradiction.  You can't make a "good" and "bad" guitar sound the same... unless you plug it into an amp and effects loop that makes them sound the same.  The only conclusion here is that you *can* make a "good" guitar and a "bad" guitar sound the same (or, more to the point - that the acoustic nuances of the instrument cease to be terribly important for some styles of music). +1 for the rest of it, of course, but I think the whole first sentence is just confusing and wrong.
Comment: @J... It seems like you think it IS possible to make a bad guitar sound like a good guitar. I've never heard that done before, but I confess it could be theoretically possible and I'm just not aware of how to do it. I know hundreds of things that won't make a bad guitar sound good - I own and/or have played various quality guitars through various quality amps and effects and I've never heard a guitar that has a poor inherent tone sound like it has a better inherent tone after any kind of processing.
Comment: `Making a good guitar and a bad guitar sound the same is completely different from making a bad guitar sound like it's a good guitar` Then I guess we are at an impasse.  If two things are the same then they are not different and they are like each other.  `I find that the very popular Mesa/Boogie Dual Rectifier amp makes every guitar sound identical.`  I agree, and it seems so do you.  I also agree that not all guitars can create all possible sounds. I think that is the best you can salvage from the opening statement.
Comment: @J... Maybe an example: A 1993 Peavey Predator Strat clone into a clean Fender Blues Deluxe sounds like plastic being scraped with an ice pick. A 2003 Fender Custom Shop Relic 65 Stratocaster into a clean Fender Blues Deluxe sounds like the souls of Jimi Hendrix and Stevie Ray Vaughan have possessed your body and are singing in perfect harmony through the amp. The same two guitars plugged into a Mesa Dual Rectifier on channel 2 modern with the gain cranked both sound like a Mesa Dual Rectifier. A Mesa Dual Rectifier does **not** sound like a good guitar, it sounds like a good **amp**.
Comment: @J... The point being that even though the Mesa made both guitars sound the *same*, it didn't make either guitar sound like it was a great *guitar*. It just gave a pleasing sound that had nothing to do with the sound of the guitar. You can no longer hear the sound of the guitar when you crank a dual recto enough, you just hear the amp. That is **not** the same thing as making a bad guitar sound like a good guitar. That's making bad guitar sound like a good amp. A fan of Fender Strats might hate Mesas - they won't like that sound no matter what Strat is plugged into that Mesa.
Comment: I get what you're saying - I just think it could be better expressed (as you've done just now).  The instrument's fundamental timbre forms the basis for the space of the sounds it can express.  This we cannot easily change with effects or processing, but if the final tone objective is agnostic to those nuances then two quite different instruments can frequently serve the same role in producing that sound.  A Jagstang will never sound like Lucille, we agree.  But a $300 Les Paul clone fitted with EMG-81s and cranked on overdrive won't really sound any different from a $3000 Les Paul in same.
Answer: To add to @Todd_Wilcox 's fine answer consider this:
If you pick up different guitars and play them without an amp do you notice differences? Maybe one has a body where you can feel the resonance and another not as much. Maybe one sounds beefy and one tinny. One might have very good sustain of all the notes where another might have dead spots and even another might have notes that die out very quickly. Others might have varying degrees of action height and neck relief which will affect how the instrument plays and sounds.
Even though a pickup only gets the magnetic signal produced by the vibrating strings (unless the pickup is microphonic, a whole other discussion) factors like the quality and type of wood, construction and setup will affect what that vibrating string sounds like before it even gets to the pickup.
If a guitar doesn't sound good with nothing but a 1/4" cable directly into a clean amp I'd rather move on to the next one rather than start running it through pedals. Also, A guitar with a good fundamental tone will sound better than a mediocre one when you start to add effects and processing to it.
Comment: I just want to emphasize and possibly clarify one point in this answer: It's rare that the sound coming out of a musical instrument has to do *only* with the actual sound-producer, because there is a feedback of vibrations ("feedback" in its general-purpose sense, not screaming amplifier feedback).  With string instrumented, the vibrating string causes the wooden instrument to vibrate, which then changes the vibration of the string, which affects the vibrations in the wood, and so on.
Answer: It's much more efficient to start with a guitar that already sounds how one wants it to sound rather than trying to correct the sound of the guitar with electronics, or post-processing in the case of changing the sound of a recorded guitar.
Furthermore, guitar players simply prefer guitars that sound good to them. As a player, I very frequently pick up one of my electric guitars to practice or try to work out an idea I have in my head or even aimlessly "noodle" and I'm much more inclined to play a guitar that sounds good to me unplugged than one that does not.


Como filtrar time em um campo datime no eloquent?

Question: Como consigo comparar se um horário é igual a um horário armazenado em uma coluna datetime usando o Eloquent?
Comment: Como você está armazenando a data no banco?
Comment: nesse formato (2018-01-01 14:50:35)
Comment: Você quer que a consulta seja por data e hora ou só por hora?
Comment: consultar apenas pela hora
Answer: Considerando que você quer desconsiderar a data, mas considerar apenas o horário, você precisa usar a função TIME do Mysql para formatar a coluna com formato datetime para formato de tempo. Assim sendo, é necessário usar o método DB::raw() do Laravel, para ele aceitar uma expressão Mysql no WHERE.
Exemplo:
 // Pega todos os usuários que foram cadastrados às 23:59:01

 Usuario::where(DB::raw('TIME(created_at)'), '=', '23:59:01')->get();

Se você quiser ignorar os segundos, provavelmente terá que fazer um whereBetween, e especificar os segundos 00 e 59. Assim:
 // Retorna os usuários que foram cadastrados às 13:38, independente dos segundos

 Usuario::whereBetween(DB::raw('TIME(created_at)'), ['13:38:00', '13:38:59'])->get();

Se precisar dessas horario dinamicamente, pode usar a função date com o parâmetro H:i:s.
  Usuario::where(DB::raw('TIME(created_at)'), '=', date('H:i:s'))->get()

Além do mais, é perfeitamente possível definir a data atual, ignorando os segundos, para o caso do whereBetween
Usuario::whereBetween(DB::raw('TIME(created_at)'), [date('H:i:00'), date('H:i:59')])->get();

Atualização
A função HOUR que eu havia colocando anteriormente estava errada. HOUR retorna o valor inteiro da hora de uma data.
Por exemplo:
 2015-01-01 23:40:30

Retonaria:
 23

Já a função TIME retorna 23:40:30, como String.
Comment: Quem deu o negativo poderia explicar? Porque eu fiz a resposta exatamente como o AP pediu.
Comment: @VirgilioNovic valeu por assinalar. Realmente... O `HOUR` retorna a hora, o `TIME` retorna `23:59:01`.
Comment: @VirgilioNovic não estou muito certo, kkk. Se quem negativou antes tivesse assinalado isso, já teria feito a edição. Mas muito obrigado, cara.  Eu tinha testado com `TIME` e coloquei `HOUR` na resposta, uma grande navalhada, kkkkk
Comment: Veja não fui eu que deu o negativo, mas, a sua resposta está errada ou o usuário perguntou errado, porque? `hour` pega somente a hora e o que pude perceber na pergunta dele é horas, minutos e segundos de um `datetime`? veja a pergunta é muito confusa e até as suas respostas estão erradas, porque você pega exemplo 19 horas e compara com um hora completa também tem problemas
Comment: Foi exatamente o que ele falou pra eu fazer nos comentários. Dá uma olhada ali.
Comment: Mesmo assim as suas comparações estão erradas, é isso que eu estou querendo dizer!
Comment: Como erradas? Você testou? Eu testei aqui e deu certo. Ele pediu pra pegar "o horário que foram armazenadas". Se foi armazenada as `13:10:01` de uma data qualquer, a consulta funciona corretamente. Agora, se o usuário necessitar de outra coisa, ele é que precisa especificar na pergunta (e isso não seria motivo válido pra negativo).
Comment: Caro Wallace `Usuario::where(DB::raw('HOUR(created_at)'), '=', '23:59:01')->get();` você que precisa testar porque `23 != '23:59:01'`  ou estou enganado?
Comment: Eu acho que não entendi o `23` aí. O usuário pediu pra pesquisar pelo horário, e não pela "hora".
Comment: @VirgilioNovic ahhhhhhhhhhhhhh, sim. Você tem razão. Eu coloquei a função errada. O certo é `TIME`
Comment: se o usuário pediu para verificar pela hora blz, então deveria ser `Usuario::where(DB::raw('HOUR(created_at)'), '=', '23')` ??? ou não. porque Hour retorna somente o valor da hora
Comment: talvez agora a pessoa que viu o seu problema coloque o up para você! era bom ele ter dito... neh mas, não é assim que funciona para alguns usuários


Squid Reverse Proxy with SSL

Question: I'm trying to use squid as a reverse proxy in front of a single website, to decrypt the SSL on the proxy and then to encrypt the connection to the webserver (this is in order to use squid as an ICAP client for a zero trust CDR product).
I can see that this requires two config lines:
https_port 220.127.116.11:443 accel for the listener
and
cache_peer 220.127.116.11 parent 443 for the webserver.
Following the examples I've found here and elsewhere, I hit various errors from Squid, in particular this one:
FATAL: No valid signing certificate configured for HTTPS_port

A known-working configuration for Squid 4.x would be very helpful!
Answer: Evidently the examples I found were all for earlier versions of squid.
For this problem, my main takeaway was that cert= and key= in the https_port config line are no longer correct and we need to use tls-cert= and tls-key= instead.
So (for Squid v4.15) I just need the webserver certificate and its private key, and these lines in squid.conf:
https_port 188.8.131.52:443 accel defaultsite=mysite.com tls-cert=/etc/squid/myserver.pem
cache_peer 22.214.171.124 parent 443 0 no-query originserver login=PASS ssl

This works for a .PEM which includes the certificate and the unencrypted private key. If the key is in a separate file, this should work:
https_port 188.8.131.52:443 accel defaultsite=mysite.com tls-cert=/etc/squid/myserver.pem tls-key=/etc/squid/myserver.key
cache_peer 18.104.22.168 parent 443 0 no-query originserver login=PASS ssl

If that key is encrypted, you'll either need to start squid manually (eg run squid -N in a screen session) or add an sslpassword_program config line to provide the PEM passphrase.
NB:
I found that an http_port config line (eg http_port 3128) was still required for squid to start up.
All the configuration file directives are documented here: http://www.squid-cache.org/Doc/config/

Squid Reverse Proxy with SSL


Argument type 'lambda expression' is not assignable to parameter type 'System.Action'

Question: This issue drives me insane since past couple hours.
I have 2 versions of the same property I wrote:
public IMvxCommand ButtonClickedCommand
{
    get
    {
        return new MvxCommand(() =>
            {
                Mvx.Resolve<IMvxWebBrowserTask>().ShowWebPage("http://google.com");
            });
    }
}

And
public IMvxCommand ButtonClickedCommand
{
    get
    {
        return new MvxCommand((Action) (() =>
            {
                Mvx.Resolve<IMvxWebBrowserTask>().ShowWebPage("http://google.com");
            }));
    }
}

Both methods are correct, both are being run when button is clicked and they do what they have to do. But the first one shows me this:

The second:

If there is no solution for it, and it's some kind of a bug I will drop it, but the other project I'm working on, is using the v3 library also, and there is no such issue.
Lucas
//Edit
I'd like to add more detail to the issue, so that maybe it will help find the reason of the problem.
There is generaly no problem with lambda expressions if I write them for the methods I create myself. For example:
public void fun()
{
    fun2(() =>
             {
                 GetType();
             });
}

public void fun2(Action action)
{
}

This snippet above is using a lambda expression for the required Action parameter, so the situation very similar to the one from the first snippet, and yet there is no problem with that. The problem is, if I pass the lambda expression to the constructor of MvxCommand object that I will not explicitly cast to Action.
Answer: I doubt this has anything to do with mvvmcross or mvvm
A quick search for this error message suggests this is more likely to be down to tooling - especially r# - eg see hits like:

http://devnet.jetbrains.com/thread/292248
http://caliburn.codeplex.com/discussions/212685
http://youtrack.jetbrains.com/issue/RSRP-178647?projectKey=RSRP

If you are running any extensions like r# and you remove or disable them, then this may remove the warning.

If disabling them helps, then I would recommend asking the extension vendor(s) for support.
If disabling them does not help, then I would recommend investigating the differences between the two projects where the problem does/doesn't occur - that will hopefully yield the answer.
Comment: Suspending the R# did make the warning/error go away. It is strange that the method I wrote did not show the warning though. I will mark this message as the answer for now. I will try to investigate the problem and if I encounter the root of the cause I will post back. Thanks Stuart.


Hide div that contains specific text

Question: I want to hide a div based on the text inside. In the example below I want to hide the ones with "Handtekening" and the one with "Thuis". I prefer to do that with CSS. Is that possible?
The class names of the divs have to be the same...

     Pakket

     Handtekening

     Thuis

If not possible with CSS, how can it be done with JavaScript?
Comment: Would this be for dynamically added text?
Comment: Possible duplicate of [How to CSS: select element based on inner HTML](https://stackoverflow.com/questions/4811962/how-to-css-select-element-based-on-inner-html)
Comment: Should `thuiS` be hidden? What about `pThuisis`? Or `This is thuis text`?
Answer: Here's an easy vanilla Javascript solution:
const divs = document.getElementsByClassName('test');

for (let x = 0; x < divs.length; x++) {
    const div = divs[x];
    const content = div.textContent.trim();

    if (content == 'Handtekening' || content == 'Thuis') {
        div.style.display = 'none';
    }
}

Working JSFiddle here
Remember to include the script at the end of your HTML page (right before the  tag).
Comment: You should not use `.innerHTML` in this instance. `.textContent` would be more appropriate, or `.innerText` if you need compatibility with <IE9. In general, you should avoid using `.innerHTML`, unless you *know* it's what you *need*.
Comment: Ouch! This may work for OP's specific example, but generally it will not.  Imagine if the text I'm looking for is `img` and a div doesn't contain this text but contains an image.
Comment: Works! To make It perfect, is it also possible to use something like contains? So if the tekst inside the div is "Handtekening test" that I select on contains Handtekening?
Comment: Indeed, just use indexOf instead. Here's an updated JSFiddle: https://jsfiddle.net/1v5qed2n/2/
Comment: Yes, using `indexOf()` is safer here, for checking the content.
Answer: If you have control over the HTML output and have no problems with the text document getting twice as big, you can duplicate the content of each of those divs. Otherwise JavaScript is the way to go. Here is the CSS solution:

Pakket

Handtekening

Thuis

Then use the selector for an attribute containing a string:
div[content~=Thuis] { display:none; }

The one above will match when "Thuis" is contained in the text as a separate word. If you want to match any occurrence of the string, you should use:
div[content*=and] { display:none; }

Answer: No, it won't be possible with pure CSS. You need to use JavaScript to do it.
This is code you can use for that:
var divs = document.querySelectorAll(".test");
Array.from(divs).forEach(function(div) {
  if (div.textContent.indexOf("Handtekening") >= 0 || div.textContent.indexOf("Thuis") >= 0) {
    div.style.display = "none";
  }
});

var divs = document.querySelectorAll(".test");
Array.from(divs).forEach(function(div) {
  if (div.textContent.indexOf("Handtekening") >= 0 || div.textContent.indexOf("Thuis") >= 0) {
    div.style.display = "none";
  }
});

  Pakket

  Handtekening

  Thuis

Answer: Here's one more solution:

Array.from( document.querySelectorAll('div.test') )
  .filter( node => /\b(Handtekening|Thuis)\b/i.test(node.textContent) )
  .forEach( node => node.style.display = 'none' );

     Pakket

     HANDTEKENING

     Test thuis blah blah

The main difference from chsdk's solution is that I'm using a single regexp test instead of multiple .indexOf() calls.  IMO this is cleaner, more flexible and possibly more efficient as well.

The \b anchors in the regexp match word boundaries, so that e.g. "Thuis test" is matched but "Thuistest" is not.  I suspect this is what the OP wants, but if not, the \b anchors can easily be removed and/or replaced with something else.  For example, the regexp:
/^\s*(Handtekening|Thuis)\b/i

would match only if the words "Handtekening" or "Thuis" occur at the beginning of the content (possibly after some whitespace).  Replacing the second \b with \s*$ would also require there to be nothing (except possibly whitespace) after the matched word.
The i flag at the end of the regexp literal makes the matching case-insensitive.  If not desired, the i can simply be removed.  I wanted to include it for illustrative purposes, though.

Ps. Some older browsers (such as, notably, Internet Explorer) may not support the ES6 arrow functions and the Array.from() method used in the code above.  If compatibility with such old browsers is desired, here's an alternative implementation free from any such newfangled stuff:

var nodes = document.querySelectorAll('div.test');
for (var i = 0; i < nodes.length; i++) {
    if ( /\b(Handtekening|Thuis)\b/i.test(nodes[i].textContent) ) {
        nodes[i].style.display = 'none';
    }
}

     Pakket

     HANDTEKENING

     Test thuis blah blah

AFAICT, this should be compatible with IE down to version 9, and of course with all modern browsers as well.
Answer: You could do the easy thing of hiding the elements with a second class.
So let's say we'll add the class="hidden".
See the example below:

.test {
    color: blue;
}

.hidden {
    display: none;
    /* or visibility: hidden; */
}

    Pakket

    Handtekening

    Thuis

By adding the second class we're able to make a selection of which
 element you'd like to show and which not.
Answer: To select elements based on text you can use js and check if text is equal to ones you want to hide. If it is you can set display property to none to hide that element.

[...document.querySelectorAll('.test')].forEach(function(e) {
  if (['Handtekening', 'Thuis'].includes(e.textContent.trim())) {
    e.style.display = 'none'
  }
})

  Pakket

  Handtekening

  Thuis

Comment: can you explain [...document.querySelectorAll('.test')] I know it converts to an array...
Comment: Because querySelectorAll returns `NodeList` if you want to use regular `forEach()` loop you need to transform that to array and you can use `...` spread syntax for that.
Comment: thanks you are right is an ES6 feature https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment , destructuring
Comment: @NenadVracar The browsers which supports ES6 must contain forEach with the prototype of `nodelist`
Comment: @RenzoCC This is not destructuring. Destructuring is different from what he is doing here.
Comment: And what is it then. can you please provide me a link
Comment: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
Answer:
With CSS 3: no
With JavaScript: yes
With XPath: yes (something like //div[contains(text(),'Handtekening')]/.)

You can test your XPath here.
Answer: You can do it just like this,
let filteredOut = ['Handtekening', 'Thuis'];

Array.from(document.querySelectorAll(".test")).forEach((elm) => {
 if(filteredOut.includes(elm.textContent.trim())) elm.style.display = "none";
});

DEMO

Collect the values that are needs to be filtered out in a separate array.
Iterate over all the elements and check its value presents in the filter array.
If it exists, just hide it.

Side Note: You can use a class to add to the caught elements instead of inserting inline styles.
Answer: You also have jQuery that makes this easy if you already use this
library: contains(text).

text: A string of text to look for. It's case sensitive.
The matching text can appear directly within the selected element, in any of that element's descendants, or a combination thereof. As with attribute value selectors, text inside the parentheses of :contains() can be written as a bare word or surrounded by quotation marks. The text must have matching case to be selected.

$( ".test:contains('Thuis'),.test:contains('Handtekening')" ).css( "display", "none" );

https://codepen.io/gc-nomade/pen/zEMbLz
Comment: Related: *[The Many Memes of Meta](https://meta.stackexchange.com/questions/19478/the-many-memes-of-meta/19492#19492)*
Answer: You can do it with JavaScript:

var elements = document.getElementsByClassName('test');

for(var i = 0; i<elements.length; i++){

 if(elements[i].innerText==='Handtekening' || elements[i].innerText==='Thuis'){
  elements[i].style.display = 'none';
 }

}

Pakket

Handtekening

Thuis

Answer: Here's pure JavaScript solution:
// Define your variables
var objectsToCheck = document.getElementsByClassName("test");
var hideText = "Pakket";

// Loop through your div objects
[].forEach.call(objectsToCheck, function (o) {

  // Check if text appears in div under class "test"
  if(o.innerText.toLowerCase() == hideText.toLowerCase()){
      o.style.display = "none";
  }
});

Answer: You can use querySelector to fetch elements and use element.classList.toggle to add/remove a class that will hide the value.

document.querySelector('#btn').addEventListener('click', function(){
  var text = document.querySelector('#txt').value.trim();

  var list = document.querySelectorAll('.test');
  for(var i = 0; i< list.length; i++) {
    list[i].classList.toggle('hide', list[i].textContent.trim() === text);
  }
})
.hide {
  display: none;
}

Pakket

Handtekening

Thuis

<input type='text' id='txt' />
<button id='btn'>Hide Div</button>

Hide div that contains specific text


Groovy override static getAt (subscript) operator

Question: I am trying to override the static getAt operator in Groovy. It runs OK but I am stumped by a nasty warning in IntelliJ.
class SubscriptTest {

    static def map = [
        (SubscriptKey.ONE)  : 'one',
        (SubscriptKey.TWO)  : 'two',
        (SubscriptKey.THREE): 'three',
    ]

    static Object getAt(SubscriptKey key) {
        map[key]
    }
}

enum SubscriptKey {
    ONE,
    TWO,
    THREE
}

When I run
println SubscriptTest[SubscriptKey.ONE]

It prints one. But I also get the below warning in IntelliJ.

'getAt' in 'org.codehaus.groovy.runtime.DefaultGroovyMethods' cannot be applied to '(SubscriptKey)'

Not sure how to fix / suppress this warning.
Answer:
I am trying to override the static getAt operator in Groovy

There is no static getAt method, there's a not-static getAt method. Here's an example of how to override the non-static getAt method
// run this code in the Groovy console
class SubscriptTest {

    static def map = [
        (SubscriptKey.ONE)  : 'one',
        (SubscriptKey.TWO)  : 'two',
        (SubscriptKey.THREE): 'three',
    ]

    Object getAt(String key) {
        'overriden getAt invoked'
    }
}

enum SubscriptKey {
    ONE,
    TWO,
    THREE
}

assert new SubscriptTest()['key'] == 'overriden getAt invoked'

Comment: I also think it's a way IntelliJ parses your code, and tries to match `getAt` with [DefaultGroovyMethods](http://docs.groovy-lang.org/latest/html/api/org/codehaus/groovy/runtime/DefaultGroovyMethods.html) As a workaround you could try to find and disable inspection rule in an editor.


How is $\{x \in A | f(x) \notin A \} = \overline{ \{ x \in A | f(x) \in A \}}$?

Question: I was reading Discrete Math book when I came across a solution which used the following equality.
$\{x \in A | f(x) \notin A \} = \overline{ \{ x \in A | f(x) \in A \}}$
How can it be proved?
Comment: If $f : B\to C$ is a function with $A\subset B\cap C$, then for all $x\in A$, $f(x)\in A$ or not, the two options being mutually exclusive.
Answer: As long as $\overline X$ is defined as $A\setminus X$, it is more generally true that
$$\{\,x\in A\mid \Phi(x)\,\}=\overline{\{\,x\in A\mid \neg \Phi(x)\,\}}.$$
To see this note that
$$ \begin{align}x\in\overline{\{\,x\in A\mid \neg \Phi(x)\,\}}&\iff x\in A\land \neg(x\in A\land\neg \Phi(x))\\
&\iff x\in A\land(x\notin A\lor \neg\neg\Phi(x)\\
&\iff x\in A\land \Phi(x)\\&\iff x\in\{\,x\in A\mid \Phi(x)\,\}\end{align}$$
Here, you have $\Phi(x)\equiv f(x)\in A$ and so $\neg\Phi(x)\equiv f(x)\notin A$.
Comment: Where is the first $x\in A$ in $ x\in A\land \neg(x\in A\land\neg \Phi(x)) $ coming from? And how did you go about the last equivalence, going from predicate logic to generalizing the set?
Answer: For every $x\in A$, either $f(x)\in A$ or $f(x)\not\in A$, so $$\{x\in A\mid f(x)\not\in A\}\cup\{x\in A\mid f(x)\in A\}=A.$$
Also, for no $x$ can we have $f(x)\in A$ and $f(x)\not\in A$, so
$$\{x\in A\mid f(x)\not\in A\}\cap\{x\in A\mid f(x)\in A\}=\varnothing.$$
Thus the two sets are complements of each other with respect to $A$.


Ignorar pasta e classes com __autoload

Question: Tenho a seguinte estrutura de pastas no meu projeto:

Dentro de app tenho a seguinte estrutura:

E a seguinte função nativa do php para dar auto load nas classes:
<?php

require_once '/app/config.php';

function __autoload($class_name) {

    $folders = array(
        'class',
    );

    foreach ($folders as $folders_files) {
        $path = ROOT . 'app' . SEPARATOR . $folders_files . SEPARATOR . $class_name . '.php';

        var_dump($path);

        if (file_exists($path)) {
            require_once $path;
        } else {
            die('File not found: ' . $path);
        }
    }
}

Gostaria de saber como ignorar a pasta twitteroauth e as classes dentro dela. Será possível?
UPDATE
Tentei com spl_autoload_register(); e obtenho o mesmo erro:

File not found in: C:\wamp64\www\twitter-login\app\class\OAuthException.php

<?php
function autoload ($class_name) {
    $folders = array(
        'class',
    );

    foreach ($folders as $folders_files) {
        $path = ROOT . 'app' . SEPARATOR . $folders_files . SEPARATOR . $class_name . '.php';

        if (file_exists($path)) {
            require_once $path;
        } else {
            die('File not found in: ' . $path);
        }
    }
}

spl_autoload_register("autoload");

Answer: Tente da seguinte forma, sem usar o else com die assim, ele irá ignorar e não irá mostrar erros. Apenas exceptions do próprio wampserver.
Obs: Irá mostrar erros se a classe não existir, faça o teste, insira no seu código, $teste = new Teste;.
<?php
spl_autoload_register(function ($class) {

    $folders = array(
        'class'
    );

    foreach ($folders as $folders_files) {
        $path = ROOT . 'app' . SEPARATOR . $folders_files . SEPARATOR . $class . '.php';

        if (preg_match('/[a-zA-Z]+$/', $class)) {
      if (file_exists($path)) {
          require $path;
          return true;
      }
        }
    }
});

Comment: Its very good, vlw men, funcionou aoksokaosk.
Comment: Disponha. Amigão

Ignorar pasta e classes com __autoload


Efeito em Jquery não funciona como esperado

Question: Criei um div que ao clicar com o mouse em cima, o background dela é preenchida por uma determinada cor.
Existem diversas div's que agem dessa forma, alinhadas lado a lado.
Os id's dessas div's estão nomeados de forma crescente, então se tenho 4 div's por exemplo terei as div's de id's (c0,c1,c2,c3).
Caso eu clique na div c2 por exemplo, todas as div's que estão antes dela precisam receber o efeito de background preenchido.
até ai está tudo ok!

$('.circulo').click(function() {

  this.style.backgroundColor = '#0099ff';

});

$('#fase-range li').click(function() {

  var id = $(this).attr('id');

  var num = id.split('');

  num = num[1];

  for (i = 0; i < num; i++) {

    var newId = 'c' + i;

    $('#' + newId).css('background-color', '#0099ff');
    //alert(newId);
  }

});
.fase-range {
  list-style-type: none;
  margin: 0;
  padding: 0;
}

.fase-range li {
  display: inline-block;
  margin-right: -0.1%;
}

.lilinha {
  width: 2%;
}

.licirculo {
  width: 1.1%;
  top: 50%;
  transform: translateY(50%);
  margin-left: -0.25%;
}

.ambiente {
  margin-left: 5%;
  width: 90%;
  margin-top: 10%;
  padding: 1%;
}

.circulo {
  border: 1px solid #3366ff;
  width: 100%;
  border-radius: 100%;
  height: 20px;
  cursor: pointer;
  transition: 3s;
}

.linha {
  border-top: 1px solid #3366ff;
  width: 100%;
}

No entanto quando clico em alguma div, as outras div's que recebem o efeito parecem ignorar o transition, e o border-radius aplicados a elas.

Como posso fazer pra que isso não aconteça?
Teria que aplicar esses efeitos diretamente por Jquery?
Por que o css perde a prioridade de setar os efeitos?
Answer: Isso ocorre porque você está aplicando o efeito no pai, e não no .circulo, experimente usar dessa forma informando que quem vai receber o parametro, é o filho.
$('.circulo').click(function() {
    this.style.backgroundColor = '#0099ff';
});

$('#fase-range li').click(function() {
    var id = $(this).attr('id');
    var num = id.split('');
    num = num[1];
    for (i = 0; i < num; i++) {
    var newId = 'c' + i;
        $('#' + newId + ' .circulo').css('background-color', '#0099ff');
        //alert(newId);
    }
});


Unable to relate the given sources/set up equation with the given info to solve quadrilateral problem

Question:
$ABCD$ is a square with area 625, $CDEF$ is a rhombus with an area of 500, area of the shaded region is $55x$. Find $x$ wherein $x$ is a single digit non-zero number.

Answer: $AB = BC = CD = AD = \sqrt {625} = 25$
$CD\times \text{alt rhombus} = 500$ so $\text {alt rhombus} = 20$.
Let the point where $BC$ intersects $FE$ be $X$ and consider the side of the triangle $XCE$.
$XC = 20$ and $CE = CD = 25$.
Can you finish it from there?

 $XE = \sqrt {CE^2 - XC^2} =\sqrt{25^2 - 20^2} = 15$

.

 Area of $\triangle XCE = \frac 12 20*15 =150$

.

 Area of the white area within the trapezoid $DFXC$ is $500 - 150=350$.

.

 Area of the shaded area is $625 - 350 = 275$

.

 $55x = 275$

.

 $x = \frac {275}{55} = 5$
Comment: I tried taking the portion of rhombus outside the square and put it inside, forming a rectangle of are 500 and height 20, therefore the area of the portion in the square uncovered by the rectangle is 625 - 500 = 125. But I did not know how to find out the area of the shaded region in the square onto where the triangle portion was put. Is there a way to continue from where I left? Or am I just complicating it?
Comment: "I tried taking the portion of rhombus outside the square and put it inside,"  Why????  *leave* it outside.  Figure out the area that is outside (it's a right triangle.. and you know what the hypotenuse and one of the legs is), subtract that area from the whole rhombus, and that will give you the area of the portion of the rhombus that is *inside* the square.
Answer:
$x^2 = 625$
$xy = 500$
$y^2 + z^2 = x^2$


Using squid to anonymize HTTP traffic

Question: I'm trying to set up a SQUID server on Ubuntu to anonymize all HTTP traffic.
The goal is to hide the source IP make all the requests appear to be generated from the SQUID porxy.
I tried with the deafult configuartion but is not working as expected. How should I edit the squid.conf file?
Thanks
Comment: Can you be more specific about 'not working as expected'?
Answer: Most likely, your problem is with the X-Forwarded-For: header that Squid inserts in the outgoing request. To remove it, use forwarded_for directive as described here:
http://www.squid-cache.org/Doc/config/forwarded_for/
Comment: +1 that is definitely the case.

Using squid to anonymize HTTP traffic


Create a new revisions only at the time of specific state transition

Question: I am using Revisioning and Workflow module along with Drupal 6 to create new states of the node and revisions.Currently if I select 'New revision in draft, pending moderation (requires "Create new revision")' under workflow settings it will create a new revision only when a node is published.But I want it other way.I want to create a new revision only at aspecific state change of my choice.
For e.g. The node is in 'Finally Submitted' state and it is transitioned to 'Moderation' state. At this transition I want to a new revision to be created otherwise not.
How is that achievable?
Answer: I would look into using Rules, You can have something like the below:
<code>Event: Workflow state has changed
If: Workflow state is x (choose your state)
DO: Create a new pending revision of the node
</code>
Comment: Thanks, that exactly answers my question. Now I have to check out how to implement this on multiple nodes from different content type at one go, specially when the nodes are shown through Views inside a Panel


I am unable to send email from java

Question: I am using code like
in the below code userid username username and password gives password of mail from where i am going to send mail
Properties props = System.getProperties();
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", host);
props.setProperty("mail.transport.protocol", "smtps");
props.put("mail.smtp.user", userid);
props.put("mail.smtp.password", password);
props.put("mail.smtp.port", "465");
props.put("mail.smtps.auth", "true");
Session session = Session.getDefaultInstance(props, null);
MimeMessage message = new MimeMessage(session);
InternetAddress fromAddress = null;
InternetAddress toAddress = null;

try {
fromAddress = new InternetAddress(from);
toAddress = new InternetAddress(to);
} catch (AddressException e) {

e.printStackTrace();
}

message.setFrom(fromAddress);
message.setRecipient(RecipientType.TO, toAddress);
message.setSubject(subject);
message.setText(text);

//SMTPSSLTransport transport =(SMTPSSLTransport)session.getTransport("smtps");

Transport transport = session.getTransport("smtps");
transport.connect(host, userid, password);
transport.sendMessage(message, message.getAllRecipients());
transport.close();

but it is giving me error like
 javax.mail.MessagingException: Could not connect to SMTP host: smtp.gmail.com, port: 465;
  nested exception is:
javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target
at com.sun.mail.smtp.SMTPTransport.openServer(SMTPTransport.java:1972)
at com.sun.mail.smtp.SMTPTransport.protocolConnect(SMTPTransport.java:642)

Can any one suggest me whats problem with my code.....
Thank u in advance.....
Comment: Take a look at this article, they use the port 587 instead: http://www.mkyong.com/spring/spring-sending-e-mail-via-gmail-smtp-server-with-mailsender/
Answer: Properties props = new Properties();
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.starttls.enable", "true");
            props.put("mail.smtp.host", "smtp.gmail.com");
            props.put("mail.smtp.port", "587");

This is the Properties setup I have used to successfully send an email using a gmail account. you can then create a session using:
Session session = Session.getDefaultInstance(props, new javax.mail.Authenticator() {
                protected PasswordAuthentication getPasswordAuthentication() {
                    return new PasswordAuthentication(emailAddress, password);
                }
              });

It's a slightly different approach, but it's worked in code I'm using.

I am unable to send email from java