easy_install prefix option does not work

Question: # echo $PYTHONPATH
 /usr/lib/python3.6/site-packages
# whoami
 root
# easy_install --prefix=/usr/lib/python3.6/site-packages django==1.9
 TEST FAILED: /usr/lib/python3.6/site-packages/lib/python2.7/site-packages does NOT support .pth files
 error: bad install directory or PYTHONPATH

 You are attempting to install a package to a directory that is not
 on PYTHONPATH and which Python does not read ".pth" files from.  The
 installation directory you specified (via --install-dir, --prefix, or
 the distutils default setting) was:

    /usr/lib/python3.6/site-packages/lib/python2.7/site-packages

 and your PYTHONPATH environment variable currently contains:

    '/usr/lib/python3.6/site-packages'

 Here are some of your options for correcting the problem:

 * You can choose a different installation directory, i.e., one that is
  on PYTHONPATH or supports .pth files

 * You can add the installation directory to the PYTHONPATH environment
  variable.  (It must then also be on PYTHONPATH whenever you run
  Python and want to use the package(s) you are installing.)

 * You can set up the installation directory to support ".pth" files by
  using one of the approaches described here:

    https://pythonhosted.org/setuptools/easy_install.html#custom-installation-locations

 Please make the appropriate changes for your system and try again.
# ls /usr/lib/python3.6/site-packages/lib/python2.7/site-packages
#

After reading answer, I couldn't  find .pydistutils.cfg file in the file system
easy_install command tries to install in install path/usr/lib/python3.6/site-packages/lib/python2.7/site-packages which is invalid. This install path is getting created, amidst easy_install

Question:
How to resolve the install path using easy_install?
Answer: 1.Are you using easy_install that works with Python2? Try to use easy_install that works with Python3.
Look at this.
2.--prefix set installation prefix.
When you use easy_install --prefix=/usr/lib/python3.6/site-packages,
the dir is :
'/usr/lib/python3.6/site-packages/' + 'lib/python2.7/site-packages'

