phpmyadmin not displaying picture from database

Question: I have a phpmyadmin setup and all is fine and well but I can't seem to get the interface to display the pictures from the database, What could be the issue ?
I've enabled the gd2 extension in php , it doesn't seem to have solved the issue
Here is an image:
Image not displaying in tables
Here is a snapshot of that column's configuration
Column configuration 1,
Column configuration 2
Interestingly enough when I try to open the image in a new tab this comes up: Error
Is this a possible bug or I'am I just and idiot ?
Comment: Let's see the relevant code.
Comment: Code ? You mean the Error code? [Right Here](https://i.stack.imgur.com/3HSiG.png)
Comment: Perhaps in `transformation_wrapper.php` -- there is a "cn" without a $ in front.
Answer: This problem is probably because you are not using the correct version of any dependency.
Try to Look for the right dependencies, but don't worry you're not an idiot.
Comment: How can I check can you please elaborate?

I'm using my phpmyadmin 5.0.1 all the extensions came default with php version 7.4.2
Comment: where do you have phpmyadmin installed? linux?
Comment: Or another idea is that you could try to install a more stable version since it was released on 10/2020 which is very early.
Comment: I have it installed on Microsoft IIS7.5 on a windows 7 box if you surggests that this version is too early does this mean it's possibly a bug ?
Comment: Yes posible it was a bug
Answer: There are no "pictures" in the database, only numbers, dates, and strings.  Some of those "strings" may represent images or videos, but it is up to the client to interpret them as such.  phpmyadmin is a generic client for fetching only numbers, dates, and strings.
PHP, as distinct from phpmyadmin, is a programming language that has plugins for talking to MySQL and for generating HTML code that could include  tags.  From that, a web server and web browser can display images.
phpmyadmin is written in PHP, but now you have to write a client in PHP (or something else) to get images displayed.


How to create an Array with AngularJS's ng-model and how to submit using jquery?

Question: I have to submit array of values using jquery and angularjs. When i click submit button i'm getting only first array value. How to get all array value using ng-model.Here is my all code https://jsfiddle.net/rijo/6dLxhr7j/
Script code given below
$scope.onSubmit = function(){
    sum = $scope.obj;
    console.log(sum);
        $http({
            method : 'POST',
            url : 'admin_controller.php',
            data: $.param(sum),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).then(function (response) {
            console.log("OK");
        });
    }

Please any one can help.. Thanks!
Comment: The AngularJS framework normally posts data as `'Content-Type: application/json` and there is no need to serialize it with the jQuery param method.
Comment: Look at [StackOverflow: Receive JSON POST with PHP](http://stackoverflow.com/questions/18866571/receive-json-post-with-php).
Answer: You have to post data as an object, pass your array as an object attribute value. In this case I'm using the $http.post shortcut method.
function buildParam(){
    // write any needed logic to get, build your array
    // maybe a loop extracting values from collection, etc.
    var myArray = []; // here your array of values, objects, etc.
    return myArray;
}

$scope.onSubmit = function(){
    sum = {
        myAttr: buildParam()
    };

    $http.post('admin_controller.php', sum).then(
        function(response) {
            console.log('ok');
        }
    );
}

Comment: I want to get the value as dynamic, not a static
Comment: can u give me how to get dynamic values from my html code
Comment: The $http service automatically transforms request data with `angular.toJson`. See [AngularJS $http Service API Reference - Default Transformations](https://docs.angularjs.org/api/ng/service/$http#default-transformations) or see it for yourself in the [$http service source code line #293](https://github.com/angular/angular.js/blob/master/src/ng/http.js#L293).


Regression with ARMA errors for explanatory purpose

Question: I have web log analysis data (AWStats) from a university library website. I'm looking at the number of visits per month divided by the number of faculty plus student enrollment (visits per headcount). This shows a downward trend, along with strong seasonality. Also, the undergrad enrollment has gone up steadily the last few years, while the graduate enrollment has stayed flat.
Therefore, I am fitting a regression with ARMA errors model, with the ratio of grad student headcount to undergrad headcount as an explanatory variable (since graduate students use the library more than undergrads). My interest is in explaining the downward trend, not forecasting. The time series plots for the response and explanatory variables look very similar, seasonal with spikes in the summer and a downward trend.
I have taken regular and seasonal differences for both variables and fit a model with ARMA errors. The estimate for the ratio is significant.
My question is, how can I estimate how much of the downward trend the does the regression variable explain? I don't think it explains all of it.
The AIC without the regression term is -20.02, and with the regression term is -35.16. The estimate of the slope is 3.71.
I'm more familiar with SAS, and I am using proc arima, but I could use R as well.
I want to emphasize that the question is not prediction. As there are more options to gather information online, it is natural that there might be less library usage per person. The question, at our particular institution, can part of the per-person usage be explained by the fact that the proportion of grad students in the entire student enrollment is less, as undergrad enrollment rises? We know, from survey data, that grad students use the library more. Then how much of the trend is attributable to that? 10%? 20%? 50%?
I will try posting some graphs, output, etc. when I get a chance.
Comment: If you have access to SAS, also try using Proc UCM, it is very flexible in handing explanatory variables. In addition it could also handle level shifts/outliers in your data.
Comment: I would recommend Proc UCM over ARIMA because, it is much more flexible and more interpretable especially when you want your time series data to be decomposed into trend and seasonal component. you can go to SAS website for more help. I can provide you with an eexample below. If you can post your data, I can see if I can model the data in proc ucm. http://support.sas.com/documentation/cdl/en/etsug/60372/HTML/default/viewer.htm#etsug_ucm_sect040.htm
Comment: I haven't read up on Proc UCM, I wasn't sure what it was doing. It's not using arima, right? I did want to know whether there was in fact a trend downward. I used regression with month dummy variables.
Answer: Your approach is generally correct but the devil is in the details. Unwarranted differencing can lead to very spurious results. Ignoring anomalies (pulses/seasonal pulses,level shifts and local time trends can be the downfall of a tf model. Changes in parameters over time or changes in error variance over time need to be investigated. I am afraid that both SAS and R are not up to these challenges. You might post your data or send it to me at my email address and I will try and answer your specific questions and post an analysis to the web. If your data is confidential then we can do this off line although I would prefer to enlighten others as to what can be done.
In closing ... it is generally speaking not a good idea to use percentages but rather use both observed series when constructing a model. Care should be taken to distinguish between trend and level shift activity as most software including JMP can not detect time trend changes which is precisely what you are looking for. Some software (JMP in particular) assume that both the parameters and the error variance are constant over time. Be wary of such simplistic solutions as they are often wrong and need remedial treatment. it is interesting to me that SAS's defaults for JMP is to NOT detect level shifts. I wonder why ?
Comment: In your last paragraph, do you mean instead of using the ratio, use each variable separately (undergrad enrollment and grad enrollment)?
Comment: Yes predict visits using historical data for both students and faculty. Use both inpout series to predict visits.


How to reveal the surrogate pairs in String in perl

Question: I am working a perl code base to validate customer input, my goal is to block surrogate characters.
My thought is first encoding the customer input as UTF-16 and
<code> foreach my $messageChar (@MessageChars) {
   my $messageCharUTF16 = Encode::encode("UTF-16", $messageChar);
   if (($messageCharUTF16 >= 0xD800 && $messageCharUTF16 <= 0xDBFF)|( $messageCharUTF16 >= 0xDC00 && $messageCharUTF16 <= 0xDFFF)) {
      // Then we have surrogate pairs
   }
 }
</code>
However, I am not getting the correct UTF-16 values from Encode::encode.
How can I reveal the surrogate pairs? Is there any straight-forward way to verify if a string contains surrogate characters in Perl?
Answer: It's not clear to me what you want to check, so I shall cover both possibilities.

To check if a decoded string contains any of U+D800..U+DFFF
The official Unicode standard says that no UTF forms, including UTF-16, can encode these code points, and Perl obliges.
<code>$ perl -e'use open ":std", ":encoding(UTF-8)"; print "ABC\N{U+D800}DEF\n";'
Unicode surrogate U+D800 is illegal in UTF-8 at -e line 1.
"\x{d800}" does not map to utf8 at -e line 1.
ABC\x{D800}DEF
</code>
To check for those characters, you can use
<code>$str =~ /[\x{D800}-\x{DFFF}]/
</code>
To check for any encoding error, you can use
<code>eval { encode("UTF-8", $str, Encode::FB_CROAK | Encode::LEAVE_SRC); 1 }
</code>

To check if a decoded string contains a character above U+FFFF
Characters above U+FFFF can't be encoded using UCS-2, and require a surrogates to encode using UTF-16.
<code>$ perl -e'use open ":std", ":encoding(UTF-16le)"; print "\N{U+10000}";' | od -t x2
0000000 d800 dc00
0000004
</code>
To check for those characters, you can use
<code>$str =~ /[^\0-\x{FFFF}]/
</code>


Clarify difference between hook_form_TYPE_alter and hook_form_TYPE_EDIT_alter

Question: I have a site with a lot of hook form alters for node forms and I'm finding that I have to create two separate hook functions to affect both the node create and node edit forms.
For example, I have to put both:
module_events_form_node_event_form_alter()

and
module_events_form_node_event_edit_form_alter()

With the same functionality in both functions so that it covers both new and edited nodes. Is there a way to have one hook_form_alter() to cover both form conditions?
Answer: You can either use the full form ID with content type and operation or the base form ID node_form. This is without the operation but also missing the content type. So when you alter the base form you have to check for a specific content type if you don't want to alter all node forms:
/**
 * Implements hook_form_BASE_FORM_ID_alter().
 */
function mymodule_form_node_form_alter(&$form, FormStateInterface $form_state, $form_id) {
  $node = $form_state->getFormObject()->getEntity();
  if ($node->getType() == 'event') {
    // change the node form for the content type event and any operation
  }
}

Comment: The FORM_ID contains both content type + operation (create is default and default is omitted). The BASE_FORM_ID I've suggested contains neither of them and you can check them individually. BTW if you need the operation use `$form_state->getFormObject()->getOperation()`.
Comment: To clarify, if I user form ID with content type then I must use two functions to account both new and edit forms but if I just use hook_form_alter and check for the type then I don't, correct?


How can I make bandit skip B101 within tests?

Question: I'm using bandit to check my code for potential security issues:
bandit -r git-repository/

However, the most common item found by bandit is B101. It is triggered by assert statements within tests. I use pytest, so this is not a concern, but a good practice. I've now created a .bandit file with
[bandit]
skips: B101

But that also skips a lot of other code. Is there a solution to this issue?
Answer: Based on this comment,

when using --recursive the whole path is fnmatched against the
glob_list, therefore an --exclude_dir expression test_*.py doesn't
matches and excludes (py)test files in subdirectories, for that
*/test_*.py is needed.

The following configuration should solve your problem:
assert_used:
  skips: ["*/test_*.py", "*/test_*.py"]

Comment: `**/test_*.py` glob can be used for deeper nested test modules.
Comment: FWIW I had to update an old codebase from 1.5.1 to 1.74 to get this to work
Answer: Just wanted to add to the answers above and mention the toml equivalent of skipping assert_used for specific files:
[tool.bandit.assert_used]
skips = ['*_test.py', '*/test_*.py']

Answer: A possible solution is to tell bandit to skip tests altogether. Assuming your code lives in a src subfolder, run
bandit --configfile bandit.yaml --recursive src

with the following bandit.yaml in the project's root directory
# Do not check paths including `/tests/`:
# they use `assert`, leading to B101 false positives.
exclude_dirs:
    - '/tests/'

There is a bunch of related issues and pull requests.
Update: I like Diego's solution better.
Answer: You can configure files that skip this check. This is often useful when you use assert statements in test cases.
bandit --configfile bandit.yaml

with the following bandit.yaml in the project's root directory
assert_used:
  skips: ['*_test.py', 'test_*.py']

Link to the original doc
Answer: Based on documentation, your config should look like
skips: ['B101'], not skips: B101 (which you have).
EDIT:
Ok, so if I understand correctly, you want to skip B101 on your tests folder.
I am not aware of any way to specify this, but I can think of hack of a sort - just run bandit two times - once ignoring tests, and once only on tests skipping B101. I know, it's not most elegant way, but it should solve your problem.
Comment: `skips: ['B101']` and `skips: B101` are not the same thing. Are you sure you have the right thing in your config?
Comment: This is exactly what I have in my question where I wrote it's not what I want
Comment: @ThrowAwayAccount Yes, I am. As stated in the question, I'm not asking for a solution to skip all B101 checks. I'm asking to skip B101 only for code in a given directory.
Comment: @MartinThoma that wasn't clear from your question, so I was answering something else.
So, you want to skip B101 only in /test directory?
Comment: Yes, I only want to skip B101 within the tests directory. In other directories, I want to still have this.
Comment: Thanks for clarification. Edited my answer with possible solution.
Comment: For the hack: Can I have two different configurations for bandit? Is there something like "inheritence" for bandit configuration?
Comment: No idea about "inheritance", but you can specify your used config in your CLI `bandit` command.
Now the rest depends on your specific usecase - I use precommit, where I can run bandit two times and specify config there each time (as file or just args). Same can be done in GitHub Actions. You can also create simple shell script with these defined bandit checks and run it instead of directly using CLI.
Answer: How I achieved bandit skip B101 within tests in Visual Studio Code:

in the project's root I have bandit.yaml file with the following content:

assert_used:
    skips: ["*/test_*.py"]

In the settings.json file I have:

"python.linting.banditArgs": [
    "-r",
    "--configfile",
    "${workspaceFolder}/bandit.yaml"
],

Answer: I have the following in my pyproject.toml:
[tool.bandit]
exclude_dirs = [".venv", "tests"]
skips = ["B307"]

From the command line I just add -c pyproject.toml and bandit reads the configuration from there.
In VSCode:
"python.linting.banditArgs": [
    "--configfile",
    "pyproject.toml"
]


Not Allow user to take quiz twice

Question: I am using Express, Passport, Handlebars and Mongoose/MongoDB to build a quiz for a website. I am trying to prevent the same user from taking the same quiz twice. There is only one quiz. Once they finish it, they cannot take it again. Could anyone tell me what is wrong with my code?
router.get('/tools/start-health-assessment', function(req, res) {
  User.find({
    _id: req.user._id,
    assessmentTaken: true
  }).then(function(err) {
    if (err) {
      throw err;
    } else {
      res.redirect('/users/dashboard');
    }
  });
});

This route gets the instructions page that precedes the quiz. My logic is to use the Mongo query inside this route. If assessmentTaken is true, I want to ideally redirect the user back to the dashboard. The problem I am experiencing is a stalled webpage every time I try to get to the route above i.e. the loading bar never ends.
Comment: Why aren't you reading what comes back from mongodb? As in, `function(err, user) ...`
Answer: If you already have req.user populated (I assume with the same model as in your db), why not just check that in the handler, rather than making another DB query?
EG:
router.get('/tools/start-health-assessment', function(req, res) {
    // assuming your Passport middleware won't let a request get here w/o a user on it.
    if (req.user.assessmentTaken) {
      res.redirect('/users/dashboard');
    } else {
      res.render('health-assessment'); // or whatever you call it
    }
});

Not Allow user to take quiz twice


Evaluation of Method to Classify Large Number of Unlabeled Data

Question: I have a small set of labeled training data around 300 examples with 50 features each. Also I have a large dataset of unlabeled data around 30000 examples with 50 features each. What is the best way to find the labels of the second dataset?
The way I currently use is

Train a linear classifier as much as possible with the labeled data
Use KNN to the unlabeled data 50 at a time and those that are closest to the training examples get to the labeled set.
Train the linear classifier again with the new training data

etc...
Comment: What are the labels like? Binary, multiclass, continuous...?
Comment: @AlexL The labels for the classes are numeric for example 1 for the first class 5 for the fifth etc...
Comment: What kind of linear classifier are you using and how well is it performing?
Comment: @AlexL I use SVMs. It has around 70% accuracy. The thing is that this is a methodology that I have thought myself. I was asking to find out if the way I use can be trusted and also what is the best way to tackle this situation meaning what is the best method.
Answer: There is a developing subdomain in machine learning called Active Learning where you know the labels for few and use it to suggest other unlabeled examples that would be most useful to have labels for. Then you can label those examples by-hand and re-train the classifier. It's a special form of semi-supervised learning.
So how do that? There's a python (assuming you are doing everything in Python) library called libact and its source code is on github. It claims it can work well with scikit-learn models.

In particular, libact models can be easily obtained by interfacing with the models in scikit-learn.

P.S friend of mine says it works well only on Ubuntu. So just make a note of it.
Hope this helps.
Comment: FYI, that's not what active learning is. Active learning is when the algorithm is able to ask the human to label additional examples that it thinks would be most helpful for improving the classifier.
Comment: Yes, that's why I suggested it. Basically, he can stick only with semi-supervised algorithms, where human intervention is required. Thanks for the downvote :(
Comment: Edited your answer so I can upvote it
Answer: The procedure you are using resembles a technique called self-training. The way it normally works is

Train the classifier on your labeled data.
Use it to predict the labels on all the unlabeled data.
Assume that the classifier is correct for the unlabeled examples for which it is most confident and add them to the labeled training data.
Go back to step 1.


Question about Riemann integral and Norm of partition

Question:
Why do we assume that when the Riemann integral is defined, the partition norm tends to zero?
  And if it did not tend to zero, but remained constant, would it happen?
Comment: In your last sentence, what exactly would happen? Your question is not very clear.
Comment: Riemann integral can be defined using two kinds of limiting processes which coincidentally turn out to be equivalent. See [this answer](https://math.stackexchange.com/a/2047959/72031) for more details.
Comment: When you are trying to measure the length of some object via a ruler, you can hope that a ruler with smaller units will help you measure it accurately. Similar is the case with area being defined as integral. If the partition mesh is small the quality of approximation is better. It just does not lead to a meaningful/useful idea when we have large mesh size.
Answer: The definition of the Riemann integral requires the lower and upper integrals to be defined and equal. The lower integral is defined as the supremum of lower sums over all partitions, and the upper integral is defined as the infimum across all partitions of the interval.
Note that $L(f,P') \geq L(f,P)$ where $P'$ is a refinement of $P$. A similar but converse result holds for the upper Riemann sums.
Given this, the supremum across all partitions of the lower Riemann sum must have the mesh 'tend' to zero. To see why, consider that the supremum defined above is necessarily an upper bound of the lower sum of any partition. For any partition, say $P$, and any partition, say $P'$, that is both a refinement of $P$ and that has a smaller mesh than $P$, then the lower Riemann sum on $P'$ is greater than the lower Riemann sum on $P$, as above.
In defining the lower integral as the supremum of lower sums, we see then that the mesh of partitions has to 'decrease' as we 'approach' the supremum value. An analogous result holds for the upper Riemann sums.
I would say however that at least for me, I don't think of the definition I was taught as any sort of 'approach'. In my head the definition simply tells me I am taking some bound on some set (the set here being all upper/lower Riemann sums across all possible partitions), and using these bounds as a definition. It is definitely reasonable to think of the mesh shrinking, but I am not sure that it is necessary to explicitly state this.
EDIT: In response to the second part of the question, I am not sure the premise makes sense. Again, the definition of the Riemann integral uses the upper and lower integrals, which are themselves defined as supremums/infimums. Specifically, they are the supremum/infimums across the set of all partitions over an interval. As such, I do not know that it makes sense here to talk about 'tending' to zero, as it were. It is simply a set, and you could take an infinite subset of these partitions, and define a sequence of these elements where the mesh tends to zero. But you could also take an infinite subset of partitions where the mesh doesn't tend to zero. It makes no difference, because ultimately we are concerned with the supremum or infimum value across the entire set.
Because of what I explained above you can always find partitions with a smaller mesh that better approximate the supremum value. However this is not the same as the idea that we can control the size of the mesh. We simply define the set of ALL partitions over a given interval. In this way it doesn't make sense to think about what happens if the mesh does or doesn't tend to zero. Now it is different if we talk about approximations, then yes, choosing the size of the mesh will matter. But in terms of an actual integral, it doesn't make sense.


Linq query table column list

Question: Hi I am trying to output a list of items from a table over linq to a dropdown list
I am getting an error on the linq query: Cannot implicitly convert generic.list<string> to generic.List<locations>
Can someone help please? Thanks in advance.
public static void getlocation()
{

    DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext();

    List<Location> locations = (
        from a
            in dc.Locations
        select a.Name).ToList();

    DropDownList ddLocation = new DropDownList();

    locations.ToList();

    ddLocation.DataSource = locations;
    ddLocation.DataBind();

    ddLocation.SelectedIndex = 0;

}

Answer: You are selecting a single column select a.Name and then you are trying to store the result of ToList to List<Locations>. Your current query would probably result in List<string> which is not assignable to List<Locations>
You can fix that by selecting select a
List<Location> locations = (
        from a in dc.Locations
        select a).ToList();

You also don't need locations.ToList();  in your code, since locations is already a list. That is just redundant and you are not even assigning the result of ToList to any other field.
Edit:
You need to set DataTextField and DataValueField property of your DropDownList as well like:
ddLocation.DataValueField = "ID"; //Whatever you need the ID to be when selected
ddlLocation.DataTextField = "Name";

If you just want to show names and your selected value would be name as well then you can do:
 DataClasses_AbintegroDataContext dc = new DataClasses_AbintegroDataContext();

    List<string> locations = (
        from a in dc.Locations
        select a.Name).ToList();

    DropDownList ddLocation = new DropDownList();

    ddLocation.DataSource = locations;
    ddLocation.DataBind();
    ddLocation.SelectedIndex = 0;

Not really sure why you need to create ddlLocation inside your code, You can create that in ASPX code and just do the binding in code behind.
Comment: Hi Habib, I had it like this but then the name items wasn't added to the drop down, when debugging i can see there there under name but not sure how to select that single column from the dropdown
Comment: hi I had added DropDownList ddLocation = new DropDownList(); because I couldnt get my asp tag to be seen on the code behind :S
Comment: I have this on the ASPX
Comment: @user369616 as this answer works for you, I would request you to `accept` this answer and also `upvote` it.

Linq query table column list


Passar valor de uma linha na table para inputs na mesma pagina

Question: tenho uma simples dúvida. Preciso passar os dados de uma linha na minha table para os inputs que estão na mesma pagina.
Segue as telas:

Segue o código:

Alguém tem uma solução? Imagino que vou precisar de javascript...ou não?
Comment: pensando de forma rápida, vc iria numerar as  e pegaria o valor do id via jquery e repassaria as informações dos , existem outras formas também porém essa é mais rápida
Answer: Tente fazer dessa forma

$(function(){
  $('#Tabela tbody tr').on('click',function(){
   const id = $(this).attr('id');
   const cod = $('#Tabela tbody tr[id='+id+'] td').eq(0).html(),
   nome = $('#Tabela tbody tr[id='+id+'] td').eq(1).html();
   $('#frm #cod').val( cod );$('#frm #nome').val( nome );
  });
 });

  <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />

  <form id="frm" name="frm" method="post">
   Cód<input type="text" id="cod" name="cod" />
   Nome<input type="text" id="nome" name="nome" />
  </form>

     Cód
     Nome

     01
     Fulano de Tal 01

     02
     Fulano de Tal 02

Comment: Isso mesmo, deu certinho. Valew


Verifying if these Cayley tables are from groups

Question:
For the first table I noticed that
$ab = c \implies abb = cb \implies a = cb$ but in the table, $cb = d$, so this can't be a group
For the second table, we have:
$ab = c \implies (aa)b = ac \implies bb = ac \implies e = ac$ but $ac = d$ in the table, so this can't be a group too.
Am I rigth?
Comment: In the first cayley table assuming it is a group, it being of order five (prime order) should be cyclic which is not the case here.
Answer: If all the elements are known to be distinct then you are right in both cases. Else you're first "group" gives you the relation $a=d$ so this could be true and you need to check further, and similarly for the second one.
Also in the first cayley table, notice how the diagonal is just the identity. This tells you that every (nontrivial) element has order 2 and this implies that the "group" is abelian (assuming it is a group), which simplifies matters.
Comment: The diagonal in the first table is NOT just the identity, did you notice that one entry is $c$? (Or maybe I am missing something).


What's the difference between import virtual machines types in Hyper-V 2012?

Question: I was importing a virtual machine to my Hyper-V manager and I got 3 options:
<code>Register the virtual machine in place
Restore the virtual machine in place
Copy the virtual machine
</code>
What's the difference between the three options?
Comment: Does it occur to you to - ah - read some documentation and get some basic - ah - knowledge as required by this site before asking questions like this?
Comment: Oh, and that is a double of http://serverfault.com/questions/585663/whats-the-difference-between-import-virtual-machines-types-in-hyper-v asked like yesterday.
Answer: Register: If you have a virtual machine were you have already put all of the virtual machine files exactly where you want them, and you just need Hyper-V to start using the virtual machine where it is.
Restore: If your virtual machine files are stored on a file share / removable drive / etc… and you want Hyper-V to move the files to the appropriate location for you, and then register the virtual machine.
Copy: If you have a set of virtual machine files that you want to import multiple times (e.g. you are using them as a template for new virtual machines) this is what you want to choose. This will copy the files to an appropriate location, give the virtual machine a new unique ID, and then register the virtual machine.


Qual é a finalidade do retorno da função main e a importância desta função?

Question: Gostaria de saber qual é a importância da função main e qual é a finalidade do retorno dela que é um inteiro?
Veja um exemplo mínimo da implementação da função main:
int main()
{
    printf("StackOverFlow\n");
    return (0);
}

Em que este retorno implica na execução do meu programa?
Comment: Já ouvi falar que isso é um retorno para o sistema operacional. "0" significa que o programa executou com sucesso ...
Answer: Normalmente as linguagens precisam de um ponto de partida. Em java, c, c++, ada, pascal, assembly, etc, é usado um método ou um bloco (no caso do pascal) para saber onde a aplicação irá começar.
Em Assembly o código começa no método _start (se for Linux), o C, decide que o programa deve começar no main e o pascal tem um cloco de begin e end. para dizer onde a aplicação iniciará.
O retorno do método serve para saber se ocorreu tudo bem durante a execução do seu progama.
Exemplo de uso do retorno:
$ gcc main.c -o compiled
$ echo $?

Caso o arquivo seja compilado com sucesso irá retornar 0, os outros valores são para diferentes tipos de erro.
Outro método de uso é:
$ gcc -fPIC -shared -O2 mylib.c -o libmy.so &&
$ gcc main.c -o compiled ./libmy.so &&
$ echo "compilado com sucesso!" ||
$ echo "Erro ao compilar!"

O simbolo && refere-se a uma condição e, se os 2 arquivos foram compilados com sucesso, será chamado o primeiro echo, pois ele faz parte da condição e, caso contrario, será chamado o segundo echo, pois a condição or só é chamada caso o e seja falso.
Answer: Na linguagem C o valor de retorno da função main é passado para o sistema operacional, e pode ser testado pelo processo pai.
Um exemplo concreto: no Windows, quando você trabalha numa "janela DOS", esse valor de retorno da função main é o valor que recebe a variável de ambiente ERRORLEVEL.
c:\tmp> prog_teste.exe
if %ERRORLEVEL%==0 (
    echo prog_teste executou sem erro
) else (
    echo houve erro na execução de prog_teste
)

No Linux (e UNIX) o valor de retorno é deixado na variável do shell $?, que também pode ser testada logo a seguir à execução do programa
$ ./prog_teste
if [ $? = 0 ]; then
    echo prog_teste executou sem erro
else
    echo houve error na execução de prog_teste
fi

Em C++ é permitido omitir o comando return da função main, e neste caso o valor retornado é 0.
Em C, a partir da versão C99 esta omissão também é permitida, e o comportamento é igual ao da liguagem C++.
No shell do Linux (e UNIX) é possível fazer o teste de "sucesso" de um programa sem fazer o teste explícito de comparação com 0, basta testar o nome do programa.
$ ./prog_teste
if ./prog_teste; then
    echo prog_teste executou sem erro
else
    echo houve error na execução de prog_teste
fi

Answer: Os experientes que me corrijam, mas creio que seja main a classe principal do programa, onde o programa começará a rodar.
Já o return, como temos int main(), temos a indicação que essa classe devolverá um tipo inteiro, por isso return(0). Poderíamos simplesmente criar void main(), indicando que não haverá retorno nenhum, ou seja, vazio (void).
Espero que tenha te ajudado.
Comment: Não existe classes em C, e mesmo que fosse java, seria errado afirmar que "main é uma classe". As classes só armazenam dados e métodos, não tem como colocar uma sequencia de instruções em uma classe, apenas em métodos.
Comment: Boa! esqueci que estava lidando com C... rsrsrs
poderia dizer então que é um tipo de indicador? indicar que o bloxo x faz parte do programa principal e deve começar a ser rodado dali, eria errado?
Comment: não creio que indicador seja o termo correto, acho que dizer método apenas, é mais direto.
Comment: Entendi! Obrigado pela ajuda


Does drush up do a database backup/dump?

Question: Does running drush up run a database backup? From testing, it looks like it doesn't. Should I be doing a separate database backup before I run drush up to update?
Comment: See also http://drupal.stackexchange.com/questions/3363/complete-backup-solution
Answer: To make gzipped mysql dump with drush:
drush sql-dump --gzip --result-file={PATH-TO-RESULT-FILE}
Update from the wranvaud's comment:
If you don't specify the result file it will be stored on you home folder under: ~/drush-backups/<db_name>/<timestamp>/<database_file>.sql.gz, otherwise you can specify --result-file='~/Documents/<my_backups_folder>'
Comment: if you don't specify the result file it will be stored on you home folder under ~/drush-backups///.sql.gz otherwise you can specify `--result-file='~/Documents/'`
Answer: No it doesn't. It only makes a backup of the current module directories, before it replaces them.
To create a sql dump, use
drush sql-dump > filename.sql.

But remember to move the file outside of your webroot.
Comment: I would like to remind people to do a dump outside of your website root; so hackers will stay away.
Comment: This "accepted" answer is not correct. Drush in fact does provide a dump of the database:   "drush sql-dump"
http://drushcommands.com/drush-7x/sql/sql-dump/
Comment: Um. Try reading the answer again. All of it, not just the first sentence. Because that's exactly what I wrote. The question was if "drush up" does it, not if drush can do it.
Answer: If you have the Backup and Migrate module module installed, you can call it from Drush with
$ drush bam-backup
Comment: drush natively supports a database dump, without the need for an extra module, see above
Answer: This is a bash script solution to Backup and Restore from command line with drush and Acquia-Drupal:

Note: You only have to change basepath,sitename and maybe drushpath in both scripts to fit your needs
Note 2: The Backup script will create a .tar containing your site files plus a data.sql file describing your database
Note3: The restore script will chose the last .tar backup file created by the backup script

INSTRUCTIONS
1) Find the drush path (drush is included in acquia), in my case (drushpath="/Applications/acquia-drupal/drush")
2) Create a backup_mysite file and a restore_mysite file and
    include them in your bin folder path (for example: /usr/local/bin)
3) Edit backup_mysite
#!/bin/bash
# Text color variables
txtgrn=$(tput setaf 2)    # Green
txtylw=$(tput setaf 3)    # Yellow

basepath="path-to-your-server-root" #4ex "/Users/monojones/www"
backuppath="$basepath/backups"
drushpath="/Applications/acquia-drupal/drush"
sitename="your-sitename"
tempdir="$backuppath/backup_$sitename"

if [ -d $backuppath ]; then
 echo "Backup path finded. [ $backuppath ]"
else
  echo "Creating backup path... [ $backuppath ]"
  mkdir $backuppath
fi

echo "${txtylw}Backing up $sitename ... ${txtgrn}"
if [ -d "$backuppath/$sitename" ]; then
 echo "Backup subdir finded."
else
 echo "Creating $backuppath/$sitename"
 mkdir $backuppath/$sitename
fi
echo "${txtylw}"
mkdir $tempdir
$drushpath/drush -r $basepath/$sitename  sql-dump --result-file=$tempdir/data.sql
tar -pczf $tempdir/files.tgz $basepath/$sitename $systempaths
tar -pczf $backuppath/$sitename/$sitename.backup_$(date +%Y%m%d%H%M).tar.gz $tempdir
rm -rf $tempdir

4) Edit restore_mysite
#!/bin/bash
# Text color variables
txtred=$(tput setaf 1)    # Red
txtgrn=$(tput setaf 2)    # Green
txtylw=$(tput setaf 3)    # Yellow

basepath="path-to-your-server-root" #4ex "/Users/monojones/www"
backuppath="$basepath/backups"
sitename="your-sitename"
drushpath="/Applications/acquia-drupal/drush"

echo "${txtylw}Restoring ${txtred}$sitename ${txtylw} database: ${txtgrn}"
FILE=`ls -1 $backuppath/$sitename/$sitename.backup_* | tail -n 1`
echo "Last backup file: ${txtpur} $FILE ${txtylw}"
mkdir temp_drupalbackup_$sitename
tar -C temp_drupalbackup_$sitename -zxvf $FILE ${backuppath:1}/backup_$sitename/data.sql
$drushpath/drush sql-drop
drush sql-cli <  temp_drupalbackup_$sitename/${backuppath:1}/backup_$sitename/data.sql
rm -R temp_drupalbackup_$sitename

Answer: You can also use sql-sync for backup.
$ drush sql-sync -v @site1 @site2

Comment: This is the best way to back up a site.
Answer: It is very easy now with Drush 5
"Note: Drush 5 introduced archive-dump and archive-restore commands which allow you to backup your code, files, and database into a single file."
https://drupal.org/upgrade/backing-your-site-command-line


Adaptar funçao à queryselectorall

Question: Estou tentando adaptar uma função que antes era usada apenas com QuerySelector, porém preciso que adapta-la para pegar todas as divs (QuerySelectorAll).
Vejam:
var draggableEl = document.querySelectorAll('[data-drag]')

A função
function move(event) {
    var el = draggableEl, magnetRect = magnet.getBoundingClientRect(), elRect = el.getBoundingClientRect();
    x = this._posOrigin.x + event.pageX - this._touchOrigin.x;
    y = this._posOrigin.y + event.pageY - this._touchOrigin.y;
    moveMagnet(x + elRect.width / 2, y + elRect.height / 2);
    $('body').addClass('moving');
    var touchPos = {
        top: y,
        right: x + elRect.width,
        bottom: y + elRect.height,
        left: x
    };
    overlapping = !(touchPos.top > magnetRect.bottom || touchPos.right < magnetRect.left || touchPos.bottom < magnetRect.top || touchPos.left > magnetRect.right);
    if (overlapping) {
        var mx = magnetRect.width / 2 + magnetRect.left;
        var my = magnetRect.height / 2 + magnetRect.top;
        x = mx - elRect.width / 2;
        y = my - elRect.height / 2;
        if (!$(el).hasClass('overlap')) {
            $(el).addClass('transition');
            setTimeout(function () {
                $(el).removeClass('transition');
            }, 150);

            setTimeout(function () {
                el.remove();
                setTimeout(function () {
                $('body').removeClass('moving touching');
            }, 900);
            }, 1000);
        }
        magnet.className = magnet.className.replace(' overlap', '') + ' overlap';
        el.className = el.className.replace(' overlap', '') + ' overlap';
    } else {
        if ($(el).hasClass('transition')) {
            $(el).removeClass('transition');
        }
        if ($(el).hasClass('overlap')) {
            $(el).addClass('transition');
            setTimeout(function () {
                $(el).removeClass('transition');
            }, 100);
        }
        magnet.className = magnet.className.replace(' overlap', '');
        el.className = el.className.replace(' overlap', '');
    }
    moveToPos(x, y);

}

o que define:
[].forEach.call(draggableEl, function(el) {
$(el).on('touchstart mousedown', onTouchStart).on('touchmove drag', move(el)).on('touchend mouseup', onTouchEnd);
});

Ela me retorna:  Uncaught TypeError: undefined is not a function em:
var el = draggableEl, magnetRect = magnet.getBoundingClientRect(), elRect = el.getBoundingClientRect();

Código completo:  jsfiddle.net/4yt1roa6
Comment: Testa mudar `var el = draggableEl` para `var el = this`
Answer: Analisando a primeira linha:
function move(event) {
    var el = draggableEl,

e sabendo que antes usavas var draggableEl = document.querySelector('[data-drag]') dá-me ideia que essa funcão estava a ir buscar o draggableEl ao escopo exterior, e funcionava porque só tinhas um único elemento. Isso não é boa prática, é melhor ter tudo dentro da funcão.
Partindo do principio que essa funcão é corrida por um event handler então o this será o elemento que queres e por isso podes usar:
function move(event){
    var el = this,

Para além disso esta sintaxe .on('touchmove drag', move(el)) está incorreta. Assim vais estar a correr a funcão diretamente, deve ser somente , move).
Testa assim:
$('[data-drag]')
    .on('touchstart mousedown', onTouchStart)
    .on('touchmove drag', move)
    .on('touchend mouseup', onTouchEnd);

Deste modo o jQuery vai buscar todos os elementos que tiverem uma propriedade '[data-drag]' e amarra-lhes oscultadores de eventos. Quando uma dessas funcões correr vai ser-lhe passado o elemento como this e aí podes usar como referi em cima var el = this.
Comment: @user3163662 podes fazer um jsFiddle com o problema?
Comment: Perdao foi erro de analise minha, era a funçao move() que nao sabia o que mover, adaptei e coloquei this na hora de chamar, desta forma `moveToPos(x,y,this)` está correto?
Comment: @user3163662: onde sugeres colocar `move(x,y,this)`? Pela a minha análize só precisas de mudar as linhas que juntei na resposta.
Comment: Veja bem, `moveToPos` foi usado para posicionar o elemento de acordo com o drag, na funçao move() ele é executado no final, porem como na funçao ele nao especificava qual dos drags movimentar ele acabava nao movimentando nada, dai surgiu minha midificaçao
Comment: @user3163662 ok, nesse caso é mais correto semãnticamente usar `move(x, y, el);`. Pois o `el` é uma referência do `this`.
Comment: Muito Obrigado!

Adaptar funçao à queryselectorall


Adding an img inline with the content only on a specific page

Question: I have a certain page on my site that has the following menus at the top:

I would like to add a logo just before the textual menus on the far left of the screen.  This menu is in the main content of the page.  So far I have been able to get the logo to show up just above the content by adding the img to my page.tpl.php file but I really want it to show up on the same line as my menus.
I thought maybe I could do this by adding the img into a region.tpl.php file but that would make the image show up on every page's region and I only want it to show up on this page's region.  Is there a way to the image show up inline using a page.tpl.php file?
Answer: Have you tried creating a block with your context, restricting the block to that one page, and then assigning the block to the correct region?
Your regions will depend on your theme.
Comment: All menus are available as blocks, if more functionality needed, try the menu_block module
Comment: Is it possible to put a menu inside a block?


Angular not detecting changes in ngFor in a new window from a postMessage

Question: Background: my main page opens up an external window (same origin) of another module within my project upon button click.
I also set up a BroadcastChannel so that these two windows can now communicate. Now, if this window is already open & the user clicks the triggering button once again, I want to communicate this to the window:
onAddNewFieldClick() {
    if (this.window === null) {
      this.window = window.open(window.location.origin + '/wizard', 'Field Wizard', 'resizable,scrollbar');
      this.channel = new BroadcastChannel('edit-spec-wizard-channel');
    } else {
      this.channel.postMessage(1);
    }
  }

The new window listens on this channel and appends the message data to an array that is used in an ngFor. To be extra safe. I go ahead and create a brand new array each time a new value is pushed to cause a rebind. Here is the logic that powers the component in the new window.
export class EntryComponent implements OnInit, OnDestroy {

  newFieldChannel: BroadcastChannel;
  newFields: number[] = [];
  constructor() { }

  ngOnInit() {
    this.newFieldChannel = new BroadcastChannel('edit-spec-wizard-channel');
    this.newFieldChannel.onmessage = this.newFieldChannelOnMessage.bind(this);
    this.newFields.push(1);
  }

  func() {
    this.newFields.push(1);
    this.newFields = this.newFields.slice();
  }

  private newFieldChannelOnMessage(event: MessageEvent) {
    this.newFields.push(event.data as number);
    this.newFields = this.newFields.slice();
  }

  ngOnDestroy() {
    this.newFieldChannel.close();
  }
}

And here is the template HTML:

      NEW FIELD BOX

  <button class="btn btn-primary" (click)="func()">Click me</button>

I have also included a button that triggers a function ("func()") that has the exact same logic as the postMessage handler.
Now, when I click the button in this window, I'll get the expected behavior: The correct number of "NEW FIELD BOX" divs will appear in this new window. However, when I press the original button from the main screen that posts a message over the BroadcastChannel, it WILL NOT update the UI to display the right number of "NEW FIELD BOX" divs. Using break points I can see that the array newFields does contain the right number of values, but ngFor does not re-render.
Example: I click the button on the main page that fires the onAddNewFieldClick(). It opens a new window which has one "NEW FIELD BOX" div. I click this button again which posts a message to add another. Still, only one remains on the window. I now click the button within the window that fires the function "func()." This will now render 3 "NEW FIELD BOX" divs (the original one from initialization, the one from the post message that didn't render, and the one from clicking this button).
Any ideas why change detection doesn't seem to happen from a postMessage?
Answer: The newFieldChannelOnMessage event handler is probably running outside of the Angular zone and does not trigger change detection. Try wrapping the code in NgZone.run():
import { NgZone } from "@angular/core";

constructor(private ngZone: NgZone) { ... }

private newFieldChannelOnMessage(event: MessageEvent) {
  this.ngZone.run(() => {
    this.newFields.push(event.data as number);
  });
}


Create GUI using Eclipse (Java)

Question:
Possible Duplicate:
Best GUI designer for eclipse?

Is there any Eclipse Plugin tool(s) who can help to create Graphical User Interface for (swing, awt or swt), because I'm tired of writing everytime the code of Panels, Labels, ...
Thanks
Comment: @jfpoilpret: WindowBuilder Pro has refactoring friendly bi-directional code generation, so you can modify generated code without "crashing" your design view.
Answer: Yes. Use WindowBuilder Pro (provided by Google). It supports SWT and Swing as well with multiple layouts (Group layout, MiGLayout etc.) It's integrated out of the box with Eclipse Indigo, but you can install plugin on previous versions (3.4/3.5/3.6):
Comment: The link in the answer seems to be dead. Use http://www.eclipse.org/windowbuilder/
Answer: There are lot of GUI designers even like Eclipse plugins, just few of them could use both, Swing and SWT..
WindowBuilder Pro GUI Designer - eclipse marketplace
WindowBuilder Pro GUI Designer - Google code home page
and
Jigloo SWT/Swing GUI Builder - eclipse market place
Jigloo SWT/Swing GUI Builder - home page
The window builder is quite better tool..
But IMHO, GUIs created by those tools have really ugly and unmanageable code..
Comment: Frankly i don't use GUI designers, I have MigLayout ;], but anyway, looks like it is possible [see official forum thread](http://forums.instantiations.com/viewtopic.php?f=4&t=5120&p=16229) ..
Comment: is WindowsBuilder works with swingx? If so, how?
Comment: plus 1 for pointing me to MigLayout as this is new for me. And it is good.
Answer: Yes, there is one. It is an eclipse-plugin called Visual Editor. You can download it here
Comment: According to the website the last release is 2 years ago, and it doesn't support Eclipse 3.3.
Comment: Then I would reccomend GWT - Window Builder as mentioned above...
Answer: try http://code.google.com/p/swinghtmltemplate/
this will allow you to create gui with html-like syntax

Create GUI using Eclipse (Java)


Is the real part of a positive semi-definite matrix positive semi-definite over $\mathbb C^n$

Question: Let $P$ be a positive semi-definite Hermitian matrix (i.e. $P^\dagger=P$, $x^\dagger Px \geq 0$ for all $x \in \mathbb C^n$). Then the matrix can be decomposed as $P= R+iM$ where $R$ and $M$ are strictly real matrices. Clearly $R$ is symmetric and $M$ is skew-symmetric. I call $R$ the real part of $P$.
I am almost certain that the real part $R$ must be positive semi-definite as well as I cannot find a counter-example even through numerical simulation. Is this assumption correct? Is there a way to prove the positivity of $R$ over $\mathbb C^n$ or does somebody have a counter-example?
Comment: @Omnomnomnom $P$ is already Hermitian so $(P + P^\dagger)/2 = (P + P)/2=P$ and $P$ may still have complex entries. My work requires matrices that have strictly real entries.
Comment: It is more common to use the Hermitian "real part" $(A+A^\dagger)/2$
Answer: The real part of $P$ is $(P + \overline{P})/2$.  If $P$ is positive semidefinite, so is $\overline{P}$, because
$$x^* \overline{P} x = \overline{ \overline{x}^* P \overline{x}} \ge 0$$
And a convex combination of positive semidefinite matrices is positive semidefine.
Comment: Great, thanks. Am I also able to conclude that $\overline{ \overline{x}^* P \overline{x}}=\overline{x}^* P \overline{x}$ is real since $P$ is positive semidefinite?
Comment: Yes, $v^* P v$ is real whenever $P$ is hermitian.


How to open a new window, which will be a child of the current one and located inside it

Question: How to open a new window, which will be a child of the current one and located inside it?
For example: like Google Chrome tabs
Comment: what do you mean "located inside it". windows aren't tabs
Comment: @pushkin but how to implement tabs in one window so that the contents of each tab (for example, styles) do not conflict with the styles of the application or other tabs? That is, so that it works in isolation.
Answer: If i understand you right you want to load multiple files in one window without merging their styles. In this case you should take a look at the webview tag. It's like an fully controllable iframe.
See: https://electronjs.org/docs/api/webview-tag
Comment: Thanks for the answer! What needs to be specified in the src attribute in the webview tag when I use the Vue.js environment?


How do I diagnose network corruption on an Internet path?

Question: I run a few hosts on network A that make requests to servers (which I don't own) on network B, somewhere across the Internet.  Unfortunately, many of these requests get corrupted.  If I make the requests over unencrypted HTTP, I get strange errors that hint at a corrupt request.  If I make the requests over HTTPS, I get SSL-level errors.  I can reproduce the problem by running:
<code>sh -e -c 'while true; do curl $SERVER > /dev/null; sleep 1; done'
</code>
Usually within 20 requests, curl fails with an error like "Unknown SSL protocol error" or "tlsv1 alert decrypt error".  I can reproduce this on multiple hosts in network A, accessing multiple servers on network B.  But I cannot reproduce from network A to other servers, or from other hosts to network B.  In those cases, the loop runs forever with no errors.
So it's pretty clear my TCP stream is getting corrupted between A and B.  This has been going on for over 3 days, by the way.
First question:  How can this plausibly happen?  TCP has packet-level checksums, and corrupt packets passing the checksum should be much rarer than I am seeing.  Also, if I run a network capture, I don't see many retransmits (according to wireshark's tcp.analysis.retransmit filter), which you would expect if packets were being corrupted and failing the TCP checksum.  I guess some router must be doing higher-level data mangling (NAT? transparent proxy?) and corrupting the data but fixing the checksum?
Second question:  Are there any tools I can use to isolate the problem?  I can't find any.  If I knew the network topology and I could find HTTPS servers behind each hop between A and B, I could run my test on them.  But I don't.  What other test would show up network corruption?
I've contacted the owners of network A and network B, but they haven't been helpful so far.
Update: To anyone suggesting what kind of buggy device might be in the path, is there any way to detect this other than contacting the owner?
Answer: First of all, it would be useful to see if you can replicate the data corruption using ping, rather than using TCP. Ping uses an ICMP echo, sends a known payload (that you can even specify if you need to) and will report in case the payload is corrupt when returned. At least, this is what the man page tells me.
You'll probably want to use a long packet size (maybe 1400 bytes or so) and see if you can specify a low interval, perhaps 0.1 seconds so that you can reproduce the error in a reasonable amount of time. These settings will generate approximately 15 kB/s of traffic to and from the server. (1400 bytes / 0.1 seconds + overhead)
So why use a ping instead of the TCP connection? Because, you can probably ping most hosts in the path between the server and your client, and you can therefore test only part of the path.
Starting by testing the full path (all the way to your server, to determine that the test reproduces your issue). Armed with a traceroute, you can then test only part of the path. Every test you make can divide your search space in half, and after a few tests you'll be able to find the hop that's causing your problems.
Caveat: This will not work quite the way you expect if the corruption is happening on the return path to test machine rather than on the forward path. Traceroute can only tell you what route your packets are taking to the server, not the path packets returning will take, and those paths are not neccessarilly the same. Still, it should be enough to get you somewhere.
Good luck!
Answer: Is anybody along the line using LAN/WAN Accelerators?  These pieces of hardware sometimes screwup and have to be restarted and can be the source of corruption as well as performance issues.
Answer: Could there be a flakey IDS/IPS/proxy at either network that is mangling packets only to/from the other network? That would explain why it's not reproducible from or to different hosts.


Imprimir só os negativos

Question: lista = [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52]

for n in lista:
    if n < 0:
    soma_dos_negativos = sum(n)
print('A soma dos elementos negativos é igual a {}'.format(soma_dos_negativos))

Answer: Você está fazendo um uso incorreto da função sum, enviando um número inteiro, sendo que ela espera um objeto iterável:
soma_dos_negativos = sum(n)

Uma possível correção, seria declarar a variável soma_dos_negativos antes no for:
soma_dos_negativos = 0

E no if dentro do for, passar a somar os números negativos na mesma:
soma_dos_negativos += n

O código completo ficaria mais ou menos da seguinte forma:
lista = [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52]

soma_dos_negativos = 0

for n in lista:
  if n < 0:
    soma_dos_negativos += n

print('A soma dos elementos negativos é igual a {}'.format(soma_dos_negativos))

Veja online: https://repl.it/@Dadinel/HandmadePointedAtoms

Se você deseja utilizar a função sum, é possível enviar a lista já filtrando os números negativos, ficaria mais ou menos da seguinte forma:
soma_dos_negativos = sum([n for n in lista if n < 0])

Exemplo completo:
lista = [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52]

soma_dos_negativos = sum([n for n in lista if n < 0])

print('A soma dos elementos negativos é igual a {}'.format(sum([n for n in lista if n < 0])))

Veja online: https://repl.it/@Dadinel/SaneImpracticalDirectory

Utilizando o sum dessa forma, seria possível até deixar todo esse código em apenas uma linha:
print('A soma dos elementos negativos é igual a {}'.format(sum([n for n in [12, -2, 4, 8, 29, 45, 78, 36, -17, 2, 12, 8, 3, 3, -52] if n < 0])))

Documentação: https://docs.python.org/3/library/functions.html#sum

Imprimir só os negativos


Translating media and other reference fields

Question: I am new to Drupal and I am setting up a new Drupal 10 website with multiple languages. I just wanna make sure that as a beginner I have understood the concept of translation for fields that reference to other entities.
For example, I have an Article content type with three fields:

field_related_pages that references multiple Page nodes
field_main_image that references a media entity (an Image bundle)
field_related_places which references a Places vocabulary

From what I've concluded from my search, those three fields should be marked as NON Translatable on the Article content type. Moreover, on the configuration page admin/config/regional/content-language, the Places vocabulary should be marked as translatable with all its translatable fields, the content type page should be also marked as translatable with all its translatable fields, the Image should also be marked as translatable with all its translatable fields.
Is this correct, or should I mark the field_main_image field  as translatable from the beginning in the Article content type?
Answer: Short answer: Yes, this is correct.
Only make reference fields translatable when they should have completely different values in different languages.
Comment: Thank You for your clear answer!


Apache configuration - MaxClients

Question: can someone explaine me more abou MaxClient value? I know that it's about the simultaneus client, but... it mean the request per seconds? PEr minutes? Or maybe all the users that are on the site, even that who doesn't open pages?
Answer: From TFM:

The MaxClients directive sets the limit on the number of simultaneous
  requests that will be served.

Seems pretty clear to me.
Comment: simultaneous: adjective. happening at the same time
Comment: Yes, but what "simultaneous" mean? By seconds? By minutes?
Answer: In eApache documentation they describe it clearly (in Apache 2.4 MaxClients is renamed to MaxRequestWorkers):

The MaxRequestWorkers directive sets the limit on the number of simultaneous requests that will be served. Any connection attempts over the MaxRequestWorkers limit will normally be queued, up to a number based on the ListenBacklog directive. Once a child process is freed at the end of a different request, the connection will then be serviced.

So that's the maximum number of requests your Apache instance can serve. Being on a page may or may not have one or more connections opened, that will depend on what is the web page you are serving: it may be doing some requests in background or it may have an open socket. In case of static content the request starts when the client connects and sends the request and it finishes when the connection is closed (or Apache times it out).
Comment: There is a way for check if my webpage made request in background? My site is build with joomla
Comment: You could use the development tools in your browser to see the connections or use some traffic analyzer like Wireshark of Fiddler.

Apache configuration - MaxClients


Mercurial with Trac on mod_wsgi

Question: I'm trying to set up a Trac environment running on Apache+mod-wsgi+Mercurial. I've set up everything according to the install docs. However, when I open up the URL to my Trac environment I get:

Warning: Can't synchronize with the repository (Unsupported version control system "hg": Can't find an appropriate component, maybe the corresponding plugin was not enabled? ).

I've installed mercurial-trac from ports.  What could be the problem?
Update 1
Found I had to enable the plugin via trac.ini.  But I'm still getting an error:

Unsupported version control system "hg": "Couldn't import symbols: RepoError"
Answer: Just thought to update this....turns out I was using the wrong version of the trac-mercurial plugin.

Mercurial with Trac on mod_wsgi


Editing a value in a ldap dn

Question: What is the correct syntax to edit a value in an LDAP dn? As of now I was trying the following:
serveradmin@magic:~$ ldapmodify -x -W -D cn=admin,dc=example,dc=com <<EOF
> dn: uid=foo,ou=People,dc=example,dc=com
> changetype: modify
> edit: loginShell
> loginShell: /bin/false
> EOF

However that returns the following error:
ldapmodify: modify operation type is missing at line 3, entry "uid=foo,ou=People,dc=example,dc=com"

So I'm assuming the edit is not a correct operation type. So what is the correct syntax to edit a users login shell?
Answer: The correct syntax to modify a entry is with the keyword replace. So in order to modify the login shell of the user, the command would look like this:
serveradmin@magic:~$ ldapmodify -x -W -D cn=admin,dc=example,dc=com <<EOF
> dn: uid=foo,ou=People,dc=example,dc=com
> changetype: modify
> replace: loginShell
> loginShell: /bin/false
> EOF

Editing a value in a ldap dn


Partial fraction with complex roots

Question: Is it so that partial fractions with complex roots can work sometime, and sometime not?
I have tried to check a result by WA here, and tried to solve it manually:
\begin{equation}
X(z)=\frac{104z+30}{z^2+4z+5}=\frac{A}{(z-2+i)}+\frac{B}{(z+2-i)}
\end{equation}
But I get that A does not exist: $(A\cdot 0)=104i-238$ which is false. So B equally does not exist.
Wolfram alpha does not give any solution either.
Is there something important to note when one has complex denominators?
Thanks
Comment: You should have $\dfrac{A}{(z+2+i)}+\dfrac{B}{(z+2-i)}$.  How did you get $0$?
Answer: Since $z^2+4z+5=(z+2+i)(z+2-i)$, you should search for numbers $A$ and $B$ such that$$\frac{104z+30}{z^2+4z+5}=\frac A{z+2+i}+\frac B{z+2-i}.$$But, since$$\frac A{z+2+i}+\frac B{z+2-i}=\frac{(A+B)z+(2-i) A+(2+i) B}{z^2+4z+5},$$you simply solve the system$$\left\{\begin{array}{l}A+B=104\\(2-i)A+(2+i)B=30.\end{array}\right.$$You will get that $A=52-89i$ and that $B=52+89i$.
Comment: Thanks, I see the error now!

Partial fraction with complex roots


Extracting text from a txt file using batch

Question: So I have been missing with this extractor it works great, but need a bit of help
Original Script:
@ECHO OFF
SETLOCAL

SET "sourcedir=C:\Users\user\Desktop\My Folder\New folder 1\Folder A"
SET "destdir=C:\Users\user\Desktop\My Folder\New folder 2\Folder A"

for /f "tokens=1 delims=[]" %%a in ('find /n "name"^<"%sourcedir%\(1) Homes in Texas.txt" ') do set /a start=%%a
for /f "tokens=1 delims=[]" %%a in ('find /n "location"^<"%sourcedir%\(1) Homes in Texas.txt" ') do set /a end=%%a
(
for /f "tokens=1* delims=[]" %%a in ('find /n /v ""^<"%sourcedir%\(1) Homes in Texas.txt" ') do (
 IF %%a geq %start% IF %%a leq %end% ECHO(%%b
 )
)>"%destdir%\(1) Homes in Texas.txt"
GOTO :EOF

Now like I mentions this works great when I set the script to match the file name
in this example I have set this file name Homes in Texas.txt
The problem I'm facing is I'm trying to make it read over 1000.txt files with all different names
in many different folders
Here is the layout of my original files
New Folder 1
    >> New Folder A
         | (1) Homes in Texas.txt
         | (2) Homes in Ohio.txt
    >> New Folder B
         | (1) Homes in Austin.txt
         | (2) Homes in Houston.txt
    >> New Folder C
         | New Folder 1
               | (1) Homes in Katy.txt
               | (2) Homes in Dallas.txt

Inside if each folder I have between 20 and 100 txt files
This script is only designed to edit 1 file at a time and I really need it to edit multiple files
Now inside each text file I have over 500 lines (rows), and all I need is to extract between 2 sets of lines
It will extract Name, Location and everything between
It will also extract City, and Place from the same file
I have 4 codes to search within 1 files, and I would like for the Destination to have everything it copied from 1 file to have the same original file name, and both sets of codes to be in one file
Now the end results should look like this
New Folder 2
    >> New Folder A
         | (1) Homes in Texas.txt
         | (2) Homes in Ohio.txt
    >> New Folder B
         | (1) Homes in Austin.txt
         | (2) Homes in Houston.txt
    >> New Folder C
         | New Folder 1
               | (1) Homes in Katy.txt
               | (2) Homes in Dallas.txt

It would look exactly the same as the original, BUT the context of the files will only have what was extracted nothing more
What I did to get both sets of codes extracted, was I double my script. Now I know it's bad practice, but I get the double extractions I need but in two separate files
This is my modified scripts that reads both and extracts what I need
    @ECHO OFF
    SETLOCAL

    SET "sourcedir=C:\Users\user\Desktop\My Folder\New folder 1\Folder A"
    SET "destdir=C:\Users\user\Desktop\My Folder\New folder 2\Folder A"

    for /f "tokens=1 delims=[]" %%a in ('find /n "name"^<"%sourcedir%\(1) Homes in Texas.txt" ') do set /a start=%%a
    for /f "tokens=1 delims=[]" %%a in ('find /n "location"^<"%sourcedir%\(1) Homes in Texas.txt" ') do set /a end=%%a
    (
    for /f "tokens=1* delims=[]" %%a in ('find /n /v ""^<"%sourcedir%\(1) Homes in Texas.txt" ') do (
     IF %%a geq %start% IF %%a leq %end% ECHO(%%b
     )
    )>"%destdir%\(1) Homes in Texas.txt"

    for /f "tokens=1 delims=[]" %%a in ('find /n "City"^<"%sourcedir%\(1) Homes in Texas.txt" ') do set /a start=%%a
    for /f "tokens=1 delims=[]" %%a in ('find /n "Place"^<"%sourcedir%\(1) Homes in Texas.txt" ') do set /a end=%%a
    (
    for /f "tokens=1* delims=[]" %%a in ('find /n /v ""^<"%sourcedir%\(1) Homes in Texas.txt" ') do (
     IF %%a geq %start% IF %%a leq %end% ECHO(%%b
     )
    )>"%destdir%\(2) Homes in Texas.txt"
    GOTO :EOF

This is my end results when I do it this way, when I place the bat file directly in the folder where the file is located
New Folder 2
    >> New Folder A
         | (1) Homes in Texas.txt
         | (2) Homes in Texas.txt

I have been doing a lot of research on setting this up, but I can't get it done
Comment: Consider piping the output of a `Dir` command that uses a search pattern containing wildcards for the filename to be searched into `findstr`
Answer: You have got multiple pairs of begin and end tokens (Name/Location, City/Place) that define what part of the source files to copy to the destination files, which could define ranges that somewhat overlap, which would lead to duplicate lines. To avoid that, check whether the current line is within one of the ranges and set a flag variable in case, but do not clear it if not (except for an initial clearance), then write the current line only when that flag is set, so there is only a single write operation per line.
To build the same directory hierarchy in the destination, paths relative to the source root directory are needed, which I usually derive using the xcopy command, together with its options /S or /E (to recurse into sub-directories) and /L (to just list files but not to copy anything).
The above mentioned techniques are implemented in the following script – see all the explanatory remarks:
@echo off
setlocal EnableExtensions DisableDelayedExpansion

rem // Define constants here:
set "_SOURCE=%~dp0New Folder 1"
set "_TARGET=%~dp0New Folder 2"
set "_MASK=(*) Homes in *.txt"

rem // Define pairs of begin and end tokens:
set "$TOKEN_BEGIN[0]=Name"
set "$TOKEN_END[0]=Location"
set "$TOKEN_BEGIN[1]=City"
set "$TOKEN_END[1]=Place"

rem // Change into source directory:
pushd "%_SOURCE%" && (
    rem // Loop through all matching files and return their paths relative to the source directory:
    for /F "delims=" %%F in ('xcopy /L /S ".\%_MASK%" "%TEMP%" ^| find ".\"') do (
        rem // Create respective sub-directory in the target directory:
        2> nul md "%_TARGET%\%%F\.."
        rem // Write to respective target file:
        > "%_TARGET%\%%F" (
            rem /* Read from current source file and prefix each line with line number plus colon;
            rem    the whole file becomes read here, so there is no interference with later reads: */
            for /F "delims=" %%L in ('findstr /N "^" "%%F"') do (
                rem // Get current line number and line string with the prefix:
                2> nul set /A "NUM=%%L" & set "LINE=%%L" & set "FLAG="
                rem // Loop through pairs of begin and end tokens:
                for /F "tokens=2* delims=[]=" %%A in ('2^> nul set "$TOKEN_BEGIN["') do (
                    for /F "tokens=2* delims=[]=" %%D in ('2^> nul set "$TOKEN_END[%%A]"') do (
                        rem // Determine first line position of current begin token:
                        set "BEGIN="
                        for /F "delims=:" %%N in ('findstr /N /R /C:"\<%%B\>" "%%F"') do (
                            if not defined BEGIN set "BEGIN=%%N"
                        )
                        rem // Determine last line position of current end token:
                        set /A "BEGIN+=!BEGIN*0x7FFFFFF, END=0"
                        for /F "delims=:" %%N in ('findstr /N /R /C:"\<%%E\>" "%%F"') do (
                            set "END=%%N"
                        )
                        rem /* Set a flag when the line number of the current line lies in the range defined by
                        rem    the current pair of begin and end tokens, though never clear the flag here: */
                        setlocal EnableDelayedExpansion
                        if !NUM! geq !BEGIN! (if !NUM! leq !END! (endlocal & set "FLAG=#") else endlocal) else endlocal
                    )
                )
                rem // Write currently iterated line when the flag is set:
                setlocal EnableDelayedExpansion
                if defined FLAG echo(!LINE:*:=!
                endlocal
            )
        )
    )
    rem // Return from source directory:
    popd
)

endlocal
exit /B

Comment: Oh man, I would of never figured that out, I see the changes you made, and I have tested it, and it works great, BUT, and I think it has to do with the xcopy, but it takes about 2 minutes per file, and I have over 4000 files easy, is there a way to fix that, also thanks for this `%~dp0`, I've been looking on how to setup a universal Source and Destination, for many of my files
Comment: I have this in a file, and there is more to it, but could something like this be use `FOR /f "delims=" %%q IN ('dir /b /s /a-d "%sourcedir%\(*)*.txt"') DO (` this script reads everything in folder 1 and it's subs, and sends it to another folder 2 and it's subs, but this one edit my content inside the files, like it replace names with other names, so could something like this be used, I'm looking at now to see if I can find a way to use this, but I am not sure how to intergrade it
Comment: Well, I am using `xcopy /L /S` (`/L` tells the command to not copy anything but to list files it would copy without `/L`) for the same purpose as you use `dir /S /B /A:-D`, with the difference that `xcopy` returns *relative* paths and `dir /S` returns *absolute* ones, so I can recreate the same sub-directory hierarchy at the destination location…
Comment: Thanks for the help, your script works great. I have check the answer, but for the thousands of files I have, it would take to long, I have updated my original script, but would like to update it with a `(%source%\*.txt)`, and for it to copy file name to `%target%` could you help me with that, the script I'm asking the question on is lightning fast, if I can I will update my question to show my updated script
Comment: Could you help me with setting up `(1) *.txt` to my latest script, I can deal with no Sub Folder, but I would really like to use the wildcard, I do appreciate the help you provided, but the script edits a file every 2 minutes, and to edit over 5000 files well that's just a lot of minutes...lol, with my latest script it takes 1 sec per file and all I need help with really is using the wildcard to replace `FILE` and `FILENAME` parts in my script
Comment: Let me suggest that you roll back the latest edit of your question and ask a new one instead (you can of course insert a link to this one), because as it stands now the answer does not really cover the revised question any more…
Comment: I want to thank you for your help, I now have learned how to improve my Script, and now I can extract all my files in lighting speeds. Your script did help me a ton, while I was working on my original script, when I left the house I would leave your script running, for hours, it only did a few folders, but that is a few less to worry about - Once again Thank you


Colocar tabuada em PHP em tabela HTML

Question: Estou tentando colocar a função de uma tabuada que fiz em PHP em uma tabela HTML, mas infelizmente não estou conseguindo, alguém poderia me dar um forcinha?
 <?php
function tabuada($tabuada){
   $cont = 1;

   while ($cont <= 10){
      $resultado = $tabuada * $cont;
      echo ($tabuada."x".$cont." = ".$resultado)."
";
      $cont++;
   }
}

$tabela = '
';
$tabela .= '
';
$tabela .= 'tabuada (10)	';
$tabela .= '
';
$tabela .= '
';
echo $tabela;
?>

Answer: Acontece que da maneira que você chamou a função tabuada, ela está sendo interpretada como uma string:
$tabela .= 'tabuada (10)	';

Como sua função tabuada já faz a impressão utilizando echo, bastaria chamá-la para que a tabuada seja exibida:
tabuada(10);

Porém isso claro, ficaria longe de ser impresso dentro da table.

Para que a tabuada seja impressa dentro da table, sua função tabuada precisa ser alterada e o restante do código também... Existem muitas formas de fazer isso, abaixo um exemplo tentando manter o seu código:
<?php

function tabuada($tabuada){
   $cont = 1;
   $resultado = '';

   while ($cont <= 10){
        $resultado .= '
' . $tabuada . 'x' . $cont . ' = ' . ($tabuada * $cont) . '
';
      $cont++;
   }

   return $resultado;
}

$tabela .= '
';
$tabela .= tabuada(10);
$tabela .= '
';

echo $tabela;

?>

Agora sua função tabuada retorna uma string, contendo a tabuada já dentro das tags tr e td, com isso passamos a criar a invocar a função tabuada e concatenar o seu retorno no restante do código que gera a table.
Comment: O elemento [``](https://developer.mozilla.org/pt-BR/docs/Web/HTML/Element/center) é obsoleto.

Colocar tabuada em PHP em tabela HTML


Web Scraping platform efficiency

Question:
Web scraping is efficient on windows or Ubuntu?
For scraping quotes from web which would be better scrapy or beautiful soap?
Answer: Question1: Efficiency

This is very borad coverage question. Basically the efficiency depends on following criterias:

Computer Performance
Network Stability
Anti-antispider techniques
Extraction Method
Business purpose

Here are the way they affect your efficiency:

Computer Perfomace

If you are targeting big-ecommerce sites or if the site uses massive amount of javascript(like LinkedIn) then you should consider a moderate perfomace instance(computer) to finish your job. Note that if your computer memeory is too small, scrapy-splash's docker container will automatically stop and cause your spider to fail immediatly. Compared to Windows Home Edition, you'd better choose Ubuntu, because ubuntu uses less memory etc.. No matter which operation system you choose, Server-Edition is always better than Home-Edition.

Circumstance 1: (Using Scrapy® with Selenium Web Driver)

Example1: Linked-In Sales Navigator Spider
Example2: WeiFeng Spider with reCAPCHA crackted

Circumstance 2: (Using Scrapy with Scrapy-spalsh javascript rendering service)

Example1: INC5000 Spider

Network Stability

Network Stability counts when your instance(computer) is too far away from your targeting site. Your network speed and latency will directly affect your spider and sometimes causes disaster. Low network speed will slow down your request speed, while latency will sometimes cause your spider failed to load your target webpage. This will led to error in future content extraction. Your program may catch exceptions and quit immedialy and if you are not using modern spider framwork, the error page will not be re-fetched in the future, so you will lose some data. Compared to a home-network-spider, deploy a spider on public cloud is a better solution.

Some cloud VPS Provider that you can choose from: Link
You can use IP Location Detector to find the location of your target site: Link

Anti-antispider techniques

IP Rotation:

Method 1: Use Scrapy with Crawlera
Method 2: Proxy Pool

UA Rotation:

Scrapy with UA Rotation Framework

Download Delay:

Scrapy with Download Delay

Extraction Method

This is really a borad topic, You can use fast-performance-techniques to locate elements like xpaths, bs4, css.... while you can also use low-performance-techniques like Deep Learning or Search even regular expression

Beautiful Soup (aka bs4):

Intro-bs4
BeutifulSoup is not a good solution if you want to parse complicate website HTML. It does not support xpath or css selectors so that you will have to manually figure out the website's element hierarchic and result in some code likes this.
for level1 in bs_obj.find_all("div", {"id", "classname"})
    for level 2 in bs_obj.find_all("div", {"class", "classname"})
        for level3 in bs_obj.find_all("a", {"class", "classname"})
            for level4 ........
                ....
                    ....

Xpath and CSS selectors:

Xpath tutorial by Oreilly
CSS tutorial by w3school
There is even a Xpath to CSS translator
Use Chrome Developer Mode to help you write xpath
Use Selector Gadget to automatically generate xpaths

Regular Expression (aka re):

This is a good way to extract content with a specified string pattern but it is slower than others.
Regular Expression Tutorial

Scrapy is integrated with xpath, css, re through parsel, you can check this tutorial to lean how to use them within scrapy

Question 2: Scrapy vs bs4 for scraping quotes from web

Scrapy is a scraping framwork while bs4 is a content extracting framework, so the answer is you can use BeautifulSoup in Scrapy.
There is also some User Friendly Scraping software

7 Tools for web scraping
Even scrapy company (scrapinghub) is developing their own open source H5 based scraper: Portia

Web Scraping platform efficiency


Merging two querying

Question: I will introduce my problem with a simple example.
I have two generic queries on the same table, say table 'customers'

Defined 'plushes' a table containing information about in-store plushes, the following first query retrieves for a certain subset of Customers, say first subset, their preferred plush.
WITH preferences
AS
(
    SELECT CustomerID,
    CustomerName,
    City,
    Country,
    PlushType,
    PlushPrice

    FROM customers cs
    LEFT JOIN plushes ps
    ON cs.CustomerID = ps.CustomerID

    WHERE cs.CustomerID < 4

)

SELECT CustomerID, PlushType, PlushPrice
FROM preferences

In the same way, defined 'dishes' a table containing world famous dishes, the second query retrieve for a another subset of Customers, say second subset, their preferred dish.
    WITH foodPreferences
AS
(
    SELECT CustomerID,
    CustomerName,
    City,
    Country,
    FoodName,
    FoodPrice

    FROM customers cs
    LEFT JOIN foods fs
    ON cs.CustomerID = fs.CustomerID

    WHERE fs.FoodName = 'pizza'

)

SELECT CustomerID, FoodName
FROM foodPreferences -- it returns customer 6

What I am searching for, is a query that shows customerID, plushType, plushPrice for the customers of the first OR the second subset, i.e. :

That means, I would like to apply the first query to the first OR a second  (deriving from another query) subset.
In other words, I want to run the first query for those customers who love pizza.
I am using OracleDB, with PL/Sql language.
Any idea?
P.s. I know that for the written example the structure of the used queries appears weird. Indeed, I am working with something more complex and I preferred to mirror the structure of the query I have
Comment: Oracle, More in detail Pl/sql
Comment: The second subset doesn't have a plushType or plushPrice, how do you expect to show `plushType, plushPrice for the customers of the second subset`?  I think you need to give a more concrete example *(ideally in SQL Fiddle)*
Comment: the second query defines a subset of customers. For these customer I want to run the first query
Answer: This query will do:
select customerid, plushtype, plushprice
  from customers cs
  left join plushes ps on cs.customerid = ps.customerid
  where customerid in (
          select customerid
            from customers
            where customerid < 4
        )
     or customerid in (
          select customerid
            from customers cs
            left join foods fs on cs.customerid = fs.customerid
            where fs.foodname = 'pizza'
        );

Comment: Hey, you keep moving the post (not fair) :)
Comment: You are right, but you are basing your answer on the fact the you can choose customer 6 independently from the second query.
Imagine that you don't know in advance the second subset of customers retrieved by the second query.

To make things clearer, I changed the where statement in the second query. Have a look
Comment: Modified, according to your new change.
Comment: Thank you :) I already tried this solution.. but it took more than 20 minutes to executing the query, then I stopped.... You know, nested query destroys efficiency
Comment: Ahahah you are right, my friend. But that it is my real need, unfortunately
Answer: Added this new answer that is more efficient:
with selected_customers (customerid) as (
  select customerid
    from customers
    where customerid < 4
  union
  select customerid
    from customers
    left join foods fs on cs.customerid = fs.customerid
    where fs.foodname = 'pizza'
)
select customerid, ps.plushtype, ps.plushprice
  from selected_customers cs
  left join plushes ps on cs.customerid = ps.customerid;

Merging two querying


Formatar Calendário de input em HTML5 com javascript

Question: Estou fazendo um formulário com validação em HTML5 e me deparei com uma situação um pouco ruim, quando coloco por exemplo type="date" quando passo o mouse em cima aparece as "setinhas" pra manipular data ou ascender ao calendário. O problema é que a formatação dele é horrível e eu gostaria de saber se não tem como eu usar ou CSS ou JAVASCRIPT para resolver este problema.
 <input type="date" name="DtNascimento" required="required"
oninvalid="setCustomValidity('Por favor, digite sua Data de Nascimento.')"
onChange="try{setCustomValidity('')}catch(e){}">

Comment: Existem algumas bibliotecas que já te fornecem uma formatação melhor como o [bootstrap-datepicker](https://bootstrap-datepicker.readthedocs.io/en/latest/), [jquery](https://jqueryui.com/datepicker/) e [este](http://amsul.ca/pickadate.js/date/).
Comment: Acho que vou usar o DatePicker timer mesmo então, mas mesmo assim muito obrigado.
Answer: Para problemas de formatação de campos eu uso bibliotecas javascript.
Na minha opinião a melhor para datas é a DatePicker
https://github.com/Eonasdan/bootstrap-datetimepicker
Comment: Lucas          Eu ja tinha visto esse datetimepicker mas postei aqui pra saber se realmente havia uma solução em cima desse do HTML5. Bom, pelo jeito terei de usar javascript mesmo.


useInfiniteQuery doesn't keep previous data (react-query)

Question: I'm trying to implement useInfiniteQuery for pagination scroll with filters for a backend that doesn't support pagination cursor (I'm using limit and start parameters).
I was able to retrieve my data but my hasNextPage variable is always undefined. I cannot fetch more data. When the button is used to trigger fetchNextPage, new data can be seen but it removes the previous data.

What am I doing wrong ? Here is my code:
// Query data
  const {
      data,
      status,
      error,
      isSuccess,
      hasNextPage,
      fetchNextPage,
      isFetching,
      isFetchingNextPage,
      isLoading,
      isError,
  } = useInfiniteQuery(
    [
      'vendors',
      {vendor_type: vendorTypesId},
      {country: countryId},
      {city: cityId},
      {vendor_product_types: productCategoryId},
      {page: thisPage},
      {start: start},
      {name: nameInput},
      {limit: limit},
    ],
    getVendors,
   {
      initialData: {
        pages : [{
          result: vendors,
          resultCount: 495,
          pageId: 0,
          nextPageId: 15
        }],
        pageParams: startParams
      }
    },
    {getNextPageParam: (lastPage, pages) => lastPage.nextPageId}
    {keepPreviousData: true}
  )

Update:
hasNextPage was always undefined beacause getNextPageParam and initialData were in two separated objects. I corrected it like this :
{
      initialData: {
        pages : [{
          result: vendors,
          resultCount: 495,
          pageId: 0,
          nextPageId: 15
        }],
        pageParams: startParams
      },

       getNextPageParam: (lastPage, pages) => lastPage.nextPageId
}

It now returns true but clicking on the button still erase the previous data.
Answer: I think you have the same problem as described in your update: react-query only takes one options object, where you should put all options like initialData, getNextPageParam and keepPreviousData, so something like:
useInfiniteQuery(
  'key',
  queryFn,
  {
    initialData: {...},
    getNextPageParam: () => ...,
    keepPreviousData: true,
  }
)

also, please be aware that initialData is also applied when the query key changes, because a new cache entry is created. So by supplying initialData, keepPreviousData might become irrelevant because the previous data is only shown until you have correct data for your new query key. And since initialData is persisted to the cache, it is treated as a valid response for the new query key.
if you only want to apply initialData to a specific query key (like the one that you show initially, where not filters are applied), you need to make sure of that yourselves: Set initialData to undefined for all keys where you don't want initial data, and set it to something for all the keys where you want it.
Comment: Thank you, this has gave me a better insight. I wasn't sure on how to operate your recommandation so to avoid confusion between "initialData" and new queries data, I simply replaced "getNextPageParam: (lastPage, pages) => lastPage.nextPageId" by "(lastPage, pages) => pages.length * limit" and it now seems to work...!


Ajax breaks jQuery Toggle

Question: I use a small script that hides/shows a pane when a certain element is clicked.
<code>(function($) {
Drupal.behaviors.luminary = {
    attach: function (context, settings) {
         $(".toggle-visible").click(function () {
         var targetselector = $($(this).attr('data-target-selector'));
         targetselector.slideToggle("fast");
      });
    }
}
})(jQuery);
</code>
It works well, but when an ajax event occurs, the pane will slide visible, and immediately slide invisible again. It goes down, and comes right back up. It only happens after an ajax event. Any ideas?
Answer: Change
<code>$(".toggle-visible").click(function () {
</code>
for
<code>$('.toggle-visible').unbind('click').bind('click', function() {
</code>

Ajax breaks jQuery Toggle


SyntaxError: invalid syntax data.append)=(R)

Question: Tá dando um erro de sintaxe mas acredito que não seja isso, mas não consigo identificar o que ta de errado:
```python
#retorno

df = carteira.copy()
df = df.reset_index()

colunas = df.columns
columns = list(colunas[1:])

df_rent = df(['Date'])
n = len(df_rent)

for coluna in colunas:
  data = [0]
  for idx,val in df.iterrows():
    if idx > 0:
      R = math.log(df.loc[idx,coluna] / (df.loc[idx-1,coluna])
      data.append(R)

  df_rent[coluna] = data
```

>  File "<ipython-input-109-818eeabca8c6>", line 17
    data.append(R)
       ^
SyntaxError: invalid syntax

Answer: Na linha:
...
R = math.log(df.loc[idx,coluna] / (df.loc[idx-1,coluna])
...

Há um ( que não foi fechado logo após a /.  E isto está causando o erro de Invalid Syntax.
Basta retirar este parenteses que o erro parará de acontecer:
...
R = math.log(df.loc[idx,coluna] / df.loc[idx-1,coluna])
...


What happened to Drupal's performance?

Question: I just installed Drupal 7 again on my cheap shared host. The installation went fine... I copied the 1098 files via FTP and installed it within 2 minutes. The standard installation (with all modules in the core) took about 5-10 seconds. After installing, the site runs well. It's a cheap hosting, so sometimes it's a little slow, but it's acceptable.
Yesterday, I've installed the new Drupal 8 (which is why I installed Drupal 7 today to compare). The first thing I noticed are the number of files: 12327. I understand modules like Views are included in the core now, but an increase of the number of files of over 10 times seems a little odd to me.Is there another reason for this?
Once I copied all files, I've tried to install Drupal 8. What a nightmare. The installation page takes up to 20 seconds to load. When I want to start the installation, I'm getting a notice OPcache is not enabled in PHP. Is this the reason for the slowness? Is there an alternative available?
Continuing the installation, I'm getting random errors. Searching for them on Google doesn't help getting me more information. Something about a fixed bug months ago, that's all I could find. I had to restart 3 times before the installation succeeded.
The biggest issue is the performance. Installing all these modules during the default installation took about 5-10 seconds in Drupal 7. It took about 20-30 minutes in Drupal 8. Okay, some more modules are included now, but this seems very odd. As I had to retry 3 times, it took me about 2 hours just to install Drupal 8. After installation, it was unusable slow, so I had to remove the whole installation.
I'm wondering if someone knows more about this issue. Does Drupal 8 require like 20 times more resources than Drupal 7 to run properly? Or is all of this because of the missing OPcache? Am I the only one with this issue?
Any advice would be welcome as I'd like to try the new features. Drupal 7 runs perfect on my cheap hosting, but Drupal 8 is a real nightmare.
I'm not sure what other technical information might to relevant to find/resolve this issue.
Comment: FWIW I personally would wait a version or two before deploying D8 for a live site. Even thought it's officially launched, there are still bugs lurking that are only going to be exposed by public use of the codebase. Think of the next several months as its final round of testing. The commonly-encountered bugs should be fixed in the next few releases.
Comment: You can try Drupal 8 on [simplytest.me](https://simplytest.me/) or [here](https://www.drupal.org/try-drupal).
Answer: D8 requires more resources and yes, you should have hosting with opcache enabled, which is included by default in PHP 5.5.
Drupal 8 has so many files because it includes symfony and other projects and everything is a class.
FTP is a very bad idea for D8 and web in general in 2015. Look for a better way to do web hosting.
That said, it should not take that long. I suggest you open a bug report  and provide as many details as you can about your specific PHP version, hoster, the errors that you had, ..
Comment: Git or another version control system for example. As checkout on the server (needs ssh access) or using the push based deployment processes that platform.sh/acquia dev cloud/pantheon offer. Or custom deployment processes with one of the various available tools. Anything but FTP (SFTP is the same, just encrypted). I guarantee that using FTP with Drupal 8 will frustrate you.
Comment: "FTP is a very bad idea for...web in general in 2015" - what do you mean by that? How would you transfer files? SFTP?
Comment: > I thought you meant something like "Don't use FTP anymore" - yes, that's a good idea!
Comment: Ah, understood, when you said "web in general" I thought you meant something like "Don't use FTP anymore" - but I agree, if it's a project like this that's in a repository, it's better to clone that repo on the server as opposed to downloading it elsewhere and then uploading it via FTP

What happened to Drupal's performance?


Ajax Submitted forms with ENTER

Question: I have this code:
function THEME_form_user_login_alter (&$form, &$form_state){
  $form['actions']['submit']['#ajax'] = array(
        'callback' => 'ajax_process_form',
        'wrapper' => 'user-login',
        'effect' => 'fade',
        'speed' => 'fast',
        'method' => 'replace'
    );

};

It work when i click on the submit button, but when i press ENTER Ajax doesn't get triggered.. Is there a way around that?
Edit: I tried to enable ajax on all fields and set keystroke to True, but then only one field is sent so i get an error as the form process script is expecting two fields.
Comment: I actually had to remake the AJAX function manually with some good old jQuery, and then I finally had a normal behavior.
Answer: I realize this is an old thread but it shows up high in the Google search results.
Just set your submit button's Ajax event to 'click'. I believe its default value is actually 'mousedown' which won't make it trigger when the enter key is pressed within a field of the form.
If you set it to 'click', that event will trigger when the submit button is clicked as well as when the enter button is pressed within a form field.
Answer: Just make sure you explicitly set ajax event to click and it'll work:
$form['actions']['submit']['#ajax'] = array(
    'callback' => 'ajax_process_form',
    'wrapper' => 'user-login',
    'effect' => 'fade',
    'speed' => 'fast',
    'method' => 'replace',
    // This is what you need:
    'event' => 'click'
);

Answer: I haven't tried this, but you should be able to set the event on ajax to include keydown:
function THEME_form_user_login_alter (&$form, &$form_state){
  $form['actions']['submit']['#ajax'] = array(
    'callback' => 'ajax_process_form',
    'wrapper' => 'user-login',
    'effect' => 'fade',
    'speed' => 'fast',
    'method' => 'replace'
    'event' => array('click', 'keydown'),
  );
}

I'm not sure how well keydown will work on a submit button, usually you want something more complex that makes sure that the matched key is Enter. Alternatively you could catch the Enter submit yourself and prevent default (form submit) and the click the button yourself. That would trigger the ajax call like it was clicked and would keep the Drupal powered AJAX intact, which makes things easier to handle server side.
Comment: Hi Googletorp, the keydown is useful only when the focus is on the element, in that case the submit button, so unless the user tabs out of the fields this is a pretty unlikely scenario. (i also tried adding a keydown on field, it was very odd..) I think like you said catching the Enter Keydown manually seem to be the only way to go.

Ajax Submitted forms with ENTER


Attach an image gallery carousel to nodes

Question: I want to attach an image gallery to a node, showing the images in a carousel view so that only a few thumbnails are shown and clicking on them opens a ColorBox overlay.
I have a gallery content type that contains all images in a field, and in an article the gallery is referenced using an entity reference field.
I found the Gallery Formatter module which does nearly want I want. But I don't want to display the large image on the page, only the carousel showing thumbnails. To get the full size image one should click on one of the thumbnails.
So I need a field formatter that can display the contents of an image field as a carousel. Any ideas on how I can achieve this?
Answer: Check out Adding a jQuery Image Carousel to your Node View.
Though the above article is for Drupal 6, you can follow this like below:

As the gallery is referenced in the "Article" content type, you can modify the template file for that content type, and fetch the gallery images.
After that, you can display that in carousel.

The other way is using a theme preprocess function.
function YOURTHEME_preprocess_node(&$variables) {
  // Your code.
}

Answer: I had the same problem recently, the best solution i think is to  use this module Field Slideshow. Read about it, what you need is to install this module, then u need to create two image styles for thumbnails and for image. In your content type in Manage Display settings u can configure your carousel. Also u need to install this modules
Libraries API,
Jquery Cycle plugin, JCarousel

you can read about this module here
Answer: You can achieve this with the Lightbox2 module. Check out the Grouped images example.