Use L1 logistic regression for feature selection but a nonlinear classifier for the training. Is that feature selection reliable?

Question: I am wondering the following question. Probably it is a non-sense one but hope not too much..
Assume I have a binary classification model to build and I use a linear classifier like Logistic regression with L1 penalty (so the decision boundary is still linear) for feature selection.
Then I go through the training phase and I test several algorithms (linear and nonlinear classifier) for comparison.
If I see that the best performance is given by a nonlinear classifier, does my feature selection using a linear one make sense? It is likely that if I use a nonlinear classifier for feature selection I get a different subset.
So how to deal with this?
Thanks. Luigi
Comment: Similar to this question https://stats.stackexchange.com/questions/363797/regression-as-a-way-to-determine-variable-importance
Answer: Not a nonsense question at all! "Is it likely that if I use a nonlinear classifier for feature selection I get a different subset." Yes, that is quite possible, however, I think this is still a perfectly reasonable approach. Presumably you are doing this to cut down on time, so that you can quickly train many models on a smaller feat set. If your use case is not highly sensitive to getting the absolute highest possible performance and you are okay with a pretty good model, you are done.
If not computationally/time limited and you want to squeeze out more accuracy, I would do the exact process you describe, but then at the very end plug all the features back into your final non-linear model and do some kind of stepwise feature selection, either using tree-based feat importance if you are using trees, or a model agnostic version like permutation importance. You might still be left with a similar feat set, or you might pick up some extra features that help the non-linear version, but not L1.
Comment: Yep exactly, although idk if i'd bother with both types of feature importance, but can't hurt to see how they compare. Whatever model/feature set combo has the best performance on the test set at the end of the day is what you go with. And the more experiments you try the better. Another thing you could try is multiple levels of top features. So try all the features RF, then just use the top 80% most important features, then the 60% most important (where the feat importance list is recreated from the 80% run), then 40%, then 20%. This is kinda like tuning the L1 reg parameter.
Comment: See the "backwards elimination" section of wrapper methods: https://www.analyticsvidhya.com/blog/2016/12/introduction-to-feature-selection-methods-with-an-example-or-how-to-select-the-right-variables/#:~:text=Top%20reasons%20to%20use%20feature,the%20right%20subset%20is%20chosen.
Comment: Thanks! probably I can add 2 more feature selection to the L1 logistic regression: one would be a random forest ranking the features via MDI and another always a random forest but ranking via permutation importance..I would then train the model with these different sets (if different) and evaluate which is the best by checking performance on the test set. does it sound good in your opinion?
Comment: thanks for the suggestion. I would say I have three different methods now I can try: L1-LG, RF with permutation or MDI, and wrapper methods. All quite different in nature I would say
Comment: just a doubt came in my mind, is permutation importance suitable for time series data? since you have some temporal order to maintain and serial correlation, permuting each column for me seems to violate both..


Pass an environment variable to Docker

Question: Here is a particular operation everyone can try:
docker run --env TEST='xxx' ubuntu:14.04 /bin/echo $TEST

That returns an empty string.
Comment: Possible duplicate of [Docker echo environment variable](http://stackoverflow.com/questions/19896767/docker-echo-environment-variable)
Answer: The reason why echoing isn't working is that the $TEST environment variable is substituted on your host side. To postpone the substitution to container side, wrap the echo command with single quotes:
docker run --env TEST='xxx' ubuntu:14.04 sh -c 'echo $TEST'

Answer: You're substituting TEST in your bash instead of your container.
Try this command to make sure your variable is passed correctly:
docker run --env TEST='xxx' ubuntu:14.04 /usr/bin/env

Pass an environment variable to Docker


MV command doesn't work with filename that begin with quotes

Question: I have a bunch of file with random name that begin or end with special characters, the filter using tr or sed  works perfectly, when I echo the result it gives me the appropriate output, but when I try to change the name of the file using mv it said that the filename has already the same name:
Here is my script:
#!/bin/bash

root=/home/

for file in ${root}*
        do
        new1=$(sed 's/[][ ',!@?&()`'\'']/./g' <<< "$file")
        echo $(basename "$new1")
done

Using echo command, the new filename is :

5000....file...1..of..the..dir.ts
filename..1..of..the.dir.ts

Which represent the exact output I want.
But when using the mv command (the code below) ,
#!/bin/bash

root=/home/streaming/BBQwithBaconRecipes/

for file in ${root}*
        do
        new1=$(sed 's/[][ ',!@?&()`'\'']/./g' <<< "$file")
        $(mv $file $new1)
done

the changes are not applied in this specific file, do you think because my filename are between quotes ? like this:
'5000$$$file@@1&of!!the&.dir.ts'
I really need a solution to generalize my filter and my mv command to every file possible,I think that the '' is causing the problem.
Comment: The mv command should be mv "$file" "$new1". You don't been to expand the whole move command.
Answer: The mv command doesn't need expanding. It should therefore be:
mv "$file" "$new1"


Problema com Order By Case Com mais de 9 When

Question: Como usar corretamente o ORDER BY CASE WHEN com mais de 9 registros ?
No exemplo abaixo estou utilizando um case when com mais de 9 registros e quando chega na posição 10 , 11 ,12 e 13 a ordem fica errada.
Qual é a maneira correta de utilizar neste caso ?
ORDER BY CASE descricao
WHEN 'Rec. Op. Liquida' THEN 0
WHEN 'VENDA MERCADORIA' THEN 1
WHEN 'ICMS S.T S/ VENDA' THEN 2
WHEN 'DEVOLUÇÃO DE VENDA' THEN 3
WHEN 'VENDA LÍQUIDA' THEN 4
WHEN 'ICMS' THEN 5
WHEN 'ICMS ST' THEN 6
WHEN 'TOTAL ICMS' THEN 7
WHEN 'PIS' THEN 8
WHEN 'COFINS' THEN 9
WHEN 'TOTAL PIS/COFINS' THEN 10
WHEN 'DEV X FAT' THEN 11
WHEN 'BONF X FAT' THEN 12
WHEN 'BONIFICAÇÃO' THEN 13
ELSE descricao END;

Nesta imagem esta o resultado e do lado a posição do elemento no resultado.

Exemplo no SQLFiddle SQLFiddle, não consegui fazer rodar direito
  por que uso muitas variaveis e multiplas querys, se alguem puder
   ajustar para o exemplo ficar melhor agradeço, mas o resultado pode ser visto na imagem.
Answer: Funcionou utilizando desta forma, usei dois caracteres e botei aspas
ORDER BY CASE descricao
WHEN 'Rec. Op. Liquida' THEN '01'
WHEN 'VENDA MERCADORIA' THEN '02'
WHEN 'ICMS S.T S/ VENDA' THEN '03'
WHEN 'DEVOLUÇÃO DE VENDA' THEN '04'
WHEN 'VENDA LÍQUIDA' THEN '05'
WHEN 'ICMS' THEN '06'
WHEN 'ICMS ST' THEN '07'
WHEN 'TOTAL ICMS' THEN '08'
WHEN 'PIS' THEN '09'
WHEN 'COFINS' THEN '10'
WHEN 'TOTAL PIS/COFINS' THEN '11'
WHEN 'DEV X FAT' THEN '12'
WHEN 'BONF X FAT' THEN '13'
WHEN 'BONIFICAÇÃO' THEN '14'
ELSE descricao END;


mysql add condition when limit less than

Question: I creating relative system for my site.
I need query, when result rows less than i setup - 1 condition added.
My example:
SELECT * FROM `animal` WHERE (`color_id`=1) LIMIT 4

When result rows less than 4, i adding condition
SELECT * FROM `animal` WHERE (`color_id`=1) OR (`breed_id`=1) LIMIT 4

and continue
SELECT * FROM `animal` WHERE (`color_id`=1) OR (`breed_id`=1) OR (`type_id`=1) LIMIT 4

How do that in 1 query? if it possible
Comment: Re-Running altered Queries in case of the result set is to small is not the job of MYSQL, but of your code executing the queries.
Comment: Actually there is a way to do it BUT it would be so ugly that you shouldn't use. I completely agree with @dognose here. Let your application handles it.
Comment: @dognose, JorgeCampos,  thanks guys, now i know how to do it
Comment: @JorgeCampos I answered with an "ugly" approach - wouldn't recommend to use on production systems.
Comment: @dognose I already upvoted it :)
Answer: Re-Running altered Queries in case of the result set is to small is not the job of MYSQL, but of your code executing the queries.
A really "dirty" approach would be to use Union to ensure the resultset is always big enough, and finally just limit it to 4 rows (assuming the table contains at least 4 entries):
SELECT * FROM (
    SELECT * FROM `animal` WHERE (`color_id`=1) LIMIT 4
    UNION
    SELECT * FROM `animal` WHERE (`color_id`=1) OR (`breed_id`=1) LIMIT 4
    UNION
    SELECT * FROM `animal` WHERE (`color_id`=1) OR (`breed_id`=1) OR (`type_id`=1) LIMIT 4
    UNION
    SELECT * FROM `animal` LIMIT 0,4
) as temp LIMIT 0,4

Technically this would fetch 4 rows for every query, and only add them to the resultset if it does not already contain that row. From the final result (16 rows worstcase) the first 4 rows are taken. If none of the first 3 queries delivers a result, the first 4 animals existing in the database are returned.
Answer: I'd do this in my application code.
But just to see if it works, can you try this:
select *
from `animal`
where `color_id` = 1
    or (
        `breed_id` = 1
        and (
            select count(*)
            from `animal`
            where `color_id` = 1
            ) < 4
        )
    or (
        `type_id` = 1
        and (
            select count(*)
            from `animal`
            where `color_id` = 1
                or `breed_id` = 1
            ) < 4
        ) LIMIT 4


Hook webform options WEBFORM OPTIONS ID alter()

Question: [{"value_1":"Dragon fly"},{"value_1":"Agapostemon angelicus"},{"value_1":"Albuna oberthuri"},{"value_1":"Callohesma flavopicta"}]
This is a JSON data i need to use to import for radios in drupal 8 webforms. Iam using hook_webform_options_WEBFORM_OPTIONS_ID_alter() https://www.drupal.org/docs/8/modules/webform/webform-cookbook/how-to-use-options-from-an-external-webservice
I cant use value_1 as a key in radios, cause it is not unique, so I need to somehow copy the value into the key and get the same data on both sides, too look like this.
[{"Dragon fly":"Dragon fly"},{"Agapostemon angelicus":"Agapostemon angelicus"},{"Albuna oberthuri":"Albuna oberthuri"},{"Callohesma flavopicta":"Callohesma flavopicta"}] there are many lists and many data but the same problem.
This is the code from the module I made followed by instructions:
 * Implements hook_webform_options_WEBFORM_OPTIONS_ID_alter().
 */