Maybe you should use --install-dir
Comment: [Here](http://svn.python.org/projects/sandbox/branches/setuptools-0.6/EasyInstall.txt), it talks about creating `.pydistutils.cfg` file
Comment: Provided link gives 404 Not found
Comment: @overexchange, I test the link, it works.https://stackoverflow.com/questions/3849762/python-3-easy-install-pip-and-pypi
Comment: Command(wget https://bitbucket.org/pypa/setuptools/raw/bootstrap/ez_setup.py) gives 404 not found. request-URI is wrong, I guess


Adjusting Apache Solr bias based on content length?

Question: I have a site using the Apache Solr Search Integration module with a short-form content type that is getting weighted too highly in the Solr index. I've tried adding "Bias" to the other content types and leaving the short-form content type set to Ignore, but even with other bias settings maximized the short pieces still rise to the top. Looking at the particular items that appear at the top, it seems to be that multiple instances of the search terms in a short piece cause it to rank higher.
According to the help on the bias settings page, "Any value except Ignore will increase the score of the given type in search results." Is that a limitation of the Solr module or of Solr itself? Ideally, I'd like to decrease the relevance of the short type. What are my options for doing that?
Answer: Under bias setting you should be able to reduce the priority of the fields. So reduce the priority of the fields that is not much important, and increase the priority of the fields that you would prefer for solar to prioritize.
The settings can be found on: admin/config/search/apachesolr/settings/solr/bias
0.1 is the lowest and 21.0 is the highest rating.
Comment: In this case, the field in question is the body. I need the body field to be weighted differently, depending on the content type. Plus, as I mentioned in the question, the help text specifically says "**Any value** except Ignore will **increase** the score of the given type in search results."
Comment: yes, as the help text says if you select the ignore the field will not be considered for searching
Comment: once after making the changes, you need to index the search environment and run cron once, so that your new settings will sync-up with acquia search.

Usually it take some time to get updated


Is it possible to do webserver affinity in a Docker Swarm?

Question: I have a Docker container that is a REST API webserver.  I want to use this webserver in a Docker Swarm. A couple of the REST API calls are used in an asynchronous pattern.  That is, the first call provides data for processing, and is returned a request identifier.  The second call uses the request identifier to check on the processing and get the results when processing is done.  Since there is no connection between any of the webservers in the Docker Swarm, how can I force the second REST API call back to the Docker instance that was used in the first REST API call?  Is there anyway to ensure webserver affinity for these two REST API calls in a Docker Swarm?
Answer: With Docker Swarm Mode and Ingress networking, connections are processed with round robin load balancing, and this isn't configurable. If the connection remains open, which is the case for most web browsers, you'll find that requests go back to the same instance.
You can use a reverse proxy in front of your application that is aware of each instance of the service. Docker has this with their HRM tool in the EE offering, and many of the other reverse proxies, like traefik, offer similar sticky session options.
If you can, a better design would be to utilize an external cache for any persistence, e.g. redis. This way you can perform a rolling update of your application without breaking all the sessions.
Comment: The Træfik reverse proxy approach just might be what I need. Thanks.


Extract np.array from dict in each row of pd data frame

Question: I managed to store dicts in each row of a column of a pd.dataframe.
Is there a way without a for loop to extract np.arrays from a specific key in each of the dicts at once, please?
My mini-example:
import pandas as pd
import numpy as np

d={}
d['key1']=np.array([[1, 2, 3], [4, 5, 6]])
d['key2']=np.array([1,2,3,4])
d['key3']='Mexico'

df=pd.DataFrame( index=[0,1,2,3,4,5],columns=['A'])

df.loc[0,'A'] = [d]
df.loc[1,'A'] = [d]
df.loc[2,'A'] = [d]
df.loc[3,'A'] = [d]
df.loc[4,'A'] = [d]
df.loc[5,'A'] = [d]

df

df.loc[[1,2,3],'A']

With df.loc[[1,2,3],'A'] I am able to select multiple rows, hence multiple dicts, but I am blocked to access 'key2' for each of them, for example.
Is there a way to extract data from 'key2' for all selected rows at once without looping, please? Thank you.
Edit:
Avoiding the ValueError: Incompatible indexer with Series when trying to place a dict without wrapping into an element of a dataframe, can be achieved with .at.
The example would be then extended by
df.at[0,'B'] = d
df.at[1,'B'] = d
df.at[2,'B'] = d
df.at[3,'B'] = d
df.at[4,'B'] = d
df.at[5,'B'] = d

df

Comment: What do you mean by "blocked to access 'key2'". What did you do? Which error did you get? And why do you wrap each element into a list?
Comment: Thank you for your comment. "blocked to access 'key2'" - I meant that I cannot make the next step. I figured out in the meantime that maybe the apply method could work.
Re wrapping: see below. I got an error if I don't do this.
Comment: `dict` have to be accessed individually.  Thus looping is required.
Answer: You could use:
df.loc[[1,2,3],'A'].apply(lambda x: x[0]["key2"])

1    [1, 2, 3, 4]
2    [1, 2, 3, 4]
3    [1, 2, 3, 4]

However, some code suggestions:

Dont use dict as a variable name, use d instead. dict is an inbuilt function in python.

You should use a dict of lists, then you can set each column in the data frame to a key in the dictionary:

d={}
d['key1']=[np.array([[1, 2, 3], [4, 5, 6]])]
d['key2']=[np.array([1,2,3,4])]
d['key3']=['Mexico']

Then you can create a dataframe like:
df = pd.DataFrame.from_dict(d)

and the columns will be the keys of the dictionary:
                     key1          key2    key3
0  [[1, 2, 3], [4, 5, 6]]  [1, 2, 3, 4]  Mexico

Comment: Thank you. I will try to implement your suggestions. I renamed the `dict` to `d`. I created my df with `df=pd.DataFrame(index=[0,1,2,3,4,5],columns=['A'])`, but when I do `df.loc[0,'A'] = d` with the dict from the example (now called `d` and each item is not a list), I get `ValueError: Incompatible indexer with Series`. I think this is why I put the dictionary within a list.
Comment: I have also another question, please. Regarding the `apply` method using a lambda function, isn't this indirectly somehow looping, please? But I learned now how to use the apply-method. applymap would not work because it only expects single scalars as result, please? Thank you for your patience.
Comment: Sorry yes you are right. I have deleted that part of my answer. Using `df.apply` is not the same as looping over the rows of the dataframe. `apply` is a lot faster as pandas is able to use optimized c code to perform the operations. It is not *always* the fastest way to perform the operation, but a lot of the time it is the simplest, most readable and plently quick enough.
Comment: Thank you. The first code section is the most helpful. I understand with `x[0]` one accesses the first element of the list that is the dictionary. Via the key I obtain the value. Now I have to figure out why this does not work for my real word example :-)

The second part is good to know. Currently, I just don't see why I should create a new df, when I have one and just want to extract a np.array from each dictionary in each row from one column. I apologise, if I don't see this. But many thanks for your help.
Comment: My impression from other SO is that dataframe `apply` is pretty slow, especially with a generic function.  It may with selected operations apply its own compiled methods, but it isn't going to compile your Python code.  There is a `raw` parameter that tells it to work with numpy arrays directly.
Comment: I am still a bit confused. My mini-example had in each df element a list containing a dict. If I try to store it as dict and not as list, I get this error earlier mentioned.
 But my real example has in each element of the pd.df a dict, no error is generated. There I am confused. I will figure it out.
Comment: @hpaulj: I understand only little what you say, because I am not advanced. But after having thought a while today about this problem, I can see what is the advantage of Tom McLean's suggestion. Instead of storing a dict, maybe add the 10 keys of the dict as new columns to the data frame. Accessing a np.array from an element in a column would be easier than jumping into the column, the element of the df, and then into the dict.


Where are {image_style} and {scheme} coming from?

Question: I can't find much documentation on this subject other than https://www.drupal.org/node/2122201. This leads me to think that the subject is either much easier than I think, and doesn't have documentation because everybody knows it, or that there isn't much available.
I have been working with the last example on that page, but I can't figure out where {image_style} and {scheme} are coming from.
I need to create something pretty simple, where there's a path that links to a page that requests some data from an API. For example, if someone browses to mysite.com/example/johndoe, then the page requests data from example.com/users/johndoe and displays it. So, I need to also have access to the entry in the URL to forward it to the API with my module, not just routing a ton of pages with a certain URL pattern to a single page.
I've found plenty of documentation on static page routing, and I have understood that.
Comment: `{image_style}` and `{scheme}` are URL parameters that correspond to the Image Style entity and a string respectively. I do not understand why you would not want to have a *single* controller handle a dynamic route. That is exactly the situation you are describing you want to do - have the controller make an API request based on the route parameter, and then return a render array based on the results to display. The result is not that you get a "single page", but you get infinite page because you have a dynamic route.
Comment: I think I may have messed up my description somewhere, this is all somewhat new to me. I do indeed want the controller to make an API request based on the route parameter. That is exactly what I want - am I using the wrong search terms ('dynamic routing') to look for documentation on this subject?
Answer: They are route parameters. See here: https://www.drupal.org/node/2186285


How do I display a view block next to the branding block in the header?

Question: I have created a view (Slideshow) containing a Flex Slider slideshow I want to display in the free header region right of and next to the branding block. I'm using the Bartik theme; I was disappointed to learn that seemingly blocks in the header always come out above or below each other. (I'd prefer blocks to overlap partially and use the view as a kind of background, but for now that's another cup of tea.)
I've tried to put the view in the Header region, change the weight for Branding and Slideview, and set them identical, but I cannot achieve it.
Also, I looked for any kind of format/position/size setting for blocks, but this seems to go against Drupal conceptually.
Then I wanted to tweak the block's CSS by adding a float-class similar to this one.
<code>.float-right {
 text-align: right;
 color:rgba(121, 121, 121, 1);
 font-size: 12px;
 font-style: italic;
 position: relative;
 top:-10px;
 }
</code>
I cannot find the file to alter.
What am I missing? Any hint would be highly appreciated. (As you might guess, I'm no Drupal-programmer.)
Answer: As it's 2022 you really don't want to be using float for layouts - it's hard to control and requires various hacks (like clears) to clean up subsequent element layouts.
If you start off by adding this to your stylesheet:
<code>.region-header {
  display: flex;
}
</code>
You'll see straight away that the branding block and your view appear next to each other.
You can then use align-items, justify-content, gap, etc. to arrange and space the elements as required.
Comment: That worked like a charm – thx! This is very much appreciated

(I simply cannot cast votes yet.)


WordPress delete all post attachments if not used on any other page

Question: I've looked all over and am unable to find any code relating to my query.
I essentially want to programmatically delete images, however, my issue is that some of the images used on these posts have been used on other posts and naturally deleting them would break those images.
I am doing this inside a foreach loop over get_posts() the code below is all I have which deletes the attached featured image of the post, what I would like from an answer is:

Deletes all attached media if it be via ACF Image Field or Featured Image
But only delete these if no other post has these images present in their attachment list

From what I've read the solution may sit in an SQL query followed by a count? But I've little experience with SQL to create a working answer unfortunately.
    if( has_post_thumbnail( $event->ID ) ) {
        $attachment_id = get_post_thumbnail_id( $event->ID );

        wp_delete_attachment($attachment_id, true);
    }

I've so far managed to adapt some code I've found for an MySQL query but 2 of the parts I add seems to crash the MySQL Server...
Working code that returns the ID:
SELECT i.ID FROM wp_posts i
WHERE i.post_type = 'attachment'
AND i.ID = '10038'
AND i.post_parent > 0
AND EXISTS (SELECT * FROM wp_posts p WHERE p.ID = i.post_parent)
AND NOT EXISTS (SELECT * FROM wp_postmeta pm WHERE pm.meta_key = '_product_image_gallery' AND pm.meta_value LIKE CONCAT('%', i.ID ,'%'))
AND EXISTS (SELECT * FROM wp_postmeta pm WHERE pm.meta_key = '_thumbnail_id' AND pm.meta_value = i.ID)

Broken code that crashes the server:
AND NOT EXISTS (SELECT * FROM wp_posts p WHERE p.post_type <> 'attachment' AND p.post_content LIKE CONCAT('%', i.guid,'%'))
AND NOT EXISTS (SELECT * FROM wp_postmeta pm WHERE pm.meta_value LIKE CONCAT('%', i.guid,'%'))

I believe if I can ensure the broken code lines are remedied I will be able to get the code working.
Answer: You can have a look at the media library and choose from dropdown all images that aren't attached.
Comment: I am aware but as per my post I am trying to do this programmatically on a CRON job
Comment: This is not a simple task. Have a look at [this answer](https://wordpress.stackexchange.com/questions/364025/sql-how-to-find-all-attachments-that-are-not-used-in-any-posts-pages-custom-pos)
Comment: I've read this post this morning and the 2nd answer seems to be the start of what I need but I wish to check for a specific attatchment_id and if it's used in more than 1 location delete im reading up on SQL this morning to try to figure it out but it's a difficult task!


Irrationality of $\log_2(2015)$

Question: Claim: $\log_2(2015)$ is irrational
Proof: Let's assume it is rational. Then:
$$\log_2(2015)=a/b, \quad a,b\in \mathbb Z \setminus \{0\}, b\neq 0$$
Question 1: is it okay how I chose a,b?
then we get: $2^{a/b}=2015 \Leftrightarrow 2^a=2015^b$
Now we know: $2015=31\cdot13\cdot5$ so we get:
$$2^a=(31\cdot13\cdot 5)^b=13^b \cdot 13^b \cdot 5^b \tag{$\ast$}$$
Since we know that any integer can be represented uniquely by a multiplication of primes, we would have two ways of representing the same number in such a way. So it wouldn't be unique. Thus, it isn't rational. Thus, it is indeed irrational.
Question: I don't like the step ($\ast$). I see that the argument at the end is indeed what we want but I'm not sure if it really holds, since we have one exponent for several different primes. E.g. one could also get: $2^p=2^q\cdot 31 \cdot 13 \cdot 5$ Which makes it absolutely clear.
Question: Does ($\ast$) hold?
Comment: Seems like everything you do is perfect! But I would instead say that $2^a=31^b\cdot 13^b\cdot 5^5$ forces $a=b=0$, which is a contradiction since $b\neq 0$
Comment: This is the standard proof that irrational logarithms are irrational.
Comment: At ($\ast$), you are simply invoking the fundamental theorem of arithmetic.  That is the usual proof.
Answer: What you did is correct (other than at a passage where you wrote $13$ instead of $31$). But it is simpler to say that $2^a$ is even and $2015^b$ is odd.
Comment: Thanks. Yeah that would be another way

Irrationality of $\log_2(2015)$


'Event' object has no attribute 'e3'

Question:
Hi I am new to python and I have been trying to build a simple calculator where there are three boxes, the first box has a
predefined number.
The second box is user input and the third box is where the product of the first two numbers must appear.
However I am an error 'Event' object has no attribute 'e3'

Please help
    from tkinter import *

    class Calculator(Frame):
        def Widgets(self):
            self.e1 = Entry(self)
            self.e1.grid(row=1, column=1)
            self.e1.insert(0,1)

            self.e3 = Entry(self)
            self.e3.grid(row=1, column=3)

            def estimation_value_1(self):
                self.e3.insert(0, ((e1.get())*(e2.get())))

            self.e2 = Entry(self)
            self.e2.grid(row=1, column=2)
            self.e2.bind("<Return>", estimation_value_1)

        def __init__(self,initial):
            super(Calculator,self).__init__(initial)
            self.grid()
            self.Widgets()

    Window = Tk()
    Window.title("Error")
    Window.geometry("500x500")
    Evaluation_Tool = Calculator(Window)
    Window.mainloop()

Comment: Which line does it tell you the error is on?
Comment: line 13  File "C:\Users\Siva\Desktop\Test_2.py", line 13, in estimation_value_1
    self.e3.insert(0, ((e1.get())*(e2.get())))
AttributeError: 'Event' object has no attribute 'e3'
Comment: Is that the exact code format? because that function inside the method makes no sense... please make sure the indentation and format is correct
Comment: @Incognos: Yeah, the code format is correct. I have found the solution with help of shaowen yin
Answer: def estimation_value_1(self):
    self.e3.insert(0, ((e1.get())*(e2.get())))

the first parameter of the callback function estimation_value_1 is the KeyPress Event. In your function, self is the KeyPress event, not the Calculator object.
You can implement in this way:
def estimation_value_1(event):
    self.e3.insert(0, ((self.e1.get())*(self.e2.get())))

Answer: Thank you it now works as Yin suggested. however, with a small correction. Just converting e1.get and e2.get to float makes it work
def estimation_value_1(event):
            self.e3.insert(0, ((float(self.e1.get()))*(float(self.e2.get()))))

'Event' object has no attribute 'e3'


Inferior limit of a sequence ${1, 3, 1, 5, 1, (n+1), ...}$

Question: Why in my mathbook they say that this sequence ${1, 3, 1, 5, 1, (n+1), ...}$ does not have neither superior nor inferior limit. I think that it's obvious that it has inferior limit. Or am I wrong?
Comment: Would you mind posting the title and page of the book?
Comment: Of course) It is russian mathbook. So I'll write it in russian: "Основы математического анализа" (Beginnings of analysis), page 63, authors В.А. Ильин (V.A. Ilyin), Э.Г. Позняк (A.G. Poznyak), Publisher "Физматлит", Москва ("Fizmatlit", Moscow).
Answer: You are right. The limit inferior is $1$. It is the smallest $L$ such that the original sequence has a subequence converging to $L$.
Comment: Ok, thanks for clearing this for me ;) It is not the first time I see misprints and obvious mistakes in this book. Going to prepare a list of this staff and send it to the publisher.
Answer: Yes, the book is wrong, the lim inf is clearly $1$.
By definition:
$$\liminf_{n\to\infty}x_n := \lim_{n\to\infty}\Big(\inf_{m\geq n}x_m\Big)$$
or
$$\liminf_{n\to\infty}x_n := \sup_{n\geq 0}\,\inf_{m\geq n}x_m=\sup\{\,\inf\{\,x_m:m\geq n\,\}:n\geq 0\,\}.$$
In your case $\inf_{m\geq n}x_m = 1$ for any $n>0$.


Como Achar o ultimo numero da tabela no SQL e somar +1

Question: sou iniciante em programação e preciso de ajuda com esse caso, tenho um Datagridview que vai ser carregado com dados de um banco de dados e com base nesse dados será inserido em um outro banco, porem algumas colunas precisam ter valores padrões, existe uma que estou com problemas, eu preciso achar o ultimo valor dessa tabela e somar mais + 1 sempre que adicionar uma nova linha de dados, eu consegui fazer isso no banco mas no C# não, ou seja, como eu faria essa Select, armazenaria em uma variável ? como eu passaria essa variável como referencia dentro da Select principal ? segue um print de como esta minha Select, ali esta como @Maximo pq tentei fazer um parâmetro pra ela mas não consegui Obrigado!
Answer: No banco de dados existe um mecanismo, no meu caso eu uso o Mysql/MariaDB, que é o AUTO_INCREMENT.
Este mecanismo é no campo que usa para controlar o numero do Registro.
É bom criar um campo chamado ID na tabela, e neste campo liga o AUTO_INCREMENT.
Então quando criar um novo registro este campo já ganha um numero sequencial automaticamente.
Comment: Como está escrito atualmente, sua resposta não é clara. Por favor, pode [edit] para adicionar mais detalhes, que ajudarão outras pessoas a entender como isso resolve a pergunta feita. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Answer: Cara, antes da string do insert, você pode fazer algo como:
<code>select max(REFERENCIA) + 1 as maximo from LANCAMENTO_CONTABIL
</code>
salva o valor retornado do select numa variável e concatena ela no insert
Se quiser dar uma olhada melhor:
https://www.w3schools.com/sql/sql_min_max.asp
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).
Comment: Não recomendo esse tipo de abordagem, salvo raríssimas exceções! Os ambiente são de múltiplos acessos e há uma enorme probabilidade desse "MAX" se repetir devido ao tempo de processamento Banco x Aplicação.


