Not sure what my MySQL indexing strategy should look like

Question: Here's a query I've written:
SELECT DISTINCT m.*, sm.*, s.*
FROM table_1 m
LEFT JOIN table_2 sm ON m.master_id = sm.master_id
INNER JOIN (
    SELECT s1.*, rn.field1, d.field2, m.field3, dt.field4, gl.field5
    FROM table_3 s1
        LEFT JOIN table_4 rn ON s1.secondary_id = rn.secondary_id
        LEFT JOIN table_5 d  ON s1.trait_id = d.trait_id
        LEFT JOIN table_6 m  ON s1.mix_id = m.mix_id
        LEFT JOIN table_7 dt ON s1.debit_id = dt.debit_id
        LEFT JOIN table_8 gl ON s1.graph_id = gl.graph_id
    WHERE s1.secondary_id = 26
        AND s1.dimension_id = 24
        AND s1.mix_id = 43
) s ON sm.spec_id = s.spec_id
WHERE m.master_id = 1

I'm testing it against a VERY small table (only ~3000-5000 records per table) and getting acceptable results (4.8 ms), from within a VM on my laptop.
My question/concern is what about when the tables get larger, so that the entire DB can't reside in memory?
Obviously, all of the *_id columns have indices on them (whether it's the primary key column or foreign key in the s1 table. I also have a multi column index on s1.secondary_id, s1.dimension_id, s1.mix_id.
Is this adequate, or would anyone that's more versed than me know if I should employ an different indexes, or use a different strategy altogether, for this sort of query (Query against Table1, with a join to Table2, and another join against a subquery) - it's the last part thats giving me pause about scalability.
Any thoughts are appreciated.
PS - EXPLAIN states I might be using a temporary table (i assume from the join), but beyond that I"m not sure what I'm looking at, with the types being const, ref, eq_ref, etc.
Again, it works fine right now with a very small amount of test data. I just don't want it to grind to a halt once it gets production levels of data.
Thanks
Answer: Comments:

Subqueries in the from clause in MySQL can kill performance, because they are generally materialized.
The inner join to the subquery undoes the left join because a the on clause requires that the keys be non-NULL.
You should compare numeric columns to numbers not strings.  You probably don't want the single quotes.
An index on table_3(secondary_id, dimension_id, mix_id) is definitely called for (other columns may be useful after those).
Comment: You want indexed on the WHERE clause columns.
Comment: HI Gordon, in regards to your thoughts. Are Views any better performance wise than subqueries? Or the same? I'm not worried if it takes up more storage, just looking for performance. Also, the single quotes are not actually in the real query in real life, I wrote a PHP handler that replaces PDO placeholders with the data in the query, just to be be able to see the query that's being executed, more or less.
Comment: Also, there is a 4 column index, with those 3 columns indexed, plus another one that can sometimes be used as search criteria.

Sometimes COLUMNS 1, 2, 3, 4 will be queried, other times 2, 3, 4, other times, 1,3,4, other times 1,2, and so on. Is one multicolumn index like that appropriate? Or should i create indexes for each combination that could included in the final query?
Comment: Equality conditions need to match the left most keys of the index (generally) so one index can handle multiple conditions.  From what you say, you need multiple indexes.  As for your other question, a view would substitute the results in-line without materializing a temporary table, so it might actually be faster.
Comment: @GordonLinoff - "subqueries are generally materialized" -- I think this is too strong a statement.  Furthermore, the Optimizer is getting smarter about not doing that, such as turning `IN`, which used to be notorious, into `EXISTs`.
Comment: @RickJames . . . I changed that to "subqueries in the `from` clause".
Comment: @GordonLinoff - While I agree in general, there are exceptions.  [_Example_](https://stackoverflow.com/questions/35897180/why-does-mysql-not-use-optimal-indexes/35905072#35905072) .  General case: when the derived table has `GROUP BY` or `LIMIT` to significantly decrease the number of rows.
Answer: Like you mentioned your query will work fine for the fewer number of records.
But once your DB starts getting millions (or 100s of thousands) of records your query will slow down.
You can take precautions in the beginning so that your query will not slow down:

Break the query into multiple queries : This way your database will
also not run out of memory.
check the query execution plan
to see if your query is always using the indexes. It will also tell you how much time is being used in the various join operations. And the step the DB is taking to optimize your query.
As the data is fed into the tables, there table and index space keeps on getting fragmented. Do routine de-fragmentation
One thing for sure is Relational databases are not designed for horizontal scaling but they scale very well vertically so installing additional hardware (extra memory , CPU) also help
Comment: As a "general guideline" is a table with <10,000 records considered small enough to avoid indexes?
Answer:
Don't use LEFT unless the righthand table is really optional.
Do have a 3-column 'composite' index on s1.
Do provide EXPLAIN SELECT to allow us to better answer your Question.  We need to see more than just that it used a temp table.  Maybe the Explain would provide enough info to answer your scalability question.
Do not break a query into multiple queries -- unless you are really smarter than the Optimizer.
Do not use OPTIMIZE TABLE; it is not worth the effort on InnoDB tables.  BTrees are self-defragmenting (to some degree).
MySQL does not make use of multiple CPUs in a single connection.
More RAM helps in some use cases.
DISTINCT (usually) requires a temp table and an extra pass over the data.  Since you are doing SELECT *, the only way you would need to de-dup is if you actually have dups in the tables.  That seems unlikely.
varchar = numeric-constant is the only combination that has trouble.  The commonly used int = 'number' optimizes OK.

Explains

Note the "Rows" column in the EXPLAINs.  They are all small numbers.
Note 'Primary' and 'eq-ref'.  Those are (usually) very good things to have.
So, tentatively, I predict that this query will still run fast, even when the tables are too big to be cached.  This is because only a few rows in each table (only 1 row in some of the tables) will need to be touched.  No apparent table scans or other thing that would be very costly if too big.
Comment: OK, I've converted all the LEFT joins to INNER joins. Here is a screen cap of the query and the output from EXPLAIN (http://imgur.com/a/yqkmv). And yes, it looks like it works fine without the DISTINCT. I was getting apparent duplicate records when i wrote the query without the ending WHERE, so i added distinct and never got rid of it. And without distinct, it does not create the temporary table. LINK: http://imgur.com/a/gXU1Y


Detect outliers in multi dimensions

Question: I tried to implement outlier detection for one dimension using inter quartile.
For instance, a given variable cost or revenue or profit. but I'm missing outliers in other dimensions when running for one dimension.
How to detect outliers for multi dimensional data , like cost and revenue and profit at once.
Is there any efficient algorithm for this?
Comment: It depends on your purposes. You can take a look at Mahalanobis distance if your data is normal.
Comment: Unfortunately data isn't normally distributed
Comment: Then you can use combined p-values: https://en.wikipedia.org/wiki/Fisher%27s_method , but it will work only if you have independent coordinates.
Answer: If you are working on Python, you could try SVM One Class and Least Squares Anomaly Detection, both are unsupervised learning, so you train giving "examples" of inliers.

Detect outliers in multi dimensions


Javascript multiple elements same function, one at a time

Question: I am looking for a way to make my idea work.
I have several team members, and i want them to open open up when I click on them one by one.
So basically, 4 pictures in a row, if I click the first picture, it expands (shows a previously hidden element), but the other ones stay closed. If I click the second picture, now both the first and the second one are open (because i opened the first one previously), but the remaining 2 remain closed.
I want to achieve that with a single function, because I want to keep the code clean.
I did separate functions, separate element ID's for all 4 team members and it worked, but now, when I wanted to use this code for 20 elements at once, it tricky, because I dont want to keep spamming functions and elements for each new member.
The current code doesn't work, for some reason, please take a look.

David Jones

Marketing Director

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

Thomas Nguen

Operations Director

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

Sayaka Olivie

Senior Designer

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

Phillip Ivetkovich

Senior Designer

Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim.

Comment: Note that it is `getElementsByClassName` . Check this fiddle http://jsfiddle.net/r9JTG/1/
Comment: I forgot to add css, here is the full fiddle. http://jsfiddle.net/r9JTG/2/
At least now it always opens the first one. How to make so that each of them opens the corresponding one and keep the code as clean as possible?
Answer: Please avoid:

DRY – don't repeat yourself
Run inline javascript with onclick

You need to toggle CSS class on clicked elements
(function () {
    var links = Array.prototype.slice.call(document.querySelectorAll('ul li')); // CSS selector for elements that needs toggle

    links.forEach(function (link) {
        link.addEventListener('click', function () {
            toggleClass('active', this);
        });
    });

    function toggleClass(className, element) {
        element.classList.toggle(className);
    }
}());

http://jsfiddle.net/LP4dp/
Comment: Hello, thanks for your answer. http://jsfiddle.net/LP4dp/2/ - here is the updated version, I understood how to make divnumber1 become divnumber1.active using this code, but I didn't understand how to make divnumber2 become divnumber2.active, when you click on divnumber1.
Could you please correct my code a bit? I want the .aboutusteamitemtext become display:block, when you click the .aboutusteamitemimg
Comment: At the fiddle i linked, when you click on the entire image block (.aboutusteamitemimg) - it needs to open a brother element by changing display:none to block - (.aboutusteamitemtext).
Comment: So you need to use brather selectorer – `element + its_brother {}`
Comment: I understand now, thank you! You've been of great help!
Comment: I've got a question: the code didn't work on my website, i had to copy it from here: http://jsfiddle.net/LP4dp/5/embedded/result/ - in the chrome inspect element. The js turned out 4 times larger than the original, and now works, is that normal?


Piano comping in a jazz ballad

Question: I'm having trouble when comping over a jazz ballad with a singer/solo instrument. In my case I also have drums and bass playing with me. I'm mainly stuck between playing sustained chords to fill out the music or trying to play some rhythms which feel out of place or make the music slightly empty. How can I approach comping in this situation efficiently?
Answer: I generally go the sustained chords route, but then I throw in little melodic bits to fill space or complement the singer/soloist. When the drums and/or bass are playing a steady rhythm, I might echo that or counter it by filling in spaces in their pattern.
The best way to find a solution you like is to listen to lots of jazz ballads and find out what various pianists do.
For example, from the John Coltrane Quartet's Ballads, listen to the beginning of "Say It (Over and Over Again)". McCoy Tyner is quite active, because the drums and bass are playing very simply, and the melody leaves a lot of space.

On the other hand, on "All or Nothing at All", the rhythm section has clearly worked out ahead of time a rhythmic accompaniment.

For jazz standards, "everyone" has recorded them, so when you're working on a particular ballad, listen to all the recordings you can get your hands on to hear how the pianists — and rhythm sections as a whole — handle things.
Answer: There cannot be any hard and fast rule for this - each song is different and needs to be treated differently - even to the extent of changing tack somewhere in that song.
It will depend on a) what the vocals are up to, b) what the bass is doing, c) what the drummer is playing, d) how you and the rest of the band want the overall feel to be.
There are a lot of permutations to contend with there.
a). If the song's a busy one with lots of words and notes being sung, generally don't complicate it further with a fiddly accompaniment, unless you want that particular feel.
b).If the bass is playing a steady two in the bar then that gives you more room to do whatever, be it block chords or fills.
c). A good drummer will be listening to everything going on in the song (I wish...), so will be busy or not, hopefully meshing with the bassist, making a great mini-team, and you should be listening to what they produce between then to guide what you play to fit into that jigsaw too.
d). There are many, many different ways in which to accompany even one standard song. Just listen to some recordings to appreciate the plethora of varieties available. You and/or the band may/not decide that one in particular fits the way you want to perform that song. Follow the recording that's most apposite.
So, in summation - as the song says 'Anything Goes'! There will be times when block chords, one per bar will be quite enough. Times when your left hand does very little, leaving the bass to play that part instead, or even play in unison, with stabs from the r.h. You could play part of the song in unison with the vox, or play 'fiddly bits' in between the lines sung, or harmonise with vox.
If it's an electronic piano, consider using different sounds available (that's what I do - pno, Rhodes, organ, vibes, strings, for example) but there are so many different ways with an acoustic piano that it will become a list (something we don't provide here), and won't be particularly suitable for even one individual standard.

Piano comping in a jazz ballad


Is there a good online database with a web GUI?

Question: I'm trying to find a good online/cloud database that has its own web-based GUI. If possible, I would like to find one that has APIs so I can access the data programmatically, but still has a nice frontend that allows users to log in and edit records. I know Google's Fusion Tables do this, but the interface is clumsy and difficult to use for a real database.
I haven't been able to find anything else like this... can someone make a recommendation?
Thanks!
Answer: I know RackSpace Cloud has recently rolled out their Cloud Database service. I have had very good experience with their Cloud service (Cloud Server, and Cloud Files/CDN). However I have no experience with their Cloud Database service.
RackSpace Cloud Database
Comment: Thank you for the link. This is kind of what I'm looking for, but I want something that allows editing the data and running queries through a web interface.
Comment: You could always install PHPMyAdmin to point to your cloud database.
Comment: That's true, though I'm really surprised there's no cloud database solution that caters to both developers and users. Fusion Tables seems to be unique in that regard.


Unable to call onesignal api within office but working from external wifi

Question: I am using C# to call OneSignal Create Notifications API. Its working from my home but when i try to send it from my office, it gives a 400 BAD REQUEST.
The error that i get is
The error that comes is Please include a case-sensitive header of
Authorization:   Basic <YOUR-REST-API-KEY-HERE> with a valid REST API key."],
"reference":["https://documentation.onesignal.com/docs/accounts-and-keys#section-keys-ids"]

Also, in office network, when i send it from OneSignal Dashboard it works.
Is it a firewall issue?
Tested with POSTMAN and got the same results. POSTMAN working outside office network and giving 400 Bad Request inside office network.
 using System.IO;
 using System.Net;
  using System.Text;

  var request = WebRequest.Create("https://onesignal.com/api/v1/notifications") as HttpWebRequest;

request.KeepAlive = true;
request.Method = "POST";
request.ContentType = "application/json; charset=utf-8";

 request.Headers.Add("authorization", "Basic NGEwMGZmMjItY2NkNy0xMWUzLTk5ZDUtMDAwYzI5NDBlNjxx");

var serializer = new JavaScriptSerializer();
var obj = new { app_id = "5eb5a37e-b458-11e3-ac11-000c2940e6xx",
           contents = new { en = "English Message" },
           include_player_ids = new string[] {"all"} };

var param = serializer.Serialize(obj);
byte[] byteArray = Encoding.UTF8.GetBytes(param);

string responseContent = null;

 try {
    using (var writer = request.GetRequestStream()) {
       writer.Write(byteArray, 0, byteArray.Length);
    }

   using (var response = request.GetResponse() as HttpWebResponse) {
   using (var reader = new StreamReader(response.GetResponseStream())) {
         responseContent = reader.ReadToEnd();
     }
   }
}
catch (WebException ex) {
   System.Diagnostics.Debug.WriteLine(ex.Message);
   System.Diagnostics.Debug.WriteLine(new    StreamReader(ex.Response.GetResponseStream()).ReadToEnd());
   }
    System.Diagnostics.Debug.WriteLine(responseContent);

Comment: I sure hope that those aren't your real `app_id` and `authorization` tokens...Additionally, this does appear to me to be a firewall issue or the request is being modified somehow by your work network.
Comment: @JosephGarrone Tried with POSTMAN and got the same error. How to check if the request gets modified. The POSTMAN console is same for both
Comment: It is clear: it is a firewall issue.
Answer: try following
System.Net.CredentialCache credentialCache = new System.Net.CredentialCache();
credentialCache.Add(
    new System.Uri("http://www.yoururl.com/"),
    "Basic",
    new System.Net.NetworkCredential("username", "password")
);

...
...

httpWebRequest.Credentials = credentialCache;

but i think you should use test RESTFUL tools to check what parameters can return correct value at all first.
Comment: Nice suggestion. I will use POSTMAN and see if i get the required output
Comment: If you can debug? May be able to find the problem and check request.
Answer: The issue is solved by adding the onesignal host to our firewall as a trusted site.


How to find characters that cannot be part of a word in a Unicode string?

Question: I have some text in a string, I need to check whether that particular string contains any characters which are not allowed to make a word.
Suppose I have text like "(hello}"
Here it contains to symbols '(' and '}'. How could I do it in C++. And a string may contains any unicode character.
Comment: what are the characters that are "allowed to make a word"? just letters? numbers? underscore? space? punctuation marks? for just letters see [`isalpha`](http://www.cplusplus.com/reference/clibrary/cctype/isalpha/) or [`iswalpha`](http://pubs.opengroup.org/onlinepubs/007908799/xsh/iswalpha.html).
Comment: Please [don't add signatures or taglines to your posts](http://www.stackoverflow.com/faq#signatures).
Comment: Either I did not get your question correctly, or you are looking for regular expressions in C++. If that is true, look at this thread: http://stackoverflow.com/questions/181624/c-what-regex-library-should-i-use?answertab=votes#tab-top
Comment: boost::regex, libpcre, or just simple strspn/strcspn, strpbrk...
Comment: Can you elaborate further on which characters "are allowed to make a word"?
Comment: Nope I don't wants regex. I just need to find a way to get whether this character is valid for making any word or not.
Comment: "petróleo" this is valid spanish word. if I use isalpha or iswalpha then it fails here for "ó" character.
Comment: @dearvivekkumar If you use a Spanish locale, then `std::isalpha` should work properly. Are you really trying to see if something is a word *in any language at all*?
Answer: If the string really contains Unicode (UTF-8), the problem is decidedly
non-trivial; you'll probably want to use some external library, like
ICU.  Or you can convert to wchar_t (wstring), and use the single
byte encoding solution below:
If the characters are single byte encoded, std::find_if with a
suitable predicate should do the trick.  If you're doing any text
parsing, you'll want to define as set of such predicates, once and for
all; the predicates can use the functions in the std::ctype facet of
locale, or the ones in wctype.h (which use the global locale).
Still, if you are dealing with Unicode, even converting to wide
characters may not be enough, since full Unicode can still use more than
one code point to represent a single character.  The real question is
just how serious you want to do this.  (Note too that in many languages,
like English or French, "words" can contain characters which Unicode
considers punctuation, e.g. "don't" or "aujourd'hui"—the Unicode
tables will tell you that '\'' is punctuation, not part of a word.)
Comment: May be I am not explaining  my need correctly. I have to parse a file to make word from that. that word can be in any language. i have checked for space for separating words from the text. But that does not seem to be sufficient. As suppose I have a text like "my name (vivek " then here i to three words my, name and vivek. I need to some general solution to this. I need idea how to handle this things.
Comment: Well, the biggest problem is to define what characters can or cannot be in a word.  Do you accept "don't" as a word?  Then you'll have to add some special case to your predicate.  Do you accept an 'x' with a circumflex accent in a word?  If so, even with wide characters, you'll have to handle multicode sequences (so you can't use `find_if`.  The same thing holds if you can't guarantee a specific canonized format in your input.
Answer: std::isalpha (and related is* friends) are templated on the character type AND accept a locale to allow better localization ability too. I would just iterate over the string or wstring and use the is* function(s) that indicate the behavior you're interested in (I can't tell which characters you want to allow and disallow from the problem statement).
Comment: For basic purposes, that would be my recommendation, too. For hardcore no-scripts-barred Unicode processing something like ICU would probably be better, but it totally depends on your situation. Locale-aware regexes sound pretty sexy.
Answer: Use std::wstring and std::iswalpha().


Problem with restricted download links (hook_file_download)

Question: On my site I have a bunch of files that require logged-in user for download access.
Well that's not about just display access, I also want to avoid passing download links around.
Having read about the performance implications of using private file system, I decided I cannot afford it so I thought I'd write a small module to control the download.
The code looks like the following:
<code>/**
 * Implements hook_permission().
 */
function docwatch_permission() {
  return array(
    'docwatch download restricted documents' => array(
      'title'       => t('Download restricted documents.'),
      'description' => t('Download technical documents from secured directory.'),
    ),
  );
}

/**
 * Implements hook_file_download
 */
function docwatch_file_download($uri) {
  if (strpos(file_uri_target($uri), 'secure/docs') !== 0) {
    if (!user_access('docwatch download restricted documents')) {
      // Access to the file is denied.
      return -1;
    }
    else {
      return array('Content-Type' => file_get_mimetype($uri));
    }
  }
}
</code>
And I'm using this debug code to inspect what Drupal "thinks" of the link to the file it displays:
<code>function MYTHEME_file_link(&$variables){
  $file = $variables['file'];
  $uri = $file->uri;

  if (strpos(file_uri_target($uri), 'secure/docs') !== 0) { // <-- part of the secure dir path
    if (!user_access('docwatch download restricted documents')) {
      drupal_add_js("console.log('no access')", 'inline');
      // Access to the file is denied.
      // return -1;
    }
    else {
      drupal_add_js("console.log('ok to download')", 'inline');
      // return array('Content-Type' => file_get_mimetype($uri));
    }
  } else {
    drupal_add_js("console.log('from unsecured')", 'inline');
  }
}
</code>
I then open a page where the link is displayed in two browsers, one with a logged-in status for that role, and the other - plainly anonymous. The console properly reports that difference, yet - despite that the anonymous browser is permitted to download the direct link to the document.
What am I doing wrong?
Answer:
Having read about the performance implications of using private file system, I decided I cannot afford it so I thought I'd write a small module to control the download.

The performance hit from using the private file system is minimal.
IMHO, using the private file system to control download access to files is the only sane way to do this when using Drupal.

What am I doing wrong?

You err in not using the private file system .
When you hand the direct link to the browser, it goes directly to that link.  It does not even see the PHP/JavaScript you've put in place to restrict download access.
To prevent unauthorised downloads, you must enforce that the downloads are managed by Drupal, and that this access control cannot be bypassed by requesting direct links served by the browser. This is what the private file system (aka private download method) does.
This download method stores the files attached to a node in a directory that is not accessible by the browser (preferably above the web-root). The only way to get to these files, are then through Drupal.


How to get the standard text format widget for a custom field type?

Question: I've created a custom field that loads content from a given URL. The content is rendered with the given input format. That works fine.
Currently, I just gabe a list of available text input using filter_formats and show this with a select widget. How can I replace this with the standard input format widget that is available underneath the node body textarea?
This is how it's done now:
/**
 * Implements hook_field_widget_form().
 */
function remote_content_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {

    $url = isset($items[$delta]['url']) ? $items[$delta]['url'] : '';
    $tformatter = isset($items[$delta]['tformatter']) ? $items[$delta]['tformatter'] : 0;

    $widget = $element;

    $widget += array(
        ...
    );

    $widget['url'] = array(
        ...
    );
    $widget['tformatter'] = array(
        '#type' => 'select',
        '#title' => t('Text format'),
        '#options' => _remote_content_create_format_options(),
        '#default_value' => $tformatter,
        '#description' => t('Choose the appropriate text format.'),
    );

    $element = $widget;

    return $element;
}

function _remote_content_create_format_options() {
    global $user;

    $formats = filter_formats($user);
    $options = array();

    foreach($formats as $f) {
        $options[$f->format] = $f->name;
    }

    return $options;
}

Answer: You are looking for '#type' => 'text_format'. Usage example:
$form['text'] = array(
  '#type' => 'text_format',
  '#title' => t('Text'),
  '#default_value' => $text,
  '#format' => $format,
);

You will get the text in $form_state['values']['text']['value'] and the format in $form_state['values']['text']['format'].


Argument that closure of identity in topological group is normal subgroup.

Question: Let H be the closure of $\{e\}$, where $e$ is the identity element of a topological group $G$. We know that $H$ is a subgroup of $G$. We want to prove that $H$ is normal subgroup of $G$. In Valenza's "Fourier Analysis on Number Fields" the proof is as follows:
"Since $\{e\}$ is a subgroup of $G$ so is its closure $H$. Moreover, it is the smallest closed subgroup of $G$ containing $e$ and therefore normal, since each conjugate of $H$ is likewise a closed subgroup containing $e$."
The bold argument above is the one that I don't understand. I can see that for every $g\in G$, $gHg^{-1}$ is a closed subgroup (because traslations are homeomorphisms and $H$ is closed) and that implies that $H\leq gHg^{-1}$, but I don't have any idea about how to get $gHg^{-1}\leq H$.
Any help would be appreciated.
Comment: Would you worry about $H\le g^{-1}Hg$?
Comment: @HeMan: Take that "inequality", and multiply both sides by $g^{-1}$ on the left, and $g$ on the right (or whatever it takes to isolate $H$ on the right).
Comment: I'm just saying that the argument in the book seems to me that only implies that statement.
Answer: The conjugation $x\mapsto g^{-1}xg$ is a group automorphism and also a homeomorphism. Thus if $H$ is a closed subgroup, also $g^{-1}Hg$ is a closed subgroup.
Now if $H$ is the closure of $\{e\}$, it is contained in every closed subgroup of $G$. Now $g^{-1}Hg$ is a closed subgroup, so $H\subseteq g^{-1}Hg$, for every $g$. Using $g^{-1}$ we conclude that $H\subseteq gHg^{-1}$, which implies $g^{-1}Hg\subseteq H$.
The argument above just uses the fact that each conjugate of $H$ is a closed subgroup, which is the statement you're worrying about.
Comment: How do you get the last implicación?
Comment: @HeMan Apply conjugation by $g$ to both sides.


What are the problems with small sample size based predictions when using time-series data?

Question: I had to put the majority of the question in the textbox as Cross Validated didn't like the fact my question was too long....but here it is, in terms of what I wanted to ask:
Due to a small sample size (i.e. large earthquakes are rare), does predicting 'post-large earthquake aftershocks' suffer from the same statistical problems of predicting the actual earthquake itself?
or
Does the consistency (assuming there is some) of 'post-large earthquake aftershock' effect make it valid to make 'strong' (with high probability of success) and accurate predictions about when/where and how large these aftershocks might be?
And finally are the statistical techniques different for predicting 'post-(rare) event events' vs predicting the actual (rare) event itself?
Any thoughts, links or pointers would be much appreciated.
P.S.
This question is partially related to my previous question Can survival analysis be used to predict earthquakes?
Answer: Accuracy of prediction depends on the variance of the estimate.  For averages of iid observations that variance goes down by 1/√n.  So in general for iid observations the accuracy of an estimate improves as the sample size increases (not necessarily exactly by 1/√n).  Now in you case you have a point process and events may be correlated, certainly aftershocks from the same quake will be highly correlated.  When observations are positively correlated the variance does not decrease as rapidly with increasing sample size as it does for iid observations.  So small sample size and correlation make it difficult to make accurate predictions.  However, if the individual observations have a very low variance, imrovement may not be necessary.
So the short and sweet of it is small sample size along with correlation and a large variance for the individual observstions leads to poor prediction.  But if the variance of the individual observations is small, the small sample size and correlation may not be important and accurate prediction is possible.
Comment: Is there a way to deal with the correlation to help improve accuracy?
Comment: If successive observations are negatively correlated the variance of the sum is less than the sum of the variances and the variance goes down faster than for iid observations.  That is like the old saying that errors tend to cancel each other out.  it is not really true when observations are independent but it is the case for negatively correlated observations.  That is because if one observation is high relative to the mean the next observation is likely to be small relative to the mean, a consequence of the negative correlation.
Answer: If you assume that the size of Earthquakes followed a power law distribution, and if you used the same distribution to model aftershocks, then they would not be bound to be smaller than the original earthquake.
I'm not a seismologist, but I think that aftershocks are defined to be smaller than the main shock.  So I'd expect that you could probably fit a (non power law) distribution for aftershock size (with a measurable variance), and that this should not have the rare extreme values associated with the power law distribution.


Integrating a customer feedback form with Google Analytics

Question: I'm attempting to implement a simple customer feedback system on my website and came across a couple of articles that used Google Analytics to collect feedback, which I've linked to below.
1./ Push customer feedback results directly to Google Analytics with this new integration
2./ Using Google Analytics with Website Feedback
I was wondering if this is a good practice? Is there any security risk, such as information exposure via query strings in URLs or web parameter tampering?
Answer: There's no need to link to articles. It's pretty trivial and common implementation. What you can track in GA is limited. For example, in some countries you're not allowed to store PII (Personal identifiable information).  In other countries, they have GDPR, that has even more limitations.
And of course, getting data from GA to display it publicly is a bad idea too because GA was designed for internal use. Therefore, GA is a good solution if you can legally store that data on GA's servers and if you need it for personal analysis.
Comment: Since you mentioned GDPR, is it still legal to use GA to save feedback using localstorage rather than cookies to track the user if the end-user opts out of cookies?
Comment: I think it's more about storing their feedback on third-party servers. Local storage vs cookies makes no difference. Users aren't reasonably expected to know what cookies, local storage, web SQL or session storage are.


How do you reference other branches of a python package?

Question: I'm trying to create a python package where code in one branch references code in a parallel branch.
For example:
my_package/
 ├─utils/
 │  └─foo.py
 └─other_branch/
    └─bar.py

How can I reference code from utils.foo.py in other_branch.bar.py?
Comment: `my_package.branch_1.foo.whatever`
Answer: If my_package is a valid package, you can just import from it as usual:
import my_package.branch_1.foo

Alternatively, you can use relative imports:
import ..branch_1.foo

For details, check the documentation.
Answer: It's usually bad practice to do something like that. Hierarchy should be a hierarchy logically as well and structurally.
When designing a project right, each directory will only need packages from it's sub-directories.
That being said, you should be able to do something like that:
foo.py:
from ..branch_2 import bar

You should make sure you have __init__.py in all directories.
Comment: Good answer. Good point about the hierarchy. I would probably recommend switching back to absolute imports in such cases (importing from parent or sibling packages).


Dropdown Menu - Fixed Properties

Question: I have a menu about half-way down the screen. It contains some drop-down menu lists, and when a user scrolls past a certain point, it sticks to the top of the page.

Type

Option

Location

Option

Industry

Option

Featured

Option

The CSS:
.discover_filter {
  width: 980px%;
  height: 50px;
  background-color: #ea8f18;
  padding: 0 40px;
}

.stick {
  position: fixed;
  top: 103px;
  z-index: 9999;
  width:980px;
}

.filter1 {
  float: left;

  z-index:9999;
  cursor: pointer;
  height:50px;
  background-color:#ea8f18;
  width: 170px;
  color: white;
  overflow: hidden;

  .menuitem {
    font-weight: bold;
    display:block;
    height:20px; width: 150px;
    padding: 15px 10px;
    font-size: 15pt;

  }

And the Javascript:
$('.filter1').hover(function() {
        $(this).animate({ 'height': '400px' }, 250);
    }, function() {
        $(this).animate({ 'height': '50px' }, 250);
    });

    var s = $(".discover_filter");
    var pos = s.position();
    $(window).scroll(function() {
        var windowpos = $(window).scrollTop();

        if (windowpos >= 400) {
            s.addClass("stick");
        } else {
            s.removeClass("stick");
        }
    });

The problem is, the menus push down the page below it, except when the menu has been properly fixed to the top of the page (once the user has scrolled far enough).
How can I make the menus overlay properly without pushing the page down?
Answer:
I got you. I can suggest you something different. I did it somewhere.
js

$(document).on("scroll", function () {
            if ($(document).scrollTop() > "700") {
                $(".nav_class").css({ "position": "relative" });
            }
            else {
                $(".nav_class").css({ "position": "fixed"});
            }
        });

700 = is the value you can change when you like to fix it on top of your screen.

or make two classes

CSS

.class_a
{
position:relative;
}

.class_b
{
position:fixed;
top:0; /*to fix it on top*/
}

JS

$(document).on("scroll", function () {
                if ($(document).scrollTop() > "700") {
                    $(".nav_class").removeClass('class_a');
                }
                else {
                    $(".nav_class").addClass('class_b');
                }
            });

Dropdown Menu - Fixed Properties


Getting inaccurate distance between two location points in mapbox web

Question: I have been trying to check if the direct distance between the user's current location and the shop's location is less than 4km. But when I move the user's marker, the distance measured seems to be less on the side areas of the shop but a lot more in the vertical up and down space of the shop, which doesn't look proportional as I am expecting a circularly consistent behavior. I have been puzzled with this behavior and can't find the solution. Any help or guidance is sincerely appreciated!

    <link href='https://api.mapbox.com/mapbox.js/v3.3.1/mapbox.css' rel='stylesheet' />

Answer:
var shop = [18.565461492546987, 73.91061898347883];

Your project is operating at 74 degrees of latitude. In Web Mercator, at that latitude, there is a significant difference in pixel distance between a degree of latitude and a degree of longitude. (At the equator, there is none).
I haven't inspected your code further, but I imagine it is operating correctly - a squished ellipse is what you would expect. You can verify this by moving your shop to [0, 0] and seeing if it gives the circle you were expecting.


Problemas no envio do e-Social: Assinatura do evento inválida

Question: Usando RobRichards, estou tentando obter uma resposta positiva no envio do XML, mas sempre acusa a mensagem:

"Assinatura do evento inválida. Ações Sugeridas: Verificar se houve
  alteração do evento após a assinatura. Verificar a validade da
  assinatura."

Já tentei diversas formas tanto da assinatura como no envio, mas sem sucesso.
Meu script PHP:
<?php
    use RobRichards\XMLSecLibs\XMLSecurityDSig;
    use RobRichards\XMLSecLibs\XMLSecurityKey;

    $repository = getcwd().DIRECTORY_SEPARATOR;
    require $repository.'src\XMLSecurityKey.php';
    require $repository.'src\XMLSecurityDSig.php';
    require $repository.'src\XMLSecEnc.php';
    require $repository.'src\Utils/XPath.php';
    $array['xsd'] = 'evtInfoEmpregador';
    $array['pem'] = $repository.'ARQUIVO.pem';
    $array['pass'] = 'PASSWORD';
    $array['xml'] = 'S1000.xml';
    $array['xml-assinado'] = 'S1000-assinado.xml';

    function connWsEsocial($array){
        $options = array(
            'ssl' => array(
                'verify_peer'       => false,
                'verify_peer_name'  => false,
                'allow_self_signed' => true,
                'capture_peer_cert' => true
            ),
            'http' => array('timeout' => 5) //seconds
        );
        $stream = stream_context_create($options);
        $paramsSoap = array(
            'encoding'           => 'UTF-8',
            'local_cert'         => $array['pem'],
            'passphrase'         => $array['pass'],
            'cache_wsdl'         => WSDL_CACHE_NONE,
            'exceptions'         => true,
            'trace'              => true,
            "use"                => SOAP_ENCODED,
            "style"              => SOAP_RPC,
            'stream_context'     => $stream,
            'soap_version'       => SOAP_1_1,
            'connection_timeout' => 25 //seconds
        );
        try{
            $connSoap = new SoapClient($array['wsdl'], $paramsSoap);
            return $connSoap;
        } catch(SoapFault $fault){
            trigger_error("SOAP Fault: (faultcode: {$fault->faultcode}, faultstring: {$fault->faultstring})", E_USER_ERROR);
            exit;
        }
    }

    function sendXmlEsocial($xml, $connSoap, $type){
        $headers = array();
        $headers[] = new SoapHeader('http://www.w3.org/2001/XMLSchema-instance','xsi');
        $headers[] = new SoapHeader('http://www.w3.org/2001/XMLSchema','xsd');
        $headers[] = new SoapHeader('http://www.w3.org/2003/05/soap-envelope','soap');
        $connSoap->__setSoapHeaders($headers);
        switch($type){
            case 'envio':
                $sXml = '<EnviarLoteEventos xmlns="http://www.esocial.gov.br/servicos/empregador/lote/eventos/envio/v1_1_0"><loteEventos>'.$xml.'</loteEventos></EnviarLoteEventos>';
                $paramSoapCall = new SoapVar($sXml, XSD_ANYXML);
                $response = $connSoap->EnviarLoteEventos($paramSoapCall);
                $objXml = simplexml_load_string($response->EnviarLoteEventosResult->any);
                print '<textarea style="height:300px; width:70%;">'; print_r($objXml); print '</textarea>
';
                return $objXml->retornoEnvioLoteEventos->dadosRecepcaoLote->protocoloEnvio;
            break;

            case 'consulta':
                $paramSoapCall = new SoapVar($xml, XSD_ANYXML);
                $response = $connSoap->ConsultarLoteEventos($paramSoapCall);
                $objXml = simplexml_load_string($response->ConsultarLoteEventosResult->any);
                print '<textarea style="height:300px; width:70%;">'; print_r($objXml); print '</textarea>
';
            break;
        }
    }

    $doc = new DOMDocument();
    $doc->load($array['xml']);
    $objDSig = new XMLSecurityDSig();
    $objDSig->setCanonicalMethod(XMLSecurityDSig::C14N);
    $objDSig->addReference($doc, XMLSecurityDSig::SHA256, array('http://www.w3.org/2000/09/xmldsig#enveloped-signature', 'http://www.w3.org/TR/2001/REC-xml-c14n-20010315'));
    $objKey = new XMLSecurityKey(XMLSecurityKey::RSA_SHA256, array('type'=>'private'));
    $objKey->passphrase = $array['pass'];
    $objKey->loadKey($array['pem'], TRUE);
    $objDSig->sign($objKey);
    $objDSig->add509Cert(file_get_contents($array['pem']));
    $objDSig->appendSignature($doc->documentElement);
    $doc->save($array['xml-assinado'], LIBXML_NOEMPTYTAG | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
    /*$xml = str_replace('<?xml version="1.0"?>', '', file_get_contents($array['xml-assinado']));*/
    $xml = file_get_contents($array['xml-assinado']);
    print '<textarea style="height:300px; width:70%;">'.$xml.'</textarea>
';

    $array['wsdl'] = 'https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/enviarloteeventos/WsEnviarLoteEventos.svc?singleWsdl'; //HOMOLOGAÇÃO
    $connSoap = connWsEsocial($array);
    $xmlLote = '<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1"><envioLoteEventos grupo="1"><ideEmpregador><tpInsc>1</tpInsc><nrInsc>CNPJ</nrInsc></ideEmpregador><ideTransmissor><tpInsc>1</tpInsc><nrInsc>CNPJ</nrInsc></ideTransmissor><eventos><evento Id="ID1">'.$xml.'</evento></eventos></envioLoteEventos></eSocial>';
    $protocolo = sendXmlEsocial($xmlLote, $connSoap, 'envio');

    $array['wsdl'] = 'https://webservices.producaorestrita.esocial.gov.br/servicos/empregador/consultarloteeventos/WsConsultarLoteEventos.svc?singleWsdl'; //HOMOLOGAÇÃO
    $connSoap = connWsEsocial($array);
    $cXml = '<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v1="http://www.esocial.gov.br/schema/lote/eventos/envio/consulta/retornoProcessamento/v1_1_0"><soapenv:Header/><soapenv:Body><v1:ConsultarLoteEventos><v1:consulta><eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/consulta/retornoProcessamento/v1_0_0"><consultaLoteEventos><protocoloEnvio>'.$protocolo.'</protocoloEnvio></consultaLoteEventos></eSocial></v1:consulta></v1:ConsultarLoteEventos></soapenv:Body></soapenv:Envelope>';
    sendXmlEsocial($cXml, $connSoap, 'consulta');
?>

EDIÇÃO
Segue XML:
<eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtInfoEmpregador/v02_05_00">
  <evtInfoEmpregador Id="ID1071163060000002019030716513500000">
    <ideEvento>
      <tpAmb>2</tpAmb>
      <procEmi>1</procEmi>
      <verProc>V020500</verProc>
    </ideEvento>
    <ideEmpregador>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306</nrInsc>
    </ideEmpregador>
    <infoEmpregador>
      <inclusao>
        <idePeriodo>
          <iniValid>2019-03</iniValid>
        </idePeriodo>
        <infoCadastro>
          <nmRazao>RAZAO SOCIAL</nmRazao>
          <classTrib></classTrib>
          <natJurid></natJurid>
          <indCoop>0</indCoop>
          <indConstr>0</indConstr>
          <indDesFolha>0</indDesFolha>
          <indOptRegEletron>0</indOptRegEletron>
          <indEntEd>N</indEntEd>
          <indEtt>N</indEtt>
          <contato>
            <nmCtt>NOME CONTADOR</nmCtt>
            <cpfCtt>23665896588</cpfCtt>
            <foneFixo>1123652365</foneFixo>
            <email>email@example.com</email>
          </contato>
          <softwareHouse>
            <cnpjSoftHouse>2345345243523535</cnpjSoftHouse>
            <nmRazao>SOFTWARE HOUSE LTDA</nmRazao>
            <nmCont>NOME COMPLETO</nmCont>
            <telefone>1123652365</telefone>
            <email>firstname.lastname@example.com</email>
          </softwareHouse>
          <infoComplementares>
            <situacaoPJ>
              <indSitPJ>0</indSitPJ>
            </situacaoPJ>
          </infoComplementares>
        </infoCadastro>
      </inclusao>
    </infoEmpregador>
  </evtInfoEmpregador>
</eSocial>

E o XML Lote é esse:
<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
  <envioLoteEventos grupo="1">
    <ideEmpregador>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306</nrInsc>
    </ideEmpregador>
    <ideTransmissor>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306000156</nrInsc>
    </ideTransmissor>
    <eventos>
      <evento Id="ID1071163060000002019030716513500000">XML ASSINADO</evento>
    </eventos>
  </envioLoteEventos>
</eSocial>

Esse é o XML já assinado:
<eSocial xmlns="http://www.esocial.gov.br/schema/lote/eventos/envio/v1_1_1">
  <envioLoteEventos grupo="1">
    <ideEmpregador>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306</nrInsc>
    </ideEmpregador>
    <ideTransmissor>
      <tpInsc>1</tpInsc>
      <nrInsc>07116306000157</nrInsc>
    </ideTransmissor>
    <eventos>
      <evento Id="ID1071163060000002019030716513500000">
        <eSocial xmlns="http://www.esocial.gov.br/schema/evt/evtInfoEmpregador/v02_05_00">
          <evtInfoEmpregador Id="ID1071163060000002019030716513500000">
            <ideEvento>
              <tpAmb>2</tpAmb>
              <procEmi>1</procEmi>
              <verProc>v02_05_00</verProc>
            </ideEvento>
            <ideEmpregador>
              <tpInsc>1</tpInsc>
              <nrInsc>07116306</nrInsc>
            </ideEmpregador>
            <infoEmpregador>
              <inclusao>
                <idePeriodo>
                  <iniValid>2019-03</iniValid>
                </idePeriodo>
                <infoCadastro>
                  <nmRazao>RAZAO SOCIAL</nmRazao>
                  <classTrib>01</classTrib>
                  <natJurid>2062</natJurid>
                  <indCoop>0</indCoop>
                  <indConstr>0</indConstr>
                  <indDesFolha>0</indDesFolha>
                  <indOptRegEletron>0</indOptRegEletron>
                  <indEntEd>N</indEntEd>
                  <indEtt>N</indEtt>
                  <contato>
                    <nmCtt>NOME COMPLETO</nmCtt>
                    <cpfCtt>12345678999</cpfCtt>
                    <foneFixo>1134684850</foneFixo>
                    <email>firstname.lastname@example.com</email>
                  </contato>
                  <softwareHouse>
                    <cnpjSoftHouse>01234567890000</cnpjSoftHouse>
                    <nmRazao>softwareHouse LTDA</nmRazao>
                    <nmCont>NOME COMPLETO</nmCont>
                    <telefone>1123652365</telefone>
                    <email>firstname.lastname@example.com</email>
                  </softwareHouse>
                  <infoComplementares>
                    <situacaoPJ>
                      <indSitPJ>0</indSitPJ>
                    </situacaoPJ>
                  </infoComplementares>
                </infoCadastro>
              </inclusao>
            </infoEmpregador>
          </evtInfoEmpregador>
          <Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
            <SignedInfo>
              <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
              <SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
              <Reference URI="">
                <Transforms>
                  <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                  <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
                </Transforms>
                <DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                <DigestValue>HZxjQxHchEUvK6A1CH+3OOUsgze5Czdw+1.....</DigestValue>
              </Reference>
            </SignedInfo>
            <SignatureValue>ihjBzQZ9Q4DXQNxR8UZR/fKSCEnQDOVyW+WD4ztGZztNoR8s9oySx+6CV1B+SSSIXvMQWHIzr.....</SignatureValue>
            <KeyInfo>
              <X509Data>
                <X509Certificate>MIIH/jCCBeagAw.....
  </envioLoteEventos>
</eSocial>

Comment: Por favor, poste o XML que você está usando para assinar e enviar (`$array['xml'] = 'S1000.xml';`), e poste também o trecho de código onde você substitui os placheholders `CNPJ` e `ID1`, na variável `$xmlLote` usada na função `sendXmlEsocial()`.
Comment: Pedro Gaspar, acabei de postar os dois já com os valores devidos.
Comment: Eu editei sua pergunta e coloquei os XMLs lá. Exclua depois a resposta que você postou aqui, por favor. Você pode colocar também como ficou o XML do evento depois da assinatura? Esse ID fo evento você está colocando na mão em algum momento ou a informação já vem preechida antes da assinatura? Você faz alguma alteração no XML do evento assinado depois da assinatura?
Comment: Peço desculpas pela ignorância. Sou novo e estou aprendendo a mexer aqui.

Eu não faço alteração no XML não e como eu tenho bom banco de dados para armazenar as informações dos clientes que faremos o envio, eu faço o select no banco, monto o XML e depois utilizo a função para assinatura. Depois do XML montado, antes de assinar, eu não mexo mais nele. O ID eu monto de acordo com as especificações do e-Social. Como ele pede datahora, eu monto ele na hora, antes de montar o XML e o adiciono. Depois com o XML pronto, envio para assinar. Vou postar um XML com a assinatura.
Comment: Tranquilo Leonardo, não precisa se desculpar. Sem querer ser chato, mas, ficou faltando um pedaço nesse último XML (assinado) que você postou... Coloque o XML completo, por favor, para podemos analisar melhor o problema!
Answer: Eu analisei o seu código e os XMLs e tudo parece estar certo, mas aí eu percebi que o problema parece estar nessa linha aqui:
   $doc->save($array['xml-assinado'],
              LIBXML_NOEMPTYTAG | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

Primeiro que, ao consultar a documentação do método DOMDocument::save, verifiquei que esse método só aceita a opção LIBXML_NOEMPTYTAG, então as duas outras opções (LIBXML_HTML_NOIMPLIED e LIBXML_HTML_NODEFDTD) estão de bobeira aí.
Mas o que parece estar causando o problema de fato é a opção LIBXML_NOEMPTYTAG, que, segundo a documentação, expande tags vazias:

LIBXML_NOEMPTYTAG
  Expand empty tags (e.g.
 to

)

No XML do evento do eSocial não há tags vazias, mas na assinatura há as tags <CanonicalizationMethod />, <SignatureMethod />, <Transform /> e <DigestMethod />, então, o documento assinado está sendo alterado, quando essa opção é usada.
Veja que no exemplo de uso básico da biblioteca XMLSecLibs do Rob Richards, o método DOMDocument::save é usado sem nenhuma opção:
   // Save the signed XML
   $doc->save('./path/to/signed.xml');

Altere então essa linha que comentei para:
   $doc->save($array['xml-assinado']);

que o problema deve ser resolvido.
Comment: Realmente o problema foi resolvido com a substituição dessa linha. Quero agradecer a todos pela ajuda prestada. Projeto em funcionamento.
Comment: @LeonardoDelgado, que bom que funcionou! Mas, a melhor forma de agradecer por uma resposta é marcando ela como aceita, clicando no sinal de visto (✓). Mas faça isso apenas se alguma resposta tiver respondido sua dúvida original. Quando atingir 15 pontos de reputação também poderá [votar a favor](https://pt.stackoverflow.com/help/privileges/vote-up) de uma resposta ou pergunta. Veja: [Alguém me respondeu](https://pt.stackoverflow.com/help/someone-answers) e [Por que votar?](https://pt.stackoverflow.com/help/why-vote).
Comment: Feito! Grato pela atenção e colaboração de todos!
Answer: Tive o mesmo problema de Assinatura do evento inválida, adotei este item da resposta do Pedro Gaspar
$doc->save($xml_assinado,LIBXML_NOEMPTYTAG | LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);

E também coloquei o item FALSE nesta parte para remover os prefixos "ds:" do XML assinado
$objDSig = new XMLSecurityDSig(FALSE);


Reverse translation

Question: I have a problem.
My multilingual site have 'Italian' as default language and I have a problem with the taxonomy name translation.
In views when I add taxonomy name field this is always displayed in Italian ad never translated so I think to sobstitute the name field to a php field like
<?php print t($row->name); ?>

but $row->name is italian and the t() function assume this string in english and translate it when the site is 'IT'
I tryed to use taxonomy context but drupal double the entry

How can I have in my damn view a field with the right taxonomy name?
Can I tell drupal 'translate from IT to EN when the site is English'?
Comment: Good luck with that. I gave up long time ago and now I write everything in English. Even if I never plan to display English version. Additional bonus - I don't need to change code of my modules when marketing decides to change texts.
Comment: I can't resetup all the site language and trnslated string only for ONE block in the site T_T

Why the context exist if they don't work?
Comment: I know, that's why I didn't post this as an *answer*.
Answer: This is how I did it for an array of untranslated terms:
foreach ($terms as $term => $str) {
  $translation = db_query("SELECT t.translation FROM {locales_source} s LEFT JOIN {locales_target} t ON s.lid = t.lid AND t.language = 'en' WHERE s.source = :source", array(':source' => $str))->fetchAll();
  $terms[$term] = $translation[1]->translation;
}

Reverse translation


Is there an analog to the Church-Turing thesis in model theory?

Question: Before the applications in theoretical computer science, Turing machines were developed as a model of what the idealized mathematician could possibly compute in order to give a precise definition of "effectiveness", and thus giving a universal model of computation. The affirmation that Turing machines actually are such a universal model, at least roughly speaking, is the Church-Turing thesis.
It thus seems like a natural question to ask: "Is there a universal theory for all possible mathematical theories?" In other words, does there exist some theory in which we could interpret any theory that an idealized human mathematician could possibly devise? Such a theory would be an honest to goodness "foundation of mathematics", in the sense that, unlike ZFC, in which we can express any most theories that mathematicians tend to think about, we can express anything possibly devisable.
Call this theory $X$, then for example, $X$ admits an interpretation of ZFC, ZFC + any large cardinal you could think of, MLTT, MLTT with arbitrary type universes, etc...
I would imagine that like the Chruch-Turing thesis, we could not possibly rigorously prove such a proposition, but that we should be able to find some reasonable candidate for this "$X$" theory. Has this, or similar notions, been thought about in model theory?
Comment: Doubtful, considering you'd be asking $X$ to express contradictory things.
Comment: Going back to computability theory, there are many possible turing machines, but importantly, Turing machines take input and produce output. A universal Turing machine is a Turing machine for which, given the appropriate input, the action of arbitrary Turing machines may be simulated. Thus, I suppose in model theory, the analog would not be a single theory $X$, but a function $X(x_0,x_1,x_2, \dots)$ that given appropriate input (e.x. the inputs could be additional rules and axioms) can interpret arbitrary theories in the sense I described in the original post.
Answer: Since you mention universal Turing machines, perhaps this satisfies what you are looking for:
Any reasonable, in practice usable axiomatisation of mathematics has the property that proofs in that system can be expressed as finite strings of characters from a finite alphabet; and if $T$ is a string of characters, then there is an algorithm (a computable function) which determines whether or not that is a valid proof in the system. E.g., for ZFC, the alphabet consists of (say) alphanumeric characters, parentheses, logical symbols, the symbol $\in$ and maybe some separators. The computable function checks whether the proof consists of well formed formulas, and whether each one either follows from a previous one (depending on the proof system chosen) or is an axiom (of ZFC or in the proof system).
Now such an algorithm can be formalized within a "weak" theory like Peano arithmetic. Thus, if we have $\mathrm{ZFC} \vdash \phi$, then we can also prove $\mathrm{PA} \vdash ``\mathrm{ZFC} \vdash \phi"$. For instance, we have that $\mathrm{PA} \vdash ``\mathrm{ZFC} +\mathrm{IC} \vdash \mathrm{Con}(\mathrm{ZFC})"$. Hence, every system of mathematics that I referred to above as reasonable/usable can be internalized in Peano arithmetic (or another sufficiently strong) theory.
Comment: Thanks for your answer! I think this was basically what I was looking for, but I'm curious if you could elaborate on what you mean by a "weak theory", and if you could provide me with a reference detailing the construction of such an algorithm. Does Robinson Arithmetic, for example, also suffice to formalize such an algorithm?
Comment: @Sintrastes, I don't have the expertise to answer that confidently; at best I could make educated guesses. I suggest you post another question.


Passing Json to google map api with formatting

Question: I am trying to Understand this peace of code. can anyone help me to understand this. sorry for the pretty basic question
testCtrl.geoCoords.push(new Array(testCtrl.allOrgUnits[i].name, testCtrl.allOrgUnits[i].coordinates.substring(1,testCtrl.allOrgUnits[i].coordinates.length-1).split(",")));

I have coordinates like
coordinates":"[-12.2231,8.466]

How this peace of code is changing the coordinates.
coordinates.substring(1,testCtrl.allOrgUnits[i].coordinates.length-1).split(",")));

Comment: You could add this as comment under the solution answer :  http://stackoverflow.com/questions/33973087/getting-data-into-the-json/33973153#33973153
Answer: if coordinates is a string like "[-12.2231,8.466]"
coordinates.substring(1, coordinates.length - 1).split(",") will return the Array ["-12,2231", "8.466"].
coordinates.substring(1, coordinates.length - 1) == "-12.2231,8.466"
then
"-12.2231,8.466".split(",") == ["-12,2231", "8.466"].
You can find the method documentation here: substring, split


executable in path, findable by which, yet cannot execute without fully qualifying path?

Question: I've got a bizarre seeming shell issue, with a command in the $PATH that the shell (ksh, running on Linux) appears to cowardly refuse to invoke.  Without fully qualifying the command, I get:
#  mycommand
/bin/ksh: mycommand: not found [No such file or directory]

but the file can be found by which:
#  which mycommand
/home/me/mydir/admbin/mycommand

I also explicitly see that directory in $PATH:
#  echo $PATH | tr : '\n' | grep adm
/home/me/mydir/admbin

The exe at that location seems normal:
#  file /home/me/mydir/admbin/mycommand
/home/me/mydir/admbin/mycommand: setuid setgid ELF 64-bit LSB executable, x86-64, version 1 (SYSV), for GNU/Linux 2.6.4, dynamically linked (uses shared libs), not stripped

# ls -l mycommand
-r-sr-s--- 1 me mygroup 97892 2012-04-11 18:01 mycommand

and if I run it explicitly using a fully qualified path:
#  /home/me/mydir/admbin/mycommand

I see the expected output.  Something is definitely confusing the shell here, but I'm at a loss what it could be?
EDIT: finding what looked like a similar question: Binary won't execute when run with a path. Eg >./program won't work but >program works fine
I also tested for more than one such command in my $PATH, but find only one:
# for i in `echo $PATH | tr : '\n'` ; do test -e $i/mycommand && echo $i/mycommand ; done
/home/me/mydir/admbin/mycommand

EDIT2:
As of this morning, the problem has vanished, and I'm now able to execute the executable.
That could be thought of as validating the suggestion to logout and login, but I'd done that last night without success.  That logout/login should have also done the equivalent of running the 'hash -r' command that was suggested (which fwiw also appears to be a ksh builtin, and not just a bash builtin).
In response to some of the answers:

This is an executable not a script (see the ELF reference in the file command output).
I don't think that a strace would have helped.  That ends up forcing the command to execute fully qualified.  I suppose that I could have done a strace attach on the current shell, but since I can no longer repro there's no point of trying that.
there were no semicolons in the $PATH.  Since I can no longer repro, I won't clutter up this question with the full $PATH.
trying another shell (i.e. bash) would have been something I'd also have tried, as was suggested.  With the problem gone, I now won't know if that would have helped.

It was also suggested to me was checking the directory permissions.  Doing so, for each of the directories up to this one I see:
# ls -ld $HOME $HOME/mydir $HOME/mydir/admbin
drwxr-xr-x 10 me root    4096 2012-04-12 12:20 /home/me
drwxrwsr-t 22 me mygroup 4096 2012-04-12 12:04 /home/me/mydir
drwxr-sr-x  2 me mygroup 4096 2012-04-12 12:04 /home/me/mydir/admbin

The $HOME directory ownership is messed up (shouldn't be root group).  That could cause other issues, but I don't see how it would have caused this one.
Comment: Your scripting kung-fu is awesome.
Comment: I know this sounds overly simplistic but I once had the same problem and it turned out to be a semi-colon used as a path separator instead of a colon.
Comment: Can you provide your whole PATH setting?
Comment: This is an outstandingly well-written question.
Comment: could have been the shell's caching?
Answer: You probably need to update your shell's cache of items in your $PATH using hash -r.
Comment: `$ apropos hash | grep ksh` -- nothing. You've answered with a `bash` built-in, but that's not the shell in question.
Comment: Perfectly logical answer for the normal admin. Gotta love linux ^^ Thanks.
Answer: Also, in such cases, check what happens when the program is called by passing its executable as an argument to the dynamic linker (might refuse to do so while setuid/setgid on some systems).
ldd(1) output of both cases might also be revealing. "no such file or directory" on an executable file really means that the dynamic linker specified in the executable file cannot be found (imagine the executable having an ELFin form of #!/lib/ld-linux.what.so.ever inside)
This behaviour had people dumbfounded that were there to witness the end of the libc5 era, and now occasionally dumbfounds people in the era of mixed i386/amd64 with different means of supporting two library sets in the wild.
Relative RPATH in executable vs $PWD?
PS the other question is related to MacOSX, which probably uses dyld and not the libc provided linker. Very different kind of animal.
Answer: Alright, I don't have an answer. I did prove out a few things and think I may add to this later:

Created a testfile -- your permissions show it is setuid and executable.
Tried setting it on a mount point with nosuid: still runs
Tried setting it on a mount point with noexec: gives a different error

So, by all accounts, I'm still as confused. Just for grins and on the off chance this is a shell-related bug, can you try it with a different shell?
Answer: I'm guessing that your script doesn't have a valid shell after the #!.  For instance, on some older SCO systems, scripts with #!/bin/bash don't work because bash REALLY lives in /usr/bin/bash.  Dumb, but hey SCO is almost dead for a reason, no?
Check your shell and make sure it points to a real binary/script.
Edit:  It doesn't tell if it's a script or a binary, but assuming your 'ls -l' output is correct, then you probably don't have a 93kbyte script...  so this is probably a binary meaning my answer is totally incorrect.
Have you tried logging out and back in?  I know if I use a binary that's in /usr/bin then install a /usr/local/bin version from source, the system still tries to execute the original one until I log out and back in.
Comment: It was an executable and not a script (see the ELF info from file in the question).  Yes, I'd logged out and in.
Answer: No answer, just a bunch of thoughts:

Check if the filename contains whitespace; this gets silently ignored when using tab-completion and use as a parameter.
Try another script/program in the directory.
Try strace-ing the shell trying to execute the script and see where it breaks.
Answer: My guesses:

You had an alias named mycommand.  For example:
alias mycommand=something

You had a function named mycommand.  For example:
mycommand() { something; }

Next time you have this problem, try running command -V mycommand to see what kind of command the shell believes mycommand is.
Comment: neither of those were the case for this command.
Answer: I had exactly the same problem, and failed to find an answer because the original poster's problem resolved itself. But this didn't work for me, and I finally managed to track the problem down. So I'm adding the following as an answer to the original post.
The symptoms I faced were the following.  There is a script (myscript.pl) in the /my/home
directory.  Now trying to run it:
> /my/home/myscript.pl
myscript.pl:  permission denied.

Verified permission of the file (execution flag is set). Verified $PATH (though there should not be an issue).
So then I try (after verifying the executable flag is set on the script):
> cd /my/home/
> ./myscript.pl:  permission denied.

Hmmm...  So perhaps the script is not calling the right scripting language (perl, in this case).  The top of the script has the correct magic:
#!/usr/bin/perl

and indeed /usr/bin/perl exists and works. So the following call works correctly.
/usr/bin/perl myscript.pl

tab auto-complete would not show the file (neither in tcsh nor in bash).
This really threw me off.  Then remembered that a few months ago my hard disk crashed,
and the young system administrator in my lab re-installed the system.  Thought he might
have screwed up the permissions on the partitions.  And indeed, in /etc/fstab, the exec permission was missing!
/dev/sda1    /my     /ext4      rw,user

Instead of
/dev/sda1    /my     /ext4      rw,user,exec

Fixed this by changing /etc/fstab and remounting:
mount -v -o remount /my

This solved the problem completely.  My guess is that a similar thing
might have happened with the original poster's problem, except that there
the permission issue was intermittent (e.g., there was a temporary change
that might have been solved with a reboot, if one took place).
Answer: Not a full answer, but wanted to report my experience as I had the exact same problem as the questioner, and thought it might help future users experiencing the same maddening problem.  I could which the file, and see it in my path, and even execute it by giving the full path, but could not execute it otherwise.  However, in my case, it only happened within a sub-shell (i.e. when it was executed from a script, in this case there were a few nested sub-shells).  I could run it from the command line just fine.
Just before the command in the nested script, I printed out the command, e.g. echo $(which mycommand)
mycommand: /home/me/bin/mycommand
Then I would try to execute it from the parent script:
/home/me/bin/some_parent_script[72]: mycommand: not found [No such file or directory]
Just like the questioner, I was unable to diagnose the source of the problem.  My PATH looked right, it was which-able, and hash did not reveal any prior entries of mycommand.  The next day when I logged in, everything magically worked again.  Now, I will note here that there was a known system issue that occurred just before I saw this problem where a mount was remounted.  Perhaps that's a clue?
If I didn't have log file after log file demonstrating that this happened, I wouldn't believe it to have been possible!  Thanks to the questioner, I no longer feel crazy!
P.S. I don't think user226160 had the EXACT same problem as the reporter, but it sounds related, and lends credence to the mount theory.


convert node/id to node/path-alias in content body

Question: I added a link to a content body from ck editor as /node/7. When viewing this page I want to show www.sitename.com/example/alias.
This is working fine in drupal 7 (earlier version of my site), but not sure which module does this work.
I have installed pathauto, redirect, pathologic modules. I also configured the text format at admin/config/content/formats and set pathologic filter as first priority. But no luck.
After installed redirect module, if I hit node/7 in browser it automatically redirect to expected alias. But I want is the content page should show only url alias even If entered /node/7 in ckeditor.
Am I missing any configurations in any of the above module? or am I missing any module?
Answer: I found a hook in Pathologic module as hook_pathologic_alter and I used it to convert node path to URL alias.
I used this hook as follows
/**
 * Implements hook_pathologic_alter().
 */
function mymodule_pathologic_alter(&$url_params, &$parts, &$cached_settings){
    if ($parts['path'] != '<front>') {

        //get the alias for the path and assign it in path
        $alias = \Drupal::service('path.alias_manager')->getAliasByPath('/'.$url_params['path']);

        //Url::fromUri which Pathologic uses need a path without slash at first, so trim it
        $url_params['path'] = ltrim($alias, '/');
    }
}

This converts a node path to alias and pass it, so Pathologic will form a URL with alias.


Multiple Levels for Modular Forms?

Question: Please pardon what I'm sure is a very naive question. I have heard discussions of modular forms for a bit and am trying to get a more fundamental understanding. People often talk about modular forms of level $N$. I have read that this means that the finite subgroup $\Gamma$ of $SL_2(\mathbb{Z})$ on which the modular form $f$ is defined contains the principal congruence subgroup $\Gamma(N)$. We can think of this subgroup as the set of matrices congruent to the identity modulo $N$. My question is this: couldn't this be true for multiple values of $N$? In other words, can a given modular form have multiple levels? Yet people seem to generally refer to a modular form as having a specific level. Is this just because we are usually interested in a specific canonical value of $N$? Thank you.
Answer: If $f$ is a modular form with respect to the principal congruence subgroup $\Gamma(N)$, then $f$ is also a modular form with respect to $\Gamma(\ell N)$ for any $\ell$. The converse is not true.
The natural place to talk about a modular form is the smallest level in which it can occur. There is a more technical definition, which is that the "natural" modular forms associated to a cannonical level $N$ are the "newforms" of level $N$. See this page on wikipedia for example. The LMFDB only displays information about newforms.
It might also be helpful to note that this is very similar to Dirichlet characters. Recall the mechanical definition of a mod $N$ Dirichlet character as a multiplicative function $\chi : \mathbb{Z} \longrightarrow \mathbb{C}^\times$ that satisfies $\chi(n) = \chi(n + N)$ and $\chi(n) = 0$ if $\gcd(n, N) > 1$.
For example, we have $\chi_{-4}(n) := (\frac{-4}{n})$, defined to have $\chi_{-4}(1) = 1$, $\chi_{-4}(3) = -1$, and $\chi_{-4}(n) = 0$ otherwise. Then $\chi_{-4}$ is a Dirichlet character mod $4$, but it's also a Dirichlet character mod $20$, or $444$, or any multiple of $4$. The analogous notion of "level" and "newform" with characters is "conductor" and "primitive character".

Multiple Levels for Modular Forms?


Is Fartlek more effective than regular training

Question: Fartlek is intended to be a type of interval training without fixed distances, times or paces.
Is this more effective than regular distance and interval training in separate workouts?
Comment: Shouldn't this really be on skeptics?
Answer: To me, fartlek is not just fun. As our body is a very adaptive system, if one sticks to a training routine long enough, his body gets used to it, and thus will not make much improvement. So variation is the key (at least to me and itself is fun) so that fartlek can trick the body to keep adapting to different training intensity and condition, thus it can be effective than, but not replace, regular training.
Answer: Fartlek is not more effective than any proper interval training - just more fun! After all, you decide when to speed up during the run and for how much and how long... And in my experience that is not nearly as hard as when you run against the clock.
(I believe "fartlek" is derived from Danish "fartleg", which means "speed game"...)
EDIT I stand corrected. As noted by @Henrik "fartlek" is likely directly from Swedish...
Comment: I totally agree, training is way more effective when having fun, and Fartlek is a lot of fun!
Comment: Danish is close, but the swedish word is actually "fartlek", and it means the same thing!
Comment: @Henrik Close, but no cigar...
Answer: We only used Fartlek as a fitness measurement, and as a bit of fun.
It does train you, but not as well as a more rounded fitness regime. It is, however, a very good indicator of short term fitness and speed, so is useful as part of your training plan at intervals of a month or two to help you gauge progress.


Some inequalities for holomorphic function on unit disk.

Question:
D is a open unit disk centered at 0.
I can figure out why |f(z)|<1 (by using maximum modulus theorem)
also I can show the latter inequality.
My attempt is using latter term is less than |Z| which is trivial.
(But I think this is not right way.)
Problem is I can not show First inequality.
How can I show this one?
Can you give me a any little clue?
Thanks!
Comment: Trial: Using Harnack's inequality, (Very similar form) But It is not a harmonic function... So Fail.
Answer: Hint: For $|a|<1,$ let $g_a(z) = (a-z)/(1-\bar a z).$ These are well known automorphisms of $\mathbb D,$ the unit disc. Note that $g_{f(0)}\circ f$ is a self map of $\mathbb D$ that takes $0$ to $0.$ By the Schwarz lemma,
$$|g_{f(0)}(f(z))|\le |z|, z\in \mathbb D.$$
Write that out in all its glory and do the silliest things you can think of with absolute values and those inequalities should fall out.
Comment: I solved it! Thank you.
Comment: Wow. It looks working! I'll check very soon. Thanks!!
Comment: Oh, I was completely wrong. The thing what i considered solved ( latter inequality) is obtained by your suggestion, Not my idea. But again, I can't show First inequality.
Comment: Good for you. Now how about a nice little √ ?


An elementary way to prove that $\sqrt{2}+\sqrt{3}$ is irrational?

Question: An elementary way to prove that $\sqrt{2}+\sqrt{3}$ is irrational?

Disclaimer: I know about the rational root theorem. I am trying to answer it without using it.

I did the following:
$$\sqrt{2}+\sqrt{3}=\frac{a}{b}$$
$$5+2\sqrt{6}=\frac{a^2}{b^2}$$
$$24=\frac{a^4}{b^4}-10\frac{a^2}{b^2} + 25$$
$$\frac{a^2}{b^2}\left(10-\frac{a^2}{b^2} \right)= 1$$
At this point, I am a bit confused. I thought about this: If $A=\frac{a^2}{b^2}$ then $A^{-1}=\left(10-\frac{a^2}{b^2} \right)$ and then:
$$AA^{-1}=A\left(10-A \right)=10A-A^2=1\tag{$\star$}$$
This is a polynomial with roots: $A=5\pm 2\sqrt{6}$ which means that:
$$\frac{a^2}{b^2}=5\pm 2\sqrt{6}$$
$$\frac{a^2}{2b^2}-\frac{5}{2}=\pm \sqrt{6}$$
As $\frac{a^2}{2b^2}-\frac{5}{2}$ is rational and $\sqrt{6}$ is irrational, then we obtain a contradiction. Is this correct?
Comment: Duplicate of [Prove that $\sqrt 2 + \sqrt 3$ is irrational](https://math.stackexchange.com/questions/452078/prove-that-sqrt-2-sqrt-3-is-irrational) and likely *hundreds* more.
Comment: Hint: by your 2nd equation it suffices to show $\sqrt 6\not\in \Bbb Q$ (which can be done the same way as $\sqrt 2,$ for which there are *hundreds* of prior answers here).
Answer: From your second line of working you should get that
$$5+2\sqrt{6}=\frac{a^2}{b^2}\implies\sqrt{6}=\frac{a^2-5b^2}{2b^2}\in\mathbb{Q}$$
which is a contradiction.
Comment: Damn. I ended up saying a lot of stuff to just say what I was already saying! *facepalm*.
Answer: Your proof is corect but you could have stopped on the second line and get the same result.
You have $$ 5+2\sqrt{6}=\frac{a^2}{b^2}$$ which  implies that $\sqrt 6$ is rational and that is a contradiction that you are looking for.
Comment: @MichaelRozenberg Trusted users should A) search first when a question smells like a duplicate, and B) IMHO also steer clear from stunning displays of banalities. Not saying that it is always easy to resist the temptation to answer every trivial thing, but...
Comment: Can down-voter explain us why did you do it?
Answer: It may be addressed in vast generality, to wit:
Let
$r, s \in \Bbb N, \tag 1$
neither of which is a perfect square; if
$\sqrt r + \sqrt s = q \in \Bbb Q, \tag 2$
then
$\sqrt r = q - \sqrt s, \tag 3$
which upon squaring leads to
$r = q^2 - 2q\sqrt s + s = (q^2 + s) - 2q\sqrt s, \tag 4$
$2q\sqrt s = (q^2 + s) - r, \tag 5$
and thus
$\sqrt s = \dfrac{(q^2 + s) - r}{2q} \in \Bbb Q, \tag 6$
valid since $q \ne 0$ from (2); but this contradicts the well-known fact that an integer which is not a perfect square cannot have a rational square root, proved, for example, in the answers to this question.
Now we simply set
$r = 2, \; s = 3, \tag 7$
to obtain the specific result requested in the question title.
And so we are done.


How to prevent users of particular role to access the content view (node view) of a particular content type?

Question: I am using Content Access Module and have rebuild permissions after enabling the module.

After giving restricted access to users having role 'Data Entry Operator'.
I have a content type delivery challan for which I have ticked on the following permissions for the role ABC.
View own delivery_challan content(selected the particular permission for role 'Data Entry Operator' only ) and
View any delivery_challan content(unselected the particular permission for role 'Data Entry Operator')

Here is the screenshot of the permissions set in the content access module.

When I login as user having role Data Entry Operator , I should not be able to view the contents of type 'delivery challan'
But the issue is I am able to view the content
How can I prevent user from viewing this content??
Comment: You can able to view the content if you created the content.. As per settings you mentioned you can see own content that means content created by you.. But content is created by some one else then you should get access denied..
Comment: Yes but I am able to see others content as well. But according to view that should not be the case
Answer: Ok  there was a mistake from my side

the view 'any delivery_challan content' permission was given to
authenticated user.
And by default any user has role authenticated user.
So User having role 'Data Admin Operator' was able to view any delivery challan content as user also has the role 'authenticated user'
So the solution is to remove the authenticated role from the list of roles under the view any delivery challan content


How can I do tag wrapping in Visual Studio Code?

Question: I would like to wrap my selected HTML content within a tag in Visual Studio Code.
How do I do that?
Comment: @budji Its a built in feature with emmet... Pretty much anything you could want is also an extension now and if it isn't you can always make your own.
Comment: One of the reason I'm unable to completely move to VSCode and ditch Sublime.
Comment: I like this question and I know and extension call (Emmet Wrap with Abbrevation), but anyone would know how to do the inverse actions. For example: write first ... and include inside ** with this result ...**...
Comment: You press tab after typing the tag name.  E.g. "div[tab]".
Answer: Embedded Emmet could do the trick:

Select text (optional)
Open command palette (usually Ctrl+Shift+P)
Execute Emmet: Wrap with Abbreviation
Enter a tag div (or an abbreviation .wrapper>p)
Hit Enter

Command can be assigned to a keybinding.

This thing even supports passing arguments:
{
    "key": "ctrl+shift+9",
    "command": "editor.emmet.action.wrapWithAbbreviation",
    "when": "editorHasSelection",
    "args": {
        "abbreviation": "span",
    },
},

Use it like this:

span.myCssClass
span#myCssId
b
b.myCssClass
Comment: `Ctrl`+`p` is goToFile. Command palette is `Ctrl`+`Shift`+`P`.
Comment: This should be the answer, emmet is already installed in vscode
Comment: With VSCode 1.35.0 (and possibly earlier) this works out the box with JSX - no need for any extra config
Comment: For JSX, had to add this extra step: https://github.com/Microsoft/vscode/issues/4962#issuecomment-323880988
Comment: That Emmet function does not appear in my VSCode (Windows VSCode v 1.43.1)  What gives?
Answer: A quick search on the Visual Studio Code marketplace: htmltagwrap.

Launch Visual Studio Code Quick Open (Ctrl + P)

Paste ext install htmltagwrap and Enter.

Select HTML

press Alt + W (Option + W for Mac).
Comment: "To use, select a chunk of code and press "Alt + W" ("Option + W" for Mac)." Simple enough! Except it's not working. I tried version 0.0.3 with VS Code 1.16.1. It *almost* works. It tries to wrap the selection in `` tags, instead of the generic `` which would seem more sane thing to do. What's worse is that it fails. It produces output like `My selected text.`
Comment: UPDATE: the extension now works correctly and addresses the above issues. No more duplicate tag, and you can now customize the tag you want to be inserted via a setting. So if you want the tag to be a `` you add the following setting, `"htmltagwrap.tag": "div"`.
Comment: I tried other extensions like that. But so far I am not having any luck finding one that works. This one was closest to a working solution. I tried wrap 0.0.1 by David Taylor, and the Ctrl+i didn't work at all.
Comment: that is pretty poor implementation - works for single tag, it would be nice to have something similar to notepad++ html plugin where you can wrap selection by tag from your configurable tag selection
Comment: I'm using it with VS Code 1.36.0. It's a bit clunky. If I wrap text with it and quickly add an attribute, the attribute name gets added to the closing tag, yuk!  Code ends up like this:  My link.  The work around is to type the "<a", then wait a few seconds for it catch it's breath, then space and the attribute, it then works fine. Not good when you have a ton of html work on!  Just checked GIT and it appears nobody has touched it for the past 3 years.
Comment: This is quite good and better than the one I'm using in Atom (which I love but these little things may cause a switch). I hope this is part of the standard functions one day. I had never realized until recently how much tag wrapping I do at least in HTML.
Comment: The extension was recently updated again and it should be more graceful. Handles single and multi-selection with arbitrary tag types (e.g. HTML, custom React components, etc...)
Comment: You probably mean select Install at step 3.
Answer: If you want the Sublime-like experience with wrapping, open up the keyboard shortcuts (command ⌘/Ctrl + Shift + P → Preferences: Open Keyboard Shortcuts (JSON)) and add the following object:
{
    "key": "alt+w",
    "command": "editor.emmet.action.wrapWithAbbreviation",
    "when": "editorHasSelection && editorTextFocus"
}

Which will bind the Emmet wrap command to option
⌥/Alt + W when text is selected.
You can also use the UI to do this, open the Keyboard Shortcuts menu and search for "emmet wrap with abbreviation" to add the shortcut.

As I couldn't comment, I expanded on Alex's fantastic answer.
Comment: This is how I have added shortcut:
Preferences > Keyamp Shortcuts;...
then search emmet wrap;...
click + to add your shortcut;...
:)
Comment: @AndrewLewis - yes, that is why I kept it to language id and not file extension (files.associations).
Comment: additionally I added &&  resourceLangId == 'html' to work only for web pages
Comment: @surpavan, nice but It can also be handy to have in other file types e.g. html template files
Comment: In command I had to write: editor.emmet.action.wrapWithAbbreviation instead of editor.emmet.action.wrapIndividualLinesWithAbbreviation to make it work.
Comment: Shift+Alt+W is free for windows.
Comment: @Morfidon It's worth noting that these, at least at the time of writing, are different actions and the experience in Sublime matched "Wrap Individual lines". The documentation is really vague about this now (https://docs.emmet.io/actions/wrap-with-abbreviation/ ) but I believe the actions have been merged. I'll check out wrapWithAbbreviation and update the answer if it has the same capability.
Answer:
Open Keyboard Shortcuts by typing ⌘ Command + k, ⌘ Command + s or Code → Preferences → Keyboard Shortcuts
Type emmet wrap
Click the plus sign to the left of "Emmet: Wrap with Abbreviation"
Type ⌥ Option + w (use Esc once to clear if the wrong key(s) was chosen, for instance, a key combination already in use)
Press Enter
Comment: This one should be the accepted answer as of 2022, straight to the point and you get the shortcut added, thanks!
Comment: The keyboard shortcuts ***don't work*** on [Linux](https://en.wikipedia.org/wiki/Linux) (say, [Ubuntu](https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29)) or [Windows](https://en.wikipedia.org/wiki/Microsoft_Windows).
Comment: `Ctrl` + `K`, `Ctrtl` + `S` on Linux and Windows (tested on [Visual Studio Code](https://en.wikipedia.org/wiki/Visual_Studio_Code) 1.82.2).
Comment: For the second, on Linux and Windows, `Shift` + `Ctrl` + `W` and `Shift` + `Alt` + `W` aren't in use ([Visual Studio Code](https://en.wikipedia.org/wiki/Visual_Studio_Code) 1.82.2) and thus are uncomplicated to use. (In contrast to `Ctrl` + `W` and  `Alt` + `W`, which *** *** ***are*** *** *** in use.)
Comment: cont' - Though it *may* be fine to use `Alt` + `W` in this context. Or not. It changes a search setting(?).
Comment: Conclusion: Using `Shift` + `Ctrl` + `W` for the keyboard shortcut (step 4) is a workable solution.
Answer: In my opinion, there's a better answer for this using Snippets.
Create a snippet with a definition like this:
"name_of_your_snippet": {
    "scope": "javascript,html",
    "prefix": "name_of_your_snippet",
    "body": "<${0:b}>$TM_SELECTED_TEXT</${0:b}>"
}

Then bind it to a key in file keybindings.json. E.g., like this:
{
    "key": "alt+w",
    "command": "editor.action.insertSnippet",
    "args": { "name": "name_of_your_snippet" }
}

I think this should give you exactly the same result as htmltagwrap, but without having to install an extension.
It will insert tags around selected text, defaults to the  tag, and selects the tag, so typing lets you change it.
If you want to use a different default tag, just change the b in the body property of the snippet.
Comment: I don't understand the downvotes. Of course, Emmet is more complex and I can do a lot of things but for wrapping a text selection with a tag this solution is great! When you wrap, you don't have to move your eyes to the upper part of your screen/window. It happens right there, where you already were because you selected the text! It's a pretty common use case and quick solution with a low run time!
Comment: This is fine but Emmet can do this and much more, such as generating nested HTML, attributes and lists. Emmet comes out of the box with VS code.
Comment: The snippet written to file php.json has 'scope' word underlines, and tooltip is saying that 'property scope is not allowed'. Codium, version 1.60
Comment: This works great! For those that want this to work in jsx/tsx, add `javascriptreact` and `typescriptreact` to the scope.
Comment: I was very excited with this however I could not make it work :/
Comment: This is fine. This is the more general solution and thus more widely applicable.
Answer: Opt + w is the quick shortcut for this.
Trigger built-in functionality via Emmet like this:

Select your text/HTML.
Option + W
In the emmet window opened in the command palette, type in the HTML tag and any HTML attributes you need.
Enter
Voilà

Note: Emmet is built into most installations, but if it isn't in yours you will have to add it manually.
Note 2: Double check the shortcut is there at Code > Settings > Keyboard Shortcuts (search for "emmet wrap").
Comment: I've not found this to be the case for 1.47.3 on Mac OS. I had to add the keybinding for Opt+w as suggested by the other answers.
Comment: Worked for me out of the box. Not sure why yours wouldn't. Perhaps you installed a plug-in that overwrote the shortcut?
Comment: The keyboard shortcuts ***don't work*** on [Linux](https://en.wikipedia.org/wiki/Linux) (say, [Ubuntu](https://en.wikipedia.org/wiki/Ubuntu_%28operating_system%29)) or [Windows](https://en.wikipedia.org/wiki/Microsoft_Windows).
Comment: In my case it was shortcut conflict with `Csv to Json` plugin.
Comment: For Linux and Windows: See [Adam Gonzales' answer](https://stackoverflow.com/questions/40155875/how-can-i-do-tag-wrapping-in-visual-studio-code?noredirect=1&lq=1#comment136038496_55363652)
Comment: Doesn't apply for all installations.
Answer: Many commands are already attached to simple Ctrl + [key]. You can also do chorded keybinding, like Ctrl A + B.
(In case this is your first time reading about chorded keybindings: They work by not letting go of the Ctrl key and pressing a second key after the first.)
I have my Emmet: Wrap with Abbreviation bound to ((Ctrl) (W + A)).
In Windows: menu File → Preferences → Keyboard Shortcuts ((Ctrl) (K + S)) → search for Wrap with Abbreviation → double-click → add your combination.
Answer: I just installed htmltagwrap from the extension marketplace and used Alt + W to wrap the tags (Windows Version).
Comment: This is already covered in [hannes neukermans' answer](https://stackoverflow.com/questions/40155875/how-can-i-do-tag-wrapping-in-visual-studio-code/40174366#40174366).
Answer: There is a fast typing of the solution.

Open the Command Palette (usually Ctrl + Shift + P)

Preferences: Open Keyboard Shortcuts (JSON)

Add this snap code
{
    "key": "ctrl+`",
    "command": "editor.action.insertSnippet",
    "when": "editorTextFocus",
    "args": {
        "snippet": "~~${TM_SELECTED_TEXT/^([\\t]*).*$/$1/}${TM_SELECTED_TEXT/^[\\t]*(.*)$/$1/}${TM_SELECTED_TEXT/^([\\t]*).*$/$1/}~~"
    },
}

You select any text and press Ctrl + `
Result:
 ~~YourText~~

Answer: Incredible that the fastest solution still is Cut & Paste:
Cut selection (Ctrl+X/Cmd+X) -> Type tag -> Paste (Ctrl+V/Cmd+V)

One would have thought a shortcut would have been built in by now.
Comment: Best method for most use cases.
Comment: A Tab is required after typing the tag.
Comment: This didn't work ([Visual Studio Code](https://en.wikipedia.org/wiki/Visual_Studio_Code) 1.82.2) on an existing installation (nothing happens when, for example, typing `div` for the tag (except for "div" being added)). Though it did work by installation on another system that had never had Visual Studio Code installed before (the exact same version, 1.82.2). In both cases, the file extension was `.html`.  ***What configuration is required for this to work?***


How are files being added to site as apache, when site is running as FastCGI?

Question: I have a web server that is running many different sites (standard vhosts setup, most sites are Joomla based, a few wordpress and other non-CMS sites) in a Parallels Automation 11.5 environment.  The version of apache on the web server, is 2.2.15, and the same problem is happening across multiple PHP versions.
Our websites have been getting hacked quite a bit, and are being to turn our server into an email spambot.  From what I can tell so far, is that a malicious person is able to upload a PHP file, generally to the docroot, but sometimes to the images folder following a wn.php (w12345678n.php) naming pattern and from what I can tell it's the WSO Web Shell.  The person then seems to use that web shell to add inject/malicious code  to the rest of the site.
The thing that strikes me as odd, is that these sites are being run as FastCGI, so all of the files are owned by the FTP User of the particular account (bob_ftp etc), but the WSO shell php file is being put onto the web server under apache:apache ownership.
I'm guessing that the files are being added via some sort of apache vulnerability but I haven't had much luck in tracking down the culprit.  Could someone please point me in the direction of how I can lock down these shenanigans?  Preferably by closing the vulnerability, but at this point I just want some way of mitigating the damage so I don't have to waste so much time on it.
Answer: Files are created under the user that runs the process. If they are owned by apache and reside in a directory writable by apache then ask yourself why apache needs to write 'at all' in that area. Tighten file permissions further: chown root, chmod o-wrx, etc. Apache only needs read permission in general, not ownership.
Verify unique uid's in /etc/passwd, apache 's uid might have a duplicate hiding there.
Btw: If you allow FTP users to write executables, then consider using chroot.


java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/invoke/MethodHandles$Lookup

Question: Apps crash every time. Simulator works well.
Running it on Bluestacks through ADB, can't try it on the device.
MinSdk - 23.
Tried: compile 'com.android.support:multidex:1.0.0'
It doesn't help.
Error:
2020-03-25 14:08:50.912 8649-8649/com.untd.carcheck E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.untd.carcheck, PID: 8649
    java.lang.NoClassDefFoundError: Failed resolution of: Ljava/lang/invoke/MethodHandles$Lookup;
        at retrofit2.Platform.<init>(Platform.java:62)
        at retrofit2.Platform$Android.<init>(Platform.java:115)
        at retrofit2.Platform.findPlatform(Platform.java:44)
        at retrofit2.Platform.<clinit>(Platform.java:34)
        at retrofit2.Platform.get(Platform.java:37)
        at retrofit2.Retrofit$Builder.<init>(Retrofit.java:430)
        at com.untd.carcheck.data.network.VinApiService$Companion.invoke(VinApiService.kt:55)
        at com.untd.carcheck.ui.VehicleActivity.<init>(VehicleActivity.kt:41)
        at java.lang.Class.newInstance(Native Method)
        at android.app.Instrumentation.newActivity(Instrumentation.java:1106)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2558)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2727)
        at android.app.ActivityThread.-wrap12(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1478)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6125)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:893)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:783)
     Caused by: java.lang.ClassNotFoundException: Didn't find class "java.lang.invoke.MethodHandles$Lookup" on path: DexPathList[[zip file "/data/app/*.*.*-1/base.apk"],nativeLibraryDirectories=[/data/app/*.*.*-1/lib/x86_64, /system/lib64, /vendor/lib64, /data/downloads, /data/priv-downloads]]
        at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:56)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:380)

Answer: try changing minsdk to 26. as MethodHandles$Lookup class was added in API level 26. refer this docs.
This means you can't install your app on a API level 23 device any more.
Comment: Or upgrade retrofit to 2.8.1
Comment: Bro! Its worked, downgrade retrofit to 2.4.0!
Comment: What if I need to install it in devices with API 23....