Empty value , Contextual Filters

Question: This is my problem:
I have 3 contextual filters, 2 Content : Has taxonomy term ID and 1 Content :Updated month
if I write in the url : test.com/International/North/06
It will show all the articles update the 06  in the International + North category
But if i write test.com/International/06 or International//06 to show just the articles update the 06 in the International category it doesn't work..
How can hide or set an empty condition on the second contextual filter to access on the third ?
Answer: contextual filters doesn't necessarily know when something is incorrect - it assumes the values are accurate and attempts to use them as you have it setup. You could do it this way:

create a custom views handler, or install Views PHP

assuming Views PHP:

for the second filter, provide a default php value that evaluates the url - if only two arguments are provided assume the second is missing and return all

Of course, this is quite presumptuous on the url information provided to Views, and will inevitably fail in some situations. Depending on how you link to the view and create the url, you are probably better off using a place-holder for the second value <code>(international/--/06)</code>, with a similar default value set up as above whereby if the place-holder is found, it would return all
Answer: In my case I was wanting to programmatically render the view.
To make the second filter render all I had to use 'all'.
e.g.
views_embed_view('notes', 'display_mode', 'international','all','06')

Empty value , Contextual Filters


Array list elements in constructor not equal to those in the function

Question: The array list request in the constructor is equal to the array list passed to this class but I try to use it in the function calcHead the elements in the array disappears.
import java.io.*;
import java.util.*;

public class C_SCAN {
    private ArrayList<Integer> requests = new ArrayList<Integer>();

    C_SCAN(ArrayList<Integer> r){
        this.requests = r;
        System.out.println(requests.size());

    }

    public int calcHead(int start , int end) throws IOException {
        BufferedWriter writer = new BufferedWriter(new FileWriter("sequence.txt", true));
        writer.write(" \nC_SCAN : ");
        int THM = 0;
        System.out.println(requests.size());
        requests.add(start);
        sortReq(requests);
        int current = requests.indexOf(start);
        for(int i = current; i > 0; i--) {
            THM += Math.abs(requests.get(i) - requests.get(i - 1));
            writer.write(String.valueOf(requests.get(i)));
        }
        THM += Math.abs(requests.get(0));
        THM += end;
        THM += end - requests.get(requests.size() -1);
        for(int i = requests.size() - 1; i > current + 1; i--) {
            THM += Math.abs(requests.get(i) - requests.get(i - 1));
            writer.write(String.valueOf(requests.get(i)));
        }
        writer.write("\ntotal head movement : " + String.valueOf(THM));
        writer.close();
        return THM;
    }

    public void sortReq(ArrayList<Integer> requests) {
        for(int i = 0; i < requests.size(); i++) {
            for(int j = 0; j < requests.size(); j++) {
                if(requests.get(j) > requests.get(i)) {
                    Collections.swap(requests, i, j);
                }
            }
        }
    }

}