time different betwen two columns in mysql higher than xx days

Question: Please help me:
I have two columns in mysql table - date1 (datetime) and date2 (datetime)
I need find rows where difference between these two days is higher the 14 days.
I tried: select * from table where timediff(date1 - date2) as days > 14
it does not work
Thanky you
Answer: SELECT *
FROM table
WHERE ABS(DATEDIFF(date1,date2)) > 14;


php preg_match problem

Question: how can i get 41P86246HOH7C1G4A983321910HDL63U9 from the following with preg_match
input type="text" value="41P86246HOH7C1G4A983321910HDL63U9" id=""
Comment: Now it looks like you're trying to parse HTML with regular expressions, which is a huge no-no.
Comment: `preg_match("41P86246HOH7C1G4A983321910HDL63U9", $str, $match");`?
Comment: @Anon.: Your example won't work since you forgot the delimiters. ;)
Comment: :) Though, it wasn't intended to be syntactically correct. Notice also the random `"` after `$match`.
Answer: DOMDocument::loadHTML("<$input>")->getElementsByTagName('input')
    ->item(0)->getAttribute('value');

Answer: What about something like this :
$str = 'input type="text" value="41P86246HOH7C1G4A983321910HDL63U9" id=""';
$m = array();
if (preg_match('#value="([^"]+)"#', $str, $m)) {
    var_dump($m[1]);
}

Which will match everything between the double quotes that come with value, and get you :
string '41P86246HOH7C1G4A983321910HDL63U9' (length=33)

But, as a sidenote : if you are trying to "parse" HTML with regex, it's generally not the "best" way ; HTML is not quite regular enough for regex...
Comment: but i want only 41P86246HOH7C1G4A983321910HDL63U9 not extra characters
Comment: what "extra character" do you get ? The regex I posted only gave ...U9 as a result ;; the other informations displayed arround that string in my answer are the output of var_dump (with Xdebug installed).
Answer: Simply, without extra characters:
preg_match('/(?<=value=")[0-9A-Za-z]+/', $str, $match);

Your result is in $match[0];
Answer: With something like this:
if(preg_match('@value="([^"]*)"@', $text, $m)){
    echo $m[1];
}

But you can also make something who split the string in each key with this value.
function attributes($text){
    $attrs = array();

    if(preg_match_all('@(\b[^=]*\b)\s*=\s*"([^"]+)"@', $text, $matches, PREG_SET_ORDER)){
        foreach($matches as $m){
            $attrs[$m[1]] = $m[2];
        }
     }

     return $attrs;
 }

 // Use like this
 $attrs = attributes('input value="bla"');
 if(isset($attrs['value'])){
     echo $attrs['value'];
 }

Answer: don't even have to use regex. Just use PHP's string methods
$str='input type="text" value="41P86246HOH7C1G4A983321910HDL63U9" id=""';
$s = explode(" ",$str);
// go through each element, find "value"
foreach($s as $a=>$b){
    if(strpos($b,"value")!==FALSE){
        $find = explode("=",$b);
        print $find[1];
    }
}

php preg_match problem


Cannot see IIS on "Add Role Services" on Server Manager, How can I install IIS?

Question: I have to install IIS on a server buut I cannot install it on Server Manager, because it is not listed on "Add Role Services" on Server Manager.
How can I install IIS on the server? My server is 2008 version.
Answer: It's not a role service. It's a role.
You will find it by going to Manage > Add Roles and Features:
Comment: my server is windows server 2008. So, I think it is called "Add Role Services", am I right?
Comment: No. The screen you are looking at it trying to add roles to an existing service (in your case, file server). IIS is a totally seperate role that you need to add.


O que é o Riot.js?

Question: Estava lendo sobre alguns frameworks e bibliotecas para desenvolvimento de UI front-end e me deparei com o Riot.js.
Dando uma rápida lida na página da biblioteca (em inglês), concluí superficialmente que eles prometem facilitar a componentização da UI por meio da sua biblioteca.
Surgiram então as dúvidas:

Como já existem várias bibliotecas/frameworks com propósito parecido (Angular, React, Vue, etc.) quais seriam as motivações para se escolher Riot.js?
As "custom tags" que eles oferecem não quebram padrões da web?
Qual seria então, uma visão geral sobre a biblioteca?
Answer: Claramente exposta na documentação, Riot foi inspirado no React do Facebook. A proposta deles é possuir sintaxe simples, e ser leve - leveza é um ponto audacioso a se tocar, porque se a leveza em questão é no desempenho da biblioteca é um desafio para eles competirem com React, principalmente devido a melhor sacada, pra mim, do Facebook - o Virtual DOM.
Riot possui Express Binding, que basicamente armazena as expressões criadas em um array, e cada expressão tem um ponteiro para o nó no DOM. Obviamente que discutir sobre a estrutura de atualização de elementos na árvore DOM é um assunto pra outro almoço (ou post), porém é importante se atentar a isso, porque o que mais difere o concorrente direto do Riot é a estrutura de componentização e Virtual DOM.
E Riot é basicamente isso, um biblioteca com sintaxe mais simples do que seus similares, que tem uma atenção especial no trabalho com templates e que tentou/tenta resolver furos do React.
Comment: Sintaxe complexa e não legível para humanos. Precisar de muito para criar, por exemplo um SPA. Riot promete entregar o "mesmo" resultado por menos, sabendo que está usando somente o necessário.
Comment: Você teria um exemplo do que seria um "furo" no React que o Riot resolva?
Answer:
Como já existem várias bibliotecas/frameworks com propósito parecido
  (Angular, React, Vue, etc.) quais seriam as motivações para se
  escolher Riot.js?

Isso depende do projeto, Riot.Js é muito leve e facilita bastante na criacao de template, agora se voce precisa de algo que precise tabalhar lado a lado com o back-end react nao seria uma boa solucao em comparaçao com as outras frameworks

As "custom tags" que eles oferecem não quebram padrões da web?

Edit:
Gerar novas tags deixa o html depedente da framework, impossibilitado a troca de framework, nao existe uma quebra de padrão e sim um novo padrão implementado.

Qual seria então, uma visão geral sobre a biblioteca?

Gerar template com mais facilidade.
e tem uma boa comparacao bem resumida sobre algumas frameworks aqui: https://nurelm.com/front-end-soup-react-polymer-riot-ember-angular-aurelia/ material em ingles
Comment: Se as *custom tags* não quebram os padrões da Web, de que forma elas atrapalhariam o desenvolvimento, já que elas fazem parte do padrão e todo desenvolvedor terá conhecimento sobre?
Comment: @BrenoCosta https://www.w3.org/TR/custom-elements/
Comment: Também tive esta dúvida, como elas se encaixam nos padrões da W3C?
Comment: Interessante! Obrigado @AndersonCarlosWoss
Comment: "Padrão web" nao estar relacionado com naming, no momento que vc cria uma nova coleção de nomes automaticamente vc esta fazendo um novo padrão. O negativo disso é a depedencia na framework impossibilitando a sua troca.
Comment: eu editei minha resposta sobre o padrao

O que é o Riot.js?


Formula to find cutting angles for a "lean to ladder."

