How to display recent posts in django

Question: Here is the case, I need the last records of the model to be displayed on the page, for this I added a new pub_date record in the models to add to the queue of records, I also added this to views.py, and it kind of displays, but both records.
views.py code
class IndexView(generic.ListView):
template_name = 'Homepage/index.html'
model = Goods
context_object_name = 'goods'

def description(self):
    return self.description_text

def price(self):
    return self.price_text

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    numbers = Number.objects.all()
    context['numbers'] = numbers
    return context

def get_context_data(self, **kwargs):
    context = super().get_context_data(**kwargs)
    avaibilitys = Avaibility.objects.order_by('-pub_date')
    context['avaibilitys'] = avaibilitys
    return context

models.py code
class Avaibility(models.Model):
name_text = models.CharField(max_length=200)
apply_text = models.CharField(max_length=200)
presence_text = models.CharField(max_length=200)
pub_date = models.DateTimeField('date published', null=True)

def __str__(self):
    return self.name_text

def __str__(self):
    return self.apply_text

def __str__(self):
    return self.presence_text

this is what displays
Comment: Hello, I think your question does not make much sense as it stands now.  At least  not to me I cannot understand it. Please provide some more connect or make a dummy example what are your classes where and how are they being called. What class does your get_context_data(() belongs to for example? What is your error exactly?Provide some more info so people can help. Cheers
Comment: Does the image show the result of `Avaibility` or `Number`?
Comment: Does it not word as you intended?
Comment: @bichanna not it doesn't, I want the last posts to be shown on the page, and both posts are displayed
Comment: @KZiovas I edited the post, do you need more information? or is it full?
Comment: @bichanna She results Avaibility
Comment: Please see my answer then.
Comment: Did you solve your problem?
Comment: @bichanna Shows this error 'Avaibility' object is not iterable. Here is the line `{% for avaibility in avaibilitys %}`
Comment: Since you need only one availability, you don't need to loop through anything.
Answer: You are just sorting the data using order_by and assign the sorted data to a variable:
avaibilitys = Avaibility.objects.order_by('-pub_date')

If you want to get only one of them, you can do this:
avaibilitys = Avaibility.objects.order_by('-pub_date').first()

EDIT
If you want the last one, do this:
avaibilitys = Avaibility.objects.order_by('-pub_date').last()

Comment: By the way, if anybody wants to get the last object, use `last()`.
Comment: @bichanna Shows this error 'Avaibility' object is not iterable. Here is the line `{% for avaibility in avaibilitys %}`
Comment: You wanted only the first one, right? Or no?
Comment: You said `I need the last records of the model to be displayed on the page`.
Comment: @bichanna No, I need the last entries, not the first

How to display recent posts in django


The series $\sum_{n=0}^\infty \frac{(-\beta)^n}{n!}\Gamma\left(\frac{n+1}{2},\alpha\right)$

Question: I've worked out the solution to an integral which involves the following expression:
$$\sum_{n=0}^\infty \frac{(-\beta)^n}{n!}\Gamma\left(\frac{n+1}{2},\alpha\right)$$
Where $\Gamma(s,z)$ is the upper incomplete gamma function. My question is: is there a convenient non-series expression for this (i.e. an expression in terms of known special functions?). Note that it is very similar to the multiplication theorem given on the Wikipedia page (unfortunately I couldn't find a better source) for the incomplete gamma function, which states:
$$\Gamma(s,z) =\frac{1}{t^s}\sum_{n=0}^\infty \frac{\left(1-\frac{1}{t}\right)^n}{n!}\Gamma\left(s+n,tz\right)$$
If that helps at all. Thanks!
Answer: Using:
$$\Gamma (a,z)=\int_z^{\infty } x^{a-1} \exp (-x) \, dx$$
we have:
$$\color{blue}{\sum _{n=0}^{\infty } \frac{(-\beta )^n \Gamma \left(\frac{n+1}{2},\alpha \right)}{n!}}=\\\sum _{n=0}^{\infty } \frac{(-\beta )^n \int_{\alpha }^{\infty }
   x^{\frac{n+1}{2}-1} \exp (-x) \, dx}{n!}=\\\int_{\alpha }^{\infty } \left(\sum _{n=0}^{\infty } \frac{(-\beta )^n x^{\frac{n+1}{2}-1} \exp (-x)}{n!}\right) \,
   dx=\\\int_{\alpha }^{\infty } \frac{e^{-x} \sum _{n=0}^{\infty } \frac{x^{n/2} (-\beta )^n}{n!}}{\sqrt{x}} \, dx=\\\int_{\alpha }^{\infty } \frac{e^{-x-\sqrt{x} \beta }}{\sqrt{x}} \, dx=\\\int_{\sqrt {\alpha}}^{\infty }\!2\,{{\rm e}^{-t \left( t+\beta
 \right) }}\,{\rm d}t
=\color{blue}{\\e^{\frac{\beta ^2}{4}} \sqrt{\pi } \text{erfc}\left(\sqrt{\alpha }+\frac{\beta
   }{2}\right)}$$


How to change cross country ski bindings

Question: I bought used cross country skis that have SNS Pilot bindings on them, and I also bought NNN boots. What equipment do I need to swap the SNS bindings for NNN bindings? And how do I do it?
I've searched the web, and I found many results about how to mount bindings on new skis, but I couldn't find any instructions for swapping bindings on used skis.
In particular, if there is epoxy, do I need a solvent to release the epoxy?
Answer: It is possible, but not recommended to change the attacks on cross-country skis.
The holes of sns attacks ("Salomon") are in a different position from the attacks nnn ("Rottefella"), then you should first fill the holes with cylindrical woods plugs (watch out the dimensions) and glue.
After the ski is like the original situation you can mount new bindings.
For epoxy resin now there are solutions to be used even without solvent, only after it is mounted leave it to dry for a long time in hot, dry conditions
Obviously if you can go to a professional you have more possibility to get a well done job
Answer: Salomon (and others?), as of 2016, makes NNN compatible bindings (and boots) under the "ProLink" name in addition to their SNS offerings. I believe that ProLink bindings have the same mounting screw holes as SNS bindings, so that might be an easier option than filling screw holes.
See http://xcskiforum.com/viewtopic.php?t=4865 for some discussion and this note from Atomic https://www.atomic.com/en/sns-bindings


Assigning value to list elements in for loop, list names depending on loop

Question: I have the following problem. I am working with two for loops (running over i and j) and use the assign function to create lists whose names depend on i and j. Now, in another for loop withing the two loops, i want to fill my created lists with rasters, namely 19 rasters. However, I am failing to call my lists as they depend on i and j, thus, I am not able to fill them.
At the end, I would like to have 25 lists carrying the names rasterList_10N_010E, rasterList_20N_010E,... that each have 19 entries with the respective rasters.
Below you find my code. I have dropped lines not important for my problem (I actually generate the rasters I want to store in my lists depending on i and j within the loops, too).
for(i in 1:5){
for(j in 1:5){
nam <- paste0("rasterList_", i*10, "N_0", j*10, "E")
assign(nam, list())

  for (k in 1:19){
     raster_test <- raster(ncol=36, nrow=18, xmn=-1000, xmx=1000, ymn=-100, ymx=900)
    #here the list with the name nam should be standing
    rasterList_10N_010E[[k]] <- raster_test
      }
    }
  }

I have tried solutions using
eval(as.name(nam))[[k]] <- raster_test

and
as.name(nam)[[k]] <- raster_test

but it did not work. I believe that the problem may be that the approach is not very R-like (I have just recently changed from Stata to R)?
Thanks!
Comment: Please forget that you've ever heard about the functions `assign` and `eval`. They are completely inadequate to solve such issues and make the the code vastly more complex for no gain.  Use named lists instead. (This type of questions is incredibly common here, and the use of `assign` and `eval` in this context is *never* the right answer; these functions are intended for very different purposes.)
Answer: Instead of creating 25 single lists I would suggest to put your lists into one list like so:
Note: I have set k = 2 for simplicity.
library(raster)
#> Loading required package: sp

rasterList <- list()

for (i in 1:5) {
  for (j in 1:5) {
    name <- paste0(i * 10, "N_0", j * 10, "E")
    rasterList[[name]] <- list()
    for (k in 1:2) {
      raster_test <- raster(ncol = 36, nrow = 18, xmn = -1000, xmx = 1000, ymn = -100, ymx = 900)
      rasterList[[name]][k] <- raster_test
    }
  }
}

length(rasterList)
#> [1] 25

rasterList[["10N_010E"]]
#> [[1]]
#> class      : RasterLayer
#> dimensions : 18, 36, 648  (nrow, ncol, ncell)
#> resolution : 55.55556, 55.55556  (x, y)
#> extent     : -1000, 1000, -100, 900  (xmin, xmax, ymin, ymax)
#> crs        : NA
#>
#>
#> [[2]]
#> class      : RasterLayer
#> dimensions : 18, 36, 648  (nrow, ncol, ncell)
#> resolution : 55.55556, 55.55556  (x, y)
#> extent     : -1000, 1000, -100, 900  (xmin, xmax, ymin, ymax)
#> crs        : NA

And if still necessary you could get your 25 lists afterwards like so:
lapply(names(rasterList), function(x) assign(paste0("rasterList_", x), rasterList[[x]], envir = .GlobalEnv))

Created on 2022-01-05 by the reprex package (v2.0.1)


two threads entering the two different synchrnozied method at same time on instance level lock

Question: I was ask in an interview that with respect to multi threading , Suppose you have 2 threads (Thread-1 and Thread-2) on same object. Thread-1 is in synchronized method1(), can Thread-2 enter synchronized method2() at same time in java by any way .
I replied no  No, here when Thread-1 is in synchronized method1() it must be holding lock on object's monitor and will release lock on object's monitor only when it exits synchronized method1(). So, Thread-2 will have to wait for Thread-1 to release lock on object's monitor so that it could enter synchronized method2().
but still please advise is there any way by which Thread-2 ,enter synchronized method2() at same time in java by any way is there any hack if to achieve this thing
below is my program , rite now I have changed the implementation now please advise on this as the output of the below program is
inside M1()
t1--->RUNNABLE
inside M2()
t2--->RUNNABLE

below is my updated code
public class Test {

     private final Object lockA = new Object();
     private final Object lockB = new Object();

    public  void m1() {
         synchronized(lockA) {
        try {
            System.out.println("inside M1()");
            Thread.sleep(100);
        }
        catch (InterruptedException ie)
        {}
         }
    }

    public  void m2() {
        synchronized(lockB) {
        try {
            System.out.println("inside M2()");
            Thread.sleep(100); }
        catch (InterruptedException ie) {}
    }
    }

    public static void main(String[] args) throws InterruptedException {
        final Test t = new Test();
        Thread t1 = new Thread()
        { public void run() { t.m1(); } };
        Thread t2 = new Thread()
        { public void run() { t.m2(); } };

        t1.start();
        //Thread.sleep(500);

        t2.start();
      //  Thread.sleep(500);

        System.out.println("t1--->"+t1.getState());
        System.out.println("t2--->"+t2.getState());
    }
}

Comment: duplicate with [Do two synchronized methods execute simultaneously](http://stackoverflow.com/questions/3160023/do-two-synchronized-methods-execute-simultaneously)
Comment: There is still no evidence here that both threads have acquired the same lock at the same time. What you are suggesting is basically inconceivable.
Comment: @EJP  , Thnaks but please advise how you can simply prove that which lock is acquired is there any way to see the lock name please advise
Comment: @Ejp Please check tis solution too http://stackoverflow.com/a/15438792/5254989
Answer: Notice that in your example threads are not competing on any thing even if MyRunnable1 class had a single method1() and your run() function was calling on this method in loop. Because thread1 and thread2 are different instances and each one has it's own copy of method1() so the locks used by synchronized are different and not one single lock.
Comment: I disagree with you because he uses single runnable, which uses same lock. The method is also shared, no other copy.
Comment: You are correct i did not notice that sorry my mistake
Answer: Two threads cannot hold the same lock at the same time. However, just because a thread is inside a synchronized method for an object, it does not follow that it holds the lock. For example, it could call await on a condition variable and release the lock while it's waiting. That allows other threads to acquire the lock by entering synchronized methods -- after all, that's what you're waiting for.
Comment: The only correct answer in this thread and the only one with a down vote...
Answer: You code is like the following:
void method1(){
      synchronized(this) {
           //...
      }
}

synchronized void method2(){
      synchronized(this) {
           //...
      }
}

And In your code, two threads can't enter two method at the same time for the lock contention. You can only do it on different instances of runnable i.e. different this.
Comment: This is not correct. See my answer -- one of those `//...` could contain code that releases the lock and lets another thread enter a `synchronized` block.
Comment: @DavidSchwartz I say in his old code sample, he can't do it except use different instance. :)
Answer: You have got the understanding correct, that every object has lock associated with it, and once Thread1 takes the lock to access synchronized method1, then Thread2 cannot access synchronized method2.
Now,coming to special case, you can always do a simple hack. Imagine Thread1 has the lock, and is accessing synchronized method1. Inside method1, if Thread1 calls wait on a variable, then it releases the lock on the object and goes to wait state. In this scenario, Thread2 can acquire the lock and enter synchronized method2. Hence, both the threads have access to different synchronized methods on same obj.
P.S. This is just for example, I would not recommend have another wait inside a synchronized block, it will lead to unnecessary complication. If any code has to do this, then it means there is flaw in logic and design.


Multiple internet connections and single firewall appliance

Question: The company that I work for has three internet connections. We're planning to install a single firewall appliance that covers all of the three connections.
I can theoretically imagine it being done by connecting all of the network lines to a single very very expensive appliance.
However, I would like to use an OpenSource solution for eg opensense or pfsense.
So I will need to assemble my own hardware.
What would be the most effecient way to do this without having to buy enterprise grade firewall appliance?
Comment: Why do you want a single point of failure?
Comment: @kasperd that's a good question. It's mainly the cost or deployment and maintenance. Also I'd like a more centralized management.
Answer: As for my experience, I can tell you that no cheap nor expensive hardware would lead you to the same performance as the embedded UTM appliance. I tried Endian both as VM and on bare metal. There's no chance it will ever perform fast as their UTMs.
I can suggest you to try the way of opensource (pfsense is a good choice too) but you'll have to see if it works well with your environment.
Many functions such as content filtering/antivirus on the http(s), or such as traffic shaping, mail proxy etc will become slow in a big environment. With Endian I experienced damn slow proxy with less than 30 clients!
If they have both free community supported software and enterprise grade hardware appliances, there should be a difference! Otherwise the price of 4-5-10000€ for their HW appliances won't be justified, compared to free ISO that can run on every 10 years old PC.
So to answer your question, if you want to go the cheap way use free software and HW you already have, but consider that you will have to give tests their time before putting such a solution in production.
Both distros mentioned here are multi-uplink ready. You can setup multi WAN having one NIC for the red side and handle routers through a managed switch using VLANs (supported by both distros) or you'll need one NIC per router. I suggest the first one. Then, you'll use your multiple WANs defining either a failover policy or a policy routing ruleset, or preferably both!
Comment: thanks for your suggestion. :) But how about connecting multiple WANs to the firewall?
Comment: Both distros mentioned in my answer are multi-uplink ready. You can setup multi WAN having one NIC for the red side and handle router through a managed switch using VLANs (supported by both distros) or you'll need one NIC per router. I suggest the first one. Then, you'll use you multiple WANs defining either a failover policy or a policy routing ruleset, or both, too!
Comment: Did you find my answer exhaustive or you're looking for further informations?
Comment: We bought an old Dell R710 and threw 128GB of RAM into it to run pfSense. It outperforms any appliance that you could purchase.

When you use pfSense, I recommend getting the Gold subscription. for $100 / year, you have automatic backups of your configuration (read: 1 hour rebuild) and you get access to the indepth documentation. You'll need to read up on multi-homed routing.
Comment: @Marco I'm still looking for answers. : ) .
Comment: @NonSecwitter thanks for your suggestion. I am more inclined towards opensense but will definitely consider your suggestion.


Lightest way to control a field's markup

Question: So far I have used Display Suite to control the output of entities. This especially applied to node's fields which by default receive multiple wrappers (like field-items, field-item, zebras and such) which I don't need. Correct me if I'm wrong, but I would say that installing Display Suite only for that purpose is a big overhead. If you agree on that, what would then be the lightest way to get exactly the markup I want?
Answer: Yes I think Display Suite is quite an overhead just to control field markup. You could obviously overwrite the templates manually, but for a quicker solution there's the excellent Fences module

Fences is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!

The difference in markup is huge. From

Foobar field:

Leaner markup means better front-end performance.

to

Foobar field

Leaner markup means better front-end performance.

Comment: Your answer had more examples. I'm pressed for time, vanpool :).
Answer: Consider the Fences module. Here is a quote about it (from the module's project page):

... is a an easy-to-use tool to specify an HTML element for each field. This element choice will propagate everywhere the field is used, such as teasers, RSS feeds and Views. You don't have to keep re-configuring the same HTML element over and over again every time you display the field.
Best of all, Fences provides leaner markup than Drupal 7 core! And can get rid of the extraneous classes too!
This kind of tool is needed in order to create semantic HTML5 output from Drupal. Without such a tool, you have to create custom field templates in your theme for every field.
Similar projects include Semantic fields, Field Wrappers and a tool inside the Display Suite extras.

You can also just create your own field formatters.


PHP - Count downloads

Question: I'ld like to count file downloads with PHP. The downloads number should be stored in a .TXT file.
How that can be done?
Comment: Related: http://stackoverflow.com/questions/146/how-do-i-track-file-downloads-with-apache-php - I particularly like grep'ing the access.log
Comment: I've edited the code to include an initial variable initialization that was previously rendered invisible by the code formatter. Also, I changed the $count++ to ++$count, in order to increment **before** writing and also treated the initial case when no file yet exists.
Comment: See also: https://dave.autonoma.ca/blog/2023/11/12/php-download-hit-counter/
Answer: $current_count = file_get_contents('count');
$f = fopen('count', 'w+');
fwrite($f, $current_count + 1);
fclose($f);

header("Location: file.zip");

Comment: what about if the file download get's interrupted ? It will also count ad download ?
Comment: @daslicht Yes, it will count as a download. What the code does is 1) increases a counter 2) redirects a user to the file to be downloaded. If a user chooses not to press 'save' or 'download' after prompted, it will still be counted in as if they would download it.
Answer: Create a file named, say, download.php, with the following content:
<?php
 $Down=$_GET['Down'];
?>

  <meta http-equiv="refresh" content="0;url=<?php echo $Down; ?>">

 <?php

  $filePath = $Down.".txt";

  // If file exists, read current count from it, otherwise, initialize it to 0
  $count = file_exists($filePath) ? file_get_contents($filePath) : 0;

  // Increment the count and overwrite the file, writing the new value
  file_put_contents($filePath, ++$count);

  // Display current download count
  echo "Downloads:" . $count;
 ?>

Put a link to it in another page, with the file to be downloaded as a parameter:
download.php?Down=download.zip
Answer reference Dreamincode answer to a similar question
Comment: Be careful, if you have your website in the internet! Everbody could download everthing from your server with this solution.
Comment: @knobli That is not true - this implementation only puts redirect between link to the file and actual file, AFAIK no new security risks are introduced.
Comment: what about if the file download get's interrupted ? It will also count ad download ?
Comment: This looks great but the counter isn't working. Anything I missed? The .txt file starts with "0" counts and a CHMOD 777.
Comment: @Uli What should exactly do after creating download.php file?
Comment: @FanaticD The file that gets downloaded is determined by the $get which in turn, is determined by the URL. An attacker could just modify the URL to get whatever file whose filename they could guess or see.  Genesis's solution shown below is more secure.
Comment: @Michael In my original comment, I was wrong. There are additional issues introduced. But you are still not quite correct about where they are. There is a reflected XSS (rendering unsanitized input from URL directly into the page) and an unvalidated redirect. You and @knobli are misunderstanding how `meta refresh` works though. An attacker can modify the URL to whatever file they want, but it will not force the download of that file. It will only redirect the user to that file (if the file is let's say .php, **it will not be downloaded**, but executed).
Comment: @Michael If you'd like to discuss this more, we can do so in [chat.stackoverflow.com](https://chat.stackoverflow.com/rooms/11/php) (PHP room).

PHP - Count downloads


Expressão lógica que controla repetição

Question: Estou resolvendo um exercício em Python que pede ao usuário que dê um palpite, sobre qual número o programa obteve para pc aleatoriamente.
from random import randint
tent = int(input('PALPITE:'))
pc = randint(0,4)
cont = 0
while tent != pc:
    pc = randint(0,4)
    tent  = int(input('Você errou! o numero que o pc escoheu foi {}.  Tente novamente '.format(pc)))

print('Parabens!Você acertou! o Número que o o computador escolheu foi {}.'.format(pc))

O código até que funciona, mas quando eu acerto o número ele diz que está errado. Quando eu coloco o input que está dentro do while para ser executando antes (em vez de randomizar o número primeiro) o resultado dá certo.
Sei que isso tem a ver com a estrutura sequencial, mas eu achei que se eu utilizasse o randint na variável pc dentro do while primeiro daria o mesmo resultado.
Por que isso acontece? Tem a ver com a expressão lógica lá em cima? É obrigatório eu ter recebido o valor do input dentro da variável primeiro para depois o Python analisar?
Comment: A resposta resolveu sua dúvida? Acha que pode aceitá-la? Veja o [tour] se não souber como faz. Isso ajudaria muito indicar que a solução foi útil para você. Também pode votar em qualquer pergunta ou resposta que achar útil no site todo
Answer: O código é um pouco confuso e comete um erro que eu sempre vejo por aí. Um iniciante comete por desconhecer e o experiente comete porque acha que não pode usar nenhuma forma de goto, aí ele fica com raiva do break que faz isso e pra evitá-lo, faz código repetitivo que piora a chance de boa manutenção (nem tanto em código simples assim, mas vai ensinando a pessoa fazer errado em casos mais complexos).
Então só vou pedir o palpite dentro do laço, uma única vez. E vou separar o pedido de palpite da mensagem de erro. Quando errar, a mensagem aparece e pede o palpite novamente. Quando acertar encerra o laço e diz que acertou.
Estou imaginando que em cada tentativa deve ser sorteado outro número, caso deve ser o mesmo então o sorteio deveria estar fora do laço. Tinha um contador não usado que eu tirei, se iria us-a´lo mesmo aumenta a chance de que o sorteio deveria ser único e não mudar a cada tentativa.
Simples e limpo:
from random import randint

while True:
    pc = randint(0, 4)
    tent = int(input('PALPITE:'))
    if tent == pc:
        break
    print('Você errou! O número que o PC escolheu foi {}. Tente novamente '.format(pc))
print('Parabens! Você acertou! O número que o computador escolheu foi {}.'.format(pc))

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Com contador talvez fosse assim:
from random import randint

pc = randint(0, 4)
contador = 0
while True:
    contador += 1
    tent = int(input('PALPITE:'))
    if tent == pc:
        break
    print('Você errou! Tente novamente '.format(pc))
print('Parabens! Você acertou em {} tentativas! O número que o computador escolheu foi {}.'.format(contador, pc))

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.

Expressão lógica que controla repetição


For each image uploaded in a node: get the url

Question: I'm begining with Drupal 8 and I want to get the url of the photos in the content I create to display them.
 The context is : a photograph upload pictures for a customer. This customer can see it on a page. To get this data in common I created a content for my shooting with an id.
 What i did is :
$photos = $shooting->field_shooting_photos->target_id;

This allow me to get the id of every pictures uploaded.
Now I want to do a foreach on $photos in my .module that will return every url in an array.
Then I will use this array in my Twig and do a foreach on it too to return every photos.
I just can't figure out how to do, I think I will have to use something like that
$path = $photo_id->getFileUri();

but I can't figure out the syntax to get it into an array.
Thank you for your help!
Solution :
Here is what I did in case it can help someone :
$photosTest = $shooting->field_shooting_photos->referencedEntities();

$photoUrls = [];

foreach($photosTest as $media) {
  $photoUrls[] =
  $photoUrls[] = [
      'render' => [
         '#theme' => 'image_style',
         '#style_name' => 'medium',
         '#uri' => $media->field_media_image->entity->getFileUri()
       ],
       'href' => $media->field_media_image->entity->getFileUri(),
     ];
}

In my Twig file I render the array :

 {% for photo in photos %}
    {{ photo.render }}
 {% endfor %}

Answer: Giving field_shooting_photos is a multi valued field of Files, this is how to generate your array of URI :
$photoUrls = [];
foreach($shooting->field_shooting_photos->referencedEntities() as $image) {
    $photoUrls[] = $image->getFileUri();
}

For media image :
$photoUrls = [];
foreach($shooting->field_shooting_photos->referencedEntities() as $media) {
    $photoUrls[] = $media->field_media_image->entity->getFileUri();
}

Note this will give you the File_id of the first image in the entite file reference list :
$shooting->field_shooting_photos->target_id;

NB : Best way is probably to generate render array or use built-in drupal themes, is none fit your needs, your may also generate a custom field formatter.
Comment: Are you trying to render this array directly in your twig file ? That's not the way to render medias and/or images in drupal (have a look at my NB). Have a look at https://www.drupal.org/docs/8/api/render-api/render-arrays and https://drupal.stackexchange.com/questions/251844/render-media-entity-image.
Comment: thank you, i'm trying your solution but I get a Call to undefined method Drupal\media\Entity\Media::getFileUri(), I probably need to do a load first no ?
Comment: That's why i said "Giving field_shooting_photos is a multi valued field of *Files*" you get an iterable of Media, so you have to deal with medias instead of File. I update my answer in few time.
Comment: Okay thank you, I'm searching on still
Comment: I gave you the piece of caode for media references in this answer.
Comment: Yes I'm testing it and it's indeed working better now, yet I still get some errors such as `Trying to get property 'field_media_image'/'entity' of non-object` and `"0"/1"/"2"/"3" is an invalid render array key` -> This refer to the number of photos uploaded on the photograph page. And the kint of `$shooting->field_shooting_photos->referencedEntities()` I do have the field_media_image
Comment: Yeah my bad I forgot that I put this variable like this in my Twig yesterday. Imma fix that, thanks for the help!


How to provide a dynamic (calculated) css property

Question: I am working on task in which each time a user scrolls or resizes the screen I would like to recalculate a css properties for an element.
Let's say I want to impl. a progress bar and the progress is reported based on the scroll position in the window

function updateScrollProgress () {
   this.progressIndicator.css('width', this.calculateProgressBarWidth() + 'px');
}

I tried to hook on scroll and resize events, but this seem to have a laggy effect.
window.on('scroll', updateScrollProgress)
window.on('resize', updateScrollProgress)

I tried in the scroll and resize event handlers to requestAnimationFrame
window.on('scroll', function(){window.requestAnimationFrame( updateScrollProgress))
window.on('resize', function(){window.requestAnimationFrame( updateScrollProgress))

And experienced huge improvement in most browsers, however it is yet occasionally laggy.
I tried to request another frame, when from the requestAnimationFrame handler:
function updateScrollProgress () {
   window.requestAnimationFrame( updateScrollProgress)
   this.progressIndicator.css('width', this.calculateProgressBarWidth() + 'px');
}

This completely eliminated the laggy effect, but comes to the cost of endless loop of calls to this method, even when no recalculations are needed.
Is there a way to hook a handler just before the browser decides to draw element(s), so that I can provide/set the those "dynamic" css values for a property?
Comment: If you've gotten rid of the lag, why is the handler being called "too often"? Usually, "too often" in this context means "is causing lag" (by running too often and thus slowing things down).
Answer: What's what you're doing when you use requestAnimationFrame. If you've gotten rid of the lag using it, it's unclear why you say the function is running "too often." Usually in this sort of context, "too often" means "is causing lag" (by running too often and slowing things down). If yours isn't, then...?
If you want the handler called less often, you can debounce it, but then you'll probably notice delays before the changes you want (because you've debounced), which it sounds like is what you're trying to avoid.
In any case, requestAnimationFrame is, for now at least, the right tool for the "just before the browser renders the frame" job.
Comment: Hope it will make it through. Unfortunately I failed to find such/similar hook to get the job done at this point. But thanks for trying with me :)
Comment: Ok, I will provide some example code. The thing is that I would like to somehow provide a different css value, just before the browser is deciding to render. Let's say I would like the height to be a function of the document scroll position for instance
Comment: @Nas - That's what `requestAnimationFrame` is: A callback just before the browser renders a frame.
Comment: But when to hook?? And execute only when a reflow of the elements is there
Comment: @Nas - Whenever you need to make a change. So if this is all based on scrolling, I'd hook the scroll event, do the calculation, and if the value is different from the last value I've used, I'd schedule a rAF callback to use that new value, and remember I'd used it. If that's too laggy for you, then waiting for the scroll event is apparently too late. If so, just always being in the rAF cycle (hooking it on load and rehooking every time) is what you'll have to do. Keep the calculation as short as possible, but it's once every 16.6ms on average where your function is probably running in micros..
Comment: Thanks - unfortunately endless loop of rAF callbacks yields the best results for now..
I was wondering if I can hook it right before the browser need to redraw and element as alternative to endless loop..
Comment: @Nas - Again, that's what you're doing when you call rAF (but only on a full-page level, I think I may see what you mean about an element-specific callback). It would appear that for whatever reason, the `scroll` event is happening too late for you, hence the `scroll`+rAF not being good neough. There's some work being done on extension points *within* the rendering stuff, but it's at least a couple of years off. I wish I could find the page I was reading about it on to show you...
Comment: Well I noticed that when I do the options with the endless looping and do a console log the code gets constantly being executed.

So What I want is not to always request another frame, but whenever for some reason a new reflow is triggered - when something causes a redrawing to hook my code..
Comment: So basically I do not want to request animation frame. I want animation frame to request me :P
Comment: @Nas :-) Which is, I believe, exactly the kind of hook being considered. Drat, I wish I could find that page...
Comment: @Nas - **Found it**: https://drafts.css-houdini.org/worklets/ I haven't had a chance to read it yet and so it may not be relevant to your problem, but...
Answer: Wrap your event function through a debounce function:
More info on debounce functions here:
https://davidwalsh.name/javascript-debounce-function
function debounce(func, wait, immediate) {
  var timeout;
  return function() {
    var context = this, args = arguments;
    var later = function() {
      timeout = null;
      if (!immediate) func.apply(context, args);
    };
    var callNow = immediate && !timeout;
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
    if (callNow) func.apply(context, args);
  };
};

var myEfficientFn = debounce(function() {
  // All the taxing stuff you do
}, 250);

window.addEventListener('resize', myEfficientFn);

Comment: Thanks, but I want to remove the laggy effect, unfortunately debouncing it will have the opposite effect :(
Comment: the lag is usually caused by the event handler being called several times a second so debouncing usually fixes this, for me at least.
Comment: Thanks, but in this case the lag is caused by handler being called late. Unfortunately debouncing will only make the call to be even later and hence prolong the lag :(


Node.js v6.2.2 crypto.createCipheriv "Invalid key length" Error

Question: Below is the source for multipassify.
The code works perfectly below Node 6 and gives an error onward.
The error looks like this:
crypto.js:184
  this._handle.initiv(cipher, toBuf(key), toBuf(iv));
               ^

Error: Invalid key length
    at Error (native)
    at new Cipheriv (crypto.js:184:16)
    at Object.Cipheriv (crypto.js:182:12)
    at multipassify.encrypt (/Users/thomasreggi/Desktop/super-octopus/node_modules/multipassify/multipassify.js:52:25)
    at multipassify.encode (/Users/thomasreggi/Desktop/super-octopus/node_modules/multipassify/multipassify.js:28:27)
    at Object.<anonymous> (/Users/thomasreggi/Desktop/super-octopus/multi.js:8:26)
    at Module._compile (module.js:541:32)
    at Object.Module._extensions..js (module.js:550:10)
    at Module.load (module.js:458:32)
    at tryModuleLoad (module.js:417:12)

Here's the source.
var crypto = require('crypto');

var BLOCK_SIZE = 16;

var multipassify = module.exports = function(secret) {
    if (!(this instanceof multipassify)) return new multipassify(secret);
    if (!(typeof secret == 'string' && secret.length > 0)) throw new Error('Invalid Secret');

    // Use the Multipass secret to derive two cryptographic keys,
    // one for encryption, one for signing
    var hash = crypto.createHash("sha256").update(secret).digest('binary');
    this._encryptionKey = hash.substring(0, BLOCK_SIZE);
    this._signingKey = hash.substring(BLOCK_SIZE, 32);
    return this;
};

multipassify.prototype.encode = function(obj) {
    if (!obj) return;

    // Store the current time in ISO8601 format.
    // The token will only be valid for a small timeframe around this timestamp.
    obj["created_at"] = new Date().toISOString();

    // Serialize the customer data to JSON and encrypt it
    var cipherText = this.encrypt(JSON.stringify(obj));

    // Create a signature (message authentication code) of the ciphertext
    // and encode everything using URL-safe Base64 (RFC 4648)
    var token = new Buffer(cipherText + this.sign(cipherText),'binary').toString('base64');
    token = token.replace(/\+/g, '-') // Replace + with -
        .replace(/\//g, '_'); // Replace / with _

    return token;
};

multipassify.prototype.generateUrl = function(obj, domain) {
    if(!domain) return;
    return "https://" + domain + "/account/login/multipass/" + this.encode(obj);
};

multipassify.prototype.sign = function (data) {
    var signed = crypto.createHmac("SHA256", this._signingKey).update(data).digest('binary');
    return signed;
}

multipassify.prototype.encrypt = function(plaintext) {
    // Use a random IV
    var iv = crypto.randomBytes(BLOCK_SIZE);
    var cipher = crypto.createCipheriv('aes-128-cbc', this._encryptionKey,iv);

    // Use IV as first block of ciphertext
    var encrypted = iv.toString('binary') + cipher.update(plaintext, 'utf8', 'binary') + cipher.final('binary');
    return encrypted;
}

I've tried messing around with converting the hash and this._encryptionKey to binary. Using this github issue as a guide but I'm having no luck trying to get this working with Node 6. Anyone know an easy way to get this working with later versions of node?
Comment: Have you printed the key and iv length just prior to being used?
Comment: @zaph the lengths for `iv` and `this._encryptionKey` are `16`.
Answer: Came across the fix in a fork of the repo.
https://github.com/achinn/multipassify/blob/176c7664c8458cdfb8f20fac97fe27b7b7d1bff4/multipassify.js
All of the "binary" statements are removed because I believe it's the default, so no sense in switching back and forth.
I also noticed that Buffer.concat([value, value]) is being used over new Buffer(value + value).
var crypto = require('crypto');

var BLOCK_SIZE = 16;

var multipassify = module.exports = function(secret) {
    if (!(this instanceof multipassify)) return new multipassify(secret);
    if (!(typeof secret == 'string' && secret.length > 0)) throw new Error('Invalid Secret');

    // Use the Multipass secret to derive two cryptographic keys,
    // one for encryption, one for signing
    var hash = crypto.createHash("sha256").update(secret).digest();
    this._encryptionKey = hash.slice(0, BLOCK_SIZE);
    this._signingKey = hash.slice(BLOCK_SIZE, 32);
    return this;
};

multipassify.prototype.encode = function(obj) {
    if (!obj) return;

    // Store the current time in ISO8601 format.
    // The token will only be valid for a small timeframe around this timestamp.
    obj["created_at"] = new Date().toISOString();

    // Serialize the customer data to JSON and encrypt it
    var cipherText = this.encrypt(JSON.stringify(obj));

    // Create a signature (message authentication code) of the ciphertext
    // and encode everything using URL-safe Base64 (RFC 4648)
    var token = Buffer.concat([cipherText, this.sign(cipherText)]).toString('base64');
    token = token.replace(/\+/g, '-') // Replace + with -
        .replace(/\//g, '_'); // Replace / with _

    return token;
};

multipassify.prototype.generateUrl = function(obj, domain) {
    if(!domain) return;
    return "https://" + domain + "/account/login/multipass/" + this.encode(obj);
};

multipassify.prototype.sign = function (data) {
    var signed = crypto.createHmac("SHA256", this._signingKey).update(data).digest();
    return signed;
}

multipassify.prototype.encrypt = function(plaintext) {
    // Use a random IV
    var iv = crypto.randomBytes(BLOCK_SIZE);
    var cipher = crypto.createCipheriv('aes-128-cbc', this._encryptionKey,iv);

    // Use IV as first block of ciphertext
    var encrypted = Buffer.concat([iv, cipher.update(plaintext, 'utf8'), cipher.final()]);
    return encrypted;
}


Qual a melhor forma de passar dados entre arquivos php

Question: Qual é a melhor maneira de passar dados entre back-end e front-end, por exemplo, envio um formulário para o back-end, ele executa um script SQL e retorna um array de dados que devem ser mostrados, qual a melhor forma de passar esses dados para o front-end?
formulario.php:
<form action='./back.php'>
    <input type='text' name='teste'>
    <input type='submit' value='Enviar'>
</form>

back.php:
$con = new mysqli("host", "user", "pass", "db");
$res = $con->query("SELECT * FROM tabela WHERE coluna = '$nome'");
$array = $res->fetch_all();

Como passar o $array para o front-end, já imaginava que sessões não era a melhor escolha
Comment: Eu não faço idéia do que é "passar dados entre arquivos". Que tipo de dados, que tipo de arquivos? Seria bom descrever um cenário real. "Passar dados entre arquivos PHP" normalmente nem se faz. O que se faz é de HTML pra PHP e vice versa. De PHP pra PHP você faz include, geralmente, ou salva em algum lugar (e é atípico, de qualquer forma). A pergunta definitivamente não está clara. Sugeriria exemplos práticos, para termos como ajudar.
Comment: Estou revertendo sua edição porque a pergunta ficou mais ampla, e invalidou as respostas anteriores.
Comment: Nos seus comentários você refuta todas as respostas. Isso é sinal de que a sua pergunta não está clara. Como funcionam esses seus controllers? Quando se diz "controller" todo mundo pensa em MVC e na função que eles têm nesse padrão. Você não diz a função dos controllers na sua aplicação, e por que eles precisam se comunicar entre si – o que aliás é bem incomum em controllers "tradicionais". Explique também sobre as views e como são carregadas.
Comment: Já te adianto que usar sessões pra tudo como você parece está fazendo é a pior solução possível.
Comment: Outra coisa. Acho que pedir a MELHOR forma vira uma questao de opiniao muitas vezes, pois em programaçao, muitas vezes, tem várias formas de fazer. Seria interessante pedir sugestões como @bacco disse. A melhor forma, quem vai identificar, é vc. Pois é vc que conhece o projeto.
Comment: Vc tem algum código que vc já fez? Pode ser que fique mais claro.
Comment: @bfavaretto por isso fiz essa pergunta
Comment: @bfavaretto reformulei a pergunta espero que tenha ficado mais claro
Comment: @Bacco realmente. Eu apaguei minha resposta pois eu posso ter interpretado errado. A pergunta está ampla.
Comment: @bfavaretto atualizei a pergunta, acredito que minha dúvida esteja mais clara agora
Comment: Já que boa parte da pergunta está riscada, foi remover isso que você mesmo considerou como importante. Caso discorde, só desfazer ;-) De toda sorte, você ganha visibilidade
Answer: A função do Controller na verdade é apenas tratar as chamadas HTTP para a aplicação. Uma alternativa para você, seria passar as regras de negócio para uma camada (diretorio) chamado Services. Assim você centraliza essas lógicas como serviços, e não enche os controladores tanto.
Voce pode por exemplo, criar uma pasta de Serviços e varias subpastas dentro.
- Services
  -- Orders
  -- Users

Eu também sugiro que você dê uma lida sobre DDD, isso pode ajudá-lo a ter uma luz:
https://www.devmedia.com.br/domain-driven-design-desenvolva-aplicacoes-com-qualidade/26116
Eu tenho algo assim, porém feito em Laravel, mas você pode ter uma ideia:

Já neste caso, você pode ter uma noção de como organizar o Services:

Use e abuse da orientação a objeto, aos poucos você perceberá benefícios e malefícios específicos, mas de inicio, acredito que esses passos já podem ajudar.
Comment: Considere que, se você tem um arquivo imenso que faz varias coisas e faz algo errado nele, ao invés de 'quebrar' apenas uma parte do sistema, você vai quebrar diversas coisas. Mas perfeito, foi apenas uma sugestão com base no pouco que estudo.
Comment: Servir servem, creio que não seja uma boa prática centralizar tudo nele.
Comment: Controladores também servem para comunicação com banco, configuração de rotas, tratamento de erros e log, entre outros
Comment: Pelo contrário, decentraliza tudo, em vários controladores. Padrão MVC.
Comment: Desculpe, não tenho conhecimento suficiente para explicar o meu ponto de vista, entretanto, eu percebo que é mais 'saudavel' em termos de manutenção, que os controllers façam as tratativas de requests/responses, assim como classes especificas de validaçoes (validators) façam sua parte.. Repositorios, Serviços, Presenter, etc..
Cada um fazendo sua parte, de forma que respeite o que aprendemos em SOLID sobre cada um deve cumprir uma unica responsabilidade.
Comment: Para complementar, eu percebo que o MVC dificulta o processo em aplicaçoes muito grandes, a ponto de ser necessário pensar no DDD, microserviços, etc..
Comment: Dividir a organização do projeto em subpastas de subpastas de subpastas não é uma solução que busco,  dividir de mais as partes do projeto deixa ele mais desorganizado na minha opinião
Answer: Bom, pelo que entendi, você está usando MVC (Talvez mudando o nome do DAO).
Seguindo esta premissa, não tem problema você criar diversos controlers na pasta controllers. Na verdade, esta é a ideia.
Exemplo de controller e seu uso:
Controler Cliente:
Métodos: Obter, Criar, Atualizar
Chamada dos métodos, URL:

http://localhost/Cliente/Obter/5 - GET, onde 5 é um id de cliente, por exemplo
http://localhost/Cliente/Criar  - POST (JSON por exemplo)
http://localhost/Cliente/Atualizar - POST (JSON por exemplo)

Com relação a passar dados entre controllers, na verdade isso não é comum. Normalmente, a view faz requisições para a Controller, que com base nas informações obtidas pelos models, respositories, etc. Envia a informação de alguma forma para a View.

Note, são camadas

A forma com que a view passa informações para a controller, pode ser GET, POST, PUT, etc.
Já a forma que o controller passa as informações para a View, ai depende. Pode mudar em cada linguagem, plataforma, framework, etc.
Recomendo ver exemplo em MVC na sua linguagem, no caso o PHP, correto?
Pra finalizar, segue umas referências.
boa sorte!
https://tableless.com.br/entendendo-o-padrao-mvc-na-pratica/
https://www.devmedia.com.br/introducao-ao-padrao-mvc/29308
O que é MVC(Model, View, Controller)?
Comment: Pode reformular essa resposta? Eu realmente não entendi nada
Comment: Humm, posso sim, mas me indique a parte que tem mais dúvidas, por favor. E se possível, veja as referências no fim da resposta.
Comment: A forma como a view e controller passam os dados de um para o outro não vem ao caso, a pwrgunta não é essa, não entendi o exemplo (lista), de uma olhada na edição da pergunta
Comment: Olha, de fato você não tem um MVC, pela falta do model, mas o padrão que estabeleceu os seus scripts sugere um MVC. Se preferir, DVC (rsrs). Com relação a comunicação da controller com a View, vou poder te ajudar melhor se postar um exemplo do seu fonte. Um controller e uma view. Você pode usar a Controller como um include por exemplo,e usar variáveis globais. Ou até, fazer requisições HTTP para a controller para obter informações (Mais indicado)
Comment: _"Com relação a comunicação da controller com a View"_, isso não vem ao caso quero saber comunicação de um controller com outro controller, passar dados de um controller para o outro controller, não posso postar código
Answer: Sua arquitetura está uma bagunça!
Vamos por partes, antes, entendendo de HTTP:

o cliente faz uma requisição
o servidor recebe essa requisição
o servidor processa essa requisição
... ainda processando...
o servidor responde com dados
o cliente faz o download da requisição
se for um browser que estiver recebendo HTML, o cliente renderiza

Assim sendo, o seu processamento é livre. E como você faz o processamento? Você disse que quer "passar de um arquivo PHP para outro arquivo PHP", o que a fundo não faz exatamente sentido... Arquivos PHP não foram feitos para falarem-se um com o outro do jeito que você indicou. Parece até que você queria que um arquivo fosse executado, voltasse para o cliente e esse, então, fizesse uma requisição logo em seguida para resgatar os dados obtidos pelo script anterior. Pelo menos foi assim que eu entendi sua fala.
Normalmente o que se faz é criar uma coleção de funções em um arquivo mais voltado ao trabalho de backend e, no arquivo mais voltado ao frontend, chamar essas tais funções e exibi-las corretamente. Para tal, você não precisa separar lindamente em todas as camadas do MVC.
Por exemplo, essa separação de obtenção de dados do banco e, então, de exibição foi feito nessa outra pergunta:

a resposta original do @Sveen usou-se do princípio de separação de interface e banco
a minha repsosta (que é uma variação da reposta do @Sveen, como eu indiquei no texto) apenas dá um ar de manutenção mais fácil; transformei um uso de inclusão de arquivos em chamada de função

Como a única diferença entre as duas respostas foi que eu usei uma função, vou focar na repsosta original, a do @Sveen. A ideia aqui foi:

isolar em um componente a exibição de uma linha do banco
no frontend, primeiro fazer a declaração básica independente dos dados do banco
então, no miolo do frontend, obter as diversas linhas e, para cada uma, chamar o exibidor de linhas

Adaptando para o seu caso, poderia ser algo assim:
back.php:
<?php
function obter_linhas($nome) {
  $con = new mysqli("host", "user", "pass", "db");
  $res = $con->query("SELECT * FROM tabela WHERE coluna = '$nome'");
  return $res->fetch_all();
}
?>

front.php:
<?php include_onde 'back.php' ?>

Hello, world!

     <?php
       foreach (obter_linhas($_GET['nome'] as $linha) {
         echo "
Olha a primeira posição do array: ".$linha[0]."
";
       }
     ?>

Pronto. Fizemos a visualização dos dados de maneira independente da obtenção. De certa forma, separamos o "front" e o "back".

Sobre a bagunça... o uso aparente se assemelha muito a algo que seria uma página adaptativa. Então, nesse caso, você não necessitaria de submeter a página para uma recarga completa. Uma recarga assíncrona da parte minimamente necessário seria o suficiente. Por exemplo, você poderia separar uma
 para os seus resultados e, quando for resgatar os valores, escrever nessa
 (inclusive descartando os valores anteriores).
Usando esse tipo de pensamento, você pode ter interfaces que exibem informações novas sem precisar de um carregamento completo da página:

Para isso, você precisaria enviar os dados (os dados mesmo, não a exibição deles; normalmente se costuma transferir em json ou xml esses dados) a partir de um endpoint PHP. No lado do cliente, o JavaScript se encarregaria de receber esses dados, interpretar e então exibi-los da maneira mais adequada possível.
Você vai encontrar mais sobre essa requisição parcial de dados pesquisando sobre AJAX. Por sinal, esse acrônimo significa (ou significava nas origens):

Asynchronous JavaScript and XML

Em tradução livre:

JavaScript e XML assíncronos

Aqui, assíncrono quer dizer que o script chamará um endpoint no servidor e ele responderá quando der, não tendo garantia de quando isso ocorre. JavaScript é a linguagem de programação que faz a chamada e depois trata a resposta obtida. E o XML hoje em dia é entendido apenas como uma transferência de dados, não precisaria ser o formato XML de transferência de dados.
Um outro uso do AJAX você pode ver aqui, no GitLab:

Aqui, ao pedir para exibir uma aba, o GitLab inicia fazendo a requisição assíncrona, então colocando o placeholder das bolinhas rodando para que eu pense eu ele está trabalhando. Quando a requisição finalmente é terminada, um JavaScript intercepta os dados e trata de exibi-los para mim da melhor maneira possível.
Comment: Me expressei mal na pergunta, aliás muito mal, mas entendi o que quiz dizer, porém não gosto de usar AJAX pra tudo, prefiro que o front renderize tudo de novo se necessário, no caso, como eu faria sem AJAX? Nesse exemplo o usuário faz uma requisição mas sem sair da página e quando tiver uma resposta renderiza na tela. E se eu quiser que o cliente realmente seja direcionado para uma outra página, como passar dessa página (controller, por exemplo) para o front?
Comment: Se você for ver, em nenhum momento eu coloquei código algum ajax. O código todo trataria apenas a separação das preocupações, sem demasiadas preocupações sobre tentar se adequar a um modelo ou a outro. Usei o mais básico do DRY, e nem tentei ser tão não repetitivo assim. Para o caso que você apresentou, colocar mais complexidade do que necessita é um anti-padrão. Você deve inserir as abstrações conforme for sentindo necessidade, e eu não senti necessidade de acordo com o que fora apresentado.
Comment: Apenas coloquei um exemplo, no sistema real é bem mais complexo. Acredito então que eu esteja fazendo errado, o meus códigos estão divididos num MVC onde o view envia uma requisição ao controller, mudando de página, isso não é o mais aconselhável? Em vez disso deveria colocar `include arquivo_controller.php` em vez de passar os dados de uma página para outra? Sempre achei que deveria evitar misturar o front com o que acontece no back
Answer: Você deve separar em vários controladores (lembre-se que é orientação à objetos, não estruturado). Você define instâncias e elas terão 1 controlador, cada.
Exemplo: instância perguntas, controlador de perguntas fará todas as operações relativas às perguntas no seu sistema.
O que você procura se chama MVC (Modelo (seu DAO), Visão, Controlador). Use POST para requisições de inserção e GET para operações de leitura.
Se você preferir usar um framework como o Laravel, lá emula com alguns métodos que o HTTP não dá suporte e organiza melhor as requisições como PUT para edições, DELETE para remoções, GET para buscas e POST para inserções.
Use Sessions somente para informações de login!
Comment: O MVC pode ser usado sem OO. O MVC vem antes de OO.
Comment: Estou seriamente em abandonar OO em PHP, eu sei l que é MVC w não o uso, antes de tentar responder se intere o suficiente do assunto. A sua resposta não responde nada
Comment: Antes de fazer uma pergunta, lembre-se que ninguém recebe nada por responder suas perguntas. Você quer abandonar o OO e utilizar controladores pra que? Queira tu ou não, o que está fazendo é o modelo MVC. O modelo MVC trás organização, se tu tira o OO, não tem nada organizado, só flutuando.
Comment: https://pt.stackoverflow.com/questions/104340/php-mistura-códigos-de-orientação-a-objetos-e-linguagem-procedural#answer-104346
Comment: @GuilhermeCostamilam. Muitos Frameworks já trazem em sua estruturas variável global, que flutua as informações entre as camadas da sua aplicação, estude a documentação destes frameworks,que vai lhe reduzir um tempão. Mas existem muitas maneira para troca de informações, seja convertendo os dados para estrutura json com o json_encore para que uma variável em javascript trate da exibição, seja você criando uma função que já estrutura o html em uma variável e você dá um include em uma pagina que tem um echo para está variável se exibida, já que com include variáveis ainda estão no escorpo.
Answer: Diante do que vejo na pergunta , é um form para um MySQL, você pode utilizar GET para listar aí você terá seus dados passados por URL onde deverá deixá-los amigáveis , você poderá usar POST para adicionar , PUT para editar e DELETE para apagar , este FORM está muito genérico mas aconselho usar um MVC para tratar entre seu Front-End e Back-End , mas se for só para estas páginas , você precisará ter o form enviando os dados para uma página que validará estes dados , incluir a conexão do banco de dados nesta página e se a validação for Success mexerá no banco, seja visualizando,  adicionando , editando ou deletando.
Aqui uso de PHP e Angular como exemplo:
// Incluindo biblioteca e configuração do banco de dados
require 'vendor/autoload.php';
require 'config/database.php';

// Retornando os dados no formato JSON
echo json_encode([
    'registros' => $registros,
    'paginacao' => [
        'registros_por_pagina' => $registrosPorPagina,
        'pagina_atual'         => $paginaAtual,
        'total_registros'      => $totalRegistros,
    ],
]);

Comment: Pergunta muito abstrata , você pode tratar com a resposta em php com json , angular , ver a melhor ferramenta e conhecimento disponível.


Performing a transaction with Rails ar-octopus gem

Question: I couldn't find in ar-octopus (https://github.com/tchandy/octopus) documentation, how can i perform a transaction.
When performing :
ActiveRecord::Base.connection.transaction do
     Octopus.using(:shard, &block)
end

the code in the block isn't running in a transaction.
Please advise.
Answer: Instead of passing &block  you can do the following :
Octopus.using(:shard) do
    ActiveRecord::Base.connection.transaction do
        block.call
    end
end

Comment: This appears to just work now with the latest Octopus. Is anyone still needing to explicitly wrap transactions with a `using` block?


For $C$ small and $D$ locally small, $D^C$ is locally small. Why is the assumption '$D$ locally small' necessary?

Question: I have a proof that does not use that $\mathcal{D}$ is locally small, so it's probably incorrect, but I do not see the mistake.
Proof
Let $F, G$ be two functors from $\mathcal{C}$ to $\mathcal{D}$. We define $m: Nat(F, G) \to Set$ to be $m(\alpha) = \{\alpha_c \ | \ c \in \mathcal{C} \}$. This is well defined because $\mathcal{C}$ is small. If $m(\alpha) = m(\beta)$, then $\alpha_c = \beta_{c'}$ for some $c, c' \in \mathcal{C}$. As $\alpha_c, \beta_{c'}$  are morphisms from $Fc \to Gc$ and $Fc' \to Gc'$ respectively, we must have that $c = c'$. So $\alpha_c = \beta_c$ for all $c \in C$. We conclude that $\alpha = \beta$ and that $m$ is an injection. So $Nat(F, G)$ must be a set.
Comment: If you choose $\mathcal C$ to be $1$, then $\mathcal D^1=\mathcal D$, so if $\mathcal D$ isn't locally small, $\mathcal D^1$ won't be.
Answer: Each $\alpha_c$ belongs to ${\mathcal D}(Fc,Gc)$, which is a set only if you assume that ${\mathcal D}$ is locally small. In particular, $\prod\limits_{c\in{\mathcal C}} {\mathcal D}(Fc,Gc)$ - to which $m(\alpha)$ belongs - is guaranteed to be a set if only if ${\mathcal D}$ is locally small.


Show that $\sum _{n=0}^{\infty}\sum _{m=0}^{\infty} f(n,m) $ is not absolutely convergent

Question: Definition. Let $X$ be a countable set,
and let $f : X → \mathbb{R}$ be a function. We say that the series $\sum_{x\in X} f(x)$ is absolutely convergent iff for some bijection $g : \mathbb{N} → X$, the sum $\sum_{n=0}^{\infty}f(g(n))$ is absolutely convergent. We then define the sum of
$\sum_{x\in X}f(x)$ by the formula
$$\sum_{x \in X} f(x) =\sum_{n=0}^{\infty}f(g(n)).$$
Consider the function $f:\mathbb{N}×\mathbb{N} \to \mathbb{R}$ defined by $$f(n,m)=\begin{cases}
      1 &  \text{ if } n=m, \\
      -1 & \text{ if } n=m+1, \\
      0 & \text{ otherwise.}
   \end{cases}
$$
That is the matrix
\begin{pmatrix}
1 & 0 & 0& 0& \dots \\
-1&1&0&0& \dots\\
0&-1&1&0&\dots\\
0&0&-1&1&\dots\\
0&0&0&-1&\dots\\
\vdots&\vdots&\vdots&\vdots&\ddots
\end{pmatrix}
Now how to show that the series $\sum _{n=0}^{\infty}\sum _{m=0}^{\infty} f(n,m)$ is not absolutely convergent? Any help will be appreciated.
Comment: It is not the function $f$ that can be absolutely convergent but the series constructed from it.
Comment: Yeah i have edited that just now. I want to show that the sum is not absolutely convergent
Answer: Suppose there exists such a bijection $g$. As the sum converges (absolutely) there is some $N$ such that for $n\geq N$  we have $|f(g(n))| <1$. This shows that only finitely many terms in $x \in X$ can have $|f(x)|=1$, a contradiction.
Note that this argument also shows that no rearrangement of the series can converge at all (even conditionally).
Comment: Here I think we have to consider partial sum. we have to show for a bijection $g:\mathbb{N} \to X=\mathbb{N}×\mathbb{N}$ , $\sum_{n=0}^{\infty}f(g(n))$ is absolutely convergent. That is $\sum_{n=0}^{\infty}|f(g(n))|$ is convergent. That means we have  $\sum_{n=0}^{N}|f(g(n))| \leq M$ $\forall N \geq 0 $ where  $ M \in \mathbb{R} \gt 0$. And I don't know if we can choose M=1 or not. Because $fg$ is a function from $\mathbb{N} \to \mathbb{R}$, and $|fg|$ is taking positive value.
Comment: I am not sure what you are trying to say. In the proof above I only used the fact that if a series of real numbers is convergent, then the terms converge to 0.
Comment: I have shown that let there exist a bijection $g:\mathbb{N} \to X=\mathbb{N}×\mathbb{N}$,  such that $\sum_{n=0}^{\infty}f(g(n))$ is absolutely convergent. That is $\sum_{n=0}^{\infty}|f(g(n))|$ is convergent. Now it is a series of non negative numbers, it's  partial sums $S_{N}:=\sum_{n=0}^{\infty}|f(g(n))|$ are increasing. So this sequence of partial sum converge if and only if it is bounded. that is $\sum_{n=0}^{N}|f(g(n))| \leq M$ for all $N \geq 0$ where $M$ is positive real number. Lets fix this $N$.
Comment: Now according to definition of $f$ we have $| fg|: \mathbb{N} \to \{0,1\}$ and By archimedean property we can choose $N' \in \mathbb{N} \gt M \geq N$ s.t  $|f(g(N'))|=1$. Then $\sum_{n=0}^{N'}|f(g(n))|=\sum_{n=0}^{N}|f(g(n))|+\sum_{n=N+1}^{N'-1}|f(g(n))|+ |f(g(N'))|= \sum_{n=N+1}^{N'-1}|f(g(n))|+1+ \sum_{n=0}^{N}|f(g(n))|    \gt  \sum_{n=0}^{N}|f(g(n))|=M$. So there exist a $N'$ s.t $\sum_{n=0}^{N'}|f(g(n))| \gt M$. So its not bounded. So $\sum_{n=0}^{\infty}|f(g(n))|$ is not convergent.


Stratified or multi-stage sampling?

Question: I just started volunteering with a small organization that wants to estimate the average and total number environmental trouble spots in a large US city. They have a clear definition of an environmental trouble spot, and planned to survey the neighborhoods on foot to identify the trouble spots. Due to limited resources, they could only survey a fraction of the city.
Before I joined the organization, they carried out their own sampling procedure, which went like this. They divided the city up into 5 large "regions," each of which are made up of many small census blocks. Each region is composed of something like, say 15-30 census tracts. They wanted to sample from each of the 5 large regions and they only had resources to sample about 20 census tracts total for the whole city. They calculated the urban population residing in each of the 5 regions, and calculated population weights to determine the number of census tracts to randomly sample within the region (such that the total for the whole city didn't exceed 20). Their logic was that more environmental hot spots would be in populated areas. Here is an example.
Region 1 - 10% of city population - selected 2 random tracts
Region 2 - 40% of city population - selected 8 random tracts
Region 3 - 30% of city population - selected 6 random tracts
Region 4 - 10% of city population - selected 2 random tracts
Region 5 - 10% of city population - selected 2 random tracts
I joined the project after they completed this sampling, and they asked me to estimate the average number of hot spots per census tract, and also to estimate the total number of hot spots in the city (more of interest).
My problem is, do you know the name of this sampling strategy? Is it a form of stratified random sampling? Or multi-stage sampling? If I know the name or classification, I can better figure out what formula to use. Any other advice on analyzing this?
Comment: Just to clarify: Did the surveyors try to identify **every** hot spot in a selected tract? Or was there any kind of selection of locations for study?
Comment: They exhaustively searched each tract. I think I found the answer (I added it below).
Answer: This is a stratified random sample. The strata are regions, fixed in advance, not sampled.  The only sampling is simple random sampling of census tracts within strata. I suggest that you consult a standard text; I recommend Sharon Lohr, Sampling: Design & Analysis, 2009.  The  statistical packages Stata, SAS, SPSS Complex Samples, and R, all have commands for analyzing survey data.  Note that you will benefit from incorporating the "finite population" correction to reduce standard errors.
Note that if there had been a second stage of sampling, e.g. a systematic sample of areas within each census tract, the design would be properly called a a stratified two-stage sample, with stratification at the first stage.
Answer: Looks like the answer is "Multi-stage Sampling." I found a great guide to this method, and the methods for calculating the average and total here: http://ecology.lifescience.ntu.edu.tw/course_932_ecology/Lab/Two-stageClusterSampling.pdf
Comment: This answer is incorrect. By definition, multistage sampling requires sampling at stages after the first. You yourself stated that the "only sampling" was the selection of census tracts within regions. To be sure that there was no further selection,  was the point of my comment.

Stratified or multi-stage sampling?


Determing intersecting quads?

Question: Is there a possibility to detect whether an object intersects another object in Opengl ?
For example: I have 2 quads(later nurbs),I am moving these quads so that at some point they intersect. Now I would like to cut out those parts which are lying over the edge. The result should be a nice smooth edge.
Comment: Are you talking about something like [CSG](http://en.wikipedia.org/wiki/Constructive_solid_geometry)?
Answer: OpenGL is not a geometry library. It's a drawing API. You send it points, lines and triangles, and it draws them. There's no notion of "geometrical objects" in OpenGL.
What you want to do is the task for geometry libraries, like GTS or similar.
Comment: I've never worked with this before. Is it compatible with OpenGL.Is it very complicated? I mean, from your experience.As I indicated in my question I am planning to use Nurbs(OpenGL-Nurbs) as well. Is it possible with this library?
Comment: @buddy: OpenGL deals with drawing things. GTS deals with processing geometry. There's no direct interaction between OpenGL and GTS. But it is of course possible, and quite common to use GTS in programs, that use OpenGL to draw stuff. OpenGL itself has no NURBS at all. The closest come evaluators, but those have been removed from OpenGL-3 core and later. NURBS always came as part of the GLU library (which is not part of OpenGL, but used to ship alongside). Anyway: You should implement your own NURBS evaluator, which emits a mesh. That mesh then can be processed by GTS.

Determing intersecting quads?


como renderizar um JSON no reactJS

Question: estou começando a aprender react e quero conectar com um server nodeJS
ele esta retornando um JSON [{nome:"joão",sobre:"victor"}]
então no react:
class Page extends React.Component{
    constructor(props){
        super(props)
        Axios.get("/teste").then((response)=>{
            this.resposta=response;
            this.string=this.resposta.data[0].nome
            console.log(this.string)
        })

    }

mas não consigo renderizar nem o return nem o string,só aparece no console.log
Answer: Boa tarde, Joao,
Creio que o erro seja na declaração da função.
Se não me engano, voce não pode criar o procedimento no constructor.
Você deve usar a função padrão do react componentDidMount() ou componentWillMount().
Assim deve funcionar:
class Page extends React.Component{
    constructor(props){
        super(props)
    }

    componentDidMount() {
        Axios
            .get("/teste/")
            .then((response) => {
                this.resposta=response;
                console.log(this.resposta)
                this.string=this.resposta.data[0].nome
                console.log(this.string)
            })
            .catch(e => console.log(e))
    }

    render() {
        return (

        );
    }
}

O que eu fiz:
Mudei a identação do procedimento do axios para facilitar o entendimento;
Coloquei o procedimento de busca na funcao componentDidMount(), que é automaticamente executada logo após o render da página;
Criei 3 console.log, um que retorna a resposta, outro que retorna a string e outro que retorna o erro. Se você nao receber no console o this.resposta, vai saber que o erro está acontecendo antes de chegar nessa parte, se receber o this.resposta e não receber o this.string, o erro está entre essas duas linhas, aí volta aqui para te ajudarmos.
Se houver qualquer erro na conexão, o axios faz o que está em .catch. Nesse caso, mostra o erro no console, aí voce pode ler e ver se consegue descobrir o erro, ou posta aqui para nós.
O conteudo da sua pagina vai ficar entre os divs que existem no render.
Tenho quase certeza que o erro era a posição do procedimento.
Testa lá e responde aqui se deu certo.
Boa sorte!
Comment: deu certo aparecer no console,mas não aparece na pagina
Comment: estou tentando mandar o string no render,mas ele não aparece
Comment: @joão.victor_a. como está a sintaxe no render? O certo seria ter "{this.string}" (sem aspas). Se não der certo, o que eu faria é armazenar o nome em um state "nome". Tente isso e fala pra gente se deu certo.

como renderizar um JSON no reactJS


Binding using data-win-bind to backgroundImageUrl

Question: I'm trying to bind the background-img: url('') property in a WinJS application.
I've got a view model property which is set to something dynamic like:
'images/' + myObject.name + '.jpg'

But I'm unsure how to use data-win-bind to set said property to the css property background-img: url(''); correctly.
My template is currently set like this:

Where backgroundImageUrl is my view model property, but this does not seem to setting things correctly.
Any ideas as to how to bind to these properties?
Answer: Your data-win-bind syntax looks correct. So there could be two possibilities.
First, make sure you've called WinJS.Binding.processAll. That's necessary to set the binding context and set up the bindings described by data-win-bind attributes. Nothing happens without it.
Second, the value of the source's backgroundImageUrl must be a string in the form that CSS expects, that is, "url('')". It can't just be the relative path itself, like you would use with an img.src target.
To do this, either make the source's property in that form, or use a binding initializer/converter to add the url('') part automatically. For more on that, I suggest looking at Chapter 6 of my free ebook, Programming Windows Store Apps with HTML, CSS, and JavaScript, 2nd Edition, with the general data-binding discussion starting on page 299 and the initializer stuff starting on page 315.


Android Data binding - Error:(119, 29) Identifiers must have user defined types from the XML file. main_radio_subscribe is missing it

Question: I been trying to control the visibility of a view using the  Implicit Attribute Listeners(reference) in android data binding which allows to access views by id and access attributes like checked, visible etc ..., however when trying to use this, it throws an error like so
Error:(119, 29) Identifiers must have user defined types from the XML file. addTodo_switch_remind is missing it

<android.support.v7.widget.SwitchCompat
        android:id="@+id/addTodo_switch_remind"
        style="@style/MediumTextViewStyle"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/addTodo_space_project"
        android:text="@string/add_todo_remind_label"
        android:textOff="@string/generic_no_text"
        android:textOn="@string/generic_yes_text" />

    <android.support.v4.widget.Space
        android:id="@+id/addTodo_space_remind"
        style="@style/FormsSpacingStyle"
        android:layout_below="@+id/addTodo_switch_remind" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/addTodo_space_remind"
        android:orientation="vertical"
        android:padding="@dimen/grid_box_single"
        android:visibility="@{addTodo_switch_remind.checked ? View.VISIBLE : View.GONE}">

Comment: post the xml and the BindingAdapter you are using for that
Answer: As you use View.VISIBLE / View.GONE in your .xml file, you should import the View type by doing adding <import type="android.view.View"/> in the data section like the following:
<data>
    <import type="android.view.View"/>

    <variable
        name="viewModel"
        type="xx.xx.MyViewModel"/>
</data>

Answer: Looks like the implicit Attribute listeners use camel case when it is used in the expressions, thanks to this post I figured it out.

        <android.support.v7.widget.SwitchCompat
            android:id="@+id/addTodo_switch_remind"
            style="@style/MediumTextViewStyle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/addTodo_space_project"
            android:text="@string/add_todo_remind_label"
            android:textOff="@string/generic_no_text"
            android:textOn="@string/generic_yes_text" />

        <android.support.v4.widget.Space
            android:id="@+id/addTodo_space_remind"
            style="@style/FormsSpacingStyle"
            android:layout_below="@+id/addTodo_switch_remind" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@id/addTodo_space_remind"
            android:orientation="vertical"
            android:padding="@dimen/grid_box_single"
            android:visibility="@{addTodoSwitchRemind.checked ? View.VISIBLE : View.GONE}">

Documenting for others who have the same issue
Comment: @Blackbelt - Nope that is the id of the appcompact checkbox
Comment: addTodoSwitchRemind should be the name of your model view class.
Answer: Step 1: create BindingAdapter:
@BindingAdapter("android:visibility")
public static void setVisibility(final View view, @IdRes int layourId) {
    SwitchCompat switcher = (SwitchCompat)view.getRootView().findViewById(layourId)
    switcher.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener(){
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
        {
            view.setVisibility(isChecked ? View.VISIBLE : View.GONE);
        }
    }
}

Step 2: import R class in databinding data section at you layout.xml:
<data>
     <import type="example.package.R"/>
</data>

Step 3: bind custom view to your switcher like this:
<android.support.v7.widget.SwitchCompat
    android:id="@+id/addTodo_switch_remind"/>

<LinearLayout
    android:visibility="@{R.id.addTodo_switch_remind">


How to run Django on Docker container

Question: I'm setting up a django server application on docker. docker runs the container well but the command to run django is not taking by docker.
I've already gone through few youtube videos but none of them worked for me
Dockerfile
FROM python:3.6-stretch

MAINTAINER ***

ENV PYTHONBUFFERED 1

COPY ./requirements.txt /requirements.txt

RUN pip install -r /requirements.txt

RUN mkdir /specfolder
WORKDIR /specfolder
COPY ./myfolder /specfolder

EXPOSE 8000

CMD ["python", "manage.py runserver"]

i've tried placing the command under docker-compose.yml file under
commands: sh -c "python manager.py runserver"

but none of them worked
docker-compose.yml file
version: "3"

services:
myapp:
    build:
        context: .
    ports:
        - "8000:8000"
    volumes:
        - ./myfolder:/specfolder

requriements.txt
django==2.2.4
pandas
xlrd
xlsxwriter

as of now under kinematics i am getting the python shell
Type "help", "copyright", "credits" or "license" for more information.
>>> 2019-08-31T13:34:51.844192800Z Python 3.6.9 (default, Aug 14 2019,
13:02:21)
[GCC 6.3.0 20170516] on linux

unable to access the 127.0.0.1:8000/myapp/login in the browser.
Comment: how did you know it didn't work? did you see any error message?
Answer: You need to make changes in your runserver command.
Change it to
python manage.py runserver 0.0.0.0:8000

Your Dockerfile will be something like this
# other command
CMD ["python", "manage.py", "runserver", "0.0.0.0:8000"]

Make changes accordingly if you are using Dockerfile or docker-compose.
Answer: I see 2 problems in your implementation.

In Dockerfile you have, CMD ["python", "manage.py runserver"]. It should be CMD ["python", "manage.py",  "runserver"]
In compose file commands: sh -c "python manager.py runserver" should be commands: python manager.py runserver.

a. If you use compose file then CMD should be removed from Dockerfile
Comment: still no use, when i access localhost:8000 it shows "This site can't be reached" page
Comment: now i am able to run the app, but unable to access it browser
Comment: Watching for file changes with StatReloader
    Performing system checks...
    System check identified no issues (0 silenced).
    You have 17 unapplied migration(s). Your project may not work properly until
   you apply the migrations for app(s): admin, auth, contenttypes, sessions.
   Run 'python manage.py migrate' to apply them.
   September 03, 2019 - 09:02:55
   Django version 2.2.4, using settings 'myproject.settings'
   Starting development server at http://0.0.0.0:8000/
   Quit the server with CONTROL-C.
Comment: i have changed by composer file to this:

    ` version: '3'

services:
  web:
    build: .
    volumes:
      - .:/myproject
    ports:
      - "8000:8000"
`

How to run Django on Docker container


Lebesgue measurable but not Riemann integrable

Question: Every bounded function $f:[a,b]\to\mathbb R$, which is Riemann integrable, it is also Lebesgue integrable.
On the other hand
$$
g(x)=\left\{
\begin{array}{lll}
1 & \text{if} & x\in\mathbb Q\cap[0,1], \\
0 & \text{if} & x\in [0,1]\setminus\mathbb Q,
\end{array}
\right. \tag{1}
$$
i.e., $g=\chi_{[0,1]\cap\mathbb Q}$, is Lebesgue integrable in $[0,1]$, but not Riemann integrable.
In fact, a bounded function $f:[a,b]\to\mathbb R$ is Riemann integrable if and only if it is almost everywhere continuous.
Now, the function $g=\chi_{[0,1]\cap\mathbb Q}$ is not Riemann integrable BUT is it  almost everywhere equal to $h\equiv 0$, which IS Riemann integrable.
My question is the following:
Is there a bounded function $f:[a,b]\to\mathbb R$, which is Lebesgue integrable, and it is not equal almost everywhere to a Riemann integrable function?
Comment: Is $$
g(x)=\left\{
\begin{array}{lll}
1 & \text{if} & x\in\mathbb Q\cap[0,1], \\
0 & \text{if} & x\in [0,1]\setminus\mathbb Q,
\end{array}
\right. \tag{1}
$$ Lebesgue measurable function?
Answer: The characteristic function of a "fat Cantor set" (a Cantor set with positive measure), is Lebesgue integrable, but is not equal almost everywhere to a Riemann integrable function, because every point of the fat Cantor set is a discontinuity of its characteristic function.
Comment: Is $$
g(x)=\left\{
\begin{array}{lll}
1 & \text{if} & x\in\mathbb Q\cap[0,1], \\
0 & \text{if} & x\in [0,1]\setminus\mathbb Q,
\end{array}
\right. \tag{1}
$$ Lebesgue measurable function?
Comment: Yes, because it is equal almost everywhere to the zero function; its Lebesgue integral equals zero. It is also equal almost everywhere to a Riemann integrable function (the zero function).


How can I print Views Exposed Filter widgets individually using views-exposed-form--mypage.tpl.php?

Question: I have five exposed filter widgets that appear on this page.  I would like to group three of them together and add a title above that group of three so that my layout goes from:
views default

A
B
C
D
E

what I want

A
TITLE

B
C
D

E

Since this customization is specific to one page, I added a views-exposed-form--mypage.tpl.php in my theme's template folder.
The code looks like this:

    <?php foreach ($widgets as $id => $widget): ?>
      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>

        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>

            <?php print $widget->operator; ?>

        <?php endif; ?>

          <?php print $widget->widget; ?>

    <?php endforeach; ?>
    <?php if (!empty($sort_by)): ?>

        <?php print $sort_by; ?>

        <?php print $sort_order; ?>

    <?php endif; ?>

Instead of the foreach loop, how can I print the individual widgets?
Answer:

    <?php foreach ($widgets as $id => $widget):
       if ($id == 'SOMETHING_ID_THATIDENTIFY_B') {
         print '
'.t('TITLE');
       }
       else if ($id == 'SOMETHING_ID_THATIDENTIFY_E') {
         print '
'; //Closing #BCD
       }
    ?>

      <div id="<?php print $widget->id; ?>-wrapper" class="views-exposed-widget views-widget-<?php print $id; ?>">
        <?php if (!empty($widget->label)): ?>
          <label for="<?php print $widget->id; ?>">
            <?php print $widget->label; ?>

        <?php endif; ?>
        <?php if (!empty($widget->operator)): ?>

            <?php print $widget->operator; ?>

        <?php endif; ?>

          <?php print $widget->widget; ?>

    <?php endforeach; ?>
    <?php if (!empty($sort_by)): ?>

        <?php print $sort_by; ?>

        <?php print $sort_order; ?>

    <?php endif; ?>

Comment: Thanks!  `$id` should be `$widget->id`, but otherwise it works!


How to express IN (list of argument) in a query LINQ?

Question: How do you write a linq query to express this:
Select * from Table
where column IN (some values);

By some values, I mean ('Value1', 'Value2', 'value3', ...).
Thanks for helping
Answer: Assuming
var some_values = new [] { "Value1", "Value2", "value3" };

Then:
data.Where(x => some_values.Contains(x))

Or:
from x in data
where some_values.Contains(x)
select x;

Comment: Hasn't touched C# in a while, wouldn't just `data.Where(some_values.Contains)` do?
Comment: @Joker_vD Yes, sure would. Which is more readable is a subjective thing, so you should pick the one you (and your team, if applicable) think is more readable.
Comment: @Joker_vD Think so, yes...?
Comment: True, i just like it more because it's seems more readable to me
Comment: That was rather easy. Thank you.
Comment: @Gert Arnold, `Enumerable.Contains` *is* a `Func` so no need for a `delegate`


Execução de PHP via Ajax jQuery

Question: Estou colocando algumas instruções dentro de um mesmo arquivo PHP que são executadas conforme o valor da variável send recebida, pelo menos era o que eu pensei. Neste código tem duas destas instruções, uma que recebe send == 'buUserBloqueia' e outra que recebe send == 'cCadSend' mas assim que a primeira recebe o comando, executa a instrução e não finaliza executando também as próximas que tem outro valor de send.
Código
// Função serve para bloquear o usuário do sistema
if((isset($_POST['send']) == "buUserBloqueia") && (isset($_POST['id']) != "")){

// Esta função bloqueia um usuário

exit();
}

// Função serve para cadastrar o usuário no sistema
if ((isset($_POST['send']) == "cCadSend")){

// Esta função cria um usuário

exit();
}

Porque será que ao submeter o Ajax com um valor de send especifico e após verificar o valor do send no PHP, o script continua executando todas as instruções abaixo dele?
Comment: Problema de atenção no código reaproveitado em que dentro da instrução estava repetindo um insert. Serviu para eu aprender que isset retorna true ou false. Abraços
Answer: Assumindo que você queira literalmente criar um roteador HTTP, essa não é a melhor forma de se fazer. Além de não ser bom para a qualidade do código, não é possível testar e acaba com a sanidade dos programadores.
Sugiro que você dê uma olhada em componentes/bibliotecas prontos para fazer esse trabalho por você, como por exemplo o Silex que é um mini-framework muito fácil de utilizar. OInclusive ele já tralida com questões de segurança por você, permitindo que trabalhar com URLs Amigáveis de forma fácil.
Veja um exemplo de como ficaria essas suas duas ações com esse framework:
 require_once __DIR__.'/../vendor/autoload.php';

 $app = new Silex\Application();

 $app->post('/usuario/criar', function(){
    //aqui cria um usuário e retorna uma resposta
 });

 $app->post('/usuario/bloquear', function(){
    //aqui bloqueia um usuário e retorna uma resposta
 });

 $app->run();

Eu tenho um repositório com uma aplicação que usa esse mini-framework que eu fiz para um trabalho de faculdade. De repente pode ajudar alguém.
Answer: Para fazer a verificação de um conjunto de ações eu prefiro utilizar o switch, acho que fica mais fácil de compreender e de modificar as instruções...
switch ($_POST['send']) {

    case 'buUserBloqueia':
        // Esta função bloqueia um usuário
        exit();
    break;

    case 'cCadSend':
        // Esta função cria um usuário
        exit();
    break;

}

Answer: A função isset() do PHP retorna true ou false.
Isto quer dizer que esta comparação isset($_POST['send']) == "buUserBloqueia" é sempre false pois isset($_POST['send']) não vai dar o valor do $_POST['send'] mas sim true ou false.
No fundo seria o mesmo que comparar if (true == "buUserBloqueia").
Sugiro que re-desenhe o seu código um pouco e fazer algo como:
if(isset($_POST['send']) && $_POST['send'] == "buUserBloqueia") && (isset($_POST['id']) != "")){

Ou colocar um if que faz exit mais cedo, antes do código que tem:
if(!isset($_POST['send'])) exit();

Execução de PHP via Ajax jQuery


Importação de Dados

Question: Olá, gostaria de saber como eu pego um valor do meu banco de dados e levo para um campo "automaticamente". Por exemplo, na imagem a abaixo, eu quero que neste campo marcado vá uma informação que já está salva em meu banco de dados. Gostaria de saber como eu faço para busca-lá e coloca-lá neste campo, se for possível fazer isso. Estou usando visual studio(c#) e sql developer(Oracle).

Na classe eu coloquei isso:
<code>public OracleDataReader ListarUs()
{
    string strQuery = "SELECT MAX(COD_FUNCIONARIO) COD_FUNCIONARIO FROM FUNCIONARIO WHERE USUARIO='"+ _usuario+"'";
    clnBancoDados ObjBancoDados = new clnBancoDados();
    return ObjBancoDados.RetornaDataReader(strQuery);
}
</code>
mas não acontece nada.
Comment: No `onLoad` do form você faz o select no banco e coloca o valor que quiser no seu `TextBox`.
Comment: Voce quer que quando voce aperte "salvar" ele mostre o codigo gerado para o funcionário na base, isso?
Comment: Você quer que mostre o próximo ID que será deste novo funcionário, certo? Por exemplo, o último funcionário têm o ID 23, o próximo cadastro teria o ID 24, então apresentaria o Cód Funcionário 24 direto nesse `TextBox`. Seria isso?
Comment: Na verdade eu já tenho esse ID. Eu tenho uma tela de login, e queria que nesse campo, fosse o ID do funcionário (que já está cadastrado e que tem um ID) que estivesse logado no sistema.
Comment: Enzo, mostre o código do que vc já fez. Senão fica parecendo que vc quer que façamos pra vc.
Comment: @enzo Tente me explicar melhor seu problema: **o que você precisa é pegar o Id do funcionário logado e colocar no textbox?** Estou certo?
Comment: Sim, isso mesmo. Como existe mais de um Funcionário, eu teria que "identificar" qual desses estaria logado, para importar o seu Id na textbox. Eu quero importar o Id, assim que eu abrisse o formulário(ele já abrir o formulário com o campo preenchido).
Answer: Um exemplo de CRUD de Usuario

Conexao no banco
<code>  using System.Configuration;
  using MySql.Data.MySqlClient;

  namespace PrjGpaci
  {
 class sisBdConn
  {
    protected MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["PrjGpaci.Properties.Settings.gpaciConnectionString1"].ToString());

    protected bool abrir()
    {
        try
        {
            conn.Open();
            return true;
        }
        catch (MySqlException ex) { return false; }
    }

    protected bool fechar()
    {
        try
        {

            conn.Clone();
            return true;
        }
        catch (MySqlException ex) { return false; }
    }
}
}
</code>

<code>  using System;
  using System.Collections.Generic;
  using System.Linq;
  using System.Text;
  using System.Data;
  using MySql.Data.MySqlClient;

  namespace PrjGpaci
  {
  class sisBdUsr:sisBdConn
  {

    /// <summary>
    /// Cadastra o usuario
    /// </summary>
    /// <param name="r"> Classe Usr</param>
    /// <returns>  verdadeiro se cadastrou ou falso se não cadastrou </returns>
    public bool cadUsr(Usr r)
    {
        try
        {

            abrir();

            string strquery = "INSERT INTO usr (id,psw,nome,tipo) VALUES (@id,@psw,@nome,@tipo)";
            MySqlCommand comand = new MySqlCommand(strquery, conn);

            comand.Parameters.AddWithValue("@id",r.Id);
            comand.Parameters.AddWithValue("@psw",r.Psw);
            comand.Parameters.AddWithValue("@nome",r.Nome);
            comand.Parameters.AddWithValue("@tipo", r.Tipo);

            comand.ExecuteNonQuery();

            fechar();
            return true;
        }
        catch (Exception)
        {

            throw;
        }
    }

    /// <summary>
    /// Atualiza as informaçoes do usuario
    /// </summary>
    /// <param name="r"></param>
    /// <returns></returns>
    public bool upUsr(Usr r)
    {
        try
        {
            abrir();

            string strquery = "UPDATE usr SET id =@id,psw =@psw,nome =@nome,tipo = @tipo WHERE codu = @codu";
            MySqlCommand comand = new MySqlCommand(strquery, conn);

            comand.Parameters.AddWithValue("@id", r.Id);
            comand.Parameters.AddWithValue("@psw", r.Psw);
            comand.Parameters.AddWithValue("@nome", r.Nome);
            comand.Parameters.AddWithValue("@tipo", r.Tipo);
            comand.Parameters.AddWithValue("@codu", r.Cod);

            comand.ExecuteNonQuery();

            fechar();
            return true;
        }
        catch (Exception)
        {

            throw;
        }
    }

    /// <summary>
    /// Consulta para login
    /// </summary>
    /// <param name="id">id</param>
    /// <param name="psw">senha</param>
    /// <returns> retorna classe usr null se não encontrar ou reotna usr com os dados do usr</returns>
    public Usr login(string id, string psw)
    {
        try
        {
            Usr u = null;
            abrir();
            string strquery = "SELECT * FROM usr WHERE Id LIKE @id AND Psw LIKE @psw";
            MySqlCommand comand = new MySqlCommand(strquery, conn);

            comand.Parameters.AddWithValue("@id", id);
            comand.Parameters.AddWithValue("@psw", psw);

            MySqlDataReader ler = comand.ExecuteReader();

                while (ler.Read())
                {
                    u = new Usr();
                    u.Cod = Convert.ToInt32(ler["codu"]);
                    u.Id = ler["id"].ToString();
                    u.Psw = ler["psw"].ToString();
                    u.Nome = ler["nome"].ToString();
                    u.Tipo = Convert.ToInt32(ler["tipo"]);
                    fechar();
                    return u;

                }

            fechar();
            return null;
        }
        catch (Exception)
        {
            return null;
            throw;
        }
    }

    /// <summary>
    /// busca todos os usuario
    /// </summary>
    /// <returns>retorna dataset</returns>
    public DataSet dataUsr()
    {
        try
        {
            abrir();
            string strquery = "SELECT codu ,id ,psw,nome,tipo FROM usr";

            MySqlCommand comand = new MySqlCommand(strquery, conn);
            DataSet ds = new DataSet();
            MySqlDataAdapter da = new MySqlDataAdapter(comand);
            da.Fill(ds);
            fechar();

            return ds;
        }
        catch (Exception)
        {
            return null;
            throw;
        }

    }

    /// <summary>
    /// Pesquisa por codigo
    /// </summary>
    /// <param name="cod"></param>
    /// <returns>retorna dataset</returns>
    public DataSet dataUsr(int cod)
    {
        try
        {
            abrir();
            string strquery = "SELECT codu ,id ,psw,nome,tipo FROM usr WHERE codu = @cod";

            MySqlCommand comand = new MySqlCommand(strquery, conn);
            comand.Parameters.AddWithValue("@cod",cod);
            DataSet ds = new DataSet();
            MySqlDataAdapter da = new MySqlDataAdapter(comand);
            da.Fill(ds, "tbUsuario");
            fechar();

            return ds;
        }
        catch (Exception)
        {
            return null;
            throw;
        }

    }

    /// <summary>
    /// Pesquisa por id
    /// </summary>
    /// <param name="id"></param>
    /// <returns>retorna dataset</returns>
    public DataSet dataUsr(string id)
    {
        try
        {
            abrir();
            string strquery = "SELECT codu ,id ,psw,nome,tipo FROM usr WHERE id LIKE @id";

            MySqlCommand comand = new MySqlCommand(strquery, conn);
            comand.Parameters.AddWithValue("@id", id);
            DataSet ds = new DataSet();
            MySqlDataAdapter da = new MySqlDataAdapter(comand);
            da.Fill(ds);
            fechar();
            return ds;
        }
        catch (Exception)
        {
            return null;
            throw;
        }

    }

    /// <summary>
    /// Pesquisa por nome
    /// </summary>
    /// <param name="nome"></param>
    /// <returns></returns>
    public DataSet pesqNome(string nome)
    {
        try
        {
            abrir();
            string strquery = "SELECT codu ,id ,psw,nome,tipo FROM usr WHERE nome LIKE @nome";

            MySqlCommand comand = new MySqlCommand(strquery, conn);
            comand.Parameters.AddWithValue("@nome", nome);
            DataSet ds = new DataSet();
            MySqlDataAdapter da = new MySqlDataAdapter(comand);
            da.Fill(ds);
            fechar();
            return ds;
        }
        catch (Exception)
        {
            return null;
            throw;
        }

    }

    /// <summary>
    /// Pesquisa o id exato do usario e retorna verdadeiro ou falso
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    public bool pesqIdExiste(string id)
    {
        try
        {
            abrir();
            string strquery = "SELECT codu ,id ,psw,nome,tipo FROM usr WHERE id = @id";

            MySqlCommand comand = new MySqlCommand(strquery, conn);
            comand.Parameters.AddWithValue("@id", id);

            MySqlDataReader ler = comand.ExecuteReader();
            while (ler.Read())
            {

                fechar();
                return true;
            }
            return false;
        }
        catch (Exception)
        {
            return false;
            throw;
        }

    }

    public bool deletaUsr(int cod)
    {
        try
        {
            abrir();
            string strquery = "DELETE FROM usr WHERE CodU = @codu";

            MySqlCommand comand = new MySqlCommand(strquery, conn);
            comand.Parameters.AddWithValue("@codu", cod);
            comand.ExecuteNonQuery();
            return true;

        }
        catch (MySqlException)
        {
            return false;
            throw;
        }

    }
}
   }
</code>
Answer: No Construtor da sua Classe Form faça a consulta no BD e seta o código do funcionário para o campo.
<code> //construtor do form.
public CadastroLogin(){

    SetCodigoFuncionario();
}

private SetCodigoFuncionario(){

   try{
     OracleDataReader = dr = ListarUs();
     txtCodigoFuncionario.Text = dr["COD_FUNCIONARIO"].ToString();
  }catch(Exception e){
     MessageBox.Show(e.Message);
}

}
</code>
Isso considerando que sua query esteja executando como esperado.
Obs. Nao fiz o codigo no VS, entao a sintaxe pode nao estar 100%

Importação de Dados