Comment: Show us the code sample that you use to instantiate your `C_SCAN` class and use the `calcHead` method.
Comment: Welcome to Stackoverflow. Please check [ask] and [mre] on how to provide all the information needed to answer ypur question in a conciese and answerable way.
Comment: https://ericlippert.com/2014/03/05/how-to-debug-small-programs/
Answer: I can assure you that the constructor list is the same reference as the one in the method
Given that you mention list elements are "gone", you seem to be moving elements around in the list as you're iterating over it (twice) and potentially overwriting them
Debug by printing the list before and after your sort method and I think you'll see an issue
The correct iteration procedure looks like this (start j = i+1) so that the indices never match and you don't compare same elements more than once
public void sortReq(List<Integer> requests) {
    for(int i = 0; i < requests.size(); i++) {
        for(int j = i + 1; j < requests.size(); j++) {

Please don't use bubble sort... Collections.sort() does the right thing, so no need to implement your own method
Also, your field initial value is never used, so the class can start like
public class C_SCAN {
    private final List<Integer> requests;

    C_SCAN(List<Integer> r){
        this.requests = r;
        System.out.println(requests.size());

    }

Answer: The problem is in the function named 'sortReq'

public void sortReq(ArrayList requests) { //....}

The argument requests to this function has the same name
as that of the data member of the class.
How to resolve the issue?
Either changing the name of the argument to sortReq function,
Or removing the argument to the function may help resolve the issue.
An important point to note:
Methods of a class can directly access the data members of the same class.
Therefore, the name of a Data member need not be passed as an argument to the method of the same class.


Symfony 2 StofDoctrineExtensionBundle timestampable with odm (MongoDB)

Question: I tried using the timestampable behavior from StofDoctrineExtenstion for my object, but it doesn't work. Object is saved successfully, but createdAt property isn't saved.
This my config:
#Doctrine ODM Configuration
doctrine_mongodb:
    connections:
        default:
            server: mongodb://localhost:27017
            options:
                connect: true
    default_database: rent
    document_managers:
        default:
            auto_mapping: true

#stof doctrine extension
stof_doctrine_extensions:
    mongodb:
        default:
            timestampable: true

and class (I also tried using timestampable behavior for my main object)
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * @MongoDB\MappedSuperclass
 */
abstract class BaseApartment
{

     /**
     * @Gedmo\Timestampable(on="create")
     * @MongoDB\Date
     */
    private $createdAt;
}

Symfony 2.0.12, my deps file:
[StofDoctrineExtensionsBundle]
    git=git://github.com/stof/StofDoctrineExtensionsBundle.git
    target=/bundles/Stof/DoctrineExtensionsBundle
    version=v1.0 (also tried version 1.1)

[gedmo-doctrine-extensions]
    git=git://github.com/l3pp4rd/DoctrineExtensions.git
    target=gedmo-doctrine-extensions

What's wrong? Any ideas?
Comment: What ever happened to this? I'm having the same issue atm.
Answer: I think this is a matter of version compatibility. The problem (well maybe not the problem, but at least one problem) seems to be that the "master" branches of gedmo-doctrine-extensions Stof's DoctrineExtensionsBundle are not compatible with each other.
For example I just made mine work with this pairing of versions (for Symfony version 2.0.15):
[gedmo-doctrine-extensions]
    git=git://github.com/l3pp4rd/DoctrineExtensions.git
    version=origin/doctrine2.1.x

[DoctrineExtensionsBundle]
    git=git://github.com/stof/StofDoctrineExtensionsBundle.git
    target=/bundles/Stof/DoctrineExtensionsBundle
    version=origin/1.0.x

Answer: Try changing the version in your deps file to:
[Stof-DoctrineExtensionsBundle]
   git=https://github.com/stof/StofDoctrineExtensionsBundle.git
   target=/bundles/Stof/DoctrineExtensionsBundle
   version=origin/1.0.x

I was having the same issue until I made that change, followed by a bin/vendors install --reinstall, and it started working for me.


How to serve static resources at runtime with Spring Boot?

Question: I have a Spring Boot application that simply has an HTML page to allow users to upload images and another page to see the uploaded images.
Here is my project structure:

With my Windows computer works fine, then I created a service on a Ubuntu server that runs the Spring Boot app, here the image upload works fine but on the other HTML page, the images are not shown and show this:

I tried to stop the service and restart it and the images are correctly shown !!!
so at runtime don't see the new images but when I restart it the images appear.
How can I solve this problem?
Here is my web configuration:
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
                 .addResourceLocations("classpath:/static/");
    }
}

Here is my image saver:
public static void saveFile(String uploadDirImg, String fileName, MultipartFile image) throws IOException {
        Path pathForSavingImg = Paths.get("src", "main", "resources", "static", "db_images");
        Path filePath = pathForSavingImg.resolve(fileName);
        image.transferTo(filePath);

    }

Answer: First let's explain why this behavior happens. You're using Maven to build and manage your project. To simplify, each time you build and run your application, Maven outputs the build result in /target directory. You can find it in /backend/target in your filesystem.
At app runtime, the app runs from /target folder, so  the classpath is /target/classes/ and not /src/main/resources. This is very important, because of what you are doing is the following (I've added comments to your class):
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry

            // here you match any resource path from the URL
            .addResourceHandler("/**")

            // to search in the classpath:/static/ folder, which in your build
            // is "/target/static" and NOT "/src/main/resources/static"
            .addResourceLocations("classpath:/static/");
    }
}

I guess you can see the problem now and the explanation of the app's behavior. Basically you upload files (images) in the /src/main/resources/static/db_images folder, while the app when it's running searches for them in the /backend/target/static/db_images.
When you reload the application, the images work because the app rebuilds again the rebuild process copies db_images folder from /src/main/resources/static/ to /target/static/ and the earlier upload can be found.
The solve the problem, a good recommendation and a known practice is using a filesystem folder outside of the project and reference it by absolute path. The upload folders are usually something you want out of your app's sources and for good reason (size of the folder is the first it comes to mind).
So if you have different environments you can add some property in application.properties to control the upload path, something like this:
# For Windows OS
upload.folder.path=D:/db_images/

or
# For Unix-like OS
upload.folder.path=/srv/db_images/

Then your WebConfiguration should look something like:
@Configuration
public class WebConfiguration extends WebMvcConfigurationSupport {

    @Value("${upload.folder.path}")
    private String uploadFolderPath;

    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
            .addResourceHandler("/**")
            .addResourceLocations("file:" + uploadFolderPath);
    }
}

Of course, the image saver should account for this and be modified accordingly.
public static void saveFile(String uploadDirImg, String fileName, MultipartFile image) throws IOException {
        Path pathForSavingImg = Paths.get(uploadFolderPath);
        Path filePath = pathForSavingImg.resolve(fileName);
        image.transferTo(filePath);

    }

Comment: There is a simpler explanation while the app works in the original setting: the OP is probably starting the application from Maven or an IDE. These tools take shortcuts when starting an application: e.g. instead of copying the resources into `target/classes` they might just add `src/main/resources` to the classpath.
Comment: Great! I have a directory under src/main/resources that has static content uploaded by the user. So i had to insert one more resourcehandler like this: registry.addResourceHandler("/blog/**").addResourceLocations("file:src/main/resources/blog/") Then I can upload and see the image right on time, don't have to reset the application


How to integrate $\int_{-\infty}^\infty {y\exp (-y^2)\over 1+y^2}dy$?

Question: How might I evaluate the integral $\int_{-\infty}^\infty {y\exp (-y^2)\over 1+y^2}dy$? I have tried integration by parts, but it seems to reach a dead end.
Wolfram Alpha's answer involved "Ei" which I am not expected to use. I reckon the problem is eliminated by the fact that limits are $\pm \infty$, but I am not sure how to do it. Thanks.
Answer: The integrand is an odd function, so the integral is zero.
Comment: Very well-spotted!! Thanks!
Comment: How often I let people know little tricks like this is absurd, in fact in stewart's calculus there is a separate chapter devoted to even and odd functions. I cannot give enough attention to knowledge like this


Erro ao fechar o navegador no selenium-webdriver

Question: Código:
firefoxbin = os.path.abspath(os.path.join(os.path.dirname(__file__), 'drivers', 'geckodriver'))

assert os.path.isfile(firefoxbin), "Driver \"{}\" não disponível.".format(firefoxbin)
        logger.debug(f"firefoxbin: {type(firefoxbin)}")
        navegador = webdriver.Firefox(executable_path=firefoxbin)
        logger.debug(f"navegador: {type(navegador)}")
        navegador.get('https://pt.stackoverflow.com/')
finally:
    navegador.close()

Error:

Exception: 'str' object has no attribute 'close'
Comment: Cadê o `try` desse `finally`?
Comment: Esqueci de colocar na pergunta, mas no código está certo. Descobri o erro e logo posto. Mas resumindo era basicamente desabilitar o marionette.
Answer: O problema aqui é que o seu código finally vai rodar não importa o que aconteça anteriormente.
Seria importante olhar em detalhes o output do seu código para entender melhor o que está acontecendo.
Mas um problema claro é que você fez a criação do webdriver (variável navegador) e não checou se ela efetivamente resultou em um objeto Webdriver.
Como o output não foi esse objeto, então, o erro diz que a string retornada pela chamada não possui um método close(), que no caso pertence ao webdriver.
Para testar, antes do finally, adicione print navegador e veja o retorno. Caso a criação tenha tido sucesso, você terá um retorno como esse:
<selenium.webdriver.firefox.webdriver.WebDriver (session="49785161406c39caa34c0ae34c90a17b")>

Caso contrário, veja se o caminho que está usando realmente possui o driver geckodriver, se o get não está retornando algum erro, ou outros problemas com a criação / uso do navegador antes de chegar no finally.
Answer: No linux a execução ocorre carretamento, no windows a compatibilidade do marionette não então foi preciso mudar o padrão do capabilities desabilitando o marionette.
Resposta:
firefoxbin = os.path.abspath(os.path.join(os.path.dirname(__file__), 'drivers', 'geckodriver'))

assert os.path.isfile(firefoxbin), "Driver \"{}\" não disponível.".format(firefoxbin)
        logger.debug(f"firefoxbin: {type(firefoxbin)}")

        cap = DesiredCapabilities().FIREFOX
        cap["marionette"] = False
        navegador = webdriver.Firefox(capabilities=cap, executable_path=firefoxbin)

        logger.debug(f"navegador: {type(navegador)}")
        navegador.get('https://pt.stackoverflow.com/')
finally:
    navegador.close()


SubQuery retornando valor nulo

Question: Estou fazendo essa query, e preciso consultar o valor de custo de um produto utilizando uma subquery, pois a tabela de nota é a mesma de entrada e saída. Os produtos não repetem. O que diferencia venda e custo. É a série da nota. Está retornando o custo como nulo. Porém se eu incluir um código de produto manualmente. Ele funciona.
Estrutua:
mercadoria = varchar(12)
SELECT *,
(select valornota from nota as u inner
join itemnota as j
on u.id_nfcapa = j.id_nfcapa
where j.mercadoria = i.mercadoria and u.serienf = '001') as custo
FROM nota as n
inner join itemnota as i on n.id_nfcapa = i.id_nfcapa
WHERE n.datanf BETWEEN '2017-08-01' AND '2017-08-31'
AND n.serie = '1'

Assim funciona:
SELECT *,
(select valornota from nota as u inner
join itemnota as j
on u.id_nfcapa = j.id_nfcapa
where j.mercadoria = 'PROD1234' and u.serienf = '001') as custo
FROM nota as n
inner join itemnota as i on n.id_nfcapa = i.id_nfcapa
WHERE n.datanf BETWEEN '2017-08-01' AND '2017-08-31'
AND n.serie = '1'

Answer: Você deve especificar quais são os campos do resultset. Tente com a modificação abaixo:
SELECT i.mercadoria, custo
 (select valornota from nota as u
  inner join itemnota as j
  on u.id_nfcapa = j.id_nfcapa
  where j.mercadoria = u.mercadoria and u.serienf = '001') as custo
 FROM nota as n
 inner join itemnota as i on n.id_nfcapa = i.id_nfcapa
 WHERE n.datanf BETWEEN '2017-08-01' AND '2017-08-31'
 AND n.serie = '1'

Comment: Rodai exatamente a sua SQL, só tirei o campo custo. Esse campo não existe na tabela. Ele é um alias da subquery. Retornou esse erro:  A subquery has returned not exactly one row.
Comment: Realmente o campo custo nao existe na tabela. Ele é apenas um alias. Você precisa inserir o nome do campo correspondente em na tabela itemnota. Qual é a estrutura das tabelas ?
Comment: mercadoria = Varchar(12)
Comment: Eduardo, para esclarecer sua dúvida é importante ter informações sobre a estrutura de campos das tabelas envolvidas, assim torna-se possível reproduzir a situação que encontrou.
Comment: Consegui resolver amigo, tirei o apelido das tabelas. Utilizei no formato TABELA.CAMPO sem usar inner join. Funcionou perfeitamente. Obrigado pela ajuda.
Comment: Fico feliz em saber disso, Eduardo. Happy programming!

SubQuery retornando valor nulo


FW changes not implemented?

Question: No local iptables involved FW request should have been opened on port 444 however telnet still times out.
request should be going out of the mgt nic eth0 looks like the route table will route my traffic through eth2 tho ?
eth0      Link encap:Ethernet
          inet addr:10.22.64.85  Bcast:10.22.65.255  Mask:255.255.254.0
          inet6 addr: fe80::216:3eff:fe70:4772/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:43429659 errors:0 dropped:0 overruns:0 frame:0
          TX packets:40122251 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:22398031295 (20.8 GiB)  TX bytes:24731287750 (23.0 GiB)

eth1      Link encap:Ethernet
          inet addr:10.22.0.85  Bcast:10.22.1.255  Mask:255.255.254.0
          inet6 addr: fe80::216:3eff:fe54:fe6d/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:303773326 errors:0 dropped:0 overruns:0 frame:0
          TX packets:273727398 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:34588960022 (32.2 GiB)  TX bytes:120395041500 (112.1 GiB)

eth2      Link encap:Ethernet
          inet addr:10.22.2.95  Bcast:10.22.3.255  Mask:255.255.254.0
          inet6 addr: fe80::216:3eff:fe0f:f2d5/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:1040479704 errors:0 dropped:0 overruns:0 frame:0
          TX packets:987417024 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:816019640603 (759.9 GiB)  TX bytes:840452320865 (782.7 GiB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:16436  Metric:1
          RX packets:25945700 errors:0 dropped:0 overruns:0 frame:0
          TX packets:25945700 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:7727291661 (7.1 GiB)  TX bytes:7727291661 (7.1 GiB)

Kernel IP routing table
Destination     Gateway         Genmask         Flags   MSS Window  irtt Iface
10.12.0.153     10.22.2.1       255.255.255.255 UGH       0 0          0 eth2
10.18.37.8      10.22.64.1      255.255.255.255 UGH       0 0          0 eth0
10.40.20.140    10.22.64.1      255.255.255.255 UGH       0 0          0 eth0
10.47.76.114    10.22.64.1      255.255.255.255 UGH       0 0          0 eth0
10.12.0.151     10.22.2.1       255.255.255.255 UGH       0 0          0 eth2
10.12.0.150     10.22.2.1       255.255.255.255 UGH       0 0          0 eth2
10.6.113.32     10.22.64.1      255.255.255.224 UG        0 0          0 eth0
10.12.38.0      10.22.64.1      255.255.255.0   UG        0 0          0 eth0
10.12.36.0      10.22.64.1      255.255.255.0   UG        0 0          0 eth0
10.6.114.0      10.22.64.1      255.255.255.0   UG        0 0          0 eth0
10.6.112.0      10.22.64.1      255.255.255.0   UG        0 0          0 eth0
10.6.113.0      10.22.64.1      255.255.255.0   UG        0 0          0 eth0
10.12.0.0       10.22.64.1      255.255.255.0   UG        0 0          0 eth0
10.22.96.0      10.22.64.1      255.255.255.0   UG        0 0          0 eth0
10.6.120.0      10.22.64.1      255.255.255.0   UG        0 0          0 eth0
10.22.2.0       0.0.0.0         255.255.254.0   U         0 0          0 eth2
10.22.64.0      0.0.0.0         255.255.254.0   U         0 0          0 eth0
10.22.0.0       0.0.0.0         255.255.254.0   U         0 0          0 eth1
0.0.0.0         10.22.2.1       0.0.0.0         UG        0 0          0 eth2

telnet 10.47.198.14 444
Trying 10.47.198.14...
times out

So if i force the source port it still times out.
telnet -b 10.22.64.85 10.47.198.14 444
Trying 10.47.198.14...

Is it possible that the firewall change hasn't worked?
Answer: You don't actually have a route setup for that address.
Which causes it to default to the default route:

0.0.0.0         10.22.2.1       0.0.0.0         UG        0 0          0 eth2

Try adding a route that actually has the destination address:
route add -net 10.47.198.14 netmask 255.255.255.255 gw 10.22.64.85

FW changes not implemented?


How to properly run and check parameterized database queries with PHP/MySQLi

Question: After reading related questions about parameter-ized queries, I realize that they are the way to go to completely (well, unless you're interpolating table values or something) prevent SQL injection, even if they are somewhat (okay, very much) verbose and repetitive. However, I've been wondering how to properly test them for error handling, and also if error-handling in some cases is even necessary.
Sorry if this is a newbie question, but aren't PHP and MySQL installed on the same server anyways? Unless one is concerned with the syntax of the connection query or the database connection codes or whatever, I'm not entirely certain that it's necessary to check for errors with every statement like:
if ($stmt->bind_param('s',$logon)) {
   if ($stmt->execute()) {
      if ($stmt->bind_result()) {

      } else { return 'bat'; }
   } else { return 'bar'; }
} else { return 'foo'; }

// or else:

$stmt->bind_param('s',$logon)) or trigger_error('Could not bind parameters!',E_USER_ERROR);

// etc.

As a side note, if the $stmt connection isn't closed for some reason, while the mysqli connection is, does that cause some some sort of internal server error? Or does closing the actual mysqli connection do the trick as well? Why should you close $stmt in the first place?
Anyways, thanks for responding.
Update: MySQL Parameterized Queries - Cache Duration [duplicate] // closing $stmt isn't necessary as PHP will do it in the end anyway.
Notes: $stmt -> prepare(...) interacts with the server.
Answer: The very helpful AND operator can help simplify all those if-else statements. While I'm sure there are other fancier ways to prevent multiple uncaught exceptions at once, this will hopefully help others who are looking for a reasonably simple way to write parameterized queries in the future, or in fact nested queries in general:
// Procedural style:

$con = mysqli_connect('localhost','blah','foo','bar');
$query1 = "SELECT xyz FROM blah WHERE xyz = ?";
$username = 'ABC';

if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
} else {
    if (($stmt =
        mysqli_stmt_init($con) ) and
        mysqli_stmt_prepare($stmt,$query1) and
        mysqli_stmt_bind_param($stmt,'s',$username) and
        mysqli_stmt_execute($stmt) and
        mysqli_stmt_bind_result($stmt,$name) and
       ( mysqli_stmt_fetch($stmt) !== FALSE) ) {
          // Be careful of the functions that can return null
          var_dump($name);
       }
}

// Object Oriented Style:

$con = new mysqli('localhost','blah','foo','bar');
    if ($con->connect_errno) {
        printf("Connect failed: %s\n", $con->connect_error);
    } else {
        if ( ($stmt = $con->prepare($query1)) and
            $stmt->bind_param('s',$username) and
            $stmt->execute() and
            $stmt->bind_result($name) and
            ($stmt->fetch() !== FALSE)) {
             var_dump($name);

        }
    }


Proving convergence of a generalized integral $\int_0^{\infty} \frac{\arctan(x)}{1+x^a}dx$

Question: So the problem i am having is proving that this integral:
$$\int_0^{\infty} \frac{\arctan(x)}{1+x^a}dx$$
converges for any $a \in (1,\infty)$
So the basic idea i have  is to try and divide the integral into two integrals but i dont know if it is the right way.
Comment: It's always best to make you title as specific as possible. It will greatly improve your chances to get an answer
Comment: "divide the integral into two integrals " - Please explain this in more detail
Answer: Use  the Comparison theorem: on the interval $ [1,+\infty)$
$$0\le\frac{\arctan x}{1+x^a}\le\frac{\pi}{2x^a}$$
The latter converge if and only if $a>1$.
Comment: While this development guarantees convergence for $a<1$, it doesn't imply that the integral of interest diverges otherwise.
Comment: I didn't say so. If and only if is for 'the latter'.
Comment: Bernard, I realize that.  In fact the question doesn't ask for more.  So, +1.  I was only trying to expand on the question of convergence/divergence.  -Mark
Answer: For $x>0$, you have
$$
\frac {\arctan  (x)}{1+x^a}\leq\frac {\pi/2}{1+x^a}\leq\frac\pi {2x^a}\leq\frac2 {x^a}.
$$


Print fields a different node

Question: I have a News page which links to a bunch of news articles and I'm looking to print the header of the News Page on the individual articles.
The field_get_items doesn't return anything right now.  Any advice would be greatly appreciated!
if ($node->type == 'article') {
         $news_header = field_get_items('page', $node, 'group_header'); print_r($news_header);

             //$url = file_create_url($node->field_header_image['und'][0]['uri']);
             //echo '';
            // }
        }

Answer: Are you loading the node first? If you are not getting anything returned then it's probably because $node isn't set. Also is the 'News node' a node type of article?
I would start by trying to retrieve the node information first:
$node = node_load(arg(1));
var_dump($node);

Also I think your field_get_items is not working as your entity type is 'page' but you are inside a check for a node type of article try:
$news_header = field_get_items('node', $node, 'group_header');

Comment: Ok that makes sense does the article have the news page as a menu parent? Or is it in the irk path?
Comment: It looks like you have no way of loading that node information while on the article, The easiest answer is to make a block as a header image for the articles.

What is the path of the hub page you want the header from? if it's 'news' you could work with that.
Comment: This is retrieving the information of the current node that I'm  in which is an article content type.  I need to retrieve a field - group_header from a different node which is content type page = news. thanks for you help on this!
Comment: Here's an example of an article path: news/2015/12/09/article-name.  news is page that lists all the news articles.

Print fields a different node


triad practice tips?

Question: I am having a hard time practicing triads.
Just figuring out 3rd or 5th of a given note, or 4th(from 5th down to 1st) of a given note takes really long time.
Is there a good way to speeding up figuring out desired notes?
Comment: What instrument do you play? Do you want to practice spelling triads note for note or play triads as chords? Your question lacks details that are important.
Answer: Practicing cadences in all the major and minor keys is a well known fundamental to practice.
An example in C major would be ii6 V I, or spelling the chords from lowest to highest, F A D to D G B to E G C, which would be played over a bass of F G C. Patterns like that can be rotated through three positions where each of the three triad tones will be placed in the top (highest pitch)  position.
Practicing cadences in that way exposes you to all the most important tonal triads, all of the "inversions" of the triads, and covers common voice leading.
Many harmony textbooks will provide exercises for playing cadences so you can see the common patterns.

Is there a good way to speeding up figuring out desired notes?

At this beginning stage, I think you want to focus on playing patterns or cadences and one-octave scales, which will train your hands to move through a key either by steps (scales and scale fragments) and movement by thirds (skipping every other scale step) which is the spacing for chords, triads and seventh chords.
Part of that training doesn't require you think through every single pitch letter you play. A big part of the practice to train your hand movements to become smooth and easy. The some portion of your practice can focus on stuff like naming pitch letters, intervals, etc.
Answer:
Just figuring out 3rd or 5th of a given note, or 4th(from 5th down to 1st) of a given note takes really long time.
Is there a good way to speeding up figuring out desired notes?

Practice more, it will get faster. When your muscles work, your brain learns. So put your muscles to work, and keep working. If you are asking for a way to learn without working, then unfortunately that's not possible. No pain, no gain.
Practice different ways of producing the triads:

(1) list the note names like C-E-G,
(2) play the triads on your instrument,
(3) write the triads in staff notation,
(4) sing the note names.

Do all of these exercises (list, play, write, sing) in different variations.

(A) in different keys, like D major with two sharps (notice that the letter names are the same, just some of them have sharps)
(B) in ascending order, one by one for all diatonic triads, like in D major: D-F#-A, E-G-B, F#-A-C#, G-B-D, ...
(C) in descending order, like in Eb major: Eb-G-Bb, D-F-Ab, C-Eb-G, Bb-D-F, ...
(D) in steps of thirds like C-E-G, E-G-B, G-B-D, B-D-F, D-F-A, F-A-C, A-C-E
(E) the same but first inversions (E-G-C)
(F) the same but second inversions (G-C-E)
(G) take a song lead sheet with chord symbols and list/play/write/sing the triads specified by the chord symbols

After you've done this an hour a day for a few weeks, report back if it's got easier.
Answer: Basing your question on the piano - guitar is the other instrument that can play triads - but is far more complex as the same note is found in differing places.
Knowing your scales is the key here. Particularly the first five notes thereof
The basic triad in root position is ^1 ^3 and ^5. Fairly straightforward. So, staring on whatever note you choose,(let's say C), and making that the root, the other two members of the triad will be E and G. Every time. Play the root, miss ^2, play^3, miss ^4 and play ^5. That works for both major and minor triads, working from the respective scales.
You will notice a similar pattern, fingering-wise, for them all, to make life easier. Every one can be played using three fingers from one hand.
Once you have all of these under your belt, you'll be aware of what the notes actually are, or at least where they are on the keyboard. From that, it's a simple substitution move to slide your whole hand downwards, so the note that was lowest is now the note in the middle - it's called the 2nd inversion.
While you're doing hall that, it's fun to play up and down through the whole piano, using the pedal if you like, single and both hands. It sound like you know what you're doing! And it'll embed the notes of those triads in a satisfying way, too.

triad practice tips?


Preimage of the set of $x$-values

Question:
What is the preimage of the set of $x$-values between $0$ and $1$?
  i.e. $f^{−1}(\{x\mid 0<x<1\})$? Explain.

I get that we have to find the inverse image
$f^{-1}(S) = \{a\in A \mid f(a) \in S\}$ where $S$ is the set of $x$-values between (but not including) $0$ and $1$. I do not know how to explain this and this is where it is giving me problems.
Comment: What do you mean with -1 ({|0 < < 1}?
Comment: inverse function
Answer: If we denote $x=f(y)$, you have to find all the $y$ values such that $0<f(y)<1$, which is by definition $f^{-1}(]0,1[)$.
Comment: Could you explain the $]0,1[$ notation?
Comment: @mapierce271 It's the open interval $(0,1)$.
Comment: It means all the values between 0 (excluded) and 1 excluded. Maybe you're used to the notation (0,1).
Answer: $ f^{-1}(\{ x :0 <x <1\})=f^{-1}((0,1))$
which is the set of values of $\mathbb {R}$ such that $ f $ evaluated in any of the elements of the set falls in the interval $( 0,1) $ written formally,
$ f^{-1}((0,1))=\{x \in \mathbb{R} : f (x)\in (0,1)\}$
Im assuming $ f:\mathbb{R}\rightarrow \mathbb {R}$

Preimage of the set of $x$-values


Why $_POST is empty when using [QSA] in .htaccess?

Question: I've got the following in .htaccess:
RewriteCond %{REQUEST_URI} !app/index\.php$
RewriteRule ^(.*\.htm)$ index.php?url=$0 [QSA,L]

Everyting works great but result URLs have empty $_POST.
I'm 100% sure that it's mod_rewrite bug, not HTML or PHP because when I change [QSA,L] to [L] it works great. But I really need QSA.
It happens at about 30% hostings so this may be some Apache config option.
Comment: Can you check to see if anything is available in $_REQUEST (which includes $_GET and $_POST) - I'm curious to see if your $_POST values are transforming into $_GET values...
Comment: Yes, I've checked. $_REQUEST is filled with $_GET values only
Comment: the thing which puzzled me a few times in the query is the $0 instead of $1
Answer: What about modifying your rule in this way. Does it change anything?
RewriteRule ^(.*)\.htm$ index.php?url=$0.htm [QSA,L]

Comment: strange. Is there a variation between servers depending on the server version? Or does it happen randomly?
Answer: I had exactly this issue.  It works on one server then not the next.  Annoying and time consuming to say the least!
After a lot of checking using this php:
foreach ($_REQUEST AS $key => $value) echo $value."
";

at the top of the index.php to check what values were being sent from the htaccess file, (and many other checks I will not go into!) I eventually found you need to specify  "RewriteBase"
Adding RewriteBase / to the top of the htaccess file made it work on the all the servers I tried.
(also, remember to set to:  RewriteBase /folder-where-file-is/
where "folder-where-file-is" is the location of the index.php file if in a sub-folder)
Hope it helps you - knowing this would certainly have helped me many many hours ago!
Comment: This is not a solution to the question.
Answer: by default,.. maybe apache not enable mod_rewrite, try type this on your console
sudo a2enmod rewrite
sample my .htaccess
<IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule>

<IfModule !mod_rewrite.c>
  ErrorDocument 404 /index.php
</IfModule>

Comment: It does not answer the question. The problem is that the POST parameter get lost when using [QSA].


How do I get rules to select a random node?

Question: I'm working on my cron rule that will post to twitter every cron run. Thing is for this rule I need it to post a random node that either conforms to specific values in certain fields, or does something else if that value is false. I could use some help figuring this out.
Basically if The value of X=y I want the view to respond with one action, but if the value of X <> y then I want it to do another. And I need it to do this on random nodes of a sepcific content type.
Any ideas?
Answer: See How to Use EntityFieldQuery, particularly the section "Random ordering".


Gauss formula for a 3-sphere embedded in $\mathbb{R}^4$

Question: Given connections $\nabla$ and $\bar{\nabla}$ as connections on $\mathbb{R}^4$ and the 3-sphere of radius $r$: $\mathbb{S}^3(r)$, the vector fields $X,Y$ tangent to $\mathbb{S^3}(r)$, how do I obtain the expression:
$$\nabla_{X} Y = \bar\nabla_{X} Y - \dfrac{1}{r^2}<X,Y>p,$$
where $p : \mathbb{S}^3 \to \mathbb{R}^4$ represents the position vector.
I came across this expression in a paper which mentions it as a standard result. However I was unable to derive it from my own limited knowledge.
Comment: There is a result that tells you that the Levi-Civita connection of an embedded manifold is obtained by an orthogonal projection of the Levi-Civita connection of the ambient manifold (you can verify this by checking the properties of the so-obtained connection). This means that
$$\begin{aligned}
\nabla_XY&=\left[\nabla_XY\right]^\top+\left[\nabla_XY\right]^\perp\\
& =\bar\nabla_XY+\left\langle\nabla_XY,\frac{p}{r}\right\rangle\frac{p}{r}\\
& =\bar\nabla_XY+\frac{1}{r^2}\left\langle\nabla_XY,p\right\rangle p\\
\end{aligned}.$$Can you go on from here?
Comment: @frog.Thanks a lot. Most of what you said is clear, excpet for the second step. How is $[\nabla_X Y]^{\perp} = < \nabla_X Y , \dfrac{p}{r}>\dfrac{p}{r}$. Oh and since your comment is almost an answer, I would be more than happy to accept it if you write it up as one.
Answer: The Levi-Civita connection of an embedded manifold is obtained by an orthogonal projection of the Levi-Civita connection of the ambient manifold (see comment). In particular,
$$\begin{aligned}
\nabla_XY&=\left[\nabla_XY\right]^\top+\left[\nabla_XY\right]^\perp\\
& =\bar\nabla_XY+\left\langle\nabla_XY,\frac{p}{r}\right\rangle\frac{p}{r}\\
& =\bar\nabla_XY+\frac{1}{r^2}\left\langle\nabla_XY,p\right\rangle p\\
\end{aligned}$$
Now, since the $\mathbb R^4$ is equipped with the flat metric, this means that $\nabla_XY=X(Y)$. Hence you obtain
$$
\langle\nabla_XY,p\rangle = \underbrace{X\langle Y,p\rangle}_{=0} -\langle Y,X(p)\rangle=-\langle X,Y\rangle,
$$
since $p$ is the inclusion map.
Comment: You can interpret $p$ as a vector in Euclidean 4-space, that makes $p$ a vector field. For the second issue, note that the normal bundle of the sphere is one dimensional and the outer unit normal to the sphere is given by $p/r$. Does that help?
Comment: No prob, what are the doubts?
Comment: If the confusion is too trivial, you can just direct me to a suitable source.
Comment: One is I am a bit confused about how to interpret $<\nabla_X Y,p>$ as one is a vector field and p is a map!. Another confusion is of course as to how $[\nabla_X Y]^{\perp} = <\nabla_X Y, \dfrac{p}{r}>\dfrac{p}{r}$??
Comment: Yes it does almost. Just one last thing about the second issue, i am still a bit unclear about that precise term although I get that the outer unit normal to the sphere is $\dfrac{p}{r}$. Why is the inner product coming up as a scalar multiple of $\dfrac{p}{r}$? Thanks anyways. You have been tremendously helpful.
Comment: Sorry for the previous overload of questions, that term is quite clear now, just the second fundamental form at work, I really need to get my basics stronger. Everything is resolved.
Comment: Ok great :-). You're very welcome.


Verificar ocorrencia em REGEX para arquivos em php

Question: Em php, tenho que abrir um arquivo do sistema e verificar se após a ocorrência 10 de um char no caso ";" qual é o conteúdo logo após ele.
exemplo: TPD;62384;P;;;;N;62308;N;;C;N;N;;F;02 qual seria o regex para este fim?
Answer: Você pode usar essa regex
(.*?;){10}(.*?);

Explicação
(.*?;) - Essa sequencia captura tudo que esta antes do caractere ; de forma lazy.
{10} - Esse é um quantificador, aqui ele expressa que a sequencia anterior deve ser capturada 10 vezes.

(.*?); - Então após a décima repetição da sequencia .*?; é colocado o segundo grupo de captura para dar match no conteúdo após a décima ocorrência de ;.
Obs: É valido lembrar que o conteúdo que você quer capturar está no segundo grupo de captura dessa regex, não no primeiro.
Você pode ver o funcionamento dessa regex aqui.
Comment: Entao se estiver na ocorrencia 1000, tenho que fazer 1000 vezes isso?
Comment: @ALE_ROM você teria que modificar o quantifier de 10 para 1000
Comment: Massa cara, Obrigado pela ajuda


What does it mean when we say p(y|x) is fixed?

Question: While reading The Elements of Information Theory on page 59. I got stuck in intuiting this line:

If p(y|x) is fixed, then p(y) is a linear function of p(x).

$p(y) = \sum_{x\in\mathcal{X}} p(y|x) p(x)$
If $p(y|x)$ is fixed, then $p(y)$ is obviously a linear function of $p(x)$.
PS: this is the theorem:

Could anyone please illustrate the linear relation between p(y) and p(x) given that p(y|x) is fixed?
Comment: Presumably $p()$ denotes a density. Is that correct?
Answer: In Cover there is a common abuse of notation where $p(x)$ is meant as some distribution on $\mathcal{X}$. It is only literally interpreted as "the mass at $x$ for some distribution $p$ over $\mathcal{X}$" when $x$ is further specified (say for instance, if $x$ is being summed over). They often switch between the two meanings in a single context. Without exposure it only gets more confusing when you involve conditionals.
"The distribution $p(x)$ of $X$" is more properly denoted $p_X$. Extending this notation, it is clear what is meant by $p_Y$, $p_{X,Y}$ and $p_{Y|X=x}$.
By "$p(y|x)$ is fixed" here they mean "the distribution $p_{Y|X=x}$ over $\mathcal{Y}$ is fixed for each $x\in\mathcal{X}$."
What you are meant to see is that for $y\in \mathcal{Y}$, $x\in \mathcal{X}$:
\begin{align}
p_Y=\sum_{x} p_{X,Y}(x,\cdot)=\sum_x p_{Y|X=x}p_X(x)
\end{align}

More info
This question touches on one thing I think Cover fails to stress enough. One of the main objects of interest in the book is a "noisy channel:" Notionally, if one feeds a noisy channel an input $x$, they get a random output $Y$ that has some distribution $p_{Y|X=x}$ over $\mathcal{Y}$. The underlying object being referred to when one talks about a "noisy channel" is this mapping from inputs to output distributions:
$$x\mapsto p_{Y|X=x}$$
 This is why "fixing $p(y|x)$" is a natural, usual thing to do: it specifies a noisy channel.
Comment: A different way of looking at it: imagine a matrix $M\in \mathbb{R}^{\mathcal{X}\times \mathcal{Y}}$ where $[M]_{x,y}=p(y|x)$, and $p_X\in \mathbb{R}^{\mathcal{X}}$ as a row-vector specifying $X$'s distribution. Then $p_Y=p_X \cdot M$! So clearly $p_Y$ is a linear function of $p_X$.


Violin left-hand thumb position

Question: Adult self-taught violinist here.  I've been learning for about three years.
I've developed a habit of allowing the left-hand thumb to protrude rather high above the fingerboard, so that the neck of the instrument rests close to the base of the thumb.  From various YouTube instructional videos and observing good players, I understand that this is sub-optimal, particularly with regard to eventually developing a good vibrato.  So I am trying to correct this, keeping the thumb lower down, with the end of the thumb touching the side or base of the instrument's neck.  I understand that the thumb and index finger should form a quasi-circular arc, almost as if pinching something.
The problem I am having is that the side and base of the violin neck are insanely slippery and I am having trouble getting the tip of the thumb to stay in position when in contact with that area.  It just slips around all over the place.
Any advice about how to deal with this issue would be appreciated.
Creative but probably bad ideas that I've had include using sandpaper to roughen the back of the violin neck and make it less slippery, or gluing something non-slippery e.g. a piece of velcro there.  I realize also that some advice might be along the lines of "get some in-person lessons", however finding a suitable teacher where I'm located at the moment is hard, especially under pandemic conditions.
Answer: I realize I'm answering an old question, but doing so for future reference. Please don't take sandpaper to your instrument! You can experiment with adding things as long as you're sure they can be removed again without damage. (Teachers often use "corn cushions" like these to mark the spot on the neck where the thumb should go, but this is less about making the grip easier and more about providing a tactile reminder.)
Your problem is that the job of holding up the violin is shared by four points on your body (for modern practice). Your chin, in the chinrest, and your shoulder under the shoulder rest (or, if you don't use a shoulder rest, your collarbone under the rib of the instrument) do some of the holding-up. With a good setup (especially with a shoulder rest), you should be able to hold the violin under your chin for at least a few seconds without using your hand at all! If you can't, you might want to experiment with where the violin is positioned on your neck, and try out different models of chinrest and shoulder rest for a firm, comfortable grip. Fortunately, the left hand does share the job with the chin/shoulder, or else your neck would get stiff quickly (in fact, it's a good idea to minimize how much work your chin/shoulder/neck are doing and keep them relaxed).
There are two points that your left hand should touch the neck of the violin: the ball of your thumb, and the base of your first (index) finger. There may be different schools of thought on the positioning of your finger, but mine is this: Feel the side of your first finger. You can feel the "bumps" of the knuckles. Starting from the tip, there's one knuckle, then another... and the third knuckle is at the base of your finger, at the edge of your palm. This is the fourth contact point, so that the violin neck is held in the "V" between your thumb and this "bump," with the entirety of your finger sticking up above the fingerboard, free to wiggle around wherever it needs to. This picture shows it well.
You may have encountered some material advising you to keep that knuckle out, away from the neck. This can be useful for a relaxed vibrato technique, but cross that bridge a few months or years from now. This is how I teach beginners to hold the instrument, and I keep my knuckle in contact with the neck unless using a very wide vibrato.
Yes, as you move your fingers from one note to the other, it can be challenging to keep holding the violin between that "V" of the ball of your thumb and your first knuckle, but as you get used to it it will seem less slippery. Just think; for several centuries your chin wasn't even helping out! There was no chinrest until late 19th century, and shoulder rests weren't common until rather late 20th, so when I play "baroque style" I keep my chin entirely off the instrument. Then it's just up to those two left-hand points, plus the friction of the side of the instrument against my neck, but it's still possible.
Answer: You can pretty well taught yourself, depends on determination, talent, love for music and your instrument, ... my boyfriend is self-taught piano player, and because of his late discovered enormous talent, he is progressing a lot faster than anybody I know from music school.
First thing important is to make sure your wrist and lower hand are aligned or slightly bent away from violin.
You can press your thumb on the rosin a bit, it will "stick" on the neck better, for hand and brains to adjust at first.
You can place a small piece of finger bandage on the neck to fill it and for it not to be so slippery
Answer:
Any advice about how to deal with this issue would be appreciated.

Very simple. Get a teacher! Have lessons!
I've been playing for two years rather than your three. Apart from when lockdown has prevented or I've been on holiday I've had a lesson every week since the first time I picked up a violin. I started doing vibrato after about 6 months. I ventured into third position after about 3 months and fifth after about 8 months. That's the kind of progress you can make if you have regular lessons and practice a lot.

Violin left-hand thumb position


How to set a navigation title with a tab view

Question: Hi I am struggling with how to set navigation titles with SwiftUI.
What I should do is probably to set the navigation title to the LIST in BrowseWordsView() and I also do not want to set it to ContentView(). I tried adding the navigationTitle modifier directly to the BrowseWordsView() but it did not work.
How can I achieve the navigation title like the pic below? The title "Browse" will become very small and move to the top centre of the screen once the screen is scrolled down.
NavigationTitleSmall:

NavigationTitleBig:

enum Tabs: String{
    case study
    case browse
    case search
}

NavigationStack {
            TabView(selection: $selectedTab) {
                // 1st view
                ContentView()
                // set the symbol and the name
                    .tabItem { Label("Study", systemImage: "pencil.line") }
                    .tag(Tabs.study)

                // 2nd view
                BrowseWordsView(viewModel: SearchedWordsObject(service: ExploreService()))
                // set the symbol and the name
                    .tag(Tabs.browse)
                    .tabItem { Label("Browse", systemImage: "book.pages") }

                // 3rd view
                SearchView()
                // set the symbol and the name
                    .tag(Tabs.search)
                    .tabItem { Label("Search", systemImage: "magnifyingglass") }
            }
            .navigationTitle(selectedTab.rawValue)
            .navigationBarTitleDisplayMode(.large)
            .navigationBarBackButtonHidden()

#BrowseWordsView
ScrollView {
      List(uniqueWords.sorted()) { unique in
            HStack {}

Comment: You should add the SwiftUI tag to your question.
Answer: TabView should always be on top of the view hierarchy. If you want to setup NavigationStack for each tabItem. Try to wrap it outside each tabItem's content, not the TabView itself. And navigation title will automatically become inline if your contentView is a kind of List/Scrollable.
TabView(selection: $selectedTab) {
    ContentView(navigationTitle: Tabs.study.rawValue)
        ...
}

The ContentView should be:
struct ContentView: View {

    var navigationTitle: String

    var body: some View {
        NavigationStack {
            ...
            .navigationTitle(navigationTitle)
            .navigationBarTitleDisplayMode(.automatic)
            .navigationBarBackButtonHidden()
        }
    }
}


What is the technical term for this type of ("rough") vocals?

Question:

I know that this is not live, I believe this is a scene from a film, so of-course it would have been recorded and mixed in a studio and then edited in to the film.
It sounds so nice and powerful! Can it (vocals of this type and duration, in general) be performed this nicely live, outside of a studio?
I looked up and viewed many performances of this same song (on talent shows, from all over the world) and even covers (which are not live) but found that none could do it or did it and came any close to perfecting it.
Answer: It's called vocal fry, vocal growl, or vocal distortion. Yes, it can sound great live.


Extracting strings from JS file with gulp-angular-gettext does not work

Question: I use angular-gettext-tools with @gabegorelick 's gulp-angular-gettext. Everyhing is okay with html files, but I fail to extract strings from js file. I tried both gettextCatalog.getString and gettext functions - together and separately - nothing worked.
My code for extraction (smth.js file) looks like this:
  $scope.openCreateOfferPopup = function($event, buttonState) {
    $event.preventDefault();
    loadTypes();
    logger('openCreateOfferPopup');
    if (buttonState) {
      var params;
      if (!$rootScope.dashboard.spots || $rootScope.dashboard.spots.length === 0) {
        params = {
          title: 'Spots needed',
          content: gettextCatalog.getString(gettext("Oops! You need to add your spot before creating an offer!"))+
          '
'+gettextCatalog.getString(gettext("Please, click on Create new spot button")),
          buttons: [{
            text: gettextCatalog.getString(gettext("Create spot")),
            href: '',
            'class': '',
            ngClick: 'openCreateSpotPopup($event)',
            ngController: 'SpotsController'
          }, {
            text: gettextCatalog.getString(gettext("cancel")),
            href: '#',
            'class': 'b-close'
          }]
        };
        DialogService.makeDialog(params, $scope);
        return;
      }

My gulp task looks like this:
import gulp from 'gulp';
import gettext from 'gulp-angular-gettext';
//import debug  from 'gulp-debug';

gulp.task('pot', function () {
    return gulp.src(['src/app/**/*.html','src/app/**/*.js',
            '!src/app/pages/static/acceptable_policy.html','!src/app/pages/static/legal.html',
        '!src/app/pages/static/privacy_policy.html','!src/app/pages/static/refund_policy.html',
        '!src/app/pages/static/terms_of_service.html'])
    //.pipe(debug({title: 'files to translate:'}))
    .pipe(gettext.extract('template.pot', {
        // options to pass to angular-gettext-tools...
    }))
    .pipe(gulp.dest('po/'));
});

I am pretty sure that js file is passed to aangular-gettext-tools - I used gulp-debug to verify it.
There are no error messages. Everything is being extracted from html, but no entries from JavaScript.
Could you point me to the source of this problem?
I have firstname.lastname@example.com using firstname.lastname@example.com and gulp 4.0.0-alpha.2
Answer: Okay, I found the culprit. Angular-gettext-tools don't work with javascript ES7.
We had a piece of code:
async function loadTypes() {
  if ($rootScope.dashboard.types) return;

  const { categories } = await Api.offerTypes();
  $rootScope.dashboard.types = categories;
}

And it siliently died on async function. Possibly, old version of espree package from angular-gettext-tools is to blame.
I requested compatibility with ES7 and printing some debug info (to know that files could not be translated due to some error) here:
https://github.com/rubenv/angular-gettext-tools/issues/140
Right now we are going to use babel to downgrade our javascript to processable version and use it for extraction.
Update to this question from official github:

espree doesn't support it so there's probably nothing we can do. When
  async/await is standardized, it will be added to espree, and we should
  support it without any changes. Until then, use a transpiler like
  babel before calling angular-gettext.


How to deal with nested uncertainties?

Question: Suppose I have some quantity $Z$ I'm estimating that has an uncertainty $\sigma_Z = f(X)$, where the function $f(X)$ is known. Say that $X$ also has some uncertainty $\sigma_X$ (which has some numerical value). Can I calculate a numerical value for $\sigma_Z$?
Comment: $f(X)$ is known or $f$ is known?
Comment: The function $f$ is known (so both). Sorry I'll clarify in the question.
Answer: It will depend on both the function $f$ and distribution of $X$. For some simulation, I have $f(X) = X^2$, and $X \sim \text{Poisson}(4)$, or $X \sim \mathcal{N}(0, 4)$. For both $X$, the standard deviation is 2. However, as numerically shown, standard deviation of $f(X)$ depends on the specific distribution $X$.
<code>set.seed(1)
f <- function(x){
    x ^ 2
}

num_sim <- 10000
x_pois <- rpois(num_sim, 4)
z_pois <- f(x_pois)

print(paste0('sd(x_pois): ', sd(x_pois), ', sd(z_pois): ', sd(z_pois)))

x_norm <- rnorm(num_sim, mean=0, sd=2)
z_norm <- f(x_norm)

print(paste0('sd(x_norm): ', sd(x_norm), ', sd(z_norm): ', sd(z_norm)))
</code>
<code>[1] "sd(x_pois): 2.01302632310105, sd(z_pois): 18.822808849991"
[1] "sd(x_norm): 1.97799168067352, sd(z_norm): 5.50156007079308"
</code>
If you know the specific parametric form of distribution of $Z$, you should be able to derive the distribution of $f(Z)$, and calculate the standard deviation. Otherwise, it would be difficult.

How to deal with nested uncertainties?


Program shuts off without anything C#

Question: using System;

namespace Zadacha
{
    class Zadacha
    {
        static int Read(int x, int y)
        {
            Random rnd = new Random();
            Console.WriteLine("Vuvedete minimalna velichina");
            string MinValue = Console.ReadLine();
            Console.WriteLine("Vuvedete maximalna velichina");
            string MaxValue = Console.ReadLine();
            int.TryParse(MinValue, out x);
            int.TryParse(MaxValue, out y);
            int value = rnd.Next(x, y);
            Console.WriteLine("Proizvodnoto chislo e: " + value);
            Console.ReadKey(true);
            return value;
        }
        static void Main()
        {

        }
    }
}

This is my code, program just starts and shutdowns after a second with no text in the console app. Everything seems fine and i do not know what is wrong. It is a uni task.
Comment: That `static void Main(){}` doesn't do anything in the first place. No wonder it terminates immediatelly
Comment: In C# the program starts in `static void Main()`
Comment: Add some calls to your Main()
Comment: You have to add to the `Main ` the call of read function `Console.ReadLine(Read(5, 5))`
Comment: Besides the empty `Main()` there is a potential problem. You call `bool int.TryParse()` but you never check if the parsing was OK (that function returns true if it could parse).
Comment: Every new programmer start with Hello world examples...and it is the answer for your question - start from beggining. Check [Hello World example](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/inside-a-program/hello-world-your-first-program)
Comment: I updated your code to  be like this:https://onlinegdb.com/SJO_abEJ4
Answer: You don't do anything in your Main method - you need to call your Read(x,y) method at least, and/or Console.ReadLine(); in order for something to happen.
For example
static void Main()
{
   Read(1,2);
}

Comment: Thanks a lot. I feel so stupid right now, not using my main().... <3
Comment: @StiviKM no worries, sometimes we need a bit of rubber ducky-ing. Make sure to mark the answer if it helped you solve your problem.
Answer: Is this what you are trying to achieve? Console apps start from Main() so you'll have to put something in there for the program to work. I guess you don't actually want to feed Read() two int you want to get the users input?
using System;

namespace Zadacha
{
    class Zadacha
    {
        static int Read()
        {
            int x = 0;
            int y = 0;
            Random rnd = new Random();
            Console.WriteLine("Vuvedete minimalna velichina");
            string MinValue = Console.ReadLine();
            Console.WriteLine("Vuvedete maximalna velichina");
            string MaxValue = Console.ReadLine();
            int.TryParse(MinValue, out x);
            int.TryParse(MaxValue, out y);
            int value = rnd.Next(x, y);
            Console.WriteLine("Proizvodnoto chislo e: " + value);
            Console.ReadKey(true);
            return value;
        }

        static void Main()
        {
            Read();
        }
    }
}

Comment: @Adelin it makes no sense proving a argument and overriding its value a few lines later
Comment: Why did you modify `Read`'s signature?
Comment: Because OP want's to get the values from the user
Comment: @bradbury9 yeah but the change shouldn't be imposed with no explanation. If OP knew about that (which this post expects since it has no explanation), they would've changed it themselves.
Comment: Either OP knew about that but got the assignment wrong (just a typo) or did not in which case the OP would have learnt from the correction. Do note it is a university/high school task, so correcting the code seems fine to me.

Program shuts off without anything C#


How do I debug a "[object ErrorEvent] thrown" error in my Karma/Jasmine tests?

Question: I have several failing tests that only output [object ErrorEvent] thrown.  I don't see anything in the console that helps me pinpoint the offending code.  Is there something I need to do to track these down?
[EDIT]: I'm running Karma v1.70, Jasmine v2.7.0
Comment: `[object ErrorEvent] thrown` is literally all it says.  There is nothing before or after.
Comment: As luck would have it, I just got this issue literally the same time you were posting this question, it turned out to be a "rogue" script tag (it could also be css link) which needed to be removed (my issue was related to CORS), or in case of css, I just added crossorigin="anonymous". Check your code for such script/css tags, in my case I found the issue to be caused by a totally different component!
Comment: @TheDude How did you narrow down this script? Line by line? Or was there some debug process that helped you narrow down where it was? I'm having the same issue and the only info I have to go on is the message: An error was thrown in afterAll. If I isolate the test itself by changing `it()` to `fit()`, even though only that single test is running, the error is still being thrown. Any debug recommendations for this type of error?
Comment: Can you include more of the error? Like multiple lines of the error before and after?
Comment: are you on angular cli aren't you? @DarrellBrogdon
Comment: Have you tried importing HttpClientTestingModule to your unit test? That's what worked for my case.
Answer:
FYI: you can find the exact error thrown just by open DevTools Console once your tests are running.

As a quickfix you can try to run your tests without sourcemaps:
CLI v6.0.8 and above
--source-map=false
CLI v6.0.x early versions
--sourceMap=false
CLI v1.x
--sourcemaps=false

Shortcut ng test -sm=false might also work

There is an open issue on that https://github.com/angular/angular-cli/issues/7296
UPDATE:
I had that issue as well, so I just migrated to the latest cli and make sure that all packages are updated in package.json also I fully reinstalled the node_modules so now the issue has gone.
Comment: For angular-cli 6, `--sourceMap=false` seems to work.
Comment: I get Uncaught [object Object] thrown in random components and in some runs I get nothing... :S I hate Angular Testing.
Comment: this worked for me. It helped reveal that the problem was with an undefined input binding.
Comment: This solution doesn't work anymore. It used to, but in 6.2.4 it doesn't
Comment: typical front solution
Comment: As of Angular 6 `--sourcemaps` option is not present.
Answer: If sourcemap=false doesn't help, try to
1) open your browser running the tests
2) click debug button
3) open the console
The error will be there
Comment: I didn't even need to click the debug button.  Just opening developer console worked for me.
Comment: The `--sourcemaps=false` thing wasn't working for me, but this worked flawlessly! Thank you!
Comment: Brilliant! I added the sourcemap option everywhere, but in the end this gave me the info I needed
Comment: Doesn't really help if the browser closes right after the test. Guess I'll write a bunch of useless tests to keep the window open, like some kind of caveman.
Answer: Try if you get a more descriptive error message by running the test from the terminal, like this:
ng test -sm=false

In your test, you can replace
it('should...')

with
fit('should...')

Now only tests preceded by fit will run.
To leave the browser open after running the test, run the test like this:
ng test -sm=false --single-run false

Personally, I have encountered this error twice. Both were only triggered when calling fixture.detectChanges().
The first time, I solved it by using string interpolation more safely in my .html file.
Unsafe example:

{{user.firstName}}

Safe(r) example (note the question mark):

{{user?.firstName}}

The same may apply to property binding:

The second time, I was using a DatePipe in my .html file, but the mock property that I used it on was not a date.
.html file:

{{startDate | date: 'dd-MM-yyyy'}}

.ts (mock-data) file (wrong):
let startDate = 'blablah';

.ts (mock-data) file (correct):
let startDate = '2018-01-26';

Comment: @DylanKapp this checks if the object is null before trying to read the object's property. See https://angular.io/guide/template-syntax#safe-navigation-operator for more details.
Comment: Any comment why '?' string interpretation is safer? This work in my scenario.
Answer: This is because the jasmine framework can not handle the ErrorEvent type so it does not extract the error message and calls error.toString() on that object instead.
I just filed an issue at jasmine repo
https://github.com/jasmine/jasmine/issues/1594
As long as it is not fixed, you can temporarily patch your installed jasmine package in the node_modules folder. In my case it is
node_modules/jasmine/node_modules/lib/jasmine-core/jasmine.js
and then change the implementation of the ExceptionFormatter from this
if (error.name && error.message) {
    message += error.name + ': ' + error.message;
} else {
    message += error.toString() + ' thrown';
}

to this
if (error.name && error.message) {
    message += error.name + ': ' + error.message;
} else if (error.message) {
    message += error.message;
} else {
    message += error.toString() + ' thrown';
}

It helps to identify the issue.
Comment: This worked for me in firstname.lastname@example.com. However, I had to patch it in

 `node_modules/jasmine_core/lib/jasmine_core/jasmine.js`
Comment: So good - took a minute to find this post but it saved my butt.  Thanks.  Same jasmine-core version
Comment: After changing this, it only printed `uncaught` for me which wasn't helpful. So I added code to print `error` object and its properties.  `if(error){
       // message+=error;
        for(var propName in error) {
          propValue = error[propName]
          message+='error prop: '+propName+', value: '+propValue;
        }
      }
`. This provided extra info which helped me in debugging - eg`error prop: filename, value: blob:http://localhost:9881/11777e3a-28d8-414e-9047-cee7d328e843`
Answer: For me it was related to having a promise resolved in the ngOnInit of a component. I had to use async, fakeAsync and tick as well as stubbing out the async service with spyOn
beforeEach(async(
  //... initialise testbed and component
))
beforeEach(fakeAsync(
  // ... setup mocks then call:
  component.ngOnInit()
  tick()
  fixture.detectChanges()
))

Angular - How to unit test component with asynchronous service call
Answer: TL;DR: It may be related to testing routing.
I'm getting [object ErrorEvent] thrown too.
An hour later, traced it to one line of code.
this.username = this.userService.getUser(this.route.snapshot.paramMap.get('id'))[0];

The problem lies with the test environment attempting to evaluate this.route.snapshot.paramMap.get('id').
If I replace it with 0, [object ErrorEvent] thrown goes away.
My userService has a user like so:
public users = [ ["admin", "First name", "Surname", etc... ] ].

So 0 just gets this user, at index 0.
Otherwise when normally running my app, this.route.snapshot.paramMap.get('id') is evaluated when the user selects a user to edit from my table of users.
So in my HTML, *ngFor="let user of users; index as i" loops to display all the users then routerLink="/edit/{{i}}" so you can click on edit buttons for each user, which when clicked go to e.g. http://localhost:4200/edit/0 to edit the aforementioned admin user's details.
Answer: what about cleaning after each test case:
  afterEach(() => {
    TestBed.resetTestingModule();
  })

Comment: I my case it helped clean-up for next tests.
Comment: I read somewhere that the TestBed is reset anyway for each test.
Answer: For me, this was caused by not defining an error handler for an api I was subscribed to.
My fix just involved adding the block of code to handle (err) below:
it('reports an error to subscribers of api calls if not authenticated', (done) => {
    let obsDataFound = dataService.find(1);
    obsDataFound.subscribe((app) => {
        // not expecting this block to be called
        done();
    }, (err) => {
        // This is the err block that I added that solved the problem
        expect(true).toBeTruthy();
        done();
    });

    let testRequest = httpMock.expectOne({method: 'GET'});
    const mockErrorResponse = { status: 401, statusText: 'Unauthorized test status message' };
    testRequest.flush(appTest, mockErrorResponse);
});

Comment: This was my case also, I was multicasting and one of the subscribers was not handling the error.
Answer: I had the same problem. One way this error happens is when you try to access anything null or undefined in template. Make sure you have safety checking on those variable.
For example this will throw [object: ErrorEvent] when config is undefined on component load.
template.html

   .....
   ......

Do this instead

   .....
   ......

Answer: What can help is, if you have the Chrome window open for your Karma test runner, to open the developer tools and check the console there. For me, this helped me to find out that the app could not use the Array.findIndex method on an undefined array (because the data structure was organized by a date string, such as data[2018][3][28],  and I happened to be pointing to the wrong date), but yet instead of just stopping at the error, the test kept running.
Comment: Thanks a bunch! I would have expected the info to be present in the console, you saved a couple of hours of my life :)
Answer: You may have a race or an async test that isn't set up quite right or is used incorrectly. I would assume that the debug case needs to be fixed and ignore that the command line passes. Just keep refreshing the karma test runner (browser) in case the error [object ErrorEvent] thrown appears intermittently, then make sure you have implemented the async condition correctly.
Hopefully this works.
Answer: For me the issue was that I had a test where I was accidentally using the auth0-lock library.
Answer: It appeared to be an async problem, because after I added enough its in one of my component specs, I was able to get a usable error message which pointed to a file and line within that file (it was related to paramMap.
In the spec that tested ParamMap, I just added:
  describe('this test', () => {
    it('will succeed', () => {
      expect(true).toBeTruthy();
    });

    it('will succeed', () => {
      expect(true).toBeTruthy();
    });

    it('will succeed', () => {
      expect(true).toBeTruthy();
    });

    it('will succeed', () => {
      expect(true).toBeTruthy();
    });
  });

Answer:
[object ErrorEvent] thrown

This error shows that you have something undefined. The easiest way to debug it from my experience is :
it('should create', () => {
    console.log(component);
    // You can check in the browser log which property is undefined
    });

Comment: This has actually turned out to be the most useful reminder of all: in my tests I have a mock authentication service, that missed a method. Seemingly unrelated, one of the tests in a component failed, but not when isolated. I have tracked the obscure `[object ErrorEvent] thrown` down to that remote missing method only thanks to the console.log :)
Answer: In my case the problem was with the service, as one of the object wil be undefined during tests running.
Service code sample was something like below access to dom,
  const elem = this.document.querySelector(element) as HTMLElement;
  elem.scrollIntoView({param1: ''});

The specs referring to this service were failing with the error '[object ErrorEvent] thrown'.
I mocked my service object inside all the specs which were referring to this and the issue got resolved.
Mock service
class MockService {
serviceMethod(div) : void {
  testElement = document.querySelector('div') as HTMLElement;
  return testElement;
  }
}

And use this mock service object in providers as below,
beforeEach(async(() => {

TestBed.configureTestingModule({
  declarations: [Component],
  providers: [
     { provide: Service, useClass: MockService },
    ],
})
  .compileComponents();
}));

Answer: I was using a proxy in my application defined in proxy.conf.json like:
'/api': { 'target': 'some path', 'changeOrigin': false }

Because Karma wasn't aware of this proxy, it kept trowing errors in the console that the API endpoint could not be found.
So after looking in the Karma documentation, I found out that what I could do was to add the "proxies" property in karma.conf.js with the same object from the proxy.conf.json:
proxies: { '/api': { 'target': 'some path', 'changeOrigin': false }}

The error in the console was gone, and the [object errorEvent] was no longer thrown.
Answer: In the end, what can worked for me:
    TestBed.resetTestingModule();
  })


recieved memory warning and crash the app when capture more than 4 images?

Question: In my app I need to upload 6 images to a server. I capture the image then upload it and then go to the next one and do the same.
When I reach the 5th image and after receiving 3 or 4 memory warning the app crashes
Here is the code of the image picker
-(void) TakePhotoWithCamera {
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        picker1 = [[UIImagePickerController alloc] init];
        picker1.sourceType = UIImagePickerControllerSourceTypeCamera;
        picker1.allowsEditing = YES;
        picker1.delegate = self;
        [self presentViewController:picker1 animated:YES completion:nil];
    }
}

Here is the method when finishing the capture
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    UIImage * img = [info objectForKey:@"UIImagePickerControllerOriginalImage"];
    [picker dismissViewControllerAnimated:YES completion:nil];
    UIButton * tappedBtn = (UIButton *) [self.horizontalScrollView viewWithTag:chosenImgBtnTag];
    [tappedBtn setImage:img forState:UIControlStateNormal];
    [self useImage:img];   // this method upload the image to the server
    info = nil;
}