Question:
I would appreciate some help in finding a formula that will help me build my cat's a lean-to ladder.
The ladder will have rails that I will cut from birch plywood, but I need to be able to find the cut angles for the top and bottom of the rails. I know I will probably need the length of the rails and the distance the bottom rail will be from the wall.
Let's say I want my rails to be 5 feet tall (once it is leaning against the wall, so it will have to be cut longer than 5 feet) and the bottom rail will be 18 inches from the wall to the outside of the rail.
This could also be of importance: The steps of the ladder will actually be much larger than traditional ladder steps, with each step being a little platform of sorts. I imagine I will make each step 10 - 12 inches deep by probably 22 inches wide.
A repeatable formula would be great, in case I need to change my measurements. Any thoughts? Also, does anyone know of a simple cad program that will help me design such projects.
Comment: 1) You should give a picture because with your description, I have no idea of what your room looks like... 2) Moreover, I have no idea, being accustomed to metric system, of the number of inches in a foot 3) I don't understand what you mean by "lean to" in " build my cat's a lean to ladder"...
Comment: Nice figure ! The angles are given by their tangents. For the base angle :  $\tan \alpha=\frac{152.4}{45.72} \implies \alpha = \tan^{-1} \frac{152.4}{45.72}=73,3°$ (decimal degrees), the complementary angle being $16.7°$
Comment: @JeanMarie "Lean to Ladders" are described [here](https://www.export.kaiserkraft.com/ladders-scaffolding/lean-to-ladders/c/5262198-KK/)
Comment: @YNK Thank you very much.
Comment: Am I right if I say that the profile of your 'lean-to ladder' amounts to the following geometric construction : a right rectangle whose hypotenuse we know + (above the hypotenuse) a kind of truncated parallelogram ?
Comment: Hi, yes, you are right, it will be a right triangle. I will not know the length of the hypotenuse, but will know the length of the other two sides. I made a diagram in Illustrator and StackExchange linked it to imgur. I hope that helps. I am so lost because I made a D in geometry. I have always had issues visualizing shapes. Algebra came much easier for me. My college degree only required 5 math credits, so I never really went beyond entry level college math. Also I put the measurements in CM.
Answer:
Let say that your feline-friendly ladder is some $\pmb{h}$ units tall and you want the bottom outside edge of its wooden rail to rest on the floor a distance of $\pmb{a}$ units from the wall. Then, you need a birch plywood plank which is longer than $\pmb{b}$ units, where,
$$b=\sqrt{a^2+h^2}.$$
According to the drawing, a finished ladder with the mentioned measurements makes an angle $\measuredangle {\pmb{\theta}}$ with the floor it stands on, where,
$$\measuredangle \theta = \tan^{-1}\left(\dfrac{h}{a}\right).$$
This is the angle you need to make at the end of the plank, which is going to become the bottom of the rail of the finished ladder. At the other end of the plank, which is going to be the top of the rail, a cut must be made with the angle $\measuredangle{\pmb{\beta}}$, where,
$$\measuredangle \beta = 90^o - \measuredangle \theta.$$
The width $\pmb{w}$ and the thickness $\pmb{t}$ of the plank you need for the rails depend on the size and the number of steps you are going to use. The readymade cat ladders available in stores usually have either $9"\times 9"-$ or $11"\times 11"-$ steps. Since you are planning to use steps larger than these industry-standard ones, you need to be careful when you chose $\pmb{w}$ and $\pmb{t}$ for you ladder.  The best advice, which we can give, is "ask an experienced carpenter".
You also need to figure out the number of steps of the ladder. Usually, steps of commercially available cat ladders are placed $9\dfrac{3}{4}"$ apart. When we tried to use this gap in a ladder having your specifications, we ran into a problem. Therefore, we decided to use ${\bf{s}} = 9\dfrac{1}{2}"$ and were able to accommodate 5 steps as shown in the diagram. Don't forget to use a step with a larger depth as the topmost step, which is normally have a hole.
If you want to use a larger gap $\bf{s}$ for your ladder, then you have to change your design, so that the topmost step rests on the wall instead of the top of the rail.
For a numerical example, see Prof. Jean Marie's last comment.
Comment: @JeanMarie I was not sure whether OP is aware of the problems, one would face in this particular do-it-yourself job. That is why decided to provide additional information than OP requested.
Comment: I am cat-egorical : it's a model-answer !
Comment: Sorry, I got busy with life, but I'm finally able to come back to this project. Thank you for taking such care to answer this. Your help is very valuable and my cats thank you.


How to add a custom function in a Drupal theme?

Question: At WordPress there is a well-known way to add a custom function for the theme and hook the code to the  like this:
function add_customcode_header(){
    if(ICL_LANGUAGE_CODE == 'en')
      {
        echo '<link rel="stylesheet" type="text/css" href="/cookie-consent/cookieconsent.min.css" />

';
    }
      else
      {
        echo '<link rel="stylesheet" type="text/css" href="/cookie-consent/cookieconsent.min.css" />

';
      }
    }
    add_action('wp_head', 'add_customcode_header');

How to adjust this code to work on Drupal 7 theme? I need to place the code on all front-end pages header according to the language. Where do I put it?
Edit: Sorry, I that did not provided enough information. I need to add this code to the  section of every page:
<link rel="stylesheet" type="text/css" href="/cookie-consent/cookieconsent.min.css" />

There are 3 languages on the website and I need to place a separate code for each of the language.
Comment: Not sure what the downvotes are for, but you should look over the D7 docs on theming and theme hooks, everything you'd want to know and transposing knowledge can be found there.
Comment: @Kevin It could be the down-votes are for the OP not explaining correctly what the code does. I totally agree that reading the documentation about theming would be a good start, or the OP would have many problems with converting code to Drupal.
Comment: @Kevin @kiamlaluno sorry guys, I just updated the thread to be more clear. I`ve worked with WordPress previously but Drupal is a bit different CMS.
Comment: Well... you certainly don't want to approach it like this.
Comment: @Kevin What would be the best way to implement this?
Comment: This is css and Js so you'll want to look in the theming docs about how to add custom style and scripts to a theme. It's oretty straightforward no PHP needed.
Answer: Since add_action('wp_head', 'add_customcode_header') would add the output of add_customcode_header() to the  tag, the Drupal 7 equivalent is implementing a preprocess function for the HTML output.
Supposing that mytheme is the machine name of the theme, and I want to add a <link> tag for Google's Font API inclusion, this the code I would use.
function mytheme_preprocess_html(&$variables) {
  if ($variables['language']->language == 'en') {
    // The page is using English.
    $element = array(
      '#tag' => 'link',
      '#attributes' => array(
        'href' => 'http://fonts.googleapis.com/css?family=Cardo&subset=latin',
        'rel' => 'stylesheet',
        'type' => 'text/css',
      ),
    );
    drupal_add_html_head($element, 'google_font_cardo');
  }
}

This would add <link href="http://fonts.googleapis.com/css?family=Cardo&subset=latin" rel="stylesheet" type="text/css" /> inside the  tag when the language used for the page is English.
Answer: There's a number of ways you can do this, but I would look into creating a custom block. Your logic that acts on the language would be in the block's output code, and you'd simply use the Block Manager to put it in the correct place in the header. This is a blog I've used before which should be useful (I'm not the author)
http://redcrackle.com/blog/how-create-block-drupal-7
In the tutorial where you see this line:
$block['content'] = t('Hello World!');

You'd instead call a function that returns the content as applicable based on the language.
Comment: If he wants to add a tag in the `head`, OP will need `template_preprocess_html`, not a block
Comment: Yes, the OP wrongly spoke of _header_, but the purpose of `add_action('wp_head', 'add_customcode_header')` is adding tags to  ``.
Comment: He said "header", which is a region of the template, not "head".


how to position/resize image after rotation using css/js so that the image is not positioned outside the div holding it or cropped out

Question: Here's a jsfiddle i'm working on.
The jsfiddle rotates an image upon button click by 90 degrees in clockwise or anti-clockwise direction. The rotated image is displayed outside the parent div when rotated.
The image may be of any height and width.
How can the rotation be modified to display the image within its parent div maintaining its aspect ratio?

var app = angular.module('rotationApp', []);

app.controller('rotationCtrl', ['$scope',
  function($scope) {
    $scope.angle = 0;
    $scope.rotate = function(angle) {
      $scope.angle += angle;
      if (($scope.angle === 360)) {
        $scope.angle = 0;
      }
      if ($scope.angle < 0) {
        $scope.angle += 360;
      }
    }
  }
]);

app.directive('rotate', function() {
  return {
    restrict: 'A',
    link: function(scope, element, attrs) {
      scope.$watch(attrs.degrees, function(rotateDegrees) {
        var r = 'rotate(' + rotateDegrees + 'deg)';
        element.css({
          '-moz-transform': r,
          '-webkit-transform': r,
          '-o-transform': r,
          '-ms-transform': r,
          transform: r
        });
      });
    }
  }
});
img {
  border: green solid 1px;
}
.container {
  margin-top: 100px;
}
.img-holder {
  border: red solid 1px;
  height: 500px;
  width: 500px;
}

        <button type="button" class="btn btn-lg btn-primary" ng-click="rotate(-90)">
          rotate left
        </button>
        <button type="button" class="btn btn-lg btn-primary" ng-click="rotate(90)">
          rotate right
        </button>

Answer: You can add a CSS margin-top property to do this like this :
        var r = 'rotate(' + rotateDegrees + 'deg)';
        element.css({
            '-moz-transform': r,
            '-webkit-transform': r,
            '-o-transform': r,
            '-ms-transform': r,
            transform: r,
            'margin-top' : '100px'
        });

And if you want to keep the image stick to the top when it is not rotate, you can add this condition :
        if(r == "rotate(0deg)" || r == "rotate(180deg)"){
            element.css('margin-top',0);
        }

See the result here
Note : If you remove that last condition, it is perfectly centered to the border.


What is a figure of the learned function in binary classification called?

Question: Correct me if I'm wrong. When we talk about overfitting and underfitting we talk about how the output function made by the neural network is fitted in relation to the data.
What is this function called? Is this just a visual aid to help understand the concept of over- and underfitting, or is it possible to actually plot this function for simple problems with 3 or less dimensions?
Image from Wikipedias overfitting article:

Can I plot these lines? What are these lines called?
Comment: A decision boundary? Note that this is just illustrative and might not show the entire function at all if it is more than two-dimensional.
Comment: Great! That's it. Now I know what to google when diving further into this topic. Put up the answer and I'll accept it. Any suggestions for a more *fitting* title?
Comment: How about: *What is a figure of the learned function in binary classification called?*
Answer: The figure shows a decision boundary for a binary prediction problem. It is a two-dimensional representation of the learned function and shows how the model would decide between the two classes in these two dimensions.
If you have more than two predictors, such a figure is less informative and you may instead want to plot the ROC curve of the model. You could technically still make a similar graph using e.g. PCA or MDS to plot the function along two axes representing the largest variability, but you should be careful how you interpret that.

As you already mentioned, one particular use of a figure of the decision boundary is to visualize over- and underfitting. Another potential use is to visualize the effect of moving the threshold for either decision. For example, in logistic regression you could choose to classify the outcomes as $A:y \leq 0.5$ and $B:y > 0.5$, but you can choose different thresholds as well.
That said, both of these purposes can be fulfilled by better alternatives (e.g. out-of-sample performance estimates) and I think this type of figure is especially useful for didactic purposes.


Calculadora NetBeans - Problemas com operações decimais

Question: Olá, boa noite. Estou tendo que fazer um trabalho de calculadora, e meu código realizava operações como 8+9, 1+7 normalmente, mas não estava fazendo 10+20=3, 50+7=12; o resultado era sempre a soma dos primeiros números. O detalhe de colocar o inteiro *=10; e inteiro += 8; como na foto ajudou bastante.

Mas por que colocar "10" e um asterisco na frente do igual? E um "+" na frente do igual no de baixo? E mais uma coisa, agora ela não está efetuando operações decimais. A vírgula até aparece na tela, mas na hora de executar a operação, ele entende que o número é inteiro. Digito 1,1+1 e ele me dá o resultado como 12. Muito grato, desde já.
Answer: O *= significa que você está fazendo uma operação de multiplicação e atribuindo o resultado para a variável que precede o operador. Dessa forma:
inteiro *= 10;

É o mesmo que:
inteiro = inteiro * 10;

Quanto ao motivo das operações da sua calculadora não funcionarem como deveriam, sugiro que reveja o seu algoritmo antes de continuar codificando.


Writing and reading files

Question: So I made a script like this:
a = open("movies.txt","r")

And I wanted to write something in this so I did:
a.write("EndGame")

But it said it could not write, why?
Comment: Because you opened the file for reading only.
Comment: You used the read handler, `"r"`. Instead, use `a = open("movies.txt","w")`. Check out [this link](https://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files).
Comment: You're mixing up the [three Rs](https://en.wikipedia.org/wiki/The_three_Rs).
Comment: Welcome to Stack OverFlow! Your question currently a [Duplicate](https://stackoverflow.com/help/duplicates), which doesn't meet this site's requirements. Please edit your question following these guidelines: https://stackoverflow.com/help/how-to-ask
Answer: that is because you have entered a wrong file mode. You used r which stands for reading while you should use the w for the writing. That code should work.
a = open("movies.txt","rw")
a.write("EndGame")
a.close()

Comment: @DanielB. Thanks for the hint. I corrected the code.
Comment: There is one double quotation mark missing behind `"rw`. I just cannot add it myself because SO keeps telling me that edits must alter at lest 6 chars.
Comment: @DanielB. thank you, I just made a stupid typo :)

Writing and reading files


How to create installable for my java application + mysql (jar created from maven build spring boot)

Question: I want to test my application in other laptop, that doesn't contain any jre or mysql installed on it, so i must manually install those softwares in order to run my jar file on it.
I want to know how installable are made?
I need to install : JRE,MySql Workbench and the sql file to create database , and make the jar file on desktop.
Note: I created the exe with launch4j, so i need just to create the installable file.
Answer: I suggest

Use flyway or liquibase (or any other) to handle your DDL migrations
Dockerize the application (externalize configuration as env variables)
Setup a nice docker compose using you app image, mysql and whatever else you need
Push to a docker registry and share

Now you have something even more portable than your .exe file.
Regards.
Comment: Thank you for the time taken to answer me, even i didn't understand what you said (as beginner i don't know what is dockerize an application ) but i will search for this solution. Regards


Laravel5 Eloquent: How to get a few articles from special condition?