function my_module_webform_options_external_countries_alter(array &$options, array &$element) {
  // Load cached options.
  if ($cache = \Drupal::cache()->get('external_countries')) {
    $options = $cache->data;
    return;
  }

  // Get data as associative array from the external webservice.
  $external_countries_url = 'https://gist.githubusercontent.com/mshafrir/2646763/raw/8b0dbb93521f5d6889502305335104218454c2bf/states_hash.json';
  $options = json_decode(file_get_contents($external_countries_url), TRUE);

  // Cache options so that we don't have to make continual requests
  // to the external webservice.
  \Drupal::cache()->set('external_countries', $options);
}

Comment: @DraganPetrovicFSD There's no need to edit your question to mark it as "SOLVED".  Instead, you should wait a couple days and then check the green box to mark your answer as the accepted answer.
Comment: Just checking that you replaced CUSTOM_MODULE with the machine name of your module?
Comment: That CUSTOM_MODULE is copied from drupal, but unfortunately, you got a point I said that I made followed by instructions, it's a typo.
Answer: I just found a solution. I probably didn't explain it well, so there was no answer. I hope that the solution to the problem I had will better explain the situation I was in.
function external_usa_list_webform_options_external_countries_alter(array &$options, array &$element) {
  // Load cached options.
  if ($cache = \Drupal::cache()->get('external_countries')) {
    $options = $cache->data;
    return;
  }

  // Get data as associative array from the external webservice.
  $external_countries_url = 'https://gist.githubusercontent.com/mshafrir/2646763/raw/8b0dbb93521f5d6889502305335104218454c2bf/states_hash.json';
  $options = json_decode(file_get_contents($external_countries_url), TRUE);

  $options = array_combine(array_values($options), array_values($options));

  // Cache options so that we don't have to make continual requests
  // to the external webservice.
  \Drupal::cache()->set('external_countries', $options);
}


Truss rod adjustment - tighten or loose?

Question: I am beginner guitar player and today after I replaced the strings and adjusted the Floyd Rose bridge of my guitar (BC Rich Gunslinger retro) I noticed that the action was increasingly high, from fret one to fret 22.
I understand from the picture below that the neck, depending of the applied tension strings vs. truss rod can have three shapes:

forward bow
flat
backwards bow

Though I am only having buzz on frets 1-3 (maximum) and the action only increases moving up the fretboard. So I imagine that the solution would be to lower the extremity of the neck where the headstock is.
I see the truss rod as a device to counter the tension on the strings. So intuitively I would imagine that I need to tighten the truss rod (turn clockwise) in order to lower the headstock extremity of the neck. Though I guess the picture above says the opposite.
So in summary: I am having a slight buzz on frets 1-3 and the action is only increasing as I go up the fretboard. Shall I tighten or loose the truss rod?
Comment: Did you change the string gauge? Why do you think this is a truss rod issue? Did you sight along the neck to look for a curve?
Comment: The problem with these images is that they don't show the neck in relation to a string with tension, which is straight, not curved like the fingerboard, so they don't give you a true picture of what is going on.  I recommend this video about adjusting the truss rod on a Strat (part 1 of 4) explained and demonstrated by an expert, John Carruthers. Go through the whole series if you want to do your own setup. Good luck!
https://youtu.be/PHHepmTX3So
Comment: Strings cannot exert pressure. When something is pulled it presents **tension**.
Comment: @dissemin8or: I did change the string gauge yes, using now thicker strings. I honestly cannot spot any bowing/ curvature on the neck. Though it a appears to be bowed (up in the headstock, down towards the upper frets) because of the buzzing pattern. If the neck is not straight, what else could it be?
Comment: @Tim: you are right that in this case the correct term is yes tension, I edited the question. Though generally speaking strings, like any other object, can exert pressure yes. If you take you strings and press them against a flat surface, how do you call the applied force over the area?!
Comment: Actually, when a string is pressed down, *more tension* is produced! The *pressure* is produced by your finger, *pressing*. The string is secondary.
Comment: Yes, you are right about the additional tension produced, though I'm talking about the definition of pressure **in general**. If you take a string (again, forget any musical instrument) and press it against any surface, the result of the force with which you pressing the string over the area is called pressure. Let us leave Isaac Newton quiet and peaceful in his grave
Comment: @dissemin8or: I checked today for neck bowing and, to my untrained eye, it seems that the neck is pretty straight. So I am now thinking about replacing the nut. If the nut was a big higher this would solve the problem, though I am not sure a new nut will do the job i.e. whether or not my nut is worn out or something like that. My floyd rose (special) is not the highest-end one.
Answer: Just as Victor pointed out, that picture has it backwards. My suggestion is to play the guitar for a few more days, then consider slightly loosening the truss rod (turn it counter-clockwise 1/6th of a turn) and see if that fixes the buzz. If the action at the middle of the neck is uncomfortably high, you've gone too far.
I would like to point out that it is normal for the action to gradually increase as you go up the neck. Because the frets are further apart lower down the neck, the string has more 'lenght' to clear the next fret and avoid buzzing. While you could set up a guitar to have the same action at every fret, this is not desirable because the action at the lower frets could be much lower.
After a certain point, adjusting the truss rod is more about feel than avoiding buzz. For example, if I feel the action on my guitar is higher than it was a few days ago, I tighten the truss rod (turn it clockwise) because the wood has likely exapnded due to temperature & humidity changes.
There is always a trade-off between action and buzz. If you want the lowest possible action for ease of play, you should try and get used to picking the strings softly. Picking the strings softly lets you get the action somewhat lower than you normally could.
nother point I'd like to bring up is that changing to different gauge strings usually requires changing the entire setup. In general, going to heavier strings will require you to tigten the trussrod in order to counteract the higher string tension. However, if you are down-tuning, that doesn't apply.
Comment: Thanks, that's helpful. In fact I went to a heavier string and tighten the truss rod a bit yesterday, let it set overnight and tightened a bit more today (each about a quarter of a turn). Will probably stop there, I don't want to strip the truss rod altogether
Answer: Basically, the truss rod battles the string tension. By loosening the truss rod, the string tension takes over and bows the neck. By tightening the truss rod, it takes over and the neck back bows. If it's concave like a bow, tighten it. If it's bending the opposite way, loosen.
I believe that image is backwards. A U shape means the strings are taking control and the rod is loose. An N shape means you went too far.
I would watch this video for more detail:

That shows you how to adjust and test the truss rod.
Happy playing!
Comment: The issue is that the buzzing pattern that I am having is neither bowed (buzzing on both extremes) nor backwards bowed (buzzing only in the middle). Although, when he explains the "bowing" (starts at around 1:15), it appears that tightening the truss rod would be the solution (provided that he did not move his elbow, when compared to loosening the truss rod on purpose i.e. adjusting the truss rod would eventually change the height of the headstock end of the neck, which is what I need)


How to render only markup in region template?

Question: I have created a region--footer.html.twig template which only contains the static markup for the footer. Now I would like to render this region at the bottom of each page so I have added the following to the end of page.html.twig:
{{ page.footer }}

This works fine as long as I have connected a block to the footer region under admin/structure/block. If no blocks are placed in the region it is regardes as empty and is not rendered. How can I change so the region--footer.html.twig is used even if there is no blocks placed in the region?
I was thinking of using a preprocess function for the region doing something like this:
function template_preprocess_region(&$variables) {
  if ($variables['region'] == 'footer') {
    $variables['content'] = 1;
  }
}