here is the method of the setImage
 - (void) useImage:(UIImage *) image {

    currentImageToUpload = image;
   [self showLoadingIndicatorOnImages];
   [[CarAdsManager sharedInstance] uploadImage:image WithDelegate:self];
 }

so please any help in this matter ?
Comment: Do you release picker1 before allocating a new one?
Comment: am using ARC so am not using release method
Comment: Do you ARC? What happens in `useImage:` ?
Comment: i just put the method ,, it calls the api so i can upload to the server
Comment: Have you checked the below answer?. It solved the same problem.
Comment: try it but not working
Answer: You should re-size(480, 480) your image after captured the image like followed,
UIImage *getNewImage;
CGSize newSize = CGSizeMake(480, 480);
UIGraphicsBeginImageContext(newSize);
[capturedImage drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
getNewImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

It will return "getNewImage" as a image. You can upload this image. It will reduce your memory warning crash.
Comment: i found the solution , it was to define the picker as static
Comment: just try it ,, but nothing new ,still the same problem it uploading faster but keep crashing after capture 4th image
Comment: dismiss your viewcontroller and then use your image to the next view controller. It may helps you.


View showing ONLY taxonomy children terms and NO parents

Question: I've managed to got my view working but my worry is that this method is not dynamic.
What I want to achieve?
To have a list of articles tagged with terms that are one level deep (children) but not their parent terms.
E.g.: assuming a taxonomy looks like this:
<code>A
  A1
  A2
B
  B1
  B2
</code>
I want to be able to go to the URL mysite.com/A/A1 or mysite.com/B/B2 and retrieve a list of articles with ONLY content tagged with A1 or B2 (in this example)
For that I added a filter and manually selected the parent terms I don't want to list:

Is there a better solution to achieve this?
Thanks!
Comment: try taxonomy term with depth
Answer: Super simple but impossible to guess solution :
With a normal filter set the "Parent term" filter not equal to "0".
This will filter parents
Answer: In your view:
Contextual filters
Content: Has taxonomy term ID (with depth)
<code> Depth: 1
 When the filter value is NOT available :
   Type : Taxonomy Term Id from url
   & Select Load default filter from term page
</code>
Content: Has taxonomy term ID depth modifier
Hope this will help you to get the result.
Answer: From Contextual filters select:
Content: Has taxonomy term ID and select checkbox Provide default value "taxonomy term id from url" and select checkbox " Load default filter from term page"
and In Relationship:
Relationships
Content: Taxonomy terms on node and select checkbox REquire this relationship.
I hope this will work you.
Comment: Haven't tried this solution. The one above did the job. Thanks!


Como manipular o MongoDB fora do arquivo de configuração?

Question: estou estudando NodeJS e MongoDB, até consigo fazer a conexão e alguns testes no banco, mas gostaria de poder exportar a conexão com o banco pra poder fazer insert/find/remove/etc de qualquer lugar da minha aplicação, tipo um module.exports da variável, pensei mais ou menos assim:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Create a new MongoClient
const client = new MongoClient(url);

var banco;
// Use connect method to connect to the Server
client.connect(function(err) {
    assert.equal(null, err);
    console.log("Connected successfully to server");

    banco = client.db(dbName);
});

module.exports = banco;

mas obviamente... isso não funciona!
Comment: É só exportar o `client` e importar aonde quiser usar.
Comment: Mas aí eu vou ter que ficar escreverndo client.connect toda hora, e se um dia eu quiser atualizar o banco para um driver mais recente?
Answer: Boa tarde eu acabei fazendo um comentário atravessado acredito que porque faz muito tempo que não utilizo o driver nativo, bom vamos la uma das formas de se carregar o driver com a conexão é utilizando promise para retorno da conexão no callback:

mongo.js

Aqui no nosso arquivo mongo.js aonde realizamos a conexão à instancia do mongodb, mas ainda não nos conectamos ao nosso banco de collections:
const MongoClient = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017'

module.exports.connectMongodb = async() => {
    return new Promise((resolve, reject) => {
        MongoClient.connect(url,{ useNewUrlParser: true }, (err, db) => {
            if(err)  return reject('Não foi possivel se conectar a instância!!')
            console.log('instance connected')
            resolve(db)
        })
    })
}

index.js

Agora em nosso index vamos chamar nossa promise:
const {connectMongodb} = require('./mongo')

const start = async() => {
    try {
        const db = await connectMongodb()
        const dbo = db.db('mydboMongo')
        dbo.createCollection('user', (err, dbs) => {
            if(err){
                return console.log(err)
            }
            console.log('collection created')
            db.close()
        })
        dbo.collection('user').insertOne({
            username: 'carlos',
            disabled: '2'
        }, (err, res) => {
            if(err){
                console.log(err)
            }
            console.log('document inserted')
            db.close()
        })
    } catch (error) {
        console.log(error.message)
    }
}
start()

Aqui ocorre o seguinte eu invoco nossa promise e adiciono await para que espere nossa promise ser resolvida ou rejeitada, lembrando que await só tera uso em function definidas como async e o nosso metodo for uma promise outro detalhe sem o trycatch não há como capturar e tratar o erro da nossa promise e sua aplicação iria crashar.
Após o resolve da nossa conexão eu tenho o db que é onde esta nossa conexão na instancia então realizamos a conexão ao nosso banco de collections db.db('mydboMongo') lembrando que aqui ele se conecta ou cria nosso banco se ja existir ele apenas conecta.
Após ser conectado realizamos duas ações, uma de criar uma coleção e outra de inserir um item na coleção criada, eu estou um pouco enferrujado com o driver nativo, fiquei muito dependente do mongoose, mas fica ai uma dica de como carregar a conexão para seus arquivos.
Para seu exemplo ficaria assim a conexão:
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'myproject';
// Create a new MongoClient
const client = new MongoClient(url);

// Use connect method to connect to the Server
module.exports.connectMongo = async() => {
    return new Promise(function(resolve, reject){
        client.connect(function(err, db) {
            //assert.equal(null, err);
            if(err) return reject('Could not connect.')
            console.log("Connected successfully to server");
            resolve(db)

        });
    })
}

No exemplo que eu defini a cima não realizei a conexão previa ao banco de collections para poder exportar db que possui o método db.close().
Answer: Acabei optando pelo pacote express-mongo-db, não era bem o que queria, mas com umas 3 linhas de código foi possivel chamar o banco a cada requisição:
var app = require('express')();

var expressMongoDb = require('express-mongo-db');
app.use(expressMongoDb('mongodb://localhost/test'));

app.get('/', function (req, res, next) {
    req.db // => Db object
});


How do I programatically submit a webform via drupal_form_submit?

Question: Drupal 7, Webform 3
I want to programmatically submit a webform via drupal_form_submit. However, I'm having difficulty finding a $form_state structure that works. I've submitted my webform via the ui and examined the $form_state variable in my validate callback function, but I still can't get it to work.
My webform has one textfield named "first_name". Below is a snippet of code I've used to test. Whenever I run it, $form_errors is null. With no errors, I would expect the code to have worked.  However, when I check the webform results, it says there are no submissions.
<?php
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
    'submitted' => array(
      'first_name' => 'David',
    ),
  ),
);
$node = node_load(55805);
$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>