Question: First, I'm sorry my poor english.
I want to got highest views with 5 articles.
I tried it, but I'm having problem with Eloquent query.
laravel source
<?php
    $up = "SELECT id FROM articles WHERE id IN (SELECT id from (SELECT id FROM articles ORDER BY view_count DESC LIMIT 0,5) x)";
    $builder = new \App\Article;
    $query = $builder->selectRaw("articles.*, $up");
?>
    @forelse($query->latest() as $article)
        thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
    @empty

        empty...

    @endforelse

DB query result
MariaDB [test]> SELECT id FROM articles WHERE id IN (SELECT id from (SELECT id FROM articles ORDER BY view_count DESC LIMIT 0,5) x);
+------+
| id   |
+------+
| 4018 |
| 4045 |
| 3800 |
| 4011 |
| 4005 |
+------+
5 rows in set (0.00 sec)

I've seen the other posts on this topic, but i didn't get the solution.
Thanks for your help.
Comment: also your code is not clean, seriously look into laravel docs.
Comment: maybe you should check out this

https://laravel.com/docs/5.5/eloquent#retrieving-single-models

pretty helpful
Comment: Why two sub-queries? Dosn't the inner query give same result as the query you are using?
Answer: First you have to your services sttuf in the controller to clean up the views and to respect the MVC pattern.
So in the controller you can use Eloquent to do that :
$articles = App\Article::orderBy('view_count', 'desc')
               ->take(5)
               ->get();

return view('SomeView')->withArticles($articles);

And in SomeView.blade.php :
@forelse($articles as $article)
    thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@empty

    empty...

@endforelse

Answer: 5 articles ordered by views you just need to write in your controller:
$articles = Article::orderBy('views', DESC)->take(5)->get();
return view('article', ['articles' => $articles
]);

in your article.blade.php:
@forelse($articles() as $article)
    thumbnail }}" alt="{{ $article->title }}" title="{{ $article->title }}">
@forelse

    empty...

@endforelese


O Blade do Laravel é uma linguagem de programação?

Question: Após uma breve discussão de porquê o HTML não é uma linguagem de programação, caracterizamos que não porque ele não é capaz de realizar cálculos, tomar decisões, mudar informações contidas em algum tipo de memória, etc.
O Blade é a linguagem utilizada pelo Laravel para construção de views. Ele contém as instruções começadas com um @, por exemplo o @if, @section, @for, etc. O mesmo utiliza expressões do Laravel e do PHP para funcionar.
Blade também tem variáveis, porém você não as declara diretamente nele. Ele recebe as variáveis pelo controlador, e você pode acessar com {{ }}.
Esse é um exemplo de um Blade:

        @if (isset($mensagem))

{{ $mensagem }}

        @else

Tudo funcional.

        @endif