Comment: What purpose would it serve? I guess you can put the markup in page.html.twig and just print content in the region template.
Comment: @Kevin - I only need to display the footer region on some specific pages. I still don't understand why a region must have a connected block to be rendered, shouldn't the template for the region be parsed anyway?
Comment: It won't render if it's empty, there's no reason to do the work. Hence, the markup residing in page.html.twig instead will always output, with the region twig override just printing content. Then it wouldn't matter.
Comment: Think of it like an HTML list - it doesn't make sense to output a `` if it's not going to contain any ``s, same deal with regions and blocks. Regions only exist to house blocks, so a region without blocks serves no purpose and shouldn't render. The obvious solution would be to create a block for your static footer, then you can put it in a region _and_ control visibility in the standard fashion
Comment: @Clive - I'm not sure I understand. I would like to separate the markup from `page.html.twig` by adding a specific region file with static html. The region template is not empty it conains all the markup for the actual footer - just not any connected blocks. So this can not be done - should not be done?
Comment: It can probably be done (I've never needed to so never checked how), but why do you need to? What's the benefit of putting the markup in a region rather than a block which needs no extra work/thought? I can't speak for the original authors' intentions but the fact that an empty region is not rendered by default probably suggests that you shouldn't use them as arbitrary containers, only when you need somewhere for blocks to go
Comment: I have to agree with @Clive here. You are misusing the region template. The region's purpose is to render blocks. If you don't render blocks, then don't use a region. Just put your static markup in a custom block or in your page template.
Answer: /**
 * Implements hook_preprocess_page() for page.html.twig.
 */
 function hook_preprocess_page(array &$variables) {
   $variables['page']['footer'] = [     # Specify the region name
     '#theme_wrappers' => ['region'],
     '#region' => 'footer',             # Specify the region name
     'phantom_block' => [
       '#markup' => ' ',
       '#weight' => "-100",
     ],
   ];
 }

This way you are adding a block with a space to the region. Forcing Drupal to render that region. But as you will put a static HTML in that region, the content of the phantom block will not be rendered.
Comment: Could you please explain how and why this should work?


How to rollback insert command in sql with a timer in vb.net?

Question: Hi I am working on a Vb.Net application . I have a compose message web form where users will compose a message , but after the users click the send button I am inserting in the message table. All is working fine , infact great . Now I am thinking of adding a undo button where I will show this button if the user will click the send button . If the user clicks the send button and leaves the undo button the insert query will be fired. But if the user clicks the send button , but then he clicks the undo button the the insert query should not be fired or it should be rolled back ...or something ...I mean the user should be back on his compose message state as before.
Answer: Well rollback refers to something else.
You should delete the entry you have just inserted and insert it again. Look into insert or replace syntax, it might help you.
Answer: What determines when a message gets sent? If it's a batch process, you could just leave the inserted data as is and eventually timeout the undo button's enabled property.


html e css, seletor de links através de ancoras, com setas next e prev

Question: Alguém poderia me dar uma dica de como fazer um seletor de links através de ancoras, com setas de avançar e recuar, parecido com o da imagem aí?? pois só sei utilizar ancoras através de slides ou com target display:block e none. queria um do mesmo jeito do da imagem ou parecido só que com setas na laterias, uma de recuar e outra de avançar, já procurei no google e não consegui achar um tutorial a respeito disso    https://i.stack.imgur.com/GO1py.png
Comment: Qual imagem?....
Comment: eu acabei de editar a pergunta, a imagem eu já inseri aí no final do texto
Comment: Cara sua pergunta está muito confusa, seu problema deve ser fácil de resolver, mas o pessoal tem que entender o que vc precisa realmente.
Comment: Vc quer só o CSS com o estilo similar ao da imagem, uma seta de cada lado e a paginação no meio?
Comment: Sim eu quero com setas nas laterais e a numeração no meio, mas é incrível que eu consigo fazer com slides e não com links, que aparentam ser bem mais simples kkkk
Answer: O bootstrap tem alguns exemplos prontos, como segue abaixo

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

Previous

1

2

3

Next

Se você usar o Laravel será mais fácil ainda bastando apenas usar o seguinte comando
{{ $users->links() }}

Fonte: Pagination
Comment: Nossa! era o que eu queria, muito obrigado!
Comment: Eu consegui achar no w3schools e não consegui fazer as setas passarem de forma linear por cima de cada link numerado, cara eu não estou entendendo de como setar cada link de forma ordenada um após o outro, pois utilizado um unica seta para seleciona-los tá bem complicado, é só por causa das setas se deixar só os números é possível e também eles não ficaram marcados na página que o usuário estiver
Comment: Por que voce nao usa um framework, como o Laravel?
Comment: Eu consegui, separei a  estilização do seletor em varias paginas html, e definindo links diferentes conforme o usuário pressionar na seta e avançar para próxima página é meio complicado, mas o negocio é utilizar o iframe pegando apenas o seletor e adicionando as paginas de forma ordenada apenas mudando a ordem do links no seletor numérico


Fail connect to AmazonMQ using Symfony messenger

Question: I tried to connect to AmazonMQ with amqps protocol in AmazonMQ and get this error:
NOTICE: PHP message: [error] Symfony\Component\Messenger\Exception\InvalidArgumentException
cfi-lms-api_1              | No CA certificate has been provided. Set "amqp.cacert" in your php.ini or pass the "cacert" parameter in the DSN to use SSL. Alternatively, you can use amqp:// to use without SSL.

Where I can get this certificate and how to properly work with amqps in case AmazonMQ? What path for cacert I should specify?
I tried use amqp protocol but Amazon MQ does not support it.
Answer: @Musa thanks for the answer! I will provide more details for somebody like me who never setup this certificate:

If you need work with Amazon MQ you should download the root certificate for mq.eu-central-1.amazonaws.com in pem format (see the answer from @Musa on how to do it).
Then you should change MESSENGER_TRANSPORT_DSN in .env file to add the new parameter cacert (see Symfony doc for more details https://symfony.com/doc/current/messenger.html#amqp-transport):

MESSENGER_TRANSPORT_DSN=amqps://username:email@example.com:5671/%2f/_messages?cacert=/path-to-root-cert/mq-eu-central-1-amazonaws-com.pem

Another possible solution is to specify Amazon Root CA 1. Every Linux distribution has this certificate (see package ca-certificates). In this case, MESSENGER_TRANSPORT_DSN must be like this:
MESSENGER_TRANSPORT_DSN=amqps://username:email@example.com:5671/%2f/_messages?cacert=/etc/ssl/certs/Amazon_Root_CA_1.pem

Answer: In the docs:
If you want to use TLS/SSL encrypted AMQP, you must also provide a CA certificate. Define the certificate path in the amqp.cacert PHP.ini setting (e.g. amqp.cacert = /etc/ssl/certs) or in the cacert parameter of the DSN (e.g amqps://localhost?cacert=/etc/ssl/certs/).
(at https://symfony.com/doc/current/messenger.html)
It says cacert is "Path to the CA cert file in PEM format."
You can download the file through your web browser, clicking the "locker" icon next to "https" in the url bar. For example, the ca cert for StackOverflow can be downloaded like so :

Prefer the one from the "root" tab, which is usually valid way longer (+ 10 years).
Source:
https://github.com/symfony/amqp-messenger/blob/5.4/Transport/Connection.php#L232
https://github.com/symfony/amqp-messenger/blob/4175a0a98507e7ec575dca9b36e6c0a5a072d3fd/Transport/Connection.php#L285
Answer: For the noobs o news with AmazonMQ/rabbitmq
Get the PEM from this url : https://www.amazontrust.com/repository/AmazonRootCA1.pem
and pass = ?cacert=/path/to/pem/Amazon_Root_CA_1.pem
I hope it helps.


File Field client side validation not working

Question: I am on Drupal 9.3.x
I just discovered that File Field in node entity form which is marked as required, not showing client side validation fail message. Rather it submitting the form and then showing the validation fail message.
This is causing issue for my modal form. I am loading the entity form's custom form mode into modal. The file field is marked as required, actually its a media field which is linked with a field field. So when user submitting the form, its not validating that, file is not uploaded and submitting the form, getting out of modal window and showing the validation fail message.
Searched in the net a lot, getting no clue. The following things tried:

Added an another test file field (not media field), its the same results
Added a custom managed file field using hook_form_alter, its the same results
Tried to submit the form through ajax, I see no form error reported for media field field

I am not sure if the as designed by Drupal or if there is any fix for it.
One more thing, field is added inside commerce product and field is showing inside inline entity form in simple mode.
Please help. :(
Answer: I don't have a complete answer for you but I have run into the same issue.  The root of the problem appears to be that Drupal doesn't support client side validation of a "managed_file".  However if you switch your field type to "file" it should work.  It appears this is an issue for many people but no true fix I've found yet.
https://www.drupal.org/project/drupal/issues/2938441
https://www.drupal.org/project/drupal/issues/2301527


The Gherkin (an egg shaped building) - equation for the curve in order to calculate the surface area of revolution

Question: I am trying to calculate the surface area of revolution for The Gherkin, an egg-shaped building in London, UK. Not sure about how to obtain the equation of the curve but I have the data points that allowed me to graph it in Excel but the equation, as it turns out, isn't simply quadratic.
Pls does anyone know any graphing programs that can determine unusual curve equations from a list of data points??  Thanks in advance.
Comment: If you have enough data points, it might make sense to model the building as a stack of truncated cones exactly determined by the known points rather than try to (possibly imperfectly) fit a curve to those points.
Answer: polyfit in Matlab is great. Returns a polynomial of degree n
Something like:
X = [ x co-ordinates in order (with spaces in between) ];
Y = [ y co-ordinates in order (with spaces in between) ];
p = polyfit(X,Y,n)
http://uk.mathworks.com/help/matlab/ref/polyfit.html
Hope it helps
Comment: Why is a polynomial adapted a good thing? Aren't there different points with the same X / or the same Y? The user David K proposed a model of truncated cones instead,


Array of integer as Scapy custom field

Question: The packet I am trying to forge is like this:
p = IP()/TCP()/Unique()

where Unique is a new layer:
class Unique(Packet):
name = "Unique"
fields_desc=[ IntField("a", 0),
         IntField("b", 0),
         IntField("c", 0)]

I don't know how to define a field that contains an array of integer.
Is there a way to do that?
Instead of having three fields "a","b" and "c", I'd like to have one field that contains the three integers.
Since 3 is a variable number, another possible approach I could use is to have n IntField where n is variable, but I don't know how to do that either and I would appreciate any help.
Answer: I guess the FieldListField is the scapy aquivalent to what you are searching for. It defines an array/list of any number of fields of the same type.
class Unique(Packet):
    name = "Unique"
    fields_desc=[FieldListField("my_array", None, IntField("bla",0))]

>>> Unique(my_array=[1,2,3,4,5]).show()
###[ Unique ]###
  my_array= ['1', '2', '3', '4', '5']
>>> hexdump(Unique(my_array=[1,2,3,4,5]))
0000   00 00 00 01 00 00 00 02  00 00 00 03 00 00 00 04   ................
0010   00 00 00 05                                        ....

Answer: class Unique(Packet):
name = "Unique"
fields_desc=[ IntField("a", 0),
         IntField("b", 0),
         FieldLenField("num_records", None),
         FieldListField("c", None, IntField("number", 0), count_from=lambda pkt: pkt.num_records)
]

You need to include FieldListField and FieldLenField.
See this documentation for more.
http://www.dirk-loss.de/scapy-doc/build_dissect.html#the-variable-length-field
Comment: It's incorrect. Size of the array is fixed, not encoded in the message as in your solution (there is no `num_records` field).

Array of integer as Scapy custom field


Some fields are empty when using tshark convert to csv

Question: I am trying to capture traffic from an ethernet using tshark, then convert it to txt for analysis, I am using the following command:
tshark -N n -T fields -i ethernet -e "frame.number" -e "_ws.col.Time" -e "_ws.col.src" -e "_ws.col.dstn" -e "_ws.col.Proto" -e "_ws.col.Len" -e "_ws.col.Info" -E header=y -E separator=, > C:\DataCapture\capture.csv

However, the output is not displaying all the columns, the length and the Info are missing as showing below:
frame.number    _ws.col.Time    _ws.col.Src    _ws.col.Dstn _ws.col.Proto   _ws.col.Len _ws.col.Info
1               0.203766         192.168.0.104  18.104.22.168     MDNS

I also tried using dumpcap, save to a file and convert, but I have received the same result, all options I tried (that I found online) give the same output, no length nor info
Just to keep in mind that I need it in text for clearer processing, and smaller size, and I don't want to keep converting from format to another as I am working on large traffic.
My tshark version is 4.0.4
Thanks,
Comment: You're specifying "_ws.col.Protocol" and "_ws.col.Length", but the column headers printed are "_ws.col.Proto" and "_ws.col.Len", so which is it?  Are you sure you're specifying all the column names properly?
Comment: I just truncated the output to make in one line, but it was was as the command, however it does not make difference, both work for the first columns, but nothing on the last two, even using the (" ") did not make any difference in the output
Comment: You are doing a live capture and it's possible the information isn't available in 1-pass, which is all you get with `tshark` when live-capturing.  You could try writing the packets to a .pcapng file and then post-processing that file with `tshark` including the `-2` option to force 2-pass mode.
Comment: I tried both, I have been experimenting with it for the past two days, it looks like this what text/csv files can get, I have tried (almost) all combinations, and again, using live and pcapng file, nothing works, I am guessing that I have to convert to text, but without specifying any field, then extract my own info, and in this case I will use the dumpcap directly rather than tshark, but thanks for your interaction
Answer: Ok, after a couple of days of investigations, I came across a way to extract (or filter) the pcapng file to a text with any information available, what I have seen online so far is using the suffix _ws.col but this does not work with all the information available, except of the source IP, Destination IP, and Protocol, (almost) everything else will display empty field.
Just one note here, I am not sure this is how it meant to be or just a workaround
So, I extracted a single packet, as per below and started experimenting with it, and the way to do it is that you can pick ANY expression between the "  " and it should work, here is an example of a code I tried:
tshark -N n -r file.pcapng -T fields -e frame.number -e ip.src -e ip.dst -e ip.proto -e frame.len -e eth.src_resolved -E header=y -E separator=, > file.txt

and here is the output of that packet extracted from the text file:
frame.number,ip.src,          ip.dst,        ip.proto, frame.len, eth.src_resolved
1,           248.79.112.255,  192.168.0.111, 6,        174,       00:0c:29:ef:e5:71

I just (TABED) the result above to make it easier to read, otherwise it is packed with , separation.
Here is the single packet extract:
[
  {
    "_index": "packets-2023-04-12",
    "_type": "doc",
    "_score": null,
    "_source": {
      "layers": {
        "frame": {
          "frame.section_number": "1",
          "frame.interface_id": "0",
          "frame.interface_id_tree": {
            "frame.interface_name": "\\Device\\NPF_{xxx-xxx-xxx-xxx-xxx}",
            "frame.interface_description": "Ethernet0"
          },
          "frame.encap_type": "1",
          "frame.time": "Apr 12, 2023 21:59:31.723135000 xxxx TZ Standard Time",
          "frame.offset_shift": "0.000000000",
          "frame.time_epoch": "1681325971.723135000",
          "frame.time_delta": "0.000000000",
          "frame.time_delta_displayed": "0.000000000",
          "frame.time_relative": "0.000000000",
          "frame.number": "1",
          "frame.len": "174",
          "frame.cap_len": "174",
          "frame.marked": "0",
          "frame.ignored": "0",
          "frame.protocols": "eth:ethertype:ip:tcp"
        },
        "eth": {
          "eth.dst": "00:0c:29:28:5a:e9",
          "eth.dst_tree": {
            "eth.dst_resolved": "00:0c:29:28:5a:e9",
            "eth.dst.oui": "3113",
            "eth.dst.oui_resolved": "VMware, Inc.",
            "eth.addr": "00:0c:29:28:5a:e9",
            "eth.addr_resolved": "00:0c:29:28:5a:e9",
            "eth.addr.oui": "3113",
            "eth.addr.oui_resolved": "VMware, Inc.",
            "eth.dst.lg": "0",
            "eth.lg": "0",
            "eth.dst.ig": "0",
            "eth.ig": "0"
          },
          "eth.src": "00:0c:29:ef:e5:71",
          "eth.src_tree": {
            "eth.src_resolved": "00:0c:29:ef:e5:71",
            "eth.src.oui": "3113",
            "eth.src.oui_resolved": "VMware, Inc.",
            "eth.addr": "00:0c:29:ef:e5:71",
            "eth.addr_resolved": "00:0c:29:ef:e5:71",
            "eth.addr.oui": "3113",
            "eth.addr.oui_resolved": "VMware, Inc.",
            "eth.src.lg": "0",
            "eth.lg": "0",
            "eth.src.ig": "0",
            "eth.ig": "0"
          },
          "eth.type": "0x0800"
        },
        "ip": {
          "ip.version": "4",
          "ip.hdr_len": "20",
          "ip.dsfield": "0x00",
          "ip.dsfield_tree": {
            "ip.dsfield.dscp": "0",
            "ip.dsfield.ecn": "0"
          },
          "ip.len": "160",
          "ip.id": "0x267a",
          "ip.flags": "0x00",
          "ip.flags_tree": {
            "ip.flags.rb": "0",
            "ip.flags.df": "0",
            "ip.flags.mf": "0"
          },
          "ip.frag_offset": "0",
          "ip.ttl": "64",
          "ip.proto": "6",
          "ip.checksum": "0x2978",
          "ip.checksum.status": "2",
          "ip.src": "126.96.36.199",
          "ip.addr": "184.108.40.206",
          "ip.src_host": "188.8.131.52",
          "ip.host": "18.104.22.168",
          "ip.dst": "192.168.0.111",
          "ip.addr": "192.168.0.111",
          "ip.dst_host": "192.168.0.111",
          "ip.host": "192.168.0.111"
        },
        "tcp": {
          "tcp.srcport": "2572",
          "tcp.dstport": "80",
          "tcp.port": "2572",
          "tcp.port": "80",
          "tcp.stream": "0",
          "tcp.completeness": "0",
          "tcp.len": "120",
          "tcp.seq": "0",
          "tcp.seq_raw": "410684482",
          "tcp.nxtseq": "121",
          "tcp.ack": "338765635",
          "tcp.ack_tree": {
            "_ws.expert": {
              "tcp.ack.nonzero": "",
              "_ws.expert.message": "The acknowledgment number field is nonzero while the ACK flag is not set",
              "_ws.expert.severity": "4194304",
              "_ws.expert.group": "150994944"
            }
          },
          "tcp.ack_raw": "338765635",
          "tcp.hdr_len": "20",
          "tcp.flags": "0x0002",
          "tcp.flags_tree": {
            "tcp.flags.res": "0",
            "tcp.flags.ae": "0",
            "tcp.flags.cwr": "0",
            "tcp.flags.ece": "0",
            "tcp.flags.urg": "0",
            "tcp.flags.ack": "0",
            "tcp.flags.push": "0",
            "tcp.flags.reset": "0",
            "tcp.flags.syn": "1",
            "tcp.flags.syn_tree": {
              "_ws.expert": {
                "tcp.connection.syn": "",
                "_ws.expert.message": "Connection establish request (SYN): server port 80",
                "_ws.expert.severity": "2097152",
                "_ws.expert.group": "33554432"
              }
            },
            "tcp.flags.fin": "0",
            "tcp.flags.str": "··········S·"
          },
          "tcp.window_size_value": "64",
          "tcp.window_size": "64",
          "tcp.checksum": "0xe582",
          "tcp.checksum.status": "2",
          "tcp.urgent_pointer": "0",
          "Timestamps": {
            "tcp.time_relative": "0.000000000",
            "tcp.time_delta": "0.000000000"
          },
          "tcp.analysis": {
            "tcp.analysis.bytes_in_flight": "120",
            "tcp.analysis.push_bytes_sent": "120"
          },
          "tcp.payload": "58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58",
          "tcp.segment_data": "58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58:58"
        }
      }
    }
  }
]

Hope this helps anyone who needs to extract specific information from pcapng file


Como criar uma single page no Wordpress para um post-type?

Question: Criei um Post-Type específico em functions.php:
// Meus posts types
function meus_posts_type() {
    // Testemunhos
    register_post_type('testemunhos',
        array(
            'labels'    => array(

                'name'  => __('Testemunhos'),
                'singular_name'     => __('Testemunhos')
            ),
            'public'        => true,
            'has_archive'   => true,
            'menu_icon'     => 'dashicons-format-chat',
            'supports'      => array('title', 'editor', 'thumbnail', 'page-attributes'),

        )
        );

        register_post_type('consultorias',
        array(
            'labels'    => array(

                'name'  => __('Consultorias'),
                'singular_name'     => __('Consultorias')
            ),
            'public'        => true,
            'has_archive'   => true,
            'menu_icon'     => 'dashicons-clipboard',
            'supports'      => array('title', 'editor', 'thumbnail', 'page-attributes'),

        )
        );

        register_post_type('treinamentos',
        array(
            'labels'    => array(

                'name'  => __('Treinamentos'),
                'singular_name'     => __('Treinamentos')
            ),
            'public'        => true,
            'has_archive'   => true,
            'menu_icon'     => 'dashicons-welcome-learn-more',
            'supports'      => array('title', 'editor', 'thumbnail', 'page-attributes'),

        )
        );

        register_post_type('clientes',
        array(
            'labels'    => array(

                'name'  => __('Clientes'),
                'singular_name'     => __('Clientes')
            ),
            'public'        => true,
            'has_archive'   => true,
            'menu_icon'     => 'dashicons-admin-multisite',
            'supports'      => array('title', 'thumbnail', 'page-attributes'),

        )
        );
}

add_action( 'init', 'meus_posts_type' );

Ok.
Fiz uma página "page-treinamentos.php" com:
<?php

get_header();

/*
    Template name: Treinamentos
*/

?>

WORKSHOPS E TREINAMENTOS

GOVERNOS | EMPRESAS | ONGs (IN-COMPANY
)
Workshops e treinamentos especializados em gestão integrada de resíduos sólidos

<?php
            if ( function_exists('yoast_breadcrumb') ) {
            yoast_breadcrumb( '
','
' );
            }
        ?>

<?php query_posts( 'post_type=treinamentos' ); ?>

       <?php if(have_posts()): while(have_posts()): the_post(); ?>
.......

Porém, quando clico no link que quero, o single.php não mostra o post do post-type, mostra o 404.php.
Como posso ler o post do post-type? Tenho que criar um single-nomeDoSingle.php? Se sim, como seria esta estrutura?
Meu single.php está desta forma:
<?php get_header();?>

<?php
            if ( function_exists('yoast_breadcrumb') ) {
            yoast_breadcrumb( '
','
' );
            }
        ?>

<?php single_post_title(); ?>

        <?php
            if (have_posts()): the_post();
                    the_post_thumbnail('medium_large', array('class' => 'img-fluid'));
                    the_content();
            endif;
        ?>

            <?php if ( is_active_sidebar('sidebar-1') ) {
                dynamic_sidebar('sidebar-1');
            } ?>

<?php //get_footer('personalizado'); ?>
<?php get_footer(); ?>

Answer: Sim. A estrutura dele é identica a um single.php.
<?php

get_header(); ?>

            <?php
                // Start the Loop.
                while ( have_posts() ) : the_post();

                    // Include the page content template.
                    get_template_part( 'content', 'page' );

                endwhile;
            ?>

<?php
get_sidebar();
get_footer();

Esse link ajuda.
Comment: Editei com o meu 'Single.php'. Da forma que você apresentou está meu 'Page.php' para listar, preciso mostrar o conteúdo do que já está listado em um 'post_type' .... @daviaragao
Comment: Não entendi o que você disse.
Answer: Fala parceiro! tudo beleza?
Você pode fazer single específicos para post types dessa maneira abaixo:
single-testemunhos.php
single-consultorias.php
single-treinamentos.php
single-clientes.php
Depois você pode seguir com mesma estrutura que é na single.php
<?php

get_header(); ?>

            <?php
                // Start the Loop.
                while ( have_posts() ) : the_post();

                    // Include the page content template.
                    get_template_part( 'content', 'page' );

                endwhile;
            ?>

<?php
get_sidebar();
get_footer();

ou seja, a hierarquia funciona dessa forma:
single-MEU_POST_TYPE
E assim, funciona também da mesma forma, para a página de arquivos, veja:
archive-testemunhos.php
archive-consultorias.php
archive-treinamentos.php
archive-clientes.php
Espero que te ajude!
Valeu.


Dificuldades na Criação de Rotas e Controller Laravel 5.1

Question: Criei um CRUD com Modal está funcionando tudo certo mas criei  requisição do formulário exibição de dados, consultas com BD tudo dentro de Rotas, não acho muito legal gostaria de passar essas funcionalidades para o Controller fazer mas não está dando certo está aparecendo o erro:

Hoje o CRUD está assim:
app\routes.php
use App\Task;
use Illuminate\Http\Request;

Route::get('/admin', function () {
    $tasks = Task::all();

    return View::make('admin')->with('tasks',$tasks);
});

Route::get('/tasks/{task_id?}',function($task_id){
    $task = Task::find($task_id);

    return Response::json($task);
});

Route::post('/tasks',function(Request $request){
    $task = Task::create($request->all());

    return Response::json($task);
});

Route::put('/tasks/{task_id?}',function(Request $request,$task_id){
    $task = Task::find($task_id);

    $task->task = $request->task;
    $task->description = $request->description;

    $task->save();

    return Response::json($task);
});

Route::delete('/tasks/{task_id?}',function($task_id){
    $task = Task::destroy($task_id);

    return Response::json($task);
});

Depois criei desta forma para que o Controller faça o trabalho mas não está dando certo
app\routes.php
use App\Task;
use Illuminate\Http\Request;

Route::controller('/admin', 'TaskController');

controllers\TaskController.php
namespace App\Http\Controllers;

use App\Task;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class TaskController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getindex()
    {
        $tasks = Task::all();

        return View::make('admin')->with('tasks',$tasks);

    }

    public function getAdd($task_id)
    {
        $task = Task::find($task_id);

        return Response::json($task);
    }

    public function postAdd(Request $request)
    {

        $task = Task::create($request->all());

        return Response::json($task);

    }

    public function getEdit($task_id)
    {
        $task = Task::find($task_id);

        return Response::json($task);
    }

    public function postEdit(Request $request, $task_id)
    {

       // $task = $request->except('_token');

        $task = Task::find($task_id);

        $task->task = $request->task;
        $task->description = $request->description;

        $task->save();

        return Response::json($task);

    }

    public function getDelete($task_id)
    {
        $task = Task::destroy($task_id);

        return Response::json($task);

    }

}

Comment: Dei uma olhada no código-fonte do `Laravel` e, se não me engano, `Route::controller` foi depreciado. Pode ser removido em versões futuras.
Comment: https://github.com/laravel/framework/commit/98fb934b669c45aad6ca118d4fe29f2bf141d7f6
Answer: Para criação do CRUD com controllers, eu sugiro que você use o método Route::resouce.
Ele é bem simples, e você apenas precisa ter um controller com os seguintes métodos:
 (get) index
 (get) edit
 (post) update
 (get) create
 (post) store
 (delete) destroy

Basta utilizar o código abaixo na rota:
 Route::resource('tasks', 'TasksController');

Uma boa referência é esse vídeo do Laracast - em inglês que fala sobre o uso desse recurso resource.
Comment: Vou dar uma olha obrigado!


Using a series to find a differential equation?

Question: So we had a homework assignment where we are asked to solve a differential equation through a series,I am not sure where to begin for this as we have not actually gone over this. If someone could help guide me through the process I would greatly appreciate it.
$$y=\sum_{n=0}^\infty\frac{(-1)^n2^n(n!)x^{2n+1}}{(2n+1)}$$
Also I tried searching for the input for factorial but no luck if someone could edit it or let me know how to add it I would appreaciate that.
Comment: And, where is your differential equation..?
Comment: Got it, Ill come back later and update the post.
Answer: I'm assuming you know how to derive a series solution to a differential equation and are just struggling to work backwards to find the correct DE for this series.
There is a very powerful method that can be used here: trial and error (with some intuition) :D
$$y= \sum_{n=0}^{\infty} \frac {(-1)^n 2^n n!}{2n+1} x^{2n+1}$$
This looks like an integral of x^2n so differentiate it:
$$y'= \sum_{n=0}^{\infty} (-1)^n 2^n n! x^{2n}$$
This is immediately nicer to work with:
$$x^2y'= \sum_{n=0}^{\infty} (-1)^n 2^n n! x^{2n+2}$$
$$\frac {d}{dx}[x^2y']= \sum_{n=0}^{\infty} (-1)^n 2^n n!(2n+2) x^{2n+1}$$
$$2xy'+x^2y''= \sum_{n=0}^{\infty} (-1)^n 2^{n+1} (n+1)! x^{2n+1}$$
This is beginning to look a lot like the series for y':
$$-x(2xy'+x^2y'')= \sum_{n=0}^{\infty} (-1)^{n+1} 2^{n+1} (n+1)! x^{2n+2}$$
$$-x(2xy'+x^2y'')= \sum_{n=0}^{\infty} (-1)^{n} 2^{n} n! x^{2n} -1$$
$$ \therefore -x(2xy'+x^2y'')=y'-1 \\ $$
$$ \\ x^2y''-(2x^2+1)y'+1=0  \\$$ This is your DE unless I made any calculation errors.


Drush command to show site information configuration

Question: I would like to display all available information about a site using its alias name.
the closer thing I could find is drush status.
<code>$ drush @loc.my-project-7-26-2-5-dev status
</code>

PHP executable        :  xxxxxxxx
  PHP configuration     :  xxxxxxxx
  PHP OS                :  xxxxxxxx
  Drush version         :  xxxxxxxx
  Drush configuration   :  xxxxxxxx
  Drush alias files     :  xxxxxxxx

I would like the site information, such as Drupal version, profile name, default theme, temporary directory path etc.. to be displayed instead.
Answer: If you are running multisite then you can do
<code>$ drush @sites status
</code>
Or site specific
<code>$ drush [site-name] status
</code>
Note : You should be in Drupal installation directory to run drush commands.


How to get rid of large classes with numbers from views?

Question: Which is the purpose of classes like that one:
<code>class="js-view-dom-id-0fc70eec09ba01f6b7c7867ee7e19f7dcec1ee8b64de9dc8b791865caf299ec7"
</code>
It's safe to change this class from twig templates?
Thanks.
Answer: They are used to uniquely target views elements with javascript for AJAX purposes. If you have enabled the use of AJAX on your views display for pagination, filtering etc without page reloads, then removing or changing those might break it. If you are not using AJAX at all, you should be fine, although this comment is not a promise or guarantee!


How do I modify Drupal so that ONLY relative URLs are used through the whole site?

Question: I have a client who says that he is unable to view his company's website from inside his company's building. Their network engineers have asked to make sure that DOMAIN.COM is not included in any of the URLs generated by Drupal.
They want only relative paths everywhere in the code. Any insights?
Comment: Modifying how Drupal and contrib modules generate URLs hardly would be practical, therefore this question probably has to do more with servers and such, and is off topic here.
Answer: You can alter all Drupal generated URLs to make them root relative using hook_file_url_alter
<code>function mymodule_file_url_alter(&$uri) {
  global $base_path;

  $scheme = file_uri_scheme($uri);

  if (!$scheme || $scheme == 'public') {
    if (!$scheme) {
      $path = $uri;
    }
    else {
      $wrapper = file_stream_wrapper_get_instance_by_scheme($scheme);
      $path = $wrapper->getDirectoryPath() . '/' . file_uri_target($uri);
    }

    // Clean up Windows paths.
    $path = str_replace('\\', '/', $path);

    $uri = $base_path . ltrim($path, '/');
  }
}
</code>
For links in content you can apply the filter supplied by Pathologic
Answer: Dan, I believe this can be achieved within apache and the .htaccess file under mod rewrite.  http://httpd.apache.org/docs/2.0/rewrite/rewrite_guide.html


What is the statistical disadvantage of playing a man down?

Question: How much does it hurt a football (soccer) team to play a man down? What about two men down?
How does that cost shift depending upon whether the team is up or down at the time of the penalty - does playing down a man more heavily impact defense or offense?
Related: Are there ever any scenarios when playing down a man can actually improve a team's odds of winning? (Doubtful, I know, but I've heard of crazier paradoxes.)
Is there research out there on short-handed odds?
(Short-footed is probably the more appropriate term.)
Comment: I would be surprised if you got satisfactory and factual answers to your questions based on real statistics.
Comment: @posdef if there were stasticial information for soccer available like there is for the predominant american sports, we'd know this quite well. I'm not aware of a repository similar to baseball-reference.com for soccer though.
Comment: @waxeagle thats exactly my point, since football isn't a predominantly american sport, it might be fruitless to expect same kind of literature about it.
Comment: @waxeagle there is https://fbref.com/, but it's still in the starting process.
Answer: There have been several papers published on this topic, which don't always agree.
Check out Ten Do It Better, Do They? which concludes that "that the impact of a red card depends on the  minute of the expulsion and does not have an impact at all if given at the end of the first half or later" though red cards do increase the number of goals scored.
Estimating the Effect of the Red Card in Soccer says,

We estimate the effect of the red card from betting data on the FIFA World Cup 2006
  and Euro 2008, showing that the scoring intensity of the penalized team drops significantly, while the
  scoring intensity of the opposing team increases slightly. We show that a red card typically leads to a
  smaller number of goals scored during the game when a stronger team is penalized, but it can lead to an
  increased number of goals when a weaker team is punished

Down to Ten: Estimating the Effect of a Red Card in Soccer finds an effect even for cards in the second half.
Being down to nine men is much rarer and probably has not been studied carefully, for lack of data if nothing else.
You also ask, "Are there ever any scenarios when playing down a man can actually improve a team's odds of winning?" I don't know of any evidence of this, but "Ten Do It Better" does note that "an old football myth suggests that...an expulsion might also be beneficial since it increases the team spirit as well as the efforts of the affected team."
Comment: On the last point: What you sometimes observe is that the team that is up adapts its style of play, but often without success because it might be simply trying to play faster to exploit the man advantage, but the team might lack of skill. Often, the team one man up does not know how to properly exploit the advantage by building up attacks in the area where there is actually an advantage (this is usually not the box).


Swift programmatic UI UIContextMenuInteraction Auto layout error (groupView) on opening context menu

Question: I have an app with a programmatic UI (No storyboards). I add a context menu to a button of my viewcontroller. On opening this menu (tap and hold on the button) I get a LayoutConstraints warning/error in the console (menu works fine otherwise:
(
    "<NSAutoresizingMaskLayoutConstraint:0x600001c9ed50 h=--& v=--& UIInterfaceActionGroupView:0x7f9d4478ceb0.height == 0   (active)>",
    "<NSLayoutConstraint:0x600001cd7c50 groupView.actionsSequence....height >= 66   (active, names: groupView.actionsSequence...:0x7f9d4610ee00 )>",
    "<NSLayoutConstraint:0x600001cb3de0 UIInterfaceActionGroupView:0x7f9d4478ceb0.top == _UIContentConstraintsLayoutGuide:0x7f9d4478bba0''.top   (active)>",
    "<NSLayoutConstraint:0x600001cb3e80 V:[_UIContentConstraintsLayoutGuide:0x7f9d4478bba0'']-(0)-|   (active, names: '|':UIInterfaceActionGroupView:0x7f9d4478ceb0 )>",
    "<NSLayoutConstraint:0x600001cad090 groupView.actionsSequence....top == _UIContentConstraintsLayoutGuide:0x7f9d4478bba0''.top   (active, names: groupView.actionsSequence...:0x7f9d4610ee00 )>",
    "<NSLayoutConstraint:0x600001cad130 groupView.actionsSequence....bottom == _UIContentConstraintsLayoutGuide:0x7f9d4478bba0''.bottom   (active, names: groupView.actionsSequence...:0x7f9d4610ee00 )>"
)

Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x600001cd7c50 groupView.actionsSequence....height >= 66   (active, names: groupView.actionsSequence...:0x7f9d4610ee00 )>

this groupView is not a view of mine! I have set translatesAutoresizingMaskIntoConstraints = false on all my custom controls (labels, fields, etc). I presume I need to set that to for the context menu somewhere, but I don't know how or where.
Relevant code:
In my viewcontroller:
        let interaction = UIContextMenuInteraction(delegate: self)
        annotationTypeButton.addInteraction(interaction)

Delegate extension:
//MARK: - UIContextMenuInteractionDelegate
extension AnnotationDetailsViewController: UIContextMenuInteractionDelegate {
    func contextMenuInteraction(_ interaction: UIContextMenuInteraction, configurationForMenuAtLocation location: CGPoint) -> UIContextMenuConfiguration? {
        return UIContextMenuConfiguration(identifier: "annotationTypeMenu" as NSCopying, previewProvider: nil) { _ in
            let children: [UIMenuElement] = self.makeAnnotationTypeActions()
            return UIMenu(title: "", children: children)
        }
    }

    func makeAnnotationTypeActions() -> [UIAction] {
        var actions = [UIAction]()
        for type in AnnotationType.allCases {
            actions.append( UIAction(title: type.rawValue, image: type.image, identifier: nil, attributes: []) { _ in
                let annotationType = AnnotationType(rawValue: type.rawValue) ?? AnnotationType.tips
                self.annotation.type = annotationType
                self.configureAnnotationTypeButton(with: annotationType)
            })
        }
        return actions
    }
}

Any help appreciated!
Answer: I got an answer on the Apple developer forums saying that the layout warning is a known issue and will be solved in iOS14!
https://developer.apple.com/forums/thread/652622?login=true&page=1#618265022


Error:You must use the "set" method to update an entry

Question: Olá, tudo bem ?
Estou com problemas na hora de enviar dados ao meu banco de dados. Estou tentando inserir dados no BD mas, ocorre o erro nesta linha :
<code>$categoriaModel->set('nomecatego', $this->request->getPost('nomecatego'));
</code>
Minha classe Model :
<code>        <?php namespace App\Models;

    use CodeIgniter\Model;

    class CategoriaModel extends Model{
        protected $table = 'categoria';
        protected $primaryKey = 'id';
        protected $allowedFields = ['nome'];
        protected $returnType = 'object';
    }
?>
</code>
Minha classe Controller :
<code>        <?php namespace App\Controllers;

    class CategoriaController extends BaseController{

        public function index(){
            //bla bla
        }

        public function inserir(){
            $data['titulo'] = 'Inserir nova categoria';
            $data['acao'] = 'cadastrar';
            $data['msg'] = '';

            if($this->request->getMethod() === 'post'){
                $categoriaModel = new \App\Models\CategoriaModel();
                $categoriaModel->set('nomecatego', $this->request->getPost('nomecatego'));

                if($categoriaModel->insert()){
                    $data['msg'] = "Cadastro feito com sucesso!";
                }
                else{
                    $data['msg'] = "Cadastro não realizado!";
                }
        }
            echo View('categoria_view', $data);
        }

    }
?>
</code>
Answer: Acabei de ter um erro parecido e que houve foi o falta do campo em $allowedFields.
Tente colocar
<code>protected $allowedFields = ['nomecatego'];
</code>
Segundo a documentação do CodeIgniter 4:

$allowedFields
This array should be updated with the field names that can be set
during save, insert, or update methods. Any field names other than
these will be discarded. This helps to protect against just taking
input from a form and throwing it all at the model, resulting in
potential mass assignment vulnerabilities.

Então, os campos passados nessa variável serão os permitidos para executar as ações de insert, update, etc.
Espero ter ajudado

Error:You must use the “set” method to update an entry


How to clear the complete back stack (and possible solution)

Question: I have three activities A, B and C.
A is the main activity of my application.
A and C can also be started from the Options Menu, B is started from A.
I would like the following behavior:

application starts with A: back stack is {A}
from A, I navigate to B   : back stack is {A,B}
from the options menu, I start C : back stack is {C}

1 and 2 are trivial but I don't succeed in getting 3 to work.
I tried quite a lot of FLAG_ACTIVITY combinations but without success
and I'm getting the impression that this isn't possible.
I'm thinking about creating a DummyRoot activity that is just used to start another activity (actual activity name to start is passed in Intent.getExtras()).  I can give this DummyRoot activity the FLAG_ACTIVITY_CLEAR_TOP.
By doing so, I would get

application starts with DummyRoot(A): back stack is {DummyRoot, A}
from A, I navigate to B   : back stack is {DummyRoot, A,B}
from the options menu, I start DummyRoot(C) : back stack is {DummyRoot, C}

Do you foresee problems with this approach?
Is this needed in the first place or is it possible to clear the back stack in a more elegant way?
Answer: So when you press back whilst in C, you want the application to quit? If so, you will need to use Flags in your manifest and when you start the Activity using the Intent. A combination here will allow you to clear the current Task and then start a fresh one with your new Activity in it. It does not seem a valid UX, but should do the trick. Please read up on the FLAGS in the documentation for more info on what they will actually do.
Comment: Can you indicate which flags I should use to remove A/B from the back stack when starting C? I did read through the documentation but didn't found a suitable combination.
Comment: I would have said that FLAG_ACTIVITY_CLEAR_TASK would be the one to look at, and also the following doc http://developer.android.com/guide/topics/fundamentals/tasks-and-back-stack.html
Comment: That looks indeed like a good candidate but ... it's only available from API level 11 and I have to support API level 8 (should have mentioned that to start with).


objects returned in wcf service response, what are they?

Question: I am developing an MVC4 application that communicates to a set of WCF services to retrieve data. I generate service references from the endpoints using svcutil.
The service operations accept a request object and return a response object. Within these object are "entities". For example, a getproduct operation returns a getproductresponse object which has a property called Product which is of type "Product".
Question I have is, the "Product" object, an entity, poco or domain object? I want to create class library that contains all of such objects but not sure what it should be called.
Answer: For MVC layer, it's DTO. However, you should not guess if the service sends you the entity, poco, or domain object. These are nothing more than just data containers for you (as MVC layer author).
One more argument to treat/call them just as DTO is because service implementation may change in the future and you may end up having something else, but with the same structure on your side.
DTO means Data Transfer Object.


What's the advantage of binding an alias to a local method?

Question: I'm working with the source code for VirtualJoystick and I'm confused about the method binding:
__bind = function(fn, me){return function(){return fn.apply(me, arguments); }; };
this._$onTouchStart = __bind(this._onTouchStart , this);

Next it creates an eventListener:
this._container.addEventListener( 'touchstart'  , this._$onTouchStart   , false );

which refers to a later-defined method:
VirtualJoystick.prototype._onTouchStart = function(event)
{
if( event.touches.length != 1 ) return;
event.preventDefault();
var x   = event.touches[ 0 ].pageX;
var y   = event.touches[ 0 ].pageY;
return this._onDown(x, y)
}

This seems convoluted to me. Why bind the alias before creating the eventListener?
Answer: Because otherwise it would be called with a this equal to the global object (or to null in strict mode).
The same would happen if you did
var temp = this._onTouchStart;
temp();

In general any time you "alias" a method, i.e. don't call it directly as a method (with the appropriate object behind the dot), you lose the this context for it. Passing a method as a parameter does exactly this kind of aliasing, which is why it's necessary for addEventListener.
__bind, or its standard version Function.prototype.bind, gets around this, making sure that the function is called with the this pointer it expects. It creates a version of the function that is always called with the bound this, instead of the contextually-determined version.
Comment: After reading your answer, I found this article which seems to cover this particular issue in more detail:
http://bitstructures.com/2007/11/javascript-method-callbacks


Azure Automation Hybrid Worker Extension Provisioning failed

Question: I am setting up a Hybrid Worker to use in Azure Automation. The worker is added to my hybrid worker pool, and it states the platform as "Extension based (V2)". I am using a System Managed Identity. I am unsure if I need to add a User Managed Identity to the VM.
My Azure Automation account was setup as Private, but failed on adding to DNS so I recreated without adding to a PrivateLink DNS.
While the Worker shows as having the extension in Azure Automation (this is the new Extension based and not the Agent based so it's automatically installed), inspecting the VMs extensions states that the HybridWorkerExtension "Provisioning Failed" as follows:

[Internal Error] The Hybrid Worker Extension failed to execute: {"Message":"Authentication failed for private links"}. More information about the failure can be found in the logs located under 'C:\WindowsAzure\Logs\Plugins\Microsoft.Azure.Automation.HybridWorker.HybridWorkerForWindows\0.1.0.18' on the VM. For more troubleshooting, please follow the steps mentioned here: 'https://aka.ms/troubleshoot-hybrid-runbook-worker-v2'

I have searched high and low, but can't seem to find 1) where this authentication handshake needs to happen 2) the best method to set this up acknowledging that I believe the Extension agent is still in preview.
I suspect this is an issue with the Hybrid Worker communicating with Azure Automation as Azure Automation is set to Private vs. Public, but with the DNS error I received on trying to create Azure Automation originally (now skipped that step by creating a new Azure Automation as it kept stating a "conflict" on creation), how do I ensure communication?
Answer: If you have setup your Azure Automation service as private, and so using private link, then you need a solution on your vNet to resolve the privatelink.azure-automation.net zone. Without this there is no way for the worker to be able to resolve the endpoint for the service to connect to.
The easiest solution for this is to use an Azure Private DNS zone for privatelink.azure-automation.net, and add in your automation service private IP and name. You also need to make sure that there is a private endpoint and associated network interface for the automation service attached to your network.
Given the current state, it might be easiest to delete any existing private link infrastructure (but not the automation account) and recreate it, having it create the DNS zone for you.
Comment: Thanks for the guidance, that is where I was leaning as well. I will test as it failed on the DNS zone.


Compute the SVD of $AB$ from the SVDs of $A$ and $B$

Question: Knowing the SVD of $\mathbb{C}^{m*n} \ni A = U_A\Sigma_AV_A$ and $\mathbb{C}^{n*s} \ni B = U_B\Sigma_BV_B$, is there any way to speed up the calculation of the SVD of $AB = U_{AB}\Sigma_{AB}V_{AB}$?
I tried starting with $AB(AB)^* = U_{AB}\Sigma_{AB}^2U_{AB}^* \text{but also} = U_A\Sigma_AV_AU_B\Sigma_B^2U_B^*V_A^*\Sigma_AU_A^*$ but I can't find a simple assignement for $U_{AB}, \Sigma_{AB}, V_{AB}$ such that this is true.
Is there a way to speed up the decomposition?
Answer: We have
\begin{align}
\Omega = \Sigma_AV_AU_B\Sigma_B
&&AB = U_A\Omega V_B
\end{align}
Only submatrix $\bar{\Omega}$ formed by first $k$ rows and first $l$ columns of $\Omega$ will contain nonzero elements, where $k$ is the rank of $\Sigma_A$ and $l$ is the rank of $\Sigma_B$.
If $\bar{\Omega}$ is smaller matrix than $AB$, then one can compute SVD of $\bar{\Omega}$, and then construct the SVD factorization of $AB$. Unfortunately, the matrix $\bar{\Omega}$ must be formed explicitly.
If $\bar{\Omega}$ and $AB$ have similar size, then knowing the SVD factorizations of $A$ and $B$ will not help you to factorize $AB$.
Comment: I'm confused by this answer. What is $k,l$? They are not mentioned in the OP


Modify Javascript Variable with URL

Question: Is it possible to change a javascript variable through the URL?
Here's an example of the code I'm trying to modify from a website. (www.example.com)

I want to change the variable x from 0 to 1.
I want to do this by appending something to the URL. I'm not sure about the syntax, but I think it may be something like this:
www.example.com#javascript: var=1;

Is it possible to change variable x by only modifying the URL?
EDIT:
The duplicate question doesn't tell me how (if it's possible) to change the variable through the URL. Please let me know if that's not the case.
Related Question:
https://security.stackexchange.com/questions/134240/modify-javascript-variable-with-url-exploit
Comment: JavaScript on the page can look at [`window.location`](https://developer.mozilla.org/en-US/docs/Web/API/Location) to decide what to do based on the URL. This requires the relevant JavaScript to already be present on the page.
Comment: That would be a serious security flaw, so browsers would not allow such a thing. If you control the JavaScript, you could (carefully) read part if the URL into a variable.
Comment: Please explain the reason for the downvotes. If you think it's a silly question, please just answer it. If it violates a site rule, please let me know. Thanks.
Comment: Please show an example URL from which you would like to retrieve/modify a variable, and show what the variable should become; without specifics this is a theoretical exercise and we're unable to offer any specific advice without guessing (which is of little use to you, and is too broad as a question). Incidentally I don't necessarily agree with the current close-reason, but unless you add some specifics the question is likely to remain closed, because we can't see that this question is not a duplicate. Or what this question is specifically asking.
Comment: Your questions shows a lack of research and is unclear. That's probably the reason for your down votes.
Comment: Sorry about that! I'll get to work clarifying it :)
Comment: @AlexanderO'Mara Let me know if it's still unclear. Thanks.
Comment: As I said before, no, directly injecting scripts by URL should not be possible without an XSS vulnerably.
Comment: @AlexanderO'Mara Ok, if you make that an answer, I can accept it :)
Comment: This question is closed, but I answered your other one on InfoSec. You might want to add the updated information from here though to make it a better question.
Comment: actually the question marked as duplicate seems to be exactly what you need.
Answer: you can use:
 if(window.location.href.indexOf("your_link_to_check") > -1) {
      var x = 1;
    }

Comment: Would it be possible to run this from the address bar in a browser? I'm pretty new to this area of programming. Thanks for your answer.
Comment: no, you can use Chrome's console to test it
Comment: What exactly would I put under "your_link_to_check"? Could you please clarify on that point?

Modify Javascript Variable with URL


Estrutura de Dados/Pilha - C

Question: 2 dias quebrando a cabeça e não consegui avançar com o código.

1 - Empilho 2 - Desempilho 3 - O item que foi desempilhado tem que ser
adicionado na Pilha2.

Não estou conseguindo verificar o envio do item desempilhado para a nova pilha. Do jeito que está, até imprime os valores(1 até 5) devido uma variável AUX dentro de um FOR, a meu ver não está correto. Se passo pilha2.topo imprime(0 até 4) e não de 1 até 5 que foi desempilhado.
#include <stdio.h>
#include <stdlib.h>

#define tamanho 5

typedef struct tipo_pilha{
    int dados[tamanho];
    int ini;
    int topo;
}tipo_pilha;

tipo_pilha pilha;
tipo_pilha pilha2;

void empilha(int elemento){
    if(pilha.topo == tamanho){
        printf("Pilha Cheia.\n");
        system("PAUSE");
    }
    else
    {
        pilha.dados[pilha.topo] = elemento;
        pilha.topo++;
    }
}
int desempilha(){
    int elemento;
    if(pilha.topo == pilha.ini){
        printf("Pilha NULL.\n");
        system("PAUSE");
    }
    else
    {
        pilha.topo--;
        elemento = pilha.dados[pilha.topo];
        return elemento;
    }
}
void empilha2(int elemento){
    if(pilha2.topo == tamanho){
        printf("Pilha Cheia.\n");
        system("PAUSE");
    }
    else{
    pilha2.dados[pilha2.topo] = elemento;
    pilha2.topo++;
    }
}
int main(){
    printf("%d \n", pilha.topo);

    int aux;
    printf("### Empilhando Pilha 1 ###\n\n");
    for(int i=1; i<=5; i++){
        aux = i;
        printf("Empilhando o %d.\n", aux);
        empilha(aux);
    }
    printf("%d \n", pilha.topo);
    printf("### Desempilhando Pilha 1 ###\n\n");
    for(int i=1; i<=5; i++){
        aux = desempilha();
        printf("Desempilhou: %d.\n", aux);
    }
    printf("%d \n", pilha.topo);

    printf("### Empilhando 2 Pilha ### \n\n");
    for(int i= 1; i<= 5;i++){
        aux = i;
        printf("Empilhando o %d.\n", aux);
        empilha2(aux);
}
    printf("%d \n", pilha2.topo);

}

Answer:
Você não precisa criar uma função para empilhar cada pilha individualmente se tomar a pilha desejada como argumento da função empilha.
É ideal que a main retorne 0 no final da execução.
No primeiro dentro da main, você não precisa copiar a variável i para outra variável, basta usá-la diretamente.

Dito isso, posso prosseguir para sua pergunta. Se você quer desempilhar uma pilha para dentro de outra, você teria que fazer algo assim:
while (pilha.ini != pilha.topo)
    empilha2(desempilha());

Answer: Pode dar certo do modo como está fazendo, mas não está bom: imagine se fossem 12 pilhas e considere quantas funções iria escrever para desempilhar. E quantas variáveis para controlar...
Vou deixar um exemplo da maneira comum de escrever isso.
Sobre o programa original

a struct pilha poderia ser anônima
considere a convenção de reservar algo diferente, como a primeira letra em maiúscula, para os tipos definidos no programa
considere a convenção de usar apenas maiúsculas no nome de constantes
se a pilha é estática tem um tamanho definido desde sempre, então talvez não precise de duas variáveis para controlar isso.
pilha e pilha2 não deveriam ser globais.
não misture lógica e printf() e muito menos system() ou pausas no meio dos comandos ou os testes vão ficar muito lentos e o uso impossível.
entenda que as operaçoes com pilhas tem nomes consagrados:

POP, PUSH e TOP retiram um elemento, inserem um elemento e retornam o elemento no topo da pilha, nessa ordem.

O EXEMPLO
a Pilha
typedef struct
{
    int tam;
    int lim;
    int dados[1 + TAMANHO_];

} Pilha;

int POP(Pilha*);
int PUSH(int, Pilha*);
int TOP(Pilha*);

int mostra(Pilha*, const char*);

POP retira um elemento da pilha e retorna o tamanho dela
PUSH insere o elemento fornecido na Pilha e retorna o tamanho dela
TOP retorna o valor no topo da pilha ou INT_MIN se a pilha estiver vazia.
um valor negativo no retorno de POP e PUSH indica erro. INT_MIN indica erro em TOP, mas a pilha pode ter esse valor então errno é usado e indica nesse caso ERANGE ou EINVAL
mostra é uma função de teste e mostra o conteúdo da pilha. Para conveniência aceita um título opcional.
reservar a primeira posição da pilha simplifica muito o programa. Veja no código.

main para o teste

O exemplo cria uma pilha orig e insere valores aleatórios até dar erro. O erro, claro, deve ser ela estar cheia.
uma nova pilha, reversa é criada e os elementos são retirados da pilha orig e colocados nessa
ao final o programa mostra as duas pilhas

int main(void)
{
    srand(220529);
    Pilha orig = {.tam = 0, .lim = TAMANHO_};
    mostra(&orig, "\nTeste: ainda vazia");
    int res = 0;
    while (0 <= (res = PUSH(rand() % 100, &orig))){};  // ate dar erro
    mostra(&orig, "\nTeste: deve estar lotada");
    // agora tira um por um e poe na outra pilha
    printf( "\nTirando os elementos e colocando na outra "
        "pilha:\n\n");
    Pilha reversa = {.tam = 0, .lim = TAMANHO_};
    for (int i = orig.tam; i > 0; i -= 1)
    {
        int el = TOP(&orig);
        POP(&orig);
        PUSH(el, &reversa);
    }
    mostra(&orig, "\nAo final: pilha original");
    mostra(&reversa, "pilha nova");
    return 0;
}

saída do exemplo

Teste: ainda vazia
0 elementos (cap:8):    [  vazia ]

Teste: deve estar lotada
8 elementos (cap:8):    [ 65, 15, 38, 24, 80, 73, 77, 82 ]

Tirando os elementos e colocando na outra pilha:

Ao final: pilha original
0 elementos (cap:8):    [  vazia ]
pilha nova
8 elementos (cap:8):    [ 82, 77, 73, 80, 24, 38, 15, 65 ]

Esse trecho
    while (0 <= (res = PUSH(rand() % 100, &orig))){};

por exemplo enche a pilha com valores aleatórios entre 0 e 99. Podia ser escrito apenas
    while (0 <= PUSH(rand() % 100, &orig));

já que PUSH() vai retornar algo positivo (o tamanho) em caso de sucesso. E esse é um programa de teste e não se espera outro erro que não seja "pilha cheia".
    Pilha reversa = {.tam = 0, .lim = TAMANHO_};
    for (int i = orig.tam; i > 0; i -= 1)
    {
        int el = TOP(&orig);
        POP(&orig);
        PUSH(el, &reversa);
    }

Essa é a maneira comum de transportar os caras de uma pilha para a outra. Claro que por definição ao final a pilha nova vai estar cheia e a original vazia e essas linhas
    mostra(&orig, "\nAo final: pilha original");
    mostra(&reversa, "pilha nova");

fazem o teste sem stress
O código do exemplo
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

#define TAMANHO_ 8

typedef struct
{
    int tam;
    int lim;
    int dados[1 + TAMANHO_];

} Pilha;

int POP(Pilha*);
int PUSH(int, Pilha*);
int TOP(Pilha*);

int mostra(Pilha*, const char*);

int main(void)
{
    srand(220529);
    Pilha orig = {.tam = 0, .lim = TAMANHO_};
    mostra(&orig, "\nTeste: ainda vazia");
    int res = 0;
    while (0 <= (res = PUSH(rand() % 100, &orig))){};  // ate dar erro
    mostra(&orig, "\nTeste: deve estar lotada");
    // agora tira um por um e poe na outra pilha
    printf( "\nTirando os elementos e colocando na outra "
        "pilha:\n\n");
    Pilha reversa = {.tam = 0, .lim = TAMANHO_};
    for (int i = orig.tam; i > 0; i -= 1)
    {
        int el = TOP(&orig);
        POP(&orig);
        PUSH(el, &reversa);
    }
    mostra(&orig, "\nAo final: pilha original");
    mostra(&reversa, "pilha nova");
    return 0;
}

// tira um cara da pilha, retorna o tamanho
int POP(Pilha* p)
{
    if (p == NULL) return -1;
    if (p->tam == 0) return -2;
    p->tam -= 1;
    return p->tam;
}

// poe um cara na pilha, retorna o tamanho
int PUSH(int el, Pilha* p)
{
    if (p == NULL) return -1;
    p->tam += 1;
    if (p->tam > p->lim)
    {
        p->tam -= 1;
        return -2;
    }
    p->dados[p->tam] = el;
    return p->tam;
}

int TOP(Pilha* p)
{
    if (p == NULL)
    {
        errno = EINVAL;
        return INT_MIN;
    }
    if (p->tam == 0)
    {
        errno = ERANGE;
        return INT_MIN;
    }
    return p->dados[p->tam];
}

int mostra(Pilha* p, const char* tit)
{
    if (p == NULL)
    {
        printf("pilha invalida\n");
        return -1;
    }
    if (tit != NULL) printf("%s\n", tit);
    printf("%d elementos (cap:%d):\t[ ", p->tam, p->lim);
    if (p->tam == 0)
    {
        printf(" vazia ]\n");
        return 0;
    }
    for (int i = 1; i
tam; i += 1)
        printf("%d, ", p->dados[i]);
    printf("%d ]\n\n", p->dados[p->tam]);
    return 0;
}

Comment: Eu e mais uma resposta inútil! Mas ao menos essa discute o problema. E o programa proposto. E tem um exemplo em C. E a saída do exemplo. ;) **funny times indeed**

Estrutura de Dados/Pilha - C


Facet block based on other facet choice

Question: I have a site where search is based on Search API (mysql server). I have two fields in my content type (brand and model) and I have created two faced block based on these fields. They work.
Now I want to make visible the model's facet block only when users have chose the brand (from the faced block).
Is this possible without a custom module or PHP code that searches in <code>$_GET</code> the brand chosen from the users?
Answer: Better is later than never :)
Try to use "dependencies" from context menu of facet block.

Facet block based on other facet choice


Inner product in matricial form

Question: I know I can write scalar product between $v$ and $w$ vectors in matricial form as $v\cdot w=v^TMw$.
I have a not canonical base.. my doubt is: in the formula, coords of $v$ and $w$ are meant to be related to canonical base or to my base?
Thanks!
Comment: We don't particularly have canonical bases for general vector spaces. In this sense, every basis is as good as any other basis! (Yes, you would like to distinguish between eigenbases and orthogonal bases, but those are special). In this case, if you're given a basis, everything should be in terms of that basis, because your vector space can't normally distinguish between other bases in the first place.
Answer: I understand your question in the way that your vetor space has some underlying inner product $(\cdot, \cdot)$, and that you have a basis $\{\mathbf{e}_k\}$,
which is known but not orthonormal in the inner product,
$$ \mathbf{v} = \sum_k v_k e_k, \quad \mathbf{w} = \sum_k w_k e_k. $$
Then
$$ (\mathbf{v}, \mathbf{w}) = \sum_k \sum_\ell v_k (e_k,e_\ell) w_\ell = v^\top M w , $$
where
$$ M_{k\ell} = (\mathbf{e}_k,\mathbf{e}_\ell). $$

Inner product in matricial form


pager is not working on update of Views 7.x-3.7 to Views 7.x-3.8

Question: Hi i have recently update one of project and so views module also updated now views pagignation is not working (from views 7.x-3.7 to views 7.x-3.8 version)
any help appreciated
thanks.
Answer: I recently had the same problem. Issue for me was Views 7.x-3.8 changes the file plugins/views_plugin_query_default.inc to move the following code from the execute function to the query function.
I fixed it using the following patch:
https://www.drupal.org/node/2276165
Comment: Awesome. Was it the patched that helped?
Comment: yes, i have applied patch #6. and it was starting to work. thanks again.
Comment: Brilliant. Could you mark my answer as the correct one please. It's my first ever answer here :)
Comment: actually i tried but i don't know how to do it. I also tried to vote this answer but i can't because i don't have sufficient reputation.
Comment: @bisw if got your answer and you can accept the answer no need of sufficient reputation. it present below the vote option.


Full control over HTTP headers in Python?

Question: Is there any Python HTTP library that helps to imitate one of popular web-browser and has HTTPS support? I would like to define the order of HTTP headers, the presence of each exact header, the order of cookies values - everything that relates to "fingerprint" of a browser. We need that to test specific web server.
Comment: For httplib, if you don't add headers, will the header contains anything you don't want?
Answer: httplib.request will take an OrderedDict for headers. Some headers will be added automatically for protocol compliance, which will be left out if you specify them in your supplied headers.
Take a look at the putheader and _send_request methods, which you could override if their behaviour didn't suit your purposes.
>>> import httplib
>>> from collections import OrderedDict
>>> h = OrderedDict(('X-A','a'),('X-B','b'),('X-C','c'))
>>> c = httplib.HTTPConnection('localhost')
>>> c.set_debuglevel(1)
>>> r = c.request('GET','/','',h)
send: 'GET / HTTP/1.1\r\nHost: localhost\r\nAccept-Encoding: identity\r\nX-A: a\r\nX-B: b\r\nX-C: c\r\n\r\n'

Comment: `httplib` also has some `HTTPS` support.
Answer: Check out Requests which is very easy to work with and has all you need.
Alternatively you can drive web browser itself from Python using Selenium
Comment: One of your link seems to be from your local network. Well, at least I cannot access.


Installing OpenSUSE 13.2 issues with video

Question: Good afternoon, I'm attempting to install the latest version of OpenSUSE (Tumbleweed) and upon choosing install I lose my video.  I'm currently running with a Nvidia GTX 970.  Unfortunately I don't have the option to use VGA with this card.  Is there a way to get around this so I can proceed through the installation?
Thanks in advance
Answer: So I was able to figure it out.  For those struggling with something similar:

boot your pc
enter the grub2 config (press e when system hits grub boot screen)
remove the "quiet splash" and replace it with nomodeset (no quotes)
press F10 to boot
install should begin

enjoy ;-)


Can playing in cold weather damage a drum set / skins?

Question: My set is in the garage, and now that it's winter, temperatures have been between 10 C and -10 C (50 F and 14 F).
Is it OK to play the drums at such low temperatures, or will it cause damage to the set or skins (which I don't have money to replace right now)?
Answer: The fluctuations in temperature cause the wood, the metal, and the skins to all expand and contract at different rates. This will cause lugs to move, the tuning to change, etc.
You are likely to damage the heads if you dive in there and start bashing because the head's probably gone slack somewhere from the movement. Spend some time making sure that the tensions are reasonable before you start playing and everything should be OK.


Problema em CkEditor com PHP PDO

Question: Tenho um script PHP que realiza uma atualização no banco de dados pra alterar as propriedades de css de alguns textos, porém a inclusão está sendo feita da seguinte forma:

INFORMAÇÃO E MONITORAMENTO, ONDE E QUANDO VOCÊ PRECISA

Ou seja, após o style está incluindo uma contra-barra.
Em todas as páginas que usam o ckeditor estão acontecendo este mesmo erro. Como devo proceder?
Answer: Provavelmente está vindo do banco de dados assim. Está escapando as aspas para não causar problemas com a sintaxe do SQL e/ou ajudar a prevenir SQL injection.
Usa stripslashes:

Remove barras invertidas de uma string.

Documentação
Exemplo:
echo stripslashes($str);

Problema em CkEditor com PHP PDO


Sobolev/Lebesgue norm estimates in $\mathbb{R}^3$

Question: I'm currently working on a project in which I have to establish some estimates for some global Sobolev and Lebesgue norms.
We know that if we have a bounded domain $\Omega$, then for any $q \leq p^*$ there is a $C > 0$ such that:
$$\|u\|_{L^q} \leq C\|\nabla{u}\|_{L^p}\tag{1}$$
for any $u$.
If the domain is not bounded, we have this estimate only for $q=p^*$ (due to Gagliardo-Niremberg Inequality), because we cannot use Holder inequality to bound $L^q$ norms by other such norms with bigger $q$.
However, if we replace $\|\nabla{u}\|_{L^p}$ by $\|u\|_{W^{1,p}}$, the $\|u\|_{L^p}$ appearing on the RHS allows us to establish:
$$\|u\|_{L^q} \leq C(q)\|u\|_{W^{1,p}} \tag{2}$$
for all $p \leq q \leq p^*$.
My question is: do we have such an estimate for unbounded domains, but also for $q < p$? More generally, for which values of $q$ can we establish estimates of the form (1) and (2), when the domain is unbounded? (I'm basically interested in the case $\Omega = \mathbb{R}^3$.)
Comment: Your first inequality is already false without some restriction that you haven't specified: consider $u \equiv 1$. The most common modification of what you wrote that actually does work is for when $u \in W^{1,p}_0$.
Comment: Anyway, for your question about $q0$ and consider a smooth function which is equal to $|x|^{-r}$ off the ball of radius $1$ centered at $0$ and is nicely smooth in the ball. Tweak $r$ to make $f$ be $L^p$ but not $L^q$. (This is not hard: for instance, in the 1D case, this function is in $L^s$ if and only if $s > 1/r$.) See if this function is in $W^{1,p}$ or not. If it is then your question probably works; if it isn't then you've just proven that your question doesn't work.
Comment: Sorry I was a bit hurry and thus I forgot this. It is true for the closure of compactly supported smooth functions under the seminorm of the RHS.
Comment: Is that built into the assumptions of what you want to do in the second part? Please clearly specify your assumptions, and (if applicable) where you are open to having assumptions introduced by the answerer.
Comment: I'm actually interested only in the second part. When we use the full Sobolev norm we do not need any restrictions on $u$ (we can prove the estimates for bounded domains by using extension theorem and then take limits, being always aware of constants which may explode) The first was just a quick attempt to explain something different I had in mind.
Comment: Well, do what I suggested and discuss what happens (maybe in your question). I don't actually know the answer to what I suggested, I just know that that tailing is the simplest thing that could break your desired result.
Answer: One word: scaling.
Consider $u_\lambda(x) = u(\lambda x)$ where $\lambda>0$. The Lebesgue norm scales as
$$\|u_\lambda\|_p = \lambda^{-n/p}\|u\|_p$$
while the norm of the gradient scales as
$$\|\nabla u_\lambda\|_p = \lambda^{1-n/p}\|\nabla u\|_p$$
This immediately shows that $\|\nabla u_\lambda\|_p$ can control $\|u\|_q$ only when $\frac{n}{q} = 1-\frac{n}{p}$, which corresponds to $q=p^*$, the critical exponent.
The full  norm of $W^{1,p}$ has a term that scales as $\lambda^{-n/p}$ and another that scales as $\lambda^{1-n/p}$. The sum of such things  dominates the powers of $\lambda$ that are between $-n/p$ and $1-n/p$, and none others. This leads to the necessary condition
$$-\frac{n}{p}\le -\frac{n}{q} \le 1-\frac{n}{p} $$
that is, $p\le q\le p^* $.