Am I doing it wrong?  Is there a better way?  Should I be using webform_client_form_submit instead?
I looked at this Q&A, but it doesn't work for me and seems a bit convoluted: How to submit webform programmatically with Ajax?
Comment: why do you need to programmatically submit the webform? Seems to me the  whole point of Webform is to automate the form and submission for you...  if you need greater control over the submission, what about using the Form API and create your own form programmatically in a custom module then process it according to your needs?
Comment: @longboardnode Because the user needs to be able to submit any pre-existing webforms.  If the user is anonymous, the webform submission is cached and the user is shown the login form in a modal box.  Once the user authenticates, the webform is programmatically submitted. I'm looking for two things: 1) Is drupal_form_submit what I should be using to programmatically submit a webform, if not, what should I be using? 2) What is the magical $form_state structure to make it work?
Answer: I used PhpStorm and xdebug to step through the form.inc code and finally found the correct structure for my $form_state.  The structure I posted was close, just needed to add the 'op' => t('Submit').  See my final working code below.
To answer my questions:

Yes, drupal_form_submit is what I should be using.
See code below for the magical $form_state structure.

<?php
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
    'submitted' => array(
      'first_name' => 'David',
    ),
    'op' => t('Submit'),
  ),
);
$node = node_load(55805);
$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>