O Blade acima foi capaz de entender se a variável $mensagem existe ou não. Tomou uma decisão.
Isso torna o Blade do Laravel uma linguagem de programação?
Comment: Uma das necessidades de uma linguagem de programação é _"mudar informações contidas em algum tipo de memória;"_, se ele apenas acessa a memória mas não a altera, acredito que não seja (por pouco). Não sou especialista então deixarei as respostas pra quem entende
Comment: @Costamilam então, o fato dela ler, mas não criar, me confunde um pouco. Apesar que, com `` você declara, e brevemente poderá ler no Blade. Mas aí você já está utilizando o PHP diretamente, mas logo o Blade também é PHP indireto. Eu não sei.
Comment: Você pode colocar CSS inline nas tags HTML ou dentro do `
Answer: Eu dei uma olhada por cima na documentação e pelo que pude perceber é turing complete, portanto é uma linguagem de programação, assim como qualquer linguagem de template bem completa. O que me fez considerar assim é que tem armazenamento de estado, capacidade de fazer algumas manipulações de dados e controle de fluxo.
É claro que ela deve ser uma camada fina em cima do PHP, mas não deixa de ter "vida própria" mesmo sendo uma transpilação. E não vou considerar que o fato dela poder injetar PHP dentro dê a capacidade total porque aí não é obter o resultado por meios próprios e sim delegando para uma outra linguagem.
Nos comentários se questionou que ela não guarda valor, mas o que é isto na documentação?
@for ($i = 0; $i < 10; $i++)

Coloquei no GitHub para referência futura.
Está criando uma variável, guardando valor nela, mudando este valor e verificando-o. A não ser que tenha algo errado que eu não sei ela permite fazer tudo o que uma máquina computacional precisa.
Comment: Por isso deixei pra outra pessoa :) boa resposta
Comment: Eu só não disse que é uma boa linguagem de programação :P :) HTML+CSS tb é uma linguagem de programação se vc considerar as duas como uma coisa só, mas...
Comment: Esse parte: `capacidade de fazer algumas manipulações de dados`? não entendi isso direito, você está querendo dizer que o `blade` de certo modo é limitado? (eu só gostaria de entender) visto que o `blade` você consegue escrever código e com isso fazer qualquer manipulação.
Comment: Eu não falei em limitação, eu só não sei toda capacidade que ele tem, mas tem o suficiente para ser uma linguagem de programação. Porém limitado ele deve ser em algum nível, tudo é, nada tem poder ilimitado.


How do I use Variable Values Stored Within Variable Values as function arguments?

Question: I'm trying to gather all function arguments within a single variable so I can use the single variable instead of entering all arguments into the function.
Below is what I've done so far to try to achieve this and it hasn't been successful.
Variable that stores all variable values together:
$bindargs = "$var1, $var2, $var3";

Function which I am trying to pass above variable as 3 separate arguments:
function($bindargs);

I want above to run the same as below:
function($var1, $var2, $var3);

Comment: Create `$bindargs` as an array and not a string.  Using a string can cause all sorts of problems and using an array is simpler.
Comment: https://phpdelusions.net/mysqli/simple
Answer: Solution: by using array
$bindargs = array('var1'=>$var1,'var2'=>$var2,'var3'=>$var3);
now pass this $bindargs to the function and use like this
function functionname($bindargs){

$var1 = $bindargs['var1'];
$var2 = $bindargs['var2'];
$var3 = $bindargs['var3'];
// now you can use your logic to perform the action on the variables which you want
}

Comment: right that's why i just removed that solution
Answer: Well, I suppose you could do something like this, with an array:
<?php

function func($a, $b, $c) {
    echo $a."\n";
    echo $b."\n";
    echo $c."\n";

}

$bindargs = ['a','b','c'];
func(...$bindargs);

I don't see why you'd want to. You lose type hinting on your arguments, and named arguments, and this all seems to me like a way just to obfuscate the code and make it difficult for whoever comes after you.
Comment: "bind" suggests the usage tho


Geometric Interpretation of cylindrical and spherical coordinates

Question: Im just wondering how I would go about geometrically interpreting these equations.
$$\rho \sin\phi = 1 $$
$$\cos \phi = \frac{-\sqrt2}{2}$$
$$\rho \cos \phi = 1$$
Answer: HINT
In spherical coordinates indicating with $\phi$ the angle between $OP$ and $z$ axis we have that

$\rho \sin\phi$ is the length of the projection of $OP$ onto $x-y$ plane
$\cos \phi = k$ is a fixed value for $\phi$
$\rho \cos \phi=z$


Setting a View's Menu Item to a Sub-Menu

Question: I'm using Drupal 7.10 and Views 3.1.
This seems like it should be simple but I can't find an answer. I have a menu structure similar to the following:
Main >
    About Us >
        History
        Contact Us
    Members >
        Wiki
        Tasks

The problem is that tasks is a view page but I can't seem to add the view to anywhere but a direct child of Main, there doesn't seem to be a way to add it so that it is a child of Members.
I can simply add a link to the page by adding another menu item but this causes the sub-menu to disappear so that, in this case Wiki disappears.
Is the only way to do this to add a block and add that block to a page? Or am I missing something?
Thanks!
Answer: Okay, so if I understand correctly you have a View Page that is part of your main site hiearchy (main menu).  Unfortunately you can only assign a View (at least through the View interface) to a particular menu, but not any of the children of that menu.  This should be a feature request in the Views issue tracker.
What you need to do is go edit the Main Menu through Administration -> Structure -> Menus, list links for Main Menu, and then find your Tasks page that was dropped in their (should be on the first level) and re-position it to where you want it in your menu hierarchy.
Comment: Yes you understood correctly and this worked! I'll make a feature request, it just seemed like I was missing something obvious but I guess not.
Comment: No problem.  Thanks for the accept and the upvote.
Comment: Err, nevermind, thanks for the accept but not the upvote :)
Comment: Might as well..


SequelizeDatabaseError: operator does not exist: character varying[] @> character varying

Question: I am getting the above error when i am trying to search one array value in array of arrays. My code:
    sequelize.define('room', {
    'id' : {'type' : DataTypes.INTEGER, 'primaryKey' : true, 'autoIncrement' : true},
    'tutor' : {'type' : DataTypes.INTEGER, 'allowNull' : false},
    'students' : {'type' : DataTypes.ARRAY(DataTypes.STRING), 'allowNull' : false},
    'subject' : DataTypes.STRING,
    'date_time' : DataTypes.DATE,
    'status' : {'type' : DataTypes.STRING , 'defaultValue' : "active"},
  }
)

var queryString = "Select * from rooms where status = :statusVar and students @> ANY(:stuArray::character varying[]) ORDER BY CASE when :orderingVar = 'date_time DESC' then date_time end DESC, case when :orderingVar = 'date_time' THEN date_time end ASC OFFSET :offsetNumber LIMIT :limitNumber;"

    return sequelize.query(queryString,{
                      replacements:{
                        statusVar: status,
                        orderingVar: orderVar,
                        limitNumber: itemPerPage,
                        offsetNumber: ((pageNumber-1)*itemPerPage),
                        tutArray: '{' + tutorUserId.toString() +'}',
                        stuArray: ['{' + studName.toString() + '}']
                      },
                        type: sequelize.QueryTypes.SELECT})

where studName = [Emily, John, Dexter];
I want to find all records where 'students' column contains any of the student names i.e., Emily or John or Dexter
Answer: I ended up doing the following and it worked
var queryString = "Select * from rooms where students && :stuArray::varchar[] and status = :statusVar ORDER BY CASE when :orderingVar = 'date_time DESC' then date_time end DESC, case when :orderingVar = 'date_time' THEN date_time end ASC OFFSET :offsetNumber LIMIT :limitNumber;"

'&&' is overlap (have elements in common) operator  Ex: ARRAY[1,4,3] && ARRAY[2,1] returns true. Note that right side of the operator also should be an array in this format stuArray: ['{' + studName.toString() + '}'] i.e., ['{Emily, John, Dexter}']


The order of the cyclic subgroups of $GL(3,q)$

Question: Derek Holt gave an counter example of my question
because i had forgotten to write this fact that $p,q$ are distinct primes. Thus i repair my question.
Let $G=P \ltimes Q$ be a finite group scuch that $P$ is a maximal subgroup of $G$ which $P$ is non-normal cyclic and $P=C_G(P)=N_G(P)$ and $G'=Q \cong C_q \times C_q \times C_q$, where $p,q$ are distinct primes.
. Also assume that $G$ has the properties that if $H,K$ be two distinct non-normal non-cyclic subgroup of $G$, then $H,K$ are conjugate in $G$.
We see that there exists a homomorphism $\varphi : P \longrightarrow Aut(Q)\cong GL(3,q)$. also clearly, $Ker(\varphi)=C_P(Q)=Z(G)$.
I want to know why $P \cong C_p$, where $p=q^2+q+1$ is a prime.
Comment: What leads you to believe that this statement is true?
Comment: I am still not clear what $p$ is. I understand that you want to assume that $p$ is prime, but what is $p$ exactly? Are you defining $p = q^2+q+1$?
Answer: Here is a counterexample with $q=11$. The group ${\rm GL}(3,11)$ has a unique conjugacy class of cyclic subgroups of order $133 = 7 \times 19$.
Let $Q$ be elementary abelian of order $11^3$, let $P \cong C_p$ with $p=133$, and let $G = P \ltimes Q$ with the action corresponding to this cyclic subgroup of ${\rm GL}(3,q)$. The action of $P$ on $Q$ is irreducible, so $P$ is maximal in $G$ and hence $P=C_G(P)=N_G(P)$. Clearly $G'=Q$.
So we have to check the condition that all non-normal non-cyclic subgroups are conjugate in $G$. Let $H$ be a non-cyclic subgroup of $G$. Since $G/Q$ is cyclic, $H \cap Q \ne 1$.
But all nontrivial subgroups of $P$ (i.e. $P$ itself and its subgroups of orders $7$ and $19$) act irreducibly on $Q$, so either $Q \le H$ or $H \le Q$, If $Q \le H$ then $H \unlhd G$, so we can assume that $H < Q$. Then $H$ non-cyclic implies that $|H|=q^2$.
Now $Q$ has exactly $q^2+q+1=133$ subgroups of order $q^2$. Since $P$ and its nontrivial subgroups act irreducibly on $Q$, they cannot normalize $H$, so these $133$ subgroups are all conjugate under the action of $P$.
Note that the fact that $Q$ has $q^2+q+1$ subgroups of order $q^2$, which must all be conjugate under the action of $P$, means that $|P|$ must be divisible by $q^2+q+1$.
If $|P| > q^2+q+1$ then by the Orbit-Stabilizer Theorem, some nontrivial element $g$ of $P$ must stabilize (i.e. normalize) some subgroup $R$ of order $q^2$. Now $\langle g,R \rangle$ is a non-normal subgroup of $G$ of order greater than $q^2$, so it cannot be conjugate to the subgroups of order $q^2$, contradicting the hypotheses. So $|P|=q^2+q+1$.
Comment: The fact that $133$ is not a prime means that it is a counterexample. You asked for help in proving that $P \cong C_p$ where $p=q^2+q+1$ is prime. I have produced an example where it is not prime, so what you are trying to prove is false. You may be angry with me, but in fact I have a lot of time (probably nearly an hour) trying to help you.
Comment: @Rima don't yell. It's an inappropriate behaviour.
Comment: Now you have edited the question. If you change a question after it has been answered, then of course the answer may no longer be correct.  You have not said what $p$ is. Is $|P|=p$?
Comment: I am apologize. you right. I I've edited my question and put in site again. I'm sorry and thanks for response
Comment: Dear Derek Holt, Forgive me for my  inappropriate behavior?
Comment: Yes forgiven! I will try and answer the question when you have said what $p$ is.
Comment: Thanks, $p,q$ are distinct  primes
Comment: Dear Derek Holt, my professor gave a hint but i dont understand! Do you understand his hint? (Hint: the generator of $P$ permutes all subgroups of $Q$). Ofcourse, i see  that $Q$ has $q^2 +q +1$ elements of order $q$ but dont understand $\vert P \vert=p^n=q^2 +q +1$. How can we say $\vert P \vert=p^n=q^2 +q +1$?
Comment: I have added an extra paragraph to my answer showing how to prove that $|P|=q^2+q+1$.
Comment: thanks a lot, can we say $\vert P \vert=q^2 +q+1$ by orbit-stabilizer theorem when $P$ acts on the set of all elemnets of order $q$ of $Q$?
Comment: I think you want to take the subgroups of order $q$ rather than the elements. There are exactly $q^2+q+q$ subgroups of order $q$, so if $|P|>q^2+q+1$ then some element of $P$ stabilizes a subgroup and you get a non-normal non-cyclic subgroup.
Comment: are you sure? in  my book, if $G \cong C_q \times C_q \times C_q$, then $G$ has $q^2+q+1$ elements of order $q$. is ok?
Comment: Every element of $G$ except the identity has order $q$, so there are $q^3-1=(q^2+q+1)(q-1)$ elements of order $q$.
Comment: i think your reason is false, because $C_q \times C_q$ has exactly $q+1$ distinct elements of order $q$ but your reason says that this number is equal to $q^2 -1$!
Comment: because you dont consider case that two subgroups are equal
Comment: You are confused. $C_q \times C_q$ has $q^2-1$ elements of order $q$ and $q+1$ subgroups of order $q$.
Comment: The subgroup Of order $q$ is equal to cyclic group generated by an elemet of order $q$, I dont understand your means!
Comment: Yes that's right. It also has $q^2+q+1$ subgroups of order $q^2$. These all have to be conjugate under the action of $P$.
Comment: Can you explain me why $Q$ has $q^2+q+1$ subgroup of order $q^2$, please?
Comment: Choose two linearly independent generators and divide by the number of pairs of linearly independent generators that generate a specific subgroup to give $(q^3-1)(q^3-q)/((q^2-1)(q^2-q))= q^2+q+1$.
Comment: Thanks a lot, i am so confused in the counting of subgroups, any way trust you instead my book! because my book exercise say that the number of subgroups of order $q$ is equal to $q^2+q+1$
Comment: Your book is correct, there are $q^2+q+1$ subgroups of order $q$.
Comment: but you say that this number is equal to $q^2+q+q$!
Comment: If $X= \lbrace x \in Q \mid |x|=q \rbrace$, then $P$ acts on $X$ by conjugation, this action is transitive?
Comment: Im so sorry, this is last question. in your answer, why $r |q^2-1$ and why an element of order r in $GL(3,q)$ fixes does not act irreducibly, so an element of order $r$ in $P$ would normalize a subgroup of $Q$ of order $q$ or $q2$
Comment: Sorry, $q^2+q+q$ was a typo. I meant $q^2+q+1$.
Comment: I have replaced the proof that $|P|$ cannot be greater than $q^2+q+1$ by a simpler argument based on the Orbit-Stabilizer Theorem.
Comment: Thank you very much, i learned a lot from you, thanks a lot


Select address functionality during checkout for Drupal Commerce 2.x

Question: I am using Drupal Commerce 2.x for my e-commerce website. I have installed the Address module which provides functionality for storing, validating and displaying international postal addresses. I've added the field for the address in the user registration form through which I can accept multiple addresses from the user.
As per the default checkout flow, the user has to mention his address manually while entering shipping details. So, is there any mechanism where the user can select the address previously set by him? Or I have to rely on customisation to achieve this functionality?
Answer: There is a patch in progress to add this feature.
To apply the patch to the most recent version of Commerce (2.1 as of this writing), based on this comment, you can add this to your composer.json:
"drupal/commerce": {
      "reverse profileSelect change to allow PR 760": "https://www.drupal.org/files/issues/2844920-reverse-profileSelect-temp-fix.patch",
      "reuse profiles": "https://patch-diff.githubusercontent.com/raw/drupalcommerce/commerce/pull/760.diff",
      "reuse profiles enhanced": "https://github.com/fliegen/commerce/commit/57c11175d279fe55db9454b4274608195211aeb8.diff",
      "checkbox same as billing": "https://www.drupal.org/files/issues/checkbox-same-as-billing-2852207-69.patch",
  }
  "drupal/commerce_shipping": {
      "profile select enhancement": "https://github.com/fliegen/commerce_shipping/commit/797b5ef351851d60b2cb6c1a55837501c2a036a5.diff",
      "profile in shipping method widget fix": "https://www.drupal.org/files/issues/profile-reuse-enhanced-2908683-1.patch",
      "auto-recalculate shipping": "https://www.drupal.org/files/issues/commerce_shipping-autorecalculate-2849756-35.patch"
  }

You don't need to add the checkbox same as billing and commerce_shipping part if you are not collecting a shipping address.


Proving set is equicontinuous using compactness

Question: Consider the space $C([0, 1])$ of continuous functions $f : [0, 1] → R$ with
the supremum norm. Define the set $S$ by
$$S = {f ∈ C([0, 1])| 0 ≤ f'(x) ≤ 1, f(0) = 0, ∀x ∈ [0, 1]}$$
Prove that $S$ is equicontinuous.
I know that if S is compact in the sup-norm metric, then S is equicontinuous, but I am not sure how to prove compactness.
Comment: No, that's too easy of an approach; usually you use Arzela-Ascoli the other way, to *get* compactness by *checking* boundedness+equicontinuity. In this problem you need to proceed directly, specifically you need to explain how knowing that $|f'(x)| \leq 1$ gives you a uniform modulus of continuity which does not depend on the particular $f$ that you're dealing with.
Answer: In order to show that a family of functions $\mathcal A$ is equicontinuous you need to show that given $\epsilon>0\exists \delta>0$ such that $|f(x)-f(y)|<\epsilon $ whenever $|x-y|<\delta$ for all $f\in \mathcal A$
Note that For any $f\in S$; $|f(x)-f(y)|=|f^{'}(c)||x-y|\le |x-y|$
Can you find a uniform $\delta >0$ for all $f\in S$ from here ?
Comment: You used Mean Value Theorem correct? And you would choose delta to equal epsilon right?
Comment: You are absolutely correct.Bingo!
Comment: Any more doubts?You can consider accepting it if you like@3141


10 names in a hat — odds that no one picks themself?

Question: I have an annual tradition where 10 names are placed in a hat, and those same 10 members randomly select one at a time. If anyone selects their own name, the entire process restarts.
What are the odds that all 10 people select a name that is NOT themself?
Comment: https://www.google.com/url?sa=t&source=web&rct=j&url=http://mathworld.wolfram.com/Derangement.html&ved=2ahUKEwiw8_yVzt7eAhWrq4MKHf92CVQQFjAEegQIDhAY&usg=AOvVaw0Z_5qIm8r2Qa70skaw6PaT.
Comment: This is a [derangement](https://en.wikipedia.org/wiki/Derangement) problem.  Did you mean [probability](https://en.wikipedia.org/wiki/Probability) rather than [odds](https://en.wikipedia.org/wiki/Odds)?
Comment: Yes, I suppose probability would be the correct term here. Given the conditions described above, how would that be calculated?
Answer: Drawing the slips so nobody gets their own is equivalent to putting them in the same order as the people, then rearranging them so none is in its original place.  A  rearrangement that achieves this is known as a derangement.
Counting derangements is trickier than one would think. A person whose slip has already been drawn can choose freely, while someone whose slip hasn't been drawn can't—and we have to somehow account for both possibilities. It gets quite intricate.
SoI won't try to explain the counting process here. I'll simply say there's a number $!n$ (the subfactorial of $n$) which counts the number of derangements of $n$ items. $!n$ can be calculated either a laborious way, or a ridiculously straightforward way.
Laborious way
The formula is
$$!n=n! \left(\frac{1}{0!}-\frac{1}{1!}+\frac{1}{2!}-... +\frac{(-1) ^n}{n!} \right)$$
(The $(-1)^n$ is just a way of saying that the plus and minus signs keep alternating.)
Easy way
$$!n≈ \frac{n!}{e}$$
The approximation is so close that for any $n>0$, $!n$ is simply the nearest integer to $\frac{n!}{e}$.
This happens because the bracketed part of the laborious formula also happens to be the first few terms of a series for calculating $\frac{1}{e}$.
Getting the answer
To get the probability of nobody drawing their own name, we need to divide the number of derangements of the slips by the total number of possible arrangements. For $n$ slips:

the number of possible arrangements is $n!$ (since there are $n$ choices for the first one, $n-1$ for the second, and so on).
the number of derangements is $!n$.

So the probability $P_n$ of nobody drawing their own slip is $$P_n=\frac{!n}{n!}.$$
We've now got several ways to calculate this for $10$ people:

divide the nearest integer to $\frac{10!}{e}$ by $10!$.
notice that $\frac{!n}{n!}$ is just the bracketed part of the laborious formula, and use that.
be satisfied with an approximation: if $!n≈ \frac{n!}{e}$, then $\frac{!n}{n!} ≈ \frac{1}{e}$.

Just for the fun of it, let's try all three.
Doing it the first way:

$$P_{10} =\frac{1,334,961}{3,268,800}=\frac{16,481}{44,800} ≈0.3679$$

The second way:

$$P_{10} = \frac{1}{0!}-\frac{1}{1!}+\frac{1}{2!}-\frac{1}{3!}...+\frac{1}{10!}≈0.3679$$

The third way:

$$P_{10}≈\frac{1}{e}≈0.3679$$

Although this is an approximation, it's not particularly approximate: it doesn't differ from the correct value until the $8$th decimal place.
So the probability that nobody out of the $10$ draws their own name is about $0.3679=36.79\%$, and is nearly exactly $\frac{1}{e}$.


Is there a way to use cross validation to do variable/feature selection in R?

Question: I have a data set with about 70 variables that I'd like to cut down.  What I'm looking to do is use CV to find most useful variables in the following fashion.
1) Randomly select say 20 variables.
2) Use stepwise/LASSO/lars/etc to choose most important variables.
3) Repeat ~50x and see which variables are selected (not eliminated) most frequently.
This is along the lines of what a randomForest would do, but the rfVarSel package seems to only work for factors/classification and I need to predict a continuous dependent variable.
I'm using R so any suggestions would ideally be implemented there.
Comment: I think your procedure is unlikely to improve on the LASSO, whose implementations in R (e.g. glmnet and penalized) do by default employ cross-validation to find the "optimal" regularization parameter. One thing you could consider is repeating the LASSO search for this parameter several times to cope with the potentially large variance of cross-validation (repeated CV). Of course, no algorithm can beat your subject-specific prior knowledge.
Comment: Are all the features important? How many samples do you have? If I understand the problem correctly, you can try to do some variant of boosting - repeatedly select subset of samples and fit all variables to them and see which ones pop-up more often.
Answer: I believe what you describe is already implemented in the caret package.  Look at the rfe function or the vignette here: http://cran.r-project.org/web/packages/caret/vignettes/caretSelection.pdf
Now, having said that, why do you need to reduce the number of features?  From 70 to 20 isn't really an order of magnitude decrease.  I would think you'd need more than 70 features before you would have a firm prior believe that some of the features really and truly don't matter.  But then again, that's where a subjective prior comes in I suppose.
Answer: There is no reason why variable selection frequency provides any information that you do not already get from the apparent importance of the variables in the initial model.  This is essentially a replay of initial statistical significance.  you are also adding a new level of arbitrariness when trying to decide on a cutoff for selection frequency.  Resampling variable selection is badly damaged by collinearity in addition to the other problems.
Answer: I have revised my answer from earlier today. I have now generated some example data on which to run the code. Others have rightly suggested that you look into using the caret package, which I agree with. In some instances, however, you may find it necessary to write your own code. Below I have attempted to demonstrate how to use the sample() function in R to randomly assign observations to cross-validation folds. I also use for loops to perform variable pre-selection (using univariate linear regression with a lenient p value cutoff of 0.1) and model building (using stepwise regression) on the ten training sets. You can then write your own code to apply the resultant models to the validation folds. Hope this helps!
################################################################################
## Load the MASS library, which contains the "stepAIC" function for performing
## stepwise regression, to be used later in this script
library(MASS)
################################################################################

################################################################################
## Generate example data, with 100 observations (rows), 70 variables (columns 1
## to 70), and a continuous dependent variable (column 71)
Data <- NULL
Data <- as.data.frame(Data)

for (i in 1:71) {
for (j in 1:100) {
Data[j,i]  <- rnorm(1) }}

names(Data)[71] <- "Dependent"
################################################################################

################################################################################
## Create ten folds for cross-validation. Each observation in your data will
## randomly be assigned to one of ten folds.
Data$Fold <- sample(c(rep(1:10,10)))

## Each fold will have the same number of observations assigned to it. You can
## double check this by typing the following:
table(Data$Fold)

## Note: If you were to have 105 observations instead of 100, you could instead
## write: Data$Fold <- sample(c(rep(1:10,10),rep(1:5,1)))
################################################################################

################################################################################
## I like to use a "for loop" for cross-validation. Here, prior to beginning my
## "for loop", I will define the variables I plan to use in it. You have to do
## this first or R will give you an error code.
fit <- NULL
stepw <- NULL
training <- NULL
testing <- NULL
Preselection <- NULL
Selected <- NULL
variables <- NULL
################################################################################

################################################################################
## Now we can begin the ten-fold cross validation. First, we open the "for loop"
for (CV in 1:10) {

## Now we define your training and testing folds. I like to store these data in
## a list, so at the end of the script, if I want to, I can go back and look at
## the observations in each individual fold
training[[CV]] <- Data[which(Data$Fold != CV),]
testing[[CV]]  <- Data[which(Data$Fold == CV),]

## We can preselect variables by analyzing each variable separately using
## univariate linear regression and then ranking them by p value. First we will
## define the container object to which we plan to output these data.
Preselection[[CV]] <- as.data.frame(Preselection[CV])

## Now we will run a separate linear regression for each of our 70 variables.
## We will store the variable name and the coefficient p value in our object
## called "Preselection".
for (i in 1:70) {
Preselection[[CV]][i,1]  <- i
Preselection[[CV]][i,2]  <- summary(lm(Dependent ~ training[[CV]][,i] , data = training[[CV]]))$coefficients[2,4]
}

## Now we will remove "i" and also we will name the columns of our new object.
rm(i)
names(Preselection[[CV]]) <- c("Variable", "pValue")

## Now we will make note of those variables whose p values were less than 0.1.
Selected[[CV]] <- Preselection[[CV]][which(Preselection[[CV]]$pValue <= 0.1),] ; row.names(Selected[[CV]]) <- NULL

## Fit a model using the pre-selected variables to the training fold
## First we must save the variable names as a character string
temp <- NULL
for (k in 1:(as.numeric(length(Selected[[CV]]$Variable)))) {
temp[k] <- paste("training[[CV]]$V",Selected[[CV]]$Variable[k]," + ",sep="")}
variables[[CV]] <- paste(temp, collapse = "")
variables[[CV]] <- substr(variables[[CV]],1,(nchar(variables[[CV]])-3))

## Now we can use this string as the independent variables list in our model
y <- training[[CV]][,"Dependent"]
form <- as.formula(paste("y ~", variables[[CV]]))

## We can build a model using all of the pre-selected variables
fit[[CV]] <- lm(form, training[[CV]])

## Then we can build new models using stepwise removal of these variables using
## the MASS package
stepw[[CV]] <- stepAIC(fit[[CV]], direction="both")

## End for loop
}

## Now you have your ten training and validation sets saved as training[[CV]]
## and testing[[CV]]. You also have results from your univariate pre-selection
## analyses saved as Preselection[[CV]]. Those variables that had p values less
## than 0.1 are saved in Selected[[CV]]. Models built using these variables are
## saved in fit[[CV]]. Reduced versions of these models (by stepwise selection)
## are saved in stepw[[CV]].

## Now you might consider using the predict.lm function from the stats package
## to apply your ten models to their corresponding validation folds. You then
## could look at the performance of the ten models and average their performance
## statistics together to get an overall idea of how well your data predict the
## outcome.
################################################################################

Before performing cross-validation, it is important that you read about its proper use. These two references offer excellent discussions of cross-validation:

Simon RM, Subramanian J, Li MC, Menezes S. Using cross-validation to evaluate predictive accuracy of survival risk classifiers based on high-dimensional data. Brief Bioinform. 2011 May;12(3):203-14. Epub 2011 Feb 15. http://bib.oxfordjournals.org/content/12/3/203.long
Richard Simon, Michael D. Radmacher, Kevin Dobbin and Lisa M. McShane. Pitfalls in the Use of DNA Microarray Data for Diagnostic and Prognostic Classification. JNCI J Natl Cancer Inst (2003) 95 (1): 14-18. http://jnci.oxfordjournals.org/content/95/1/14.long

These papers are geared toward biostatisticians, but would be useful for anyone.
Also, always keep in mind that using stepwise regression is dangerous (although using cross-validation should help to alleviate overfitting). A good discussion of stepwise regression is available here: http://www.stata.com/support/faqs/stat/stepwise.html.
Let me know if you have any additional questions!
Answer: I just found something nice over here: http://cran.r-project.org/web/packages/Causata/vignettes/Causata-vignette.pdf
Try this maybe when using the glmnet Package
# extract nonzero coefficients
coefs.all <- as.matrix(coef(cv.glmnet.obj, s="lambda.min"))
idx <- as.vector(abs(coefs.all) > 0)
coefs.nonzero <- as.matrix(coefs.all[idx])
rownames(coefs.nonzero) <- rownames(coefs.all)[idx]


How to print min of set in python?

Question: I have a set
ww = [{27, 29, 6, 71}, {75, 52, 29, 46, 7}, {20, 71}, {59}, {52, 37, 15}]

and I want to print the element that has the shortest length ie. {59} in this example.
min(ww)

would only give me {27, 29, 6, 71} instead of {59}
is there a way of using min() to do this? or any other smart methods?
Comment: Use `min(ww, key=len)`. Lists are sorted lexicographically, So you need to specify the key, See http://stackoverflow.com/questions/34050113/how-does-the-min-max-function-on-a-nested-list-work/34115735#34115735
Comment: Set the key to length
Answer: Try this,
In [3]: min(ww,key=len)
Out[3]: {59}

Or
In [4]: sorted(ww,key=len)[0]
Out[4]: {59}

Comment: Why would you ever use an O(n log n) approach ? Even to get the k shortest length sub-elements there are better approaches.

How to print min of set in python?


Tests using Postgres images via Testcontainers time out

Question: I'm working on a Spring Boot project with a Postgres database backend where JUnit 5 and Testcontainers is used for integration tests that involve database access.
Testcontainers is set up by modifying the JDBC URL like this:
spring:
  datasource:
    url: jdbc:tc:postgresql:9.6.8:///test

This setup did work fine for many months but now I'm hitting a road block.
So far there are already 20 integration test classes and adding another one leads to failing tests due to an error that looks like a time out to me.
When adding the 21st test class, another test (let's call it RandomTest) hangs for a few minutes and then fails with this error:
 java.lang.IllegalStateException at DefaultCacheAwareContextLoaderDelegate.java:98
        Caused by: org.springframework.beans.factory.BeanCreationException at AbstractAutowireCapableBeanFactory.java:1804
            Caused by: org.flywaydb.core.internal.exception.FlywaySqlException at JdbcUtils.java:68
                Caused by: java.sql.SQLException at JdbcDatabaseContainer.java:263
                    Caused by: org.postgresql.util.PSQLException at ConnectionFactoryImpl.java:659

I know it can't be a problem with the test per se, because when I run it individually, there's no problem:
./gradlew test --tests RandomTest
[...]
BUILD SUCCESSFUL in 16s

It may also be noteworthy that I only have this problem when running the tests with Gradle (both locally and on the CI server). I don't see this problem when running them in IntelliJ.
So it looks to me like this is some kind of resource problem like the Postgres instance that Testcontainers starts up running out of memory or out of connections or whatever, but that's just guessing.
I tried different configuration modifications that I found in the Testcontainers docs:

Running the container in daemon mode like this:

spring:
  datasource:
    url: jdbc:tc:postgresql:9.6.8:///test?TC_DAEMON=true

Disabling Ryuk by setting TESTCONTAINERS_RYUK_DISABLED=true
Starting Ryuk in (un-)privileged mode explicitly with ryuk.container.privileged=true|false (I tried both because I'm not sure what the default is)

None of these had a noticeable impact in terms of my problem.
I'm thinking that maybe we are overusing Testcontainers for too many tests? Should I instead use H2 for most integration tests and use Testcontainers only for a few selected tests to make sure that everything works with the production database?
Or am I missing something?
Comment: Yeah, I think I actually found the cause of the problem lying in the newly added test as described in the answer I provided. Thanks a lot to both @KevinWittek and yuppie-flu for giving me important data points to think about!
Comment: Why did you expect this issue is in any way related to Ryuk? We need more logs to understand the issue, but for me, this looks like an issue related to Spring connection pooling in conjunction with Flyway, hard to say. In your test setup, wouldn't you expect to reuse the same container for every test? Can you share a reproducer? Also the comment regarding IntelliJ vs Gradle execution hints at something weird, class loading issues?
Comment: Playing with the Ryuk config was just a shot in the dark, to be honest. Only one postgres container gets started for all the tests in one test run, yes. Not sure what you mean by reproducer? Yeah, it is a bit of a weird problem :)

I mean, the project is still running on a fairly old version of Spring Boot (2.5) and Flyway (7.7), so maybe I should try and update those first.

Anyway, thanks for your suggestions!
Comment: Is there anything special about your new RandomTest? What if instead of the RandomTest you add a copy of an old existing test, but with a different name, will the build still fail? I don't think it's something related to performance, I've seen setups with 100+ integrations test with testcontainers without any issues. I'd guess some of your tests messes up with the shared cached spring context and your new test is executed afterwards with this "broken" context.  Btw what it the exact PSQLException?
Answer: Okay, it turned out that it actually was a problem with the newly added test.
The test author had added a method that was supposed to clean up the database after the test like this:
@AfterEach
public void beforeEach() {
    fooRepository.deleteAll();
    barRepository.deleteAll();
    bazRepository.deleteAll();
}

When removing this, all the tests work fine again. I guess this clean up takes a bit longer than execution of the test itself so that the database connection is not released in time for the next test to use it, or something like this.
Comment: Yeah, maybe, I don't know. The configuration of the database connection seems to be very basic, can't imagine what could be wrong with it. There's one fairly wild stuff going on in the entities code: a manually implemented custom Hibernate type. Maybe that one's causing trouble... But for now removing the `@AfterEach` method works fine for me. It's redundant anyway because all tests already clear the repos _before_ running.
Comment: This is strange, the other tests should not start until the `AfterEach` method has finished. It still looks like some kind of Spring usage issue to me.


How to multiply a row?

Question: I have a Postgres 9.0 query returning results in a way similar to this:
item;qty
AAAA;2
EEEE;3

What I would like is to transform that into:
AAAA
AAAA
EEEE
EEEE
EEEE

Is there any way I can do that on simple, i.e., without stored procedures, functions, etc?
Comment: What will you use the duplicated values for? There might be a less-awkward solution to the ultimate problem...
Comment: [What have you tried?](http://mattgemmell.com/2008/12/08/what-have-you-tried/) Beyond that ... do you mean to say you've crammed `item` and `qty` into one column as text? If so - don't do that. Problem half way solved.
Comment: I assume you're using some sort of presentational layer after fetching the data; giving the effect of "multiplying" rows like that in the front end could make a lot more sense, as @djacobson says tell us what you're trying to do.
Comment: @djacobson Sorry for the late answer. item is a string column and qty an integer column. Think of it as a list of items in a purchase order. qty is an attribute indicating the number of equal items. Yes, the final target is to display this in a sort of presentational layer, but it's quite limited, so if possible I will prefer a solution in SQL. In the end, the solution provided by Luther_Blissett worked like a charm. Thanks all for the help!
Answer: There's a function 'generate_series' which can be used to generate a table of values. These can be used to repeat a column via joining:
select item
from data,generate_series(0,1000)
where generate_series<qty order by item;

Answer: Consider the following demo:
CREATE TEMP TABLE x(item text, qty int);

INSERT INTO x VALUES
 ('AAAA',2)
,('EEEE',3)
,('IIII',4);

SELECT regexp_split_to_table(rtrim(repeat(item||'~#~',qty),'~#~'),'~#~') AS item
FROM   x;

Produces exactly the requested result.

In my tests it performs faster by an order of magnitude than the solution with generate_series().
Additional bonus: works with any number of qty.
Weakness: you need a delimiter-string not contained in any item.
Answer: SELECT
  myTable.item
FROM
  myTable
INNER JOIN
  (SELECT 1 AS counter UNION ALL SELECT 2 UNION ALL SELECT 3) AS multiplier
    ON multiplier.counter <= myTable.qty

Increase the number of UNIONS based on your Maximum value in qty

But I'd also follow @djacobson's advice : explain why you want to do this, as the may be a completely different approach altogether.  Doing this feels, ummm, odd...
Comment: *shudders at the thought using this with qty > 5*
Comment: @NullUserException : Meh, there are a plethora of ways of creating a sequential list of numbers.  The more shuddering thought is what may be done with these results :)

How to multiply a row?


Show that $\liminf(\sqrt{x_n})=\sqrt{\liminf x_n}$

Question:
Let $(x_n)$ be a bounded sequence of real numbers such that $x_n \ge0$ for each $n \in \mathbb N$. Show that $\liminf(\sqrt{x_n})=\sqrt{\liminf x_n}$.

I assume we need to consider the subsequence of ($\sqrt{x_n}$), but I'm really confused with the  notion on "boundedness". Can I assume the question implies an upper bound on $(x_n)$?
Even then wouldn't the equation be implied? Given how roots generally affect limits.
Comment: Yes, it implies. Bounded sequence means that there exists an $M\in\mathbb{R}$ such that $x_n\leq M$ for all $n\in\mathbb{N}$.
Comment: Such problems are usually solved by expansion of the definitions. (BTW, use "\inf" instead of "inf" to make the formulas looking better)
Comment: There's pretty much nothing to do once you use the following property: $\lim \inf x_n$ is the smallest limit a convergent subsequence of $x_n$ can have.
Comment: @LeGrandDODOM The problem i'm having is actually explicitly showing it. I thought of taking one such limit e.g. $u \in S(x_n)$ and showing that if $u$ is the smallest limit in $S(x_n)$ then $\sqrt{u}$ is the smallest limit in $S(\sqrt{x_n})$. But this turns into and if and only if statement
Answer: I'll be using the following property:
Given a sequence $x_n$, $\lim \inf x_n$ is the smallest limit a convergent subsequence of $x_n$ can have.
Let $x_{n_k}$ be a subsequence of $x_n$ that converges to $\lim \inf x_n$.
Then $\sqrt{x_{n_k}}$ converges to $\sqrt{\lim \inf x_n}$. But $\sqrt{x_{n_k}}$ is a subsequence of $\sqrt{x_{n}}$. Hence $\lim \inf \sqrt{x_{n}}\leq \sqrt{\lim \inf x_n}$.
The reverse inequality can be proved in a similar fashion.
Comment: If you don't mind, could you please include the details for the reverse inequality as well? I think we could get the reverse inequality for $\lim \sup$, but I don't see how to get it for $\lim \inf$
Comment: @Blue Let $n_k$ be indexes such that $\sqrt{x_{n_k}}$ converges to  $\lim \inf \sqrt{x_{n}}$. Since $x_{n_k} = \sqrt{x_{n_k}} ^2$ is a subsequence of $x_n$ that goes to $(\lim \inf \sqrt{x_{n}})^2$ , we have $\liminf x_n \leq (\lim \inf \sqrt{x_{n}})^2$, hence $$\sqrt{\liminf x_n} \leq \lim \inf \sqrt{x_{n}}$$
Comment: Thank you so much!


Null hypothesis

Question: I have a random sample ${X_1,...,X_N}$, and we know that X bar $=3$, and the standard error $SE(X bar)=2 $. Suppose a new variable $Y_i$ is defined as $Y_i=0.17+0.1X_i$. The null hypothesis $H_0: E(Y_i)=0.25$ against a two-sided alternative at a 5% significance level.
My questions is: I know that the formula is $(Y-\mu)/SE$, and then see if it falls into the interval $[0.2, 0.3]$. I've found Y bar, wondering how to find $\mu$ and SE for Y. thanks!
Answer: (this should maybe be moved on xvalidated)
Using the usual properties for the mean and variance you have

$\overline Y=0.17+0.1\overline X = 0.47$
$SE(Y)=(0.1) SE(X) = 0.2 $

You want a two-sided 5% confidence interval so you're looking at the interval
$$0.47 \pm 1.96\times 0.2 = [0.078, 0.862]$$
and you cannot reject the null.
Comment: wait a minute, should SE(Y) be 0.2, instead of 0.02? Since there is a square root, so it should be $0.1SE(X)$?
Comment: Got it. Thanks!
Comment: Why can we reject the null?
Comment: yes I made a mistake, apologies for the confusion it's a bit late over here, fixed in the answer

Null hypothesis