Comment: I haven't checked your code if it works, but I upvoted both, your Q and A, to show my appreciation for your taking time to answer your question. Thanks, that often helps others.
Comment: Thanks. I have exactly the same issue: I needed to have an anonymous user fill in a couple of forms and then register them and then create the webform submissions using the data previously acquired. Must admit I was concerned it was going to be a major hassle but you've already done the hassle bit  :-) appreciated.
Answer: I had to make a slight amendment to David's answer above (I can't comment as I don't have enough points). The data was not submitting as the op didn't match the text on the submit button. I have correct by reading it in from the webform info attached to the node.
<?php
$node = node_load(55805);
$form_id = 'webform_client_form_55805';
$form_state = array(
  'values' => array(
'submitted' => array(
  'first_name' => 'David',
    ),
    'op' => empty($node->webform['submit_text']) ? t('Submit') : t($node->webform['submit_text']),
  ),
);

$submission = (object) array();

drupal_form_submit($form_id, $form_state, $node, $submission);
$form_errors = form_get_errors();
?>


How to call a class in a function Python

Question: I'm a complete amateur, and trying to work out how to write a function that takes a list of objects, and returns a list of the names of said objects (based on whether they pass if statement). This is the class I've written from help of tutorials:
class Student:
passmark=50

def __init__(self,name,mark):
    self.name=name
    self.mark=mark

def passes(self):
    return self.mark > Student.passmark

So from now I'm assuming I make a list of objects, say:
students = []

Though this list is just a brand new list, which was necessary sure but how would I link it to the class? From this point I want to find out which students have failed, and return them and also where I am confused:
def failed(list):
    for student in Students:
        if passmark > self.mark:
            return list

Is all I can muster, sorry I've just gotten to classes and calling classes is quite confusing for me. The above code doesn't reference the class at all, and I really am confused on how to do so. I've no syntax errors or anything, I think my logic is fatally flawed.
Comment: Have a look at Handras' answer. This is what you need to understand about lists. Comprehensions (which also exists for dictionaries and other things) are nothing but syntactic sugar over this `for`-`append` approach.
Answer: You want to take all the student from the students list. So use that in the for loop. Also, you correctly encapsulated the logic of pass/fail criteria in a method, so use that.
Here is the code I think will do want you want:
def failed(list_of_students):
   failed_students = []
   for student in list_of_students:
       if not student.passes():
           failed_students.append(student.name)
   return failed_students

A more advanced way of doing it is by using list comprehension:
def failed(list_of_students):
    return [student for student in list_of_students if not student.passes()]

It is more pythonic, but my be harder to understand for a beginner with a C or Java background.
Comment: Thank you! THIS is the right way to explain lists to newcomers. Comprehensions are for later. Except that you mustn't name a list `list`, of course ;)
Comment: Indeed, that can cause problems, so I correct the answer!
Answer: You can use a list comprehension like this:
def failed(list):
    return [student.name for student in students if not student.passes()]

Comment: This is just what I needed, though why are you using square brackets for return? Is it because of the use of list? Also this function shows those that passed, made use of 'if not' for failed students.
Comment: Ah you're right that I should use `not` for students that do not pass instead. Edited then.. Square brackets are part of the syntax of [list comprehension](https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions).
Answer: Try this code. Using list comprehension to return results. It's a very powerful python tool.
class Student:
    passmark = 50
    def __init__(self, name, mark):
        self.name=name
        self.mark=mark

    def passes(self):
        return self.mark > Student.passmark

    def __repr__(self):
        return '{} {}'.format(self.name, self.mark)

def failed(students_list):
    return [student for student in students_list if student.mark < Student.passmark]

Answer: Given a Student class like you defined:
class Student:
    passmark=50

    def __init__(self,name,mark):
        self.name=name
        self.mark=mark

    def passes(self):
        return self.mark > Student.passmark

You could instantiate a list of students with:
students = [Student("John", 49), Student("Mary", 75)]

It looks like you are also trying to define a function that will return a list of all the failed students; you could do something like this:
def failed(student_list):
    return [x for x in student_list if not x.passes()]

Answer: mark_to_pass = 50

#Approach one
class Student:
    def __init__(self, student_name, student_mark):
        self.name = student_name
        self.mark = student_mark
        self.pass_mark = self.calculate_passing_mark(mark_to_pass)

    def calculate_passing_mark(self, mark_to_pass):
        if self.mark >= mark_to_pass:
            return True
        return False

if __name__ == '__main__':
    example_student = Student("Swanson", 75)
    print(example_student.pass_mark)

With this approach every time a student object is created it will tell create a field telling you that student has passed. When working with lists such as a list of student objects you need to add the student to your list. Example
students = []
students.append(example_student)

Now you can look through your student list by doing
for student in students:
   print(student.pass_mark) # or do some other logic passed on who passed or failed. Or even here you dont need to create pass_mark object you can just check if student.mark > pass_mark

Answer: I'm assuming that failed isn't a member function of the class Student. The below code should work for what you are trying to do.
class Student:
    passmark=50
    def __init__(self,name,mark):
        self.name=name
        self.mark=mark

    def passes(self):
         return self.mark > Student.passmark

students = [Student("tom",40),Student("joe",70)]

def failed(listofStudents):
    listofStudentsThatFail = []
    for student in listofStudents:
        if not student.passes():
            listofStudentsThatFail.append(student)
    return listofStudentsThatFail

for s in failed(students):
    print s.name

The ouput when you run the code is:
tom


How to select specific column from imported table?

Question: I am using the following formula in Google Sheets to pull in some financial data:
=TRANSPOSE(IMPORTHTML("https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT,"table",4))

The IMPORTHTML result is
Forward Annual Dividend Rate 4    2.04
Forward Annual Dividend Yield 4   1.11%
Trailing Annual Dividend Rate 3   1.94
Trailing Annual Dividend Yield 3  1.05%
5 Year Average Dividend Yield 4   2.02
Payout Ratio 4                    32.93%
Dividend Date 3                   Mar 11, 2020
Ex-Dividend Date 4                Feb 18, 2020
Last Split Factor 2               2:1
Last Split Date 3                 Feb 17, 2003

I am TRANSPOSING the result to prepare the data for querying:
Forward Annual Dividend Rate 4  Forward Annual Dividend Yield 4 Trailing Annual Dividend Rate 3 ...
2.04                            1.11%                           1.94                            ...

What I need is the value of the Ex-Dividend Date 4 column (so: Feb 18, 2020) (and later also other columns so I am seeking a generic solution). I have tried multiple ways (see below, but all resulting in #VALUE! errors:
=QUERY(TRANSPOSE(IMPORTHTML("https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT","table",4)), "SELECT * LIMIT 2 OFFSET 1 WHERE COL=""Ex-Dividend Date 4"")")

=QUERY(TRANSPOSE(IMPORTHTML("https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT","table",4)), "SELECT [Ex-Dividend Date 4] LIMIT 2 OFFSET 1")

How do I query this table correctly?
Answer: try:
=INDEX(IMPORTHTML("https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT",
 "table", 4), 8, 2)

or already formatted:
=TEXT(INDEX(IMPORTHTML("https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT",
 "table", 4), 8, 2), "mm/dd/yyyy")

in QUERY:
=QUERY(IMPORTHTML("https://finance.yahoo.com/quote/MSFT/key-statistics?p=MSFT",
 "table", 4), "select Col2 where Col1 contains 'Ex-Dividend Date 4'", 0)


One-point compactification of R-Z

Question: It is not hard to prove that the compactification of $\mathbb{R}$ (the set of real numbers) minus a finite set, say $n$ elements, is homeomorphic to a union of closed curves whose intersection is a single point.  My intuition is that for $\mathbb{R}$ minus $\mathbb{Z}$ (the set of integer numbers) is homeomorphic to a union of countably many closed curves touching at only one point, but I do not know how to prove it.
Is my intuition true?  If not, what is the one-point compactification of $\mathbb{R}$ minus $\mathbb{Z}$.
Comment: What do you mean exactly when you say "touching"?
Comment: @Spark Something homeomorphic to say the Hawaiian earring.
Comment: To the OP: the guess is fine, but you have to be careful about the neighbourhoods of $\infty$. Try to write things down, see what you get.
Comment: @PedroTamaroff Oh, I first understood the sentence as "(compactification of $\mathbb{R}$) minus a finite set". Now I see what the question is.
Comment: When you say "homeomorphic to a union of countably many closed curves touching at only one point", does it mean Hawaiian earring or a quotient space of countably many disjoint union of $S^1$s?
Comment: @Spark That's what the OP should figure out, of course!
Answer: One point compactification of $\mathbb{R}\setminus \mathbb{Z}$ is homeomorphic to the Hawaiian earring. The explicit homeomorphism can be given by following:
the interval $(n,n+1)$, where $n\in \{0, 1, 2, \cdots\}$, is sent to the circle of radius $1/(2n+1)$, and the interval $(-n, -n+1)$, where $n\in\{1, 2, 3, \cdots \}$, is sent to the circle of radius $1/(2n)$.
One thing you need to be careful of is its topology near $\infty$. In the one point compactification, open sets containing $\infty$ are complements of compact sets. In Hawaiian earring, open set containing $\infty$ contains all circles except for finitely many of them. In $\mathbb{R}\setminus \mathbb{Z}$, compact sets are finite unions of compact sets in some interval $(n,n+1)$, $n\in \mathbb{Z}$ so they correspond exactly.

One-point compactification of R-Z