Why is my navigation code not working? kivy python

Question: I have a screen manager ThirdWindow which is supposed to change the screen when B1 is clicked basically a navigation thing. Please note ThirdWindow is a a different class. callback is called when B1 is clicked. it changes the screen with the help of ThirdWindow I think. I used self.manager.current it didn't worked, I also tried using it by making ThirdWindow a def in class Dre but the results were same. The print statement is not getting printed that is inside def callback(self, instance) so I think the def is not getting called on_click at all. How can I fix that? Thanks
import kivy
from kivy.app import App
from kivy.core.audio import SoundLoader
from kivy.uix.gridlayout import GridLayout
from kivy.uix.label import Label
from kivy.uix.textinput import TextInput
from kivy.uix.button import Button
from kivy.uix.stacklayout import StackLayout
from kivy.uix.relativelayout import RelativeLayout
from kivy.graphics import Rectangle
from kivy import platform
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen

class MainWindow(Screen):
    pass

class ThirdWindow(ScreenManager):
    def load(self):
        sm = ScreenManager
        sm.add_widget(Dre(name='Dre'))
        sm.add_widget(SecondWindow(name='SecondWindow'))
        self.sm.current = 'Dre'

class Dre(RelativeLayout):
    def __init__(self, **kwargs):
        super(Dre, self).__init__(**kwargs)
        self.color = [254/255, 102/255, 37/255, 1]
        self.H_color = [254/255, 102/255, 37/255]
        self.sound_theme = None
        self.init_audio()
        self.kv = Builder.load_file('Levels.py')

        if platform in ('linux', 'win', 'macosx'):
            with self.canvas.before:
                self.bg = Rectangle(size=self.size, source='Neo.png')

            self.bind(pos=self.update_bg)
            self.bind(size=self.update_bg)
        else:
            with self.canvas.before:
                self.bg = Rectangle(size=self.size, source='Neon.png')

            self.bind(pos=self.update_bg)
            self.bind(size=self.update_bg)

    def update_bg(self, *args):
        if platform in ('linux', 'win', 'macosx'):
            self.bg.pos = self.pos
            self.bg.size = self.size
            self.add_widget(Label(text='D  R  E  A  M  S',
                          pos_hint={'center_x': .5, 'center_y': .8},
                          font_size='60dp', font_name='Roboto-Bold.ttf', color=self.H_color))
            B1 = Button(text='P L A Y', font_name='Roboto-Bold.ttf', size_hint=(.2, .15),
                     pos_hint={'center_x': .5, "center_y": .3}, background_color = self.color, background_normal='')
            # B1.bind(on_press=return self.kv)
            self.add_widget(B1)

        else:
            self.bg.pos = self.pos
            self.bg.size = self.size
            self.add_widget(Label(text='D  R  E  A  M  S',
                                  pos_hint={'center_x': .5, 'center_y': .8},
                                  font_size='30dp', font_name='Roboto-Bold.ttf', color=self.H_color))
            B1 = Button(text='P L A Y', font_name='Roboto-Bold.ttf', size_hint=(.2, .15),
                        pos_hint={'center_x': .5, "center_y": .3}, background_color=self.color, background_normal='',
                        on_press=self.callback)

            self.add_widget(B1)

    def callback(self, instance):
        print('working')
        self.manager.current = 'SecondWindow'

    def init_audio(self):

        self.sound_theme = SoundLoader.load('Bg_theme.mp3')
        self.sound_theme.volume = 1
        self.sound_theme.loop = True
        if self.sound_theme:
            self.sound_theme.play()
            print('okay')
        else:
            print('not okay')

class SecondWindow(Screen):
    def __init__(self, **kwargs):
        super(SecondWindow, self).__init__(**kwargs)
        self.color = [254 / 255, 102 / 255, 37 / 255, 1]
        if platform in ('linux', 'win', 'macosx'):
            with self.canvas.before:
                self.bg = Rectangle(size=self.size, color=self.color)

class LabApp(App):
    def build(self):
        return Dre()

if __name__ == '__main__':
    LabApp().run()```

if you provide any solution please provide it in .py file.

Comment: What is in `'Levels.py`?
Comment: `Levels.py` is another folder with an empty class. I tried using another folder for different screens before but then moved them all into one script. So is it causing the problem? Pls help. I still can't figure out the problem
Answer: Many issues with your code.
First, you have defined a ScreenManager class (ThirdWindow), but you have not created an instance of it or included it in your GUI. In order to use a ScreenManager to manage Screens, you must add it to your GUI. I would suggest modifying your LabApp class to use ThirdWindow:
class LabApp(App):
    def build(self):
        return ThirdWindow()

and modify ThirdWindow to replace the load() method with an __init__() method:
class ThirdWindow(ScreenManager):
    def __init__(self, **kwargs):
        super(ThirdWindow, self).__init__(**kwargs)
        self.add_widget(Dre(name='Dre'))
        self.add_widget(SecondWindow(name='SecondWindow'))

Since the Dre class is being used as a Screen, it must be redefined as a Screen:
class Dre(Screen):

and you can add the callback to the creation of the B1 Button:
        B1 = Button(text='P L A Y', font_name='Roboto-Bold.ttf', size_hint=(.2, .15), on_release=self.callback,
                 pos_hint={'center_x': .5, "center_y": .3}, background_color = self.color, background_normal='')


Why this set is countable?

Question: Why is the following set countable? (someone told me it's apparent but I cannot figure out a rigorous proof)
$$S=\{\sum_{i=1}^nc_ie_i|n\in N^+, c_i\in Q\}$$
where $N^+$ is the set of positive integers, $Q$ is the set of rational numbers and $\{e_i\}$ is a Shauder's basis of a Banach space.
Answer: It is more or less explicitly a countable union of countable sets.
It is the union over $n \in \mathbb{N}$ of the same kind of sums but with just exactly $n$ terms.
And the sum with just $n$ terms is a rational linear combination of the first $n$ terms of the basis and so clearly bijects with $\mathbb{Q}^n$, which is countable.
Answer: Hint: There is a natural injection that you can make from $S$ to $\mathbb{N} \times \mathbb{Q}$ thus, $S$ is countable if $\mathbb{N} \times \mathbb{Q}$ is countable.

Why this set is countable?


How do I manually refresh-token while creating apps using Zapier CLI

Question: I want to perform refresh token but my gateway gives HTTP response 403 instead of 401 so I cannot use 'autoRefresh' feature of Zapier.
I tried throwing 'RefreshTokenException' when the response status is 403 as given below:
return responsePromise
    .then((response) => {
    if (response.status == 403) {
        throw new RefreshTokenException();
    }
    ...
});

But upon doing this I get an Error from Zapier (while creating zaps) stating:

RefreshTokenException is not defined

Can anyone help me with manually refreshing token using Zapier CLI platform for app creation?
Answer: David here, from the Zapier Platform team. Sorry for the slow reply, we're just now seeing some of these.
It's not defined because that's not an error we define. You've got the right idea, you just need to use RefreshAuthError instead. See these docs.
Let me know if you've got any other questions!


Programa.exe parou de funcionar

Question: Estou fazendo um programa que captura o nome completo de uma pessoa e o reproduz nesse formato: sobrenome, nome sem sobrenome (EX:João Carlos Cunha -> Cunha, João Carlos. Amanda Batista -> Batista, Amanda). Só que o usuário pode digitar quantos nome ele quiser, eu tentei limitar até 4, mas o programa para de funcionar.
Não entendo o problema.
Aqui está o código:
#include <stdio.h>
#include <stdlib.h> //para usar a função system();

int main(void)
{
int j, i, qntd_palavras=1;
char nomecompleto[100], nome1[20], nome2[20], nome3[20], nome4[20];

do
{
    printf("digite um nome completo\n> "); gets(nomecompleto); fflush(stdin); //pega o nome completo

    for(i=0, j=0;nomecompleto[i]!=' '&&nomecompleto!='\0';i++) //aqui ele pega todos os caracteres do nome completo, até achar um espaço ou o limitador
        nome1[j++] = nomecompleto[i];
    nome1[j]='\0'; //adiciona o limitador no final da string nome1

    if(nomecompleto[i++]=='\0')//aqui é verificado se tem algum outro nome
        break; //se não tiver, o while é cortado

    for(j=0, i++, qntd_palavras++;nomecompleto[i]!=' '&&nomecompleto!='\0';i++)
        nome2[j++] = nomecompleto[i]; //repete o mesmo que no passo 1
    nome2[j]='\0';

    if(nomecompleto[i++]=='\0') //idem
        break; //idem

    for(j=0, i++, qntd_palavras++;nomecompleto[i]!=' '&&nomecompleto!='\0';i++)
        nome3[j++] = nomecompleto[i];
    nome3[j]='\0';

    if(nomecompleto[i++]=='\0')
         break;

   for(j=0, i++, qntd_palavras++;nomecompleto[i]!=' '&&nomecompleto!='\0';i++)
        nome4[j++] = nomecompleto[i];
    nome4[j]='\0';

    if(nomecompleto[i++]==' ') //após quatro palavras, se houver mais alguma, o programa acusa erro e limpa a tela
    {
        printf("\n\nERROR: muitas palavras digitadas!\n\n");
        system("cls || clear");
    }
    else
        break;//se não acusar erro, o laço é terminado
}while(1);

switch(qntd_palavras) //aqui vai decidir como vai ser exibido o nome, dependendo da quantidade de palavras
{
    case 1:printf("\n\n> %s\n\n", nome1);
        break;
    case 2:printf("\n\n> %s, %s", nome2, nome1);
        break;
    case 3:printf("\n\n> %s, %s %s", nome3, nome1, nome2);
        break;
    case 4:printf("\n\n> %s, %s %s %s", nome4, nome1, nome2, nome3);
        break;
    default:break;
}
return 0;

}
Answer:     for(i=0, j=0;nomecompleto[i]!=' '&&nomecompleto!='\0';i++) //aqui ele pega todos os caracteres do nome completo, até achar um espaço ou o limitador
    //                                 ^^^^^^^^^^^^^^^^^^
        nome1[j++] = nomecompleto[i];

nomecompleto é um array.
Usado na comparação indicada do for ele é convertido num apontador para o primeiro elemento.
Esse apontador nunca será NULL (ou '\0') e esta parte da condição (nomecompleto!='\0') será sempre verdade o que não é o que esperas.

Tenta simplificar a inicialização e condições dos teus ciclos.

Programa.exe parou de funcionar


How to execute batch file on the same executable as the "main" C# application

Question: I have a given C# executable and I want to execute a batch file inside this executable. The batch file sets environment variables, and some of these operations are conditional to other environment variables (IF conditions).
I want these environment variables to be set inside the executable itself, so that the environment variables are set on the current executable.
Absolutely every method that I can find on our friend google when I write something like "C# execute batch same process" seem to be based on the method System.Diagnostics.Process method, which executes the batch file on a different process.
Thank you
Comment: This sounds like an [XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Explain your scenario better. You mean that after you `Porcess.Start()` a batch file which does some `set X=Y` calls, you want your .NET executable to return those variables when you call `System.Environment.GetEnvironmentVariable("X")`?
Comment: Why do you need to use a batch file to do that? You can set environment variables in C# directly.
Comment: What do you mean by "execute a batch file inside this executable" exactly? The command line will handle your batch file (which is obviously a different process). Are you trying to have C# code that can interpret a batch file and act on the commands directly? If so, my next question would be "why?" Could you explain your use case? I can't really think of a good reason why `System.Diagnostics.Process` wouldn't be sufficient in most cases.
Comment: Well, afaik there is no internal batch-executor in the dotnet framework (nor core), so that's what you're down to. What you _could_ do is to embed a script engine into your executable, but if you want (or have to) stick with batch, then there's Process...
Comment: You could execute your executable from within the batch file, which would let the executable use the same environment as used (and set/modified by) the batch file (with regard to environment variables).
Comment: The scenario is simple: I have a console application. I want this console application to interpret the commands inside that batch file so that the environment variables set within that batch file are taken into account on the console application.
Comment: Apps are passed a *copy* of the enviro settings precisely so another process cannot make the kinds of changes you are proposing
Answer:
I have a console application. I want this console application to interpret the commands inside that batch file so that the environment variables set within that batch file are taken into account on the console application.

But you definitely don't want to write a batch script interpreter in C#.
If you want your console app to use the environment variables assigned in the batch script, then start your executable at the end of that batch script.
Your application will then inherit that environment, and therefore those environment variables.
If you can't alter said batch script, then create a new batch script that:

Runs the original batch script, then
Runs your executable.
Comment: The code I am working on is meant to launch an older application which is currently launched via multiple batch calls. I am perfectly aware that the "ideal" would be setting all the environment variables before my executable, or set all these environment variables through C#, but I cannot do this because the decrepit system in which I need to implement this is based on bach files.

The scenario is: I have application A already running, and I want the environment variables which are defined on batch file "B.bat" to be set on application A. My only question is if there is a way to do so?


Run into issues with Drush after updating from 8.9.20 to 9.3.13

Question: I upgraded from 8.9.20 to 9.3.13 and i did an update.php after this. I do get an error:

MISSING UPDATES FOR: VIEWS
The installed version of the Views module is too old to update. Update to a version prior to 9.0.0 first (missing updates: views_post_update_remove_core_key).

If i try to update the databse with drush updatedb i get an error too:

In BootstrapHook.php line 36: Bootstrap failed. Run your command with -vvv for more information.

Is there any chance to solve this issue?
This is the status:
Drupal version : 9.3.13
Site URI       : http://default
DB driver      : mysql
DB hostname    : localhost
DB port        : 3306
DB username    : xxx
DB name        : xxx
PHP binary     : /usr/local/Cellar/php/8.0.3/bin/php
PHP config     : /usr/local/etc/php/8.0/php.ini
PHP OS         : Darwin
Drush script   : /usr/local/bin/drush
Drush version  : 11.0.9
Drush temp     : /tmp
Drush configs  : /Users/mb/Sites/vendor/drush/drush/drush.yml
/Users/mb/drush/drush.yml
Drupal root    : /Users/mb/Sites
Site path      : sites/default
Thanks for helping!
Comment: What is unclear about the error message that you need to run update.php before and not only after the upgrade?
Comment: Did you consider running your command with -vvv for more information?
Comment: https://www.drupal.org/project/drupal/issues/3169345#comment-14295352
Answer: The function views_post_update_remove_core_key was introduced in Drupal 8.8 and was removed in Drupal 9.0. See views_removed_post_updates.
To avoid this error and probably other similar errors you have to run update.php or drush updb at least one time with Drupal 8.8.12 or Drupal 8.9.20 (make sure it runs without errors while you are still on Drupal 8) before you can upgrade the code to Drupal 9. Then running update.php on Drupal 9 shouldn't throw this error.

You can add missed post updates to the state of your Drupal installation
$key_value = \Drupal::service('keyvalue');
$existing_updates = $key_value->get('post_update')->get('existing_updates', []);
$post_updates = [
  'update_test_postupdate_post_update_foo',
  'update_test_postupdate_post_update_bar',
  'update_test_postupdate_post_update_pub',
  'update_test_postupdate_post_update_baz',
];
$key_value->get('post_update')->set('existing_updates', array_merge($existing_updates, $post_updates));

(Code is from UpdatePostUpdateTest)
and then run the missed updates yourself. In this example you could simply re-save all Views by hand.
Comment: Thanks! That means that i have to go back to 8.9.20 and start the update and upgrade procedure again? Or do i have any chance to solve this within this situation?
Comment: You can try, see the edited answer. But there could be much more update code missing. It's unlikely this is only this one post update function.


Probability of two variables

Question: I have some questions about the following joint pdfs:
1. I have to evaluate $P(X>Y)$ where
$$f_{XY}(x,y)=\left\{\begin{array}{ll} \displaystyle\frac{12}{7}(x^2+xy), & 0<x,y<1 \\ 0, & \text{otherwise}\end{array}\right.$$
I want to know if it's right:
$$P(X>Y)=\int_{0}^{1}\int_{y}^{1} \frac{12}{7}(x^{2}+xy) dxdy$$
2. If
$$f_{XY}(x,y)=\left\{\begin{array}{ll} \displaystyle\frac{x}{5}+\frac{y}{25}, & 0<x<1,\quad0<y<5 \\ 0, & \text{otherwise}\end{array}\right.$$
I drew the rectangle and I concluded that
$$P(X+Y>3)=P(Y>3+X)=\int_{0}^{1}\int_{3+x}^{5}\left(\frac{x}{5}+\frac{y}{25}\right)dydx$$
Are these integrals correct?
Answer: The first one is correct and in the second one, you have a small mistake.
First one can also be written as,
$ \displaystyle P(X>Y)=\int_{0}^{1}\int_{0}^{x} \frac{12}{7}(x^{2}+xy) \ dy \ dx$
For second one, $P(X+Y \gt 3)  = P(Y \gt 3 - X)$
So it should be,
$\displaystyle \int_0^1 \int_{3-x}^5 \left(\frac{x}{5}+\frac{y}{25}\right) \ dy \ dx$

Probability of two variables


nginx: how do I add new site/server_name in nginx?

Question: I'm just starting to explore Nginx on my Ubuntu 10.04. I installed Nginx and I'm able to get the "Welcome to Nginx" page on localhost. However I'm not able to add a new server_name, even when I make the changes in site-available/default file. Tried reloading/restarting Nginx, but nothing works. One interesting observation. "http://mycomputername" in browser works. So somehow there is a command like 'server_name $hostname' somewhere over-riding my rule.
File: sites-available/mine.enpass
server {
   listen   80;
   server_name  mine.enpass ;

   access_log  /var/log/nginx/localhost.access.log;

   location / {
    root   /var/www/nginx-default;
    index  index.html index.htm;
   }
}

File: nginx.confg
user www-data;
worker_processes  1;

error_log  /var/log/nginx/error.log;
pid        /var/run/nginx.pid;

events {
worker_connections  1024;
# multi_accept on;
}

http {
include       /etc/nginx/mime.types;

access_log  /var/log/nginx/access.log;

sendfile        on;
#tcp_nopush     on;

#keepalive_timeout  0;
keepalive_timeout  65;
tcp_nodelay        on;

gzip  on;
gzip_comp_level 2;
gzip_proxied any;
gzip_types      text/plain text/css application/x-javascript text/xml application/xml    application/xml+rss text/javascript;
gzip_disable "MSIE [1-6]\.(?!.*SV1)";

include /etc/nginx/conf.d/*.conf;
include /etc/nginx/sites-enabled/*;
}

Comment: are you trying to set up virutal host functionality?
Comment: I want access my host using http://my.mydomain. etc.
Comment: One interesting observation. `http://mycomputername` works. So somehow there is a command like 'server_name $hostname' somewhere over-riding my rule.
Comment: Did you find a solution? I'm having the exact same problem but on OSX. Basically all of my server configs only work on localhost / mycomputername, no matter what the server_name is set to
Comment: A valid hostname cannot contain a period!
Answer: My recommendation is to remove the default site by removing the symlink in /etc/nginx/sites-enabled:
$ sudo rm /etc/nginx/sites-enabled/default

Then create your desired configuration in a new file, call it /etc/nginx/sites-available/your.host.name. Assuming you have your home page at /var/www/your.host.name, here's a very simple example:
server {
        listen 80;
        server_name your.host.name;

        location / {
                root   /var/www/your.host.name;
                index  index.html;
        }
}

Then create a symlink in /etc/nginx/sites-enabled:
$ sudo ln -s /etc/nginx/sites-available/your.host.name /etc/nginx/sites-enabled/your.host.name

Finally, restart nginx:
$ sudo /etc/init.d/nginx restart

Good luck.
Comment: root in location / is bad form.  It won't be available in any other locations.  Please read http://wiki.nginx.org/Pitfalls
Comment: @kolbyjack - Thats ok, I will be doing proxy_pass anyway. But I just wanted to get the first step working.
Comment: @daveadams ( Doesn't work. I'll be adding my configuration files to original question.
Comment: @kolbyjack, thanks for pointing that out. I agree it's sloppy form. @Neo, is your mine.enpass config file symlinked in sites-enabled? If so, are you using "mine.enpass" in your web browser to access it? If yes to both, then I'm stumped without more info.
Comment: @daveadams - I followed your steps exactly. http://localhost 'still' works. But http://mine.enpass doesn't :(. I can attach nginx.conf as well.
Comment: @daveadams - Isn't there a need for the rewrite rule after server_name rule?
Comment: @Neo, you only need a rewrite rule if you're doing rewriting; it's not required. Can you run `tail -f -n 0 /var/log/nginx/error.log` in one window while restarting nginx (`sudo /etc/init.d/nginx restart`) in another, and post any resulting lines?
Comment: @daveadams - Nope, no output. Restart is clean. Looks like I'm missing something very silly.
Comment: @daveadams - One interesting observation. `http://mycomputername` works. So somehow there is a command like 'server_name $hostname' somewhere over-riding my rule.
Answer: try changing server_name  mine.enpass ; to server_name  mine.enpass; in your sites-available/mine.enpass file
Comment: no luck. I'm able to make even proxy_pass work. But can't change the server_name!!
Comment: I honestly don't know where could be the problem,  `include /etc/nginx/sites-enabled/*;` is the last line in the http {}, so there shouldn't be a chance for any other files/configs to override your server_name...
Comment: addam: Im pretty sure nginx does not read and apply configuration from top to bottom.
Answer: Is it possible you have not added mine.enpass to your /etc/hosts file?
This was the basic mistake I made, having the same issues with nginx but in OSX (stumbled upon the solution here)
Comment: mine.enpass is NOT a valid hostname!


Invoke code-behind method when browser is closing

Question: I need to find a way to intercept browser closing and invoke a metod to update a record with several information about logged user in DB. It's very important this record is updated when the user is logging-out or when he close the browser. Obviously when the user clicks 'Logout' I handle the update in the server-side event, but what if the user simply exit from browser?
Someone suggest to use the window.onbeforeunload event and make an asynchronous call to some WS or WebMethod to execute the code, but this doesn't convince me at all: the problem with onbeforeunload is that it shows a confirm prompt. I need to avoid this message and simply invoke the method.
So I'm wondering if there is a 'server-side' solution without using ajax or javascript.
For example... a way to trigger some event on session abandon or session clear, or some other way to solve this problem just working on code-behind...
Comment: I disagree with the people who have down voted this question. People should be encouraged to ask questions. Even if it is absolutely impossible to provide an answer for OP's question, we can still politely say that.
Answer: There is no way you could have a server-side solution to know something that happens in the client browser.
Answer: I do not believe there is any way to do what you need server-side only. Client side is the only way. Server has no way of knowing when browser window was closed, this is limitation of HTTP protocol.
Answer: Yes, you can put an event in the Global.AsaX which will fire when the session ends.  Now if you need data from the client to update the db etc., you'll need a way of getting it there, but if not, then the Session_End will do the trick.
Note: Session end is slightly different than the browser closing, so it this will depend on what you want the event firing to do.
How to handle session end in global.asax?
Answer:
I'd like to find a 'server-side' solution without using ajax or
  javascript.

I suspect that it's impossible with that requirement.
Maybe you could do something like:

Have a hidden IFRAME on the page
Set the Refresh header on this IFRAME (or use a META element) to contact the server every couple of seconds
If you do not hear from the client for some period of time, assume the browser has been closed.

However, I imagine that this solution will not scale well.
Answer: Have you considered something like signalr? I use it to detect when someone has a record open.
public class ChatHub : Hub
{
     public override Task OnDisconnected()
     {
         Broadcaster.Disconnected(Context.ConnectionId);
         return base.OnDisconnected();
     }
}

Comment: This could be a very usefull suggestion. Thank you very much. I'll take a try.
Answer: For the moment I changed radically the approach to my problem.
To update pending rows I implemented a timed job using Quartz.NET framework, that runs every night.


Roots of $z^3 + 3iz^2 + 3z + i = 0$?

Question: I am asked to solve the equation in the title by first solving $\Big(\frac{z+1}{z-1}\Big)^n = i$, which is fine, but I can't seem to manipulate this equation to get the equation. I've tried $n =$ multiples of $3$ or any combinations of $n$, but to no avail. Please advise, thank you!
Comment: $z=i$ is a root. You may divide out by $(z-i)$ to get a quadratic factor
Answer: $(z+1)^3 = -i(3z^2+1) +3z^2+1 = (3z^2+1)(1-i)$
$(z-1)^3 = z^3-3z^2+3z-1 = (z^3+3z) - (3z^2+1)= -i(3z^2+1) - (3z^2+1) = -(1+i)(3z^2+1)$
Thus: $\left(\dfrac{z+1}{z-1}\right)^3= \dfrac{(z+1)^3}{(z-1)^3} = \dfrac{(3z^2+1)(1-i)}{(3z^2+1)(-(1+i))}= \dfrac{-1+i}{1+i}= a+bi$.
Can you find $a, b$ and take cube roots using Demoivre's formula? and this is what the hint tells you to do first.
Answer: Note the $\left(\frac{z+1}{z-1}\right)^3 = i \implies (z+1)^3 = i (z-1)^3 \implies (1-i)z^3 + 3 (1+i)z^2 +3(1-i) z + (1+i)=0$. But $1+i = i(1-i)$. Therefore,
$$\left(\frac{z+1}{z-1}\right)^3=i \implies (1-i)(z^3+3iz^2+3z+i)=0.$$

Roots of $z^3 + 3iz^2 + 3z + i = 0$?


How do I customize the html of each field in a view?

Question: I have a custom theme and I want to edit the HTML of a view. I am able to create template overrides but I get stuck, it seems like the editable part of a view does not go deep enough.
I have a view displaying all of a content type. The content type has the following fields a name, an image, a link, and a description. I want to edit all of these with custom elements, classes, ids, etc and change the order of them. However the deepest I can get into a view is the $row variable, which already has this content formatted.
I've ran a function called views_get_current_view(). When I run it's return through print_r I see the information I need deep inside of it, but when I try to grab that information Drupal runs out of memory, I do not want to allocate more memory and I don't think that's the best way to solve the problem.
Long story short - I'm trying to get the fields of each node in a view and customize their html, when I get that data from a view it seems to already be already coded.
Thanks
Comment: If you are using a View that displays content and not fields, eg, the whole node as it looks on a page or teaser, you can create a template called `node--view--VIEWNAME.tpl.php` (or even `node--view--VIEWNAME--DISPLAYNAME.tpl.php`) and then modify that however you want. If this isn't what's going on, and you have a View with fields, then you can reorder them in the Views UI and can definitely theme them independently as well.
Comment: possible duplicate of [Overriding views-view-fields.tpl.php](http://drupal.stackexchange.com/questions/5412/overriding-views-view-fields-tpl-php)
Answer: If you are create any content type and select any content type name ex : your created a "news" is content type and many field as a 'id','name' etc.
after you have add a one php file name as a 'node--news.tpl.php'
and clear caches
this file always call a news content data


Erro Intermitente (could not obtain ole control window handle) Delphi

Question: Bom dia, eu tenho uma aplicação que roda em 8 mil máquinas, entretanto, estou tendo um erro numa pequena parcela(media de 100) todos os dias.
Recebo a msg (could not obtain ole control window handle) e não consegue mais fechar essa msg em tela ate que a aplicação precisa ser fechada, o problema que ela integra com outros componentes o quais dependem de um fluxo para ser desconectado quando a aplicação for fechada.
Eu pesquisei e tentei simular tudo que foi citado, mas tudo sem sucesso, eu coloquei um Application.Message para monitorar os erros, e coloquei para não registrar o erro na tela. O problema foi mascarado mas não resolvido, no EventViewer recebo o erro dizendo que o Windows fechou a aplicação por um problema na KERNELBASE.dll.
Utilizo o delphi 7 e Windows 7 nas maquinas, minha aplicação tem um modulo de WebBrowser o qual carrega n aplicações de terceiros(Ate suspeito que alguma dessas aplicações poderiam gerar algum erro de integração).
Obrigado a todos.
Answer: Essa mensagem de erro em específico é bem abstrata, e pode-se tratar de inúmeros erros diferentes, primeiramente verifique se as máquinas utilizadas possuem o internet explorer instalados. Caso não esteja instalado o TWebBrowser não vai funcionar, pois utiliza dlls do IE.


Benefits of a join table?

Question: I am trying to explain the benefits of a join table to a colleague, and below is an explanation. Am I correct?
Currently he has the relationship between a pic and tag with two tables. A pic table and a tag table. The pic table has a tag_id this is a FK to an entry in the tag table. Here was my response:
First lets look at pics and tags tables. So in your current architecture lets imagine two pics (a & b). We tag pics a & b with the hashtag #wtf. We now have two entries in out tags table:
pic_id  title
------  -----
a       wtf
b       wtf

Do you see the issue? So imagine we have 1000 wtf tags on a 1000 different pics. With this same architecture we now have a bloated tags table with all this repeated data (and wasted space). This issue arises when we have a many to many relationship. In this case many pics can have many tags, and many tags can have many pics. How would we fix this? The answer is a join table. So we create a new table. Lets call it pic_tag. This table would have columns pic_id & tag_id. So now new tables would look like:
pic_tag
pic_id  tag_id
------  ------
a       1
b       1

tags
id   name
--   ----
1    wtf

pic
id  name
--  ----
a   pic1
b   pic2

So this does a couple of things for us. First it saves space. We only store the string 'wtf' one time. Second, to find all pics with the tag 'wtf' we first go to the tag table and find the id of 'wtf', then go to the pic_tag table and search for that id which is much more efficient that searching a bloated 'tags' table for a given text. Said another way, search for ints is much faster than searching for text.
Comment: No data duplication, integrity of data are pros, slower performance is a con.
Comment: @AD.Net: "slower performance" --- this is just incorrect. You cannot tell having your data normalized will make *something* slower, just because there is no abstract *performance* metric, but the number of different performance aspects, which may be *much better* for the given structure
Answer: The main benefit is that there are relationships that can only be modeled with a join table.
Say you have two entities A and B. If the relationship A:B is 1:1, the two can be represented by a single table. If A:B is 1:N (like 1 customer can have N orders but each order comes from only one customer), then you could model this as a foreign key from orders table to customers table. But if A:B is N:M (your tags scenario is a good example) you need a way to represent 0, 1 or N tags for each picture. There is no sound relational representation for that other than a join table.
Note you could represent multiple tags per picture while breaking some principles of relational design (like storing multiple tags or FK's to tags) in a single column. Whether to do that or not is a design decision.
Other benefits: you can change your mind whether the relationship is 0:1, 0:N, 1:(0-5), 1:N etc. without changing the core data model -- addressing that logic in triggers or application logic. You can create additional indexes to help with joins. You can introduce more uniqueness constraints to enforce data logic etc.
But the main benefit is, join tables are the only relationally sound way to model certain types of relationships.

Benefits of a join table?


Lie algebra of dimension $3$ and $L=[L,L]$ must be simple

Question:
Suppose $\dim L=3$ and $L=[L,L]$. Prove that $L$ must be simple. [Observe first that any homomorphic image of $L$ also equals its derived algebra.] Recover the simplicity of $\mathfrak{sl}(2,F)$, $\operatorname{char}F\ne 2$.

First, the part in brackets. Suppose the homomorphic image of $L$ under $\varphi$ is $M$. Since $M$ is an algebra, we must have $[M,M]\subseteq M$. Now, consider an element $\varphi(z)\in M$. Since $L=[L,L]$, we have that $$z=a_1[x_1,y_1]+\ldots+a_k[x_k,y_k]$$ for scalars $a_1,\ldots,a_k\in F$ and $x_1,\ldots,x_k,y_1,\ldots,y_k\in L$. Then $$\varphi(z)=a_1\varphi([x_1,y_1])+\ldots+a_k\varphi([x_k,y_k])=a_1[\varphi(x_1),\varphi(y_1)]+\ldots+a_k[\varphi(x_k),\varphi(y_k)],$$ showing that $M\subseteq [M,M]$.
Now suppose $\dim L=3$ and $L=[L,L]$, and that $L$ is not simple. So $L$ has an ideal $I$ that is neither $0$ nor $L$. So $I$ has dimension $1$ or $2$. What then?
Comment: @anon That's true, edited.
Answer: If $I$ is a non-trivial ideal of $L$, then $M=L/I$ has dimension one or two. In two earlier questions you have shown that this implies that $[M,M]$ is a proper subspace of $M$. This violates your observation about homomorphic images of $L$.
Comment: Okay, got it. Actually, I wonder why the simplicity of $\mathfrak{sl}(2,F)$ doesn't hold when $\operatorname{char}F=2$? It seems to be that both $\dim L=3$ and $L=[L,L]$. Am I missing something?
Comment: $[e_{11}-e_{22},e_{12}]=2e_{12}$, $[e_{11}-e_{22},e_{21}]=-2e_{21}$, so if $2=0$ the ideal $[L,L]$ is smaller than normally. It does not contain any non-diagonal elements in that case.
Comment: $\dim L=3$ using the usual basis $e_{12},e_{21},e_{11}-e_{22}$, while $L=[L,L]$ by checking that each of the $3$ basis elements equals some commutator.
Comment: But $[{\frak gl}_2,{\frak gl}_2]={\frak sl}_2$ holds even in characteristic two.
Comment: Ah, I made a mistake by using $e_{11}$ in my calculation, but it actually doesn't belong to $\mathfrak{sl}_2$. Thanks Jyrki!


is there a proper way to replace the value in dataframe with another in efficient way?

Question: Following is the example of the dataframe iam working with. here iam traying to replace the ED values with the homezip.
EmpZipCode         homeZip
839E2              839E2
ED                 A83C3
ED                 938B4
ED                 B82E2
893D9              893D9

Here iam trying to replace unk value with homezip in a way that it takes off the first
alphabet if present else keeps all the value. Desired is as below:
EmpZipCode         homeZip
839E2              839E2
83C3               A83C3
938B4              938B4
82E2               B82E2
893D9              893D9

Answer: We need two np.where here , the 1st one is remove the alpha of the home zip, the 2nd one is replace the ED with previous output
s = np.where(df.homeZip.str[0].str.isalpha(),df.homeZip.str[1:], df.homeZip)
df['EmpZipCode'] = np.where(df['EmpZipCode'].eq('ED'), s , df.EmpZipCode)
df
Out[23]:
  EmpZipCode homeZip
0      839E2   839E2
1       83C3   A83C3
2      938B4   938B4
3       82E2   B82E2
4      893D9   893D9

Comment: @gannu first we do the adjust in homezip if it is first letter alpha, we remove it , then when have the pre-clear fill value, just need to assign when it is ED


Leap Motion JS - update in background

Question: I am playing around with Leap Motion's JS SDK. Whichever example I see on the internet it does run fine even when the browser window is in background = the example get updated on every frame. However, I cannot figure out what to do to actually achieve the same thing, my examples always stop when the browser window loses focus. Let's take this very small example:

Controller.setBackground() says: Informs the Leap Motion WebSocket server that your application always wants to receive frames of tracking data when it is in the background and not being actively used. Note that setting this option true could lead to unintended input to your application while the user interacts with other applications. Most applications should not receive frames in the background.
Kind of doesn't work to me, what am I doing wrong? Thanks a lot!
Comment: Is the background frames policy set in the Leap software's control panel? It should be by default, but you never know.
Comment: @nphx Yep, it is. Seems like this issue only happens with JS SDK 0.4.2. It seems to work alright with 0.3.0. Hm...
Answer: The answer is that this is a bug: https://github.com/leapmotion/leapjs/issues/158
You aren't doing anything wrong.
{ed} The issue has been fixed.

Leap Motion JS - update in background


Impute missing value

Question: In machine learning when I impute missing values which of the following I perform :
1-Impute data set and then split it?
2-Split dataset to Training and testing datasets and then Impute each datasets separately.
Comment: Ideally, you "learn" the imputation on the training data and then apply it to test. Whether this is possible/necessary depends on the use case. We don't know anything about it, so you can't really expect good help.
Answer: First split, then impute missing data on the training set using information from the training set only. Anything else leaks data from the testing set to the training data.
After that, whether you want to impute for the test set using the test set only or the whole dataset depends on your situation. Usually, you will want to impute using the whole set; after all, you are also applying the model you learned from the training data to the test data. However, there might be situations where you can only "transfer" the model from the training set to the test set, not any other information, e.g., for privacy reasons. In such a case, it might make more sense to impute on the test set using the test set only.
I personally am not a big fan of imputation... it usually makes you feel too sure of your conclusions and predictions.

Impute missing value


Firefox 3 window focus and blur

Question: $(window).blur(function(){
        windowFocus = false;
    }).focus(function(){
        windowFocus = true;
    });
The problem is that in firefox 3, when I create a new tab, it does not lose windowFocus. Where as in ff2, ie7 it does lose. In ff3 it only loses window focus when i select another program.
Anyone have a solution to this problem?
Answer: Attach to the events on document instead:
$(document).blur(function(){
        windowFocus = false;
}).focus(function(){
        windowFocus = true;
});

...FWIW, this appears to have been fixed in FF3.5.
Comment: @Shog9: that will search for the window object in the document object, the comma only works in string selectors for specifying multiple selectors. Try this instead: $(window).add(document)...
Comment: will this work for ie6/7/8 and ff2? or do i need to write it as a  hack?
Comment: No, but you can probably get away with just wiring up both (since the document can't have focus without the window having focus): $(window, document)...
Comment: @Pim Jager: ah, of course... I've made that mistake a few times, sad to say! $([window, document]) should also work.

Firefox 3 window focus and blur


How to get the reference of one variable of one class in another class in python?

Question: I have a class C1, and another class C2 which takes one instance of C1 as a variable. If I want to get the variable of C1 in C2, I have to use self.c1.variable. How can I get a reference of the variable of C1 in C2 so that I can get it directly?
class C1():
    def __init__(self,a):
        self.variable = a

class C2():
    def __init__(self, c1):
        self.c1 = c1

    def print_variable(self):
        print self.c1.variable

c1 = C1(1)
c2 = C2(c1)
c2.print_variable()

Comment: can you explain more about what you exactly want to do?
Comment: @trahane I just want to use a shorter code to get c1.variable. If I have the third class C3 which contains C2, I have to access c1's variable in C3 via self.c2.c1.variable. That's not a good way if I want to use this variable frequently.
Answer: You can use @property decorator to achieve that:
class C2():
    def __init__(self, c1):
        self.c1 = c1

    @property
    def variable(self):
        return self.c1.variable

In case you want to modify the variable in C2 instance:
    @variable.setter
    def variable(self, value):
        self.c1.variable = value

Comment: Thanks. That's exactly what I want.


Composing a polonaise, anything else to consider?

Question: So the thought has came to me several times to write a polonaise. I'm not Polish so I barely know anything about that side of the polonaise. But so far I have come across these commonalities across all polonaises(except maybe some of Bach's polonaises and some other early polonaises):

Triple meter(typically 3/4 time, though some are written with a 6/8
feel in mind)
Moderate to fast tempo(it gets especially fast if you look only at Chopin's polonaises)
Common melodic rhythm
Relatively simple bass line compared to the complex melody
Ternary form(often complex ternary form which is like ternary form sections inside a ternary form piece)

But then there are those things that differ. I will be using Chopin as an example since his polonaises are extremely well known, but don't feel as though I'm being too Chopin-centric.
Heroic Polonaise:

This polonaise has more of a 6/8 feel to it. And not just because of the eighth note bass line but also because of beams of eighths going across the bar. Also, I think there are some bars where the eighths are grouped in 3's, implying 6/8, even though it is written in 3/4 time. Also, in the B section, it feels more like a mazurka in terms of the rhythm. This is one of those cases where I would argue that 6/8 is the true time signature and that 6/8 is used as a triple meter(after all if 6 can be divided by both 2 and 3, no reason that 6/8 can't be triple meter just because it is most often duple meter)
Here is a typical polonaise rhythm:

And here is the rhythm I feel and see in the B section of Chopin's Heroic Polonaise(and I mean the large scale B section, not the small scale B section within the large scale A section):

That is a typical mazurka rhythm. No idea why Chopin would write the B section of a polonaise like a mazurka in terms of the rhythm.
Military Polonaise:

This one has clearer 3/4 feel to it. Also it sticks to the typical polonaise rhythm almost to the dot throughout, no section of it feels like a mazurka.
Polonaise in C minor:

This one is even more rhythmically confusing. Sometimes it sounds like a mazurka rhythm, sometimes it sticks to a typical polonaise rhythm, and other times it just sounds like a waltz rhythm. I guess the rhythmic confusion fits the mood of the polonaise though as does the tempo being on the slow side of Allegro.
So is there anything else I have to consider besides the rhythm, form, complexity of melody vs bass, tempo being moderate to fast, and most importantly triple meter when writing a polonaise?
Comment: Treat neither Chopin's Heroic Polonaise (in A flat major) nor his Tragic Polonaise (in F sharp minor) as perfect examples of polonaises. I've read (and agree) that the central E major section (what I assume is what you call the B section) of the Heroic Polonaise is a krakowiak and one of the central A major sections of the Tragic Polonaise is a mazurka. With that being said, I don't get where in that B section has a 6/8 feel or even the rhythm you describe--my experience with that section is that it does indeed adhere rhythmically to its 3/4 borders and does not use hemiolas.
Comment: The 6/8 feel that I get isn't specific to the B section of the Heroic Polonaise. It actually starts pretty early on in the polonaise, at 0:27 in the video of the Heroic Polonaise. You can see eighths grouped in 3's and beams going across the bar, both implying 6/8, despite being written in 3/4. The mazurka rhythm is what I feel specifically in the B section of the Heroic Polonaise. It starts at 3:00 in the video, where you can clearly see the mazurka rhythm in the melody over sixteenths in the bass. 4:00 is where it starts getting the polonaise rhythm once again before the A section repeat.
Comment: I listened to the Heroic Polonaise at 0:27, and I got the impression that, despite what the note beaming says, that section uses a hemiola (i.e. 2-2-2 groupings across 2 measures) and does not split any one measure rhythmically into 3 eighth notes + 3 eighth notes.
Answer: If you want to understand what a Polonaise is, Chopin is not a good place to start from. He was writing "Polish Nationalism for ex-pats in Paris", not "dance music."
The Polonaise is a very simple dance. It is just a walk, with the third beat of every the bar a bit longer than the first two to make time for a slightly longer step.
If you want to understand any dance form, the best place to start is by actually dancing it, but the next best is watching other people:

Bach's Polonaises capture the essential features of the dance rhythm, and would be easy to actually dance to - unlike any of Chopin's Polonaises.
Comment: Some wag once wrote that if Chopin's waltzes were ever performed at a ball, all the ladies would have to be at least countesses.
Answer: One characteristic of a polonaise is the use of "feminine" endings in phrases; the tonic (or cadence-ending chord) often occurs on the second beat of a measure. (I don't know the provenance of the terms masculine and feminine endings. Masculine and feminine for phrase beginnings are funny in the masculine and feminine are often used reversed; sometimes one masculine means a pickup note and other places feminine has that meaning. It's not like with electrical receptacle where the meaning is obvious.)
The last measure may have a V7 or V (or the like) on beat 1 of the last (non-extension) measure and the I or i (or vi) on the 2 beat, usually tied to the 3 beat.)
Comment: I believe the idea of masculine/feminine endings is based on traditional/stereotypical masculine and feminine personality traits. The masculine ending is stronger/more direct as it arrives on the downbeat. The feminine ending is weaker/indirect as it arrives on a weak beat.
Comment: Perhaps about the endings; though one might argue that the dominant on the 1 beat is fairly strong sounding. Strangely, I have seen both having or not having pickup measures described as masculine or feminine. Maybe it's like "natural" and "reverse" turns in dancing; "They had to call it something."


Implement photo disperse transition similar to Photos on iPad

Question: On the iPad, when you tap an album in Photos, the photos in the album "explode" out from the stack of photos and align neatly into a grid. That's a very cool transition and I want to try to replicate it, but I could not find any open source projects that have attempted to do just that. How could this be accomplished?
The setup is two view controllers, currently segueing via the usual push transition. The first view controller already has the assets collections PHFetchResult, and it could easily obtain the assets for each collection. I understand one must use the UIViewControllerTransitioningDelegate, but how this specific transition effect can be accomplished is what I'm wondering about. Wondering if anyone has already attempted this (in Objective-C or Swift preferably Swift), and if not, how it can be implemented.
Comment: I believe that's a transition between two UICollectionViewLayouts. You should check out this year's and last year's WWDC videos; I'm pretty sure they have one covering this (and maybe some sample code).
Answer: A search for "UICollectionView Photo Stack" will get you pointed in the right direction.
Example? http://skeuo.com/uicollectionview-custom-layout-tutorial
Ultimately, you're going to be dealing with creating one layout that stacks all of the items in one spot. When the item is tapped, you invalidate the layout and introduce the grid-based layout.


In Fantasy Sports, is it proven that first pick tends to win the league most often?

Question: Since most leagues use the "snake style" draft, there are positives and negatives to picking first, or last. First pick gets the First overall pick in the draft, but then has to wait until the last pick of the 2nd round. Then once again they get first pick in the 3rd round.
On the other hand, last pick in the first round gets to pick first in the 2nd round - therefore they get two successive picks.
It generally seems that most people consider the first pick the best for your chances of winning obviously, I just wanted to see if stats backed that up entirely.
Is there any historical fantasy data to help prove which pick position tends to win the most?
Answer: This article indicates (through an analysis of 100 leagues across several sites), that there is not a strong correlation between picking first or last and winning your league.

This chart shows that most often the winner was in the 7th position. However I would not take the results as conclusive one way or the other. But I would say that there is not a strong correlation between draft position and overall results in a fantasy league.
Comment: I will say that first pick is really rough. I picked first this year and I can tell you, going first in round one and then last in round 2, even if you get 2 picks in a row is brutal.


HTML body width: fitting page, but with maximum value

Question: How do I make a webpage fit to the size of the browser width, while I still have
a maximum width (say, e.g., width="1000px") for the body?
Thanks in advance.
Answer: You can set content to match the size of a browser viewport by using vw and vh properties (w3schools).
If you're saying you want the body to have max-width of 1000px but be scrollable if vw < 1000, it should probably be placed within a child element of some kind:
HTML:

CSS:
.viewport {
  height: 100vh;
  width: 100vh;
}
.my_element {
  max-width: 1000px;
}
Comment: Thanks, especially max-width was useful.
Answer: What below code will do is that till the body width gets to 1000px it will take the full width of browser after exceeding 1000px  it stop increasing body width

body {
  padding: 0;
  margin: 0;
  max-width: 1000px;
  margin: 0 auto;
}
div {
  background-color: #000;
  height: 20px;
}

Comment: Thanks, "max-width" did exactly what I needed.


CKEditor strips all inline CSS and some tokens

Question: I'm trying to add a color and font size to some text using the CKEditor. As soon as I save it these are stripped out.
I've also noticed some tokens are stripped down when certain settings are enabled.
I went to add a bit of text in a different font and color but when I saved it and viewed the text the spans were stripped of their "style" tag.
I went to config/content/formats/manage and enabled Limit allowed HTML and added span to the list like so :

 <s>

After saving this all the attributes inside of span are still stripped. I also noticed that many of the tokens I was using (such as site:url) are broken and only half of it remains.
I went back and disabled the Limit allowed HTML option and then when I saved the text the styles and token would save properly.
When viewing the text in an email, the tokens had worked just fine but the span had it's css striped.
I've tried looking for an answer but most are saying I need to enable and add the span to the limit html option but this definitely does not work for me.
There is also Correct faulty HTML enabled, would that be a problem for this?
How can I enable in line styling with the CKEditor?
Answer: See

https://drupal.stackexchange.com/a/282373/79805
https://stackoverflow.com/a/60836391/9302793
https://drupal.stackexchange.com/a/215158/79805

for some further reference :)

You could try using custom CKEditor styles. For using custom styles you'll need a custom module.

MYMODULE/

/MYMODULE.module
/MYMODULE.libraries.yml
/css/style.css

MYMODULE/MYMODULE.module:
function MYMODULE_editor_js_settings_alter(array &$settings) {

  foreach ($settings['editor']['formats'] as $name => $value) {

    // You can check for specific editors.
    // if ($settings['editor']['formats'] == 'basic_html') {
    //
    // }

    // Otherwise, add our custom styles to all editors.
    $settings['editor']['formats'][$name]['editorSettings']['stylesSet'] = [

      [
        'name' => 'Custom Color Text',
        'element' => 'p',
        'attributes' => [
          'class' => "custom-color-text"
        ]
      ],
      [
        'name' => 'Custom Color Link',
        'element' => 'a',
        'attributes' => [
          'class' => "custom-color-link"
        ]
      ],
    ];
  }
}

function MYMODULE_preprocess_node(&$variables) {

  // Attach our styles library.
  $variables['#attached']['library'][] = 'MYMODULE/styles';
}

// Nice to haves:
function MYMODULE_ckeditor_css_alter(&$css, $editor) {

  // Add our ckeditor style sheet to ckeditor.

  // This adds our theme styles to the editor field.
  $css[] = drupal_get_path('theme', 'MYTHEME') . '/css/style.css';

  // This adds our styles from the module directory.
  $css[] = drupal_get_path('module', 'MYMODULE') . '/css/style.css';
}

MYMODULE/css/style.css:
.custom-color-text {
  color: #f00;
}

.custom-color-link {
  color: #00f;
}

MYMODULE/MYMODULE.libraries.yml:
styles:
  version: 1.x
  css:
    theme:
      css/style.css: {}

These will now be available in the "style" dropdown in the CKEditor field.
Comment: This works for adding the style to the editor. I'm trying to use this in an email so I don't know how to get this bit of css to attach to the email. I am using a custom theme so I guess I could just add it to that template, I'm hesitating there because it seems disjointed but do-able. Is there an easy way to just add the inline? I am not styling more than one or two lines.
Comment: There's always a way with Drupal. Sometimes it's a question of time, and sometimes budget. As you'll have a class available, I would see if I could just include the CSS rules in the head of the email document?
Comment: Yes I was going to add the class name to the custom theme, just wouldn't be my preferred I guess.


Read a PDF and find a specific column to add to a list

Question: So can anyone find a way to read out just the numbers in a column of a .PDF file programmatically? In other words, is it possible to drop a PDF file and make something that sucks it up, reads out all of a column?
The column is of the following format:

401232111555713
Comment: See this http://stackoverflow.com/a/7515625/231316. @Jared's post is a great place to start but just remember that PDFs don't store tables, only things that happen to look like tables.
Comment: @ChrisHaas I realize that, but since I just want a single column Jared's answer worked perfectly! thanks
Answer: The following code will open and read any PDF into a string using iTextSharp:
public static string ReadPdfFile(string fileName)
{
    StringBuilder text = new StringBuilder();

    if (File.Exists(fileName))
    {
        PdfReader pdfReader = new PdfReader(fileName);

        for (int page = 1; page <= pdfReader.NumberOfPages; page++)
        {
            ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();

            string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

            currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
            text.Append(currentText);
        }
        pdfReader.Close();
    }
    return text.ToString();
}

From there you can simply run some REGEX to get the column using the pattern you laid out:
string text = ReadPdfFile(@"path\to\pdf\file.pdf");
Regex regex = new Regex(@"(?<number>\d{15})");
List<string> results = new List<string>();
foreach (Match m in regex.Matches(text))
{
    results.Add(m.Groups["number"].Value);
}

Comment: This uses the `SimpleTextExtractionStrategy` --- depending on the use case in question, you may need a different text extraction strategy, e.g. the `LocationTextExtractionStrategy.`
Answer: You'll need to use some PDF processing library. Here's a SO link that has discussion on that topic:
Reading PDF in C#


Problem in restoring floating toolbar for QMainWindow

Question: I am seeing a problem while restoring QMainWindow state having QCombobox in floating toolbar. After restoring floating toolbar, my QCombobox is not able to get focus until i click on toolbar handle and move it.
Following is gif showing problem, Using QT 5.13.

File floating_toolbar.pro
QT       += core gui

greaterThan(QT_MAJOR_VERSION, 4): QT += widgets

TARGET = floating_toolbar
TEMPLATE = app

DEFINES += QT_DEPRECATED_WARNINGS

 #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000    # disables all the APIs deprecated before Qt 6.0.0

CONFIG += c++11

SOURCES += \
        main.cpp \
        mainwindow.cpp

HEADERS += \
        mainwindow.h

# Default rules for deployment.
qnx: target.path = /tmp/$${TARGET}/bin
else: unix:!android: target.path = /opt/$${TARGET}/bin
!isEmpty(target.path): INSTALLS += target

File : main.cpp
#include "mainwindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

File : mainwindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    void closeEvent(QCloseEvent *event);
    void readSettings();
    bool eventFilter(QObject* xObj, QEvent* xEvent);
    ~MainWindow();

    public slots:
    void mCheck();
};

#endif // MAINWINDOW_H

File : mainwindow.cpp
#include "mainwindow.h"
#include <QToolBar>
#include <QComboBox>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QLayout>
#include <QSettings>
#include <QEvent>
#include <QDebug>
#include <QMouseEvent>
#include <QApplication>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    QToolBar* lToolbar = new QToolBar(this);
    QComboBox* lComobox = new QComboBox(this);
    lComobox->setEditable(true);

    lToolbar->setWindowTitle("MyToolBar");
    lToolbar->setObjectName("NiceBaby");
    lToolbar->addWidget(lComobox);
    //lToolbar->addAction("check", lComobox, SLOT(clearEditText()));

    addToolBar(lToolbar);
    lToolbar->installEventFilter(this);
    readSettings();

}

void MainWindow::mCheck()
{

}
void MainWindow::closeEvent(QCloseEvent *event)
{
    QSettings settings("MyCompany", "MyApp");
    settings.setValue("windowState", saveState());
    QMainWindow::closeEvent(event);
}
void MainWindow::readSettings()
{
    QSettings settings("MyCompany", "MyApp");
    restoreState(settings.value("windowState").toByteArray());
}

MainWindow::~MainWindow()
{

}

bool MainWindow::eventFilter(QObject* xObj, QEvent* xEvent)
{
    //qDebug()<<xEvent->type();

    return QMainWindow::eventFilter(xObj, xEvent);
}

Comment: Its KDE on RHEL6.5
Comment: Which distro are you using? Gnome or KDE?
Comment: Please let me know if same happens on other distros i.e. Ubuntu. And it might help if you post the link to download the exact same RHEL6.5 you are using.
Comment: I idea that occured to me was to simulate a click, more on https://stackoverflow.com/questions/35777414/how-can-i-simulate-mouse-clicks-by-posting-events-to-the-qt-event-system, did you tried something like that?
Comment: Could you post your MCVE code? Looks like maybe a bug... and QWidgets in a toolbar can act pretty strangely sometimes, depending on platform. The `QToolBar` code is a bit convoluted due interactions with `QMainWindow` and platform integration requirements. Looks like something is stealing the focus until the toolbar gets "activated" (or something) by clicking on the handle.
Comment: I tried on Ubuntu 16.04.1 LTS , Same behavior.
Comment: Confirmed also in Linux  Mint 19.2 (Ubuntu 18.4 base I believe). `Linux-RHEL_7_4-X86_64`. Tested Qt 5.13.1, 5.12.4, and 5.7.1. Not an issue in Windows, with either MSVC or MinGW.  Seems to be pretty clearly a focus issue -- eg. the context menu still works and you can paste text into the box, and even select text. But if you try typing the focus is elsewhere. I put a `QLineEdit` into the main window and it keeps focus instead... you highlight text in the toolbar combobox and start typing and the input goes into the QLineEdit inside the main window instead.
Comment: Confirmed also in Arch Linux with KDE (kwin 5.16.4), QtCreator 4.9.2, Qt 5.13.0. Same behavior.
Comment: @OMG, so do you not find my answer acceptable? No bounty, no acceptance... is there something I'm missing? Did you find a better solution?
Comment: @MaximPaperno your workaround worked for me but unfortunately at that time bounty was expired. Anything i can do now?
Comment: You could accept the answer. I don't care much about the points, but it does clearly indicate that the answer is the "one that helped most" (at least at the time) to any future visitors. Up to you, of course.  https://stackoverflow.com/help/someone-answers   (On a more personal level: there's no way to tell who voted on an answer, so an answer giver typically has no idea if the asker found the answer useful at all (or even looked at it) w/out some kind of acknowledgement, eg. acceptance or a comment, etc.)
Answer: OK, a workaround is to reset the window flags on the toolbar when it is first shown and is floating.  I tracked this down by seeing what happens once a toolbar is dropped after being dragged (but not plugged into main window). (It calls setWindowState() and all that does in this situation is hide the toolbar, call updateWindowFlags(), and show it again).
This could be handled from the QMainWindow::showEvent() or from the eventFilter installed onto the QToolBar.  I think it's simpler from the former.
UPDATE: This problem actually happens whenever the toolbar is first shown even if not at app startup, e.g. from the toggle view menu by the user once app starts. I updated the code below to fix that issue as well. And see notes below about another issue with minimizing the main window.
I added this to the MainWindow class from the MCVE:
  protected:
    void showEvent(QShowEvent *e) override {
      QMainWindow::showEvent(e);
#ifdef Q_OS_LINUX
      if (lToolbar->isFloating()
          // remove the next condition and the toolsbar will get hidden the 2nd time main window is minimized.
          && lToolbar->windowFlags().testFlag(Qt::X11BypassWindowManagerHint)
          ) {
        const bool vis = !lToolbar->isHidden();
        qDebug() << lToolbar->isFloating() << vis << lToolbar->windowFlags();
        lToolbar->hide();
        lToolbar->setWindowFlag(Qt::X11BypassWindowManagerHint, false);
        if (vis)
          lToolbar->show();
#endif
    }

    QToolBar* lToolbar;  // Use this in MainWindow constructor to save the instance pointer.

I also noticed another issue with the initially-floating toolbar. When the main window is minimized, the toolbar doesn't get hidden but stays where it was on the screen. Regardless of what is in the toolbar (eg. no combo box, just QActions).  This workaround could also sort-of address that issue (see code comment), but only the 2nd time the window is minimized. Needs a better workaround for the first minimize.
Can others confirm this? Potentially a larger issue than the editable combo and I'd be surprised if no one noticed before.
I guess this should be filed as a Qt bug either way.
UPDATE2: This version also fixes the minimize issue. I guess something happens after the QMainWindow::showEvent() that changes how the toolbar behaves. Which explains why the above workaround works only after the 1st minimize. So scheduling the toolbar "fix" for later works around that also.
class MainWindow : public QMainWindow
{
...
#ifdef Q_OS_LINUX
  protected:
    void showEvent(QShowEvent *e) override
    {
      QMainWindow::showEvent(e);
      if (lToolbar->isFloating() && lToolbar->windowFlags().testFlag(Qt::X11BypassWindowManagerHint) ) {
        //  QMainWindow::show() after QMainWindow::restoreState() will break the minimizing again so we should delay calling adjustToolbar().
        QMetaObject::invokeMethod(this, "adjustToolbar", Qt::QueuedConnection);
        // If we're sure restoreState() is only called after show() then adjustToolbar() could be called here directly instead.
        //adjustToolbar();
      }
    }

  private slots:
    void adjustToolbar() const
    {
      const bool vis = !lToolbar->isHidden();
      qDebug() << lToolbar->isFloating() << vis << lToolbar->windowFlags();
      lToolbar->hide();
      lToolbar->setWindowFlag(Qt::X11BypassWindowManagerHint, false);
      if (vis)
        lToolbar->show();
    }
#endif

  private:
    QToolBar* lToolbar;
};

ADDED: A QToolBar subclass which applies the workaround on its own, nothing special needed in the QMainWindow. The minimize fix still only works when the adjustToolbar() function is queued or if restoreState() is only called after show() (see code comments).
class ToolBar : public QToolBar
{
    Q_OBJECT
  public:
    using QToolBar::QToolBar;

#ifdef Q_OS_LINUX
  protected:
    void showEvent(QShowEvent *e) override
    {
      QToolBar::showEvent(e);
      if (isFloating() && windowFlags().testFlag(Qt::X11BypassWindowManagerHint) ) {
        //  QMainWindow::show() after QMainWindow::restoreState() will break the minimizing again so we should delay calling adjustToolbar().
        QMetaObject::invokeMethod(this, "adjustToolbar", Qt::QueuedConnection);
        // If we're sure restoreState() is only called after show() then adjustToolbar() could be called here directly instead.
        //adjustToolbar();
      }
    }

  private slots:
    void adjustToolbar()
    {
      const bool vis = !isHidden();
      hide();
      setWindowFlag(Qt::X11BypassWindowManagerHint, false);
      if (vis)
        show();
    }
#endif
};

UPDATE3: The minimizing issue also exists with floating QDockWidget if the QMainWindow state is restored before it is shown. In fact with "older" Qt versions the floating widget doesn't show up at all (doesn't with <= 5.9.5 but does with >= 5.12.4, don't have anything in between to try ATM). So the proper approach is to show() the main window first and then restoreState(). Unfortunately this doesn't seem to work for QToolBar.
UPDATE4: Filed as QTBUG-78293
Answer: It seems to work normally on macOS:
Comment: I think the OP environment is Linux
Comment: Yes, Problem is on Linux.


How can I turn this into an Ansible Playbook?

Question: I'm very, very new to Ansible so I just need someone to break down how to set up a yaml file to use as a playbook.
I wrote this string of code that does work:
ansible Test --user exampleuser --ask-pass -c local -m ping

Output:
192.168.1.4 | SUCCESS => {
    "changed": false,
    "ping": "pong"

How to I format what I wrote so I can just type:
ansible-playbook test.yaml

Comment: you can start [here](https://docs.ansible.com/ansible/latest/modules/ping_module.html?highlight=ping)
Answer: Below is the content of yaml file should look like
---
- hosts: Test
  connection: local
  remote_user: exampleuser
  tasks:
    - ping:

Comment: Thank you! I was confused as to where "ping" should go.


Need looping Powershell script to email me when site has error message

Question: Running 08 windows server on a VM
We need to be notified by email or by other means whenever the site is either 404 or goes to maintenance page.
Therefore, we need the script to be constantly checking the site for errors.
When this occurs, we also need the IIS to restart itself using the script.
Since this runs on a server, we need it to execute once and keep on looping.
I need any sort of guidance as to where begin. I was dumped this project, with no prior experience on Powershell.
Thanks.
Comment: I would suggest leaning a bit about powershell first.  this isn't a complicated script but I wouldn't want to encourage you to run a script you don't understand on a public facing webserver.  See https://technet.microsoft.com/en-us/scriptcenter/dd742419 for a starting point
Answer: Typically that is called monitoring and is something you don't do from the server itself (dead servers have typically great difficulty announcing their own deaths) but from second host.
Many monitoring systems have agents that can be installed on the servers that are being monitored and which can be called to attempt a service restart automatically as first aid, and only when that fails a notification is sent to whoever is on pager duty.
Don't try to reinvent the wheel.
Comment: dead servers don't serve pages at all and is not the ask.  This is a very common ask, since most of the time you wouldn't want to buy/build a monitoring solution for a simple page check. Don't buy a railroad for a 3 minute walk.
Comment: Well we dont want an outside service to let us when know when the server is down. We just need to know when the site is down, considering how IIS is the issue. Not the server.
Comment: @kaizen think long term for a bit here.  You may be having problems with IIS today, but a full monitoring system will be able to help you with your Out of memory issues, or disk full issues tomorrow.  You don't have to use an external services to monitor IIS.  There are many fine monitoring systems that you can run within your network.


Passing array to function - array is empty inside function

Question: I tried almost everything, I have two codes:
First one, pokaz_ofe, calls correct function - "generuj_oferte" in ajaxQuery() function, but I cant access postTab array in ajaxQuery(). Without delete postData it was using old array from another call (other that in "pokaz_ofe" function).
function ajaxQuery(postData, func_var) {
    $.ajax({
        type: "POST",
        url: "ajax/pokaz_lst.php",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(postData),
        success: func_var
    })
    postData = [];
    delete postData;
}
function pokaz_ofe(id,tab) {
    if(!tab) {
      var postTab = [
        { "id": id }
      ]
    }
    else {
      var postTab = [
        { "id": id },
        { "listaId": tab}
      ]
    }
    ajaxQuery(postTab, generuj_oferte);
}
function generuj_oferte(res) {
    $(document).ready(function(){
        $('#modal-oferta').html( res );
    });
}

And this is the different code which works, but I want it more flexible:
function pokaz_ofe(id,tab) {
    if(!tab) {
      var postData = [
        { "id": id }
      ]
    }
    else {
      var postData = [
        { "id": id },
        { "listaId": tab}
      ]
    }
    $.ajax({
        type: "POST",
        url: "ajax/pokaz_ofe.php",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(postData),
        success: generuj_oferte
    })
}

Comment: You should pass it inside a function, declaring its scope inside an anonymous function `succes: function(res){ general_offerte(res); }`, thats will allow you to access it.
Comment: works for me. http://jsfiddle.net/9kkjuzjx/   without the `delete` call: http://jsfiddle.net/9kkjuzjx/1/
Answer: It was rly stupid one mistake... now it is:
function ajaxQuery(filename, postData, func_var) {
    $.ajax({
        type: "POST",
        url: "ajax/" + filename + ".php",
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(postData),
        success: func_var
    })
    postData = [];
    delete postData;
}

It was all about filename.


Debian - NGINX startup job (initd) doesn't stop

Question: I just compiled the last Nginx version (1.7) on my debian 7.4 machine based on different web posts and docs merged here. It works fine.
I also need to change the startup job to target the new Nginx executable. The result is that I can start but can't stop the http sever with the service command.
Nginx 1.7.0 executable location :
/opt/nginx/sbin/nginx.

I removed the previous initd run nlevels configuration by type in
sudo update-rc.d nginx remove

in /etc/init.d/nginx I replaced these two lines :
# PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
# DAEMON=/usr/sbin/nginx

with
PATH=/opt/nginx/sbin:/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DAEMON=/opt/nginx/sbin/nginx

Then set run levels
sudo update-rc.d nginx defaults

The sudo service nginx start works fine, but the stop command doesn't work. sudo service nginx stop does nothing, nginx jobs are stil there
root      3252     1  0 09:17 ?        00:00:00 nginx: master process /opt/nginx/sbin/nginx
www-data  3253  3252  0 09:17 ?        00:00:00 nginx: worker process

Note : I didn't uninstall the old 1.2 Nginx installation.
It's really boring and error prone to kill and restart the process after each configuration update ....
Thanks for your help.
Answer: Fix
The system needs to know the process ID of the nginx daemon to be able to kill it when the stop request is issued. The file containing this PID must be declared in the PIDFILE variable in the /etc/init.d/nginx startup script AND in the nginx configuration file. I forgot this latter.
/etc/init.d/nginx
PIDFILE=/var/run/nginx.pid

/path/to/nginx.conf
pid     /var/run/nginx.pid;

Here is the whole startup script source
#! /bin/sh
### BEGIN INIT INFO
# Provides:          nginx
# Required-Start:    $local_fs $remote_fs $network $syslog
# Required-Stop:     $local_fs $remote_fs $network $syslog
# Default-Start:     2 3 4 5
# Default-Stop:      0 1 6
# X-Interactive:     true
# Short-Description: nginx-1.7.0
# Description:       HTTP server and Reverse proxy
### END INIT INFO

# Author: Emmanuel Brunet <email@example.com>
#
# Please remove the "Author" lines above and replace them
# with your own name if you copy and modify this script.

# PATH should only include /usr/* if it runs after the mountnfs.sh script
PATH=/sbin:/usr/sbin:/bin:/usr/bin
DESC="nginx server"
NAME=nginx
DAEMON=/usr/sbin/$NAME
PIDFILE=/var/run/$NAME.pid
SCRIPTNAME=/etc/init.d/$NAME

[ -x "$DAEMON" ] || exit 0
[ -r /etc/default/$NAME ] && . /etc/default/$NAME
. /lib/init/vars.sh
. /lib/lsb/init-functions

do_start()
{
    # Return
    #   0 if daemon has been started
    #   1 if daemon was already running
    #   2 if daemon could not be started

    start-stop-daemon --start --pidfile $PIDFILE --exec $DAEMON --test > /dev/null \
        || return 1
    start-stop-daemon --start  --pidfile $PIDFILE --exec $DAEMON  \
        || return 2
}

do_stop()
{

    start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 --pidfile $PIDFILE --name $NAME
    RETVAL="$?"
    [ "$RETVAL" = 2 ] && return 2
    start-stop-daemon --stop --quiet --oknodo --retry=0/30/KILL/5 --exec $DAEMON
    [ "$?" = 2 ] && return 2
    rm -f $PIDFILE
    return "$RETVAL"
}

do_reload() {
    #
    # If the daemon can reload its configuration without
    # restarting (for example, when it is sent a SIGHUP),
    # then implement that here.
    #
    echo "reloading" $DESC
    start-stop-daemon --stop --signal 1 --quiet --pidfile $PIDFILE --name $NAME
    return 0
}

case "$1" in
  start)
    [ "$VERBOSE" != no ] && log_daemon_msg "Starting $DESC" "$NAME"
    do_start
    case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  stop)
    [ "$VERBOSE" != no ] && log_daemon_msg "Stopping $DESC" "$NAME"
    do_stop
    case "$?" in
        0|1) [ "$VERBOSE" != no ] && log_end_msg 0 ;;
        2) [ "$VERBOSE" != no ] && log_end_msg 1 ;;
    esac
    ;;
  status)
    status_of_proc "$DAEMON" "$NAME" && exit 0 || exit $?
    ;;
  #reload|force-reload)
    #
    # Insert code here if needed
    #;;
  restart|force-reload)
    #
    # Insert code here if needed
    #
    echo "Restarting $DESC"
    do_stop
    case "$?" in
      0|1)
        do_start
        case "$?" in
            0) log_end_msg 0 ;;
            1) log_end_msg 1 ;; # Old process is still running
            *) log_end_msg 1 ;; # Failed to start
        esac
        ;;
        *)
        # Failed to stop
        log_end_msg 1
        ;;
    esac
    ;;
        *)
    #echo "Usage: $SCRIPTNAME {start|stop|restart|reload|force-reload}" >&2
    echo "Usage: $SCRIPTNAME {start|stop|status|restart|force-reload}" >&2
    exit 3
    ;;
    esac

Hope that helps.


Interaction term in a longitudinal study using LME-Model

Question: I have longitudinal data with a pre and post condition where 4 groups where used. The groups where a control group (CG), a control group with high protein intake (CGPR),  a training group (IG) and a training group with high protein intake (IGPR).
I was wondering if it is possible to fit an interaction term between protein intake and training with lmer().
My model would look like this:
final_model <- lmer(Outcome~Time+Training+ProteinIntake+Training:ProteinIntake +(1|ID), data=data, REML=F).
My Question is if it is valid to compare CG and CGPR with IG and IGPR for the effect of training AND CG and IG with CGPR and IGPR for the effect of Protein Intake and also including the interaction term Training x ProteinIntake. I am not really sure, because i will include the groups in multiple in comparisons and due to that i think they will have shared variance.
Thank you for any help!
Answer: Whether to include an interaction term depends on whether you suspect that the effect of training depends on protein intake, and vice-versa. Your design is similar to a classic two-way analysis of variance, which would include an interaction between the treatment groups to allow for that possibility.
The comparisons you suggest make sense, but they shouldn't generally be labeled as the effect of either training or protein intake. With the Training:ProteinIntake interaction term, there no longer is a single "effect of training" or a single "effect of protein intake," as the effect of training depends on protein intake, and vice-versa. If the interaction is small you might be able to construct such individual estimates for training and protein intake, but explain carefully to your audience what they mean.
It's not completely clear what you mean by "shared variance" here, as there are several sources of variance in the data and your model. There's an error variance in the linear model, a variance of intercepts among individuals captured in your random-effect term, and variances and covariances of the coefficient estimates from the model. In that sense there is always a "shared variance" in this type of modeling.
Comment: Thank you for your answer @EdM.
With shared variance i was referring to that in the effect of training, i coded both IG and IGPR group as one and CG and CGPR as one (also the same for the Protein comparison). There i include the "subgroups" into multiple comparisons, and i wondered if that would be a problem with sharing variance (i hope its clear what i mean). Or would it be more accurate to include the subgroups first and then include the Training and ProteinIntake comparisons afterwards like this: `lmer(OC~Time+Group+Training+ProteinIntake+Training:ProteinIntake+(1|ID)`?
Comment: @JanSch that extra `Group` term seems to be collinear with the combinations of `Training` and `ProteinIntake` and thus lead to some coefficients that wouldn't be estimated. A standard way to set up this analysis is to use 0/1 for coding the `Training` predictor (0 for control, 1 for trained) and 0/1 for coding the `ProteinIntake` predictor (0 for no extra intake, 1 for extra protein intake), and proceed with the model shown in the question. Then use post-modeling tools like those in the [`emmeans` package](https://cran.r-project.org/package=emmeans) to evaluate differences among the groups.


Retorno array Json Mysql

Question: Tenho duas tabelas dentro em um banco de dados, e preciso que retorne os dados em uma array
Hoje tenho o retorno somente da tabela tbl_categorias_fotos
O retorno e assim.
<code>    [
    {
        "id_cat_fotos": "3",
        "nome_cat_fotos": "Transformador Principal",
        "desc_nome_cat_fotos": "O transformador principal e o componente que recebe a tensão da distribuidora"
    },
    {
        "id_cat_fotos": "4",
        "nome_cat_fotos": "Transformador Secundário",
        "desc_nome_cat_fotos": "O Transformador principal e o componente que recebe a tensão do transformador Principal"
    },
    {
        "id_cat_fotos": "5",
        "nome_cat_fotos": "Titulo",
        "desc_nome_cat_fotos": "Descrição Teste 00",
    }
    ]
</code>
Estou tentando puxar os dados da tabela tbl_fotos_empresa que são referentes a um determinado usuário
<code>    [
{
    "id_cat_fotos": "3",
    "nome_cat_fotos": "Transformador Principal",
    "desc_nome_cat_fotos": "O transformador principal e o componente que recebe a tensão da distribuidora",
    "fotos": {
        "nome_foto_empresa": "Nome da foto",
        "descri_foto_empresa": "Descricao"
    }
},
{
    "id_cat_fotos": "4",
    "nome_cat_fotos": "Transformador Secundário",
    "desc_nome_cat_fotos": "O Transformador principal e o componente que recebe a tensão do transformador Principal"
},
{
    "id_cat_fotos": "5",
    "nome_cat_fotos": "Titulo",
    "desc_nome_cat_fotos": "Descrição Teste 00",
    "fotos": {
        "nome_foto_empresa": "xIIv52hz_1557963798.jpg",
        "descri_foto_empresa": "Descricao"
    },
    "fotos": {
        "nome_foto_empresa": "lCq3QcRF_1557967320.jpg",
        "descri_foto_empresa": "Descricao"
    },
    "fotos": {
        "nome_foto_empresa": "lCq3QcRF_1557967388.jpg",
        "descri_foto_empresa": "Descricao"
    }
}
]
</code>
Sera que consigo concatenar o mesmo SQL e exibir como o exemplo acima?
Alguem pode me dar uma dica de como buscar e exibir
<code>$sql = "SELECT * FROM  tbl_categorias_fotos";
$result = $conn->query($sql);

while($row = $result->fetch_assoc()) {

    $array[] = array(
            'id_cat_fotos' => $row["id_cat_fotos"],
            'nome_cat_fotos' => $row["nome_cat_fotos"],
            'desc_nome_cat_fotos' => $row["desc_nome_cat_fotos"]
    );

}
</code>
Answer: Se você tiver só uma foto por categoria, você poderia fazer uma select único:
<code>$sql = "SELECT * FROM  tbl_categorias_fotos cat LEFT JOIN tbl_fotos_empresa fotos ON cat.id_cat_fotos = fotos.id_cat_fotos";
</code>
Utilizei o LEFT JOIN para caso alguma categoria não tenha foto mesmo assim ele retornar;
<code>while($row = $result->fetch_assoc()) {

    $array[] = array(
        'id_cat_fotos' => $row["id_cat_fotos"],
        'nome_cat_fotos' => $row["nome_cat_fotos"],
        'desc_nome_cat_fotos' => $row["desc_nome_cat_fotos"],
        'fotos' => array(
                      'nome_foto_empresa' => $row["nome_foto_empresa"],
                      'descri_foto_empresa' => $row["descri_foto_empresa"]
        )
    );
}
</code>
Acredito que desta maneira você irá conseguir a saída que você quer, depois é só converter em json, utilizando json_encode();
Por favor, faça os ajustes quanto as colunas do seu banco. Espero ter passado a ideia.
Comment: montei aqui, mas vc acha que teria como se uma categoria possuísse mais de uma foto, ela seja exibida na mesma array de fotos?
Comment: Talvez nessa situação você teria que fazer alguma tratativa, tal como. trazer tudo ou seja tuplas repetidas, porém dispensar a parte repetida e ir incluindo só as fotos. ou para cada interação das categorias você fazer uma consulta passando o id da categoria para foto especifica de cada categoria. porém isso iria consumir muito recurso dependendo da quantidade de categorias. deu para entender?
Comment: Sim entendi, e cheguei nesta mesma conclusão, terá muito mais consumo que o necessário, estou vendo com o DEV do APP se podemos incluir estas fotos apos o clique na categoria, que creio que sera muito mais viável
Comment: Sim! Existe um tecnologia chamada Ajax, que você pode tornar tais chamadas muito mais versáteis e rápidas. Desta maneira suas fotos seriam carregadas por demanda. Você poderia fazer o seguinte utilizar este select da resposta para trazer somente uma foto e quando o cliente clicasse sobre a categoria carregar as outras através do Ajax.
Comment: Espero ter ajudado. Qualquer duvida é só falar. Se a resposta tiver lhe ajudado não esqueça de qualifica-la .

Retorno array Json Mysql


É possível criar e remover arquivos .properties do Android, pela própria aplicação?

Question: É possível criar e remover arquivos .properties do Android, pela própria aplicação?
Ex: após criar uma anotação ele cria um arquivo .properties com o nome daquela anotação!
Answer: Não é possível criar ficheiros a partir da aplicação. Podes no entanto interagir com um ficheiro já existente. Para o efeito deverás:

Criar no teu projecto, no local desejado o ficheiro que vais utilizar a partir da aplicação.
Após o ficheiro criado, podes utilizar uma função do género da que apresento em baixo para guardar dados no mesmo:
public void CreatePropertiesFile(Context context) {

  Properties prop = new Properties();
  String propertiesPath = context.getFilesDir().getPath().toString() + "/app.properties";

  try {
    FileOutputStream out = new FileOutputStream(propertiesPath);
    prop.setProperty("HomeVersion", "0");
    prop.setProperty("DatePlaySquare", "0");
    prop.setProperty("CustomerID", "0");
    prop.setProperty("DeviceToken", "0");
    prop.setProperty("CurrentVersionMobile", "0");
    prop.setProperty("Domain", "Megazy");
    prop.setProperty("DownloadNewVersion","0");
    prop.store(out, null);
    out.close();
  } catch (IOException e) {
    System.err.println("Failed to open app.properties file");
    e.printStackTrace();
  }
}

Deverás adaptar a função às tuas necessidades, mas já ficas com uma ideia de como podes realizar a operação.

Isto é apenas um exemplo retirado desta resposta no SOEN colocada pelo utilizar @user3113670.
Outro bom exemplo pode ser encontrado nesta resposta também no SOEN colocada pelo utilizador @Javanator.

A Saber
Em Android, quando falamos em guardar dados, falamos quase sempre em Data Storage mais especificamente Preferências Partilhadas. Existe um tutorial muito bom sobre este assunto:
Android Essentials: Application Preferences (Inglês)
Créditos desta informação para o utilizador @Rajesh nesta resposta no SOEN que evidenciou os links para a documentação e tutorial.


Scrapy - extract href from link with specific attribute value

Question: I'm working with Scrapy. I have a list of a-carousel-card where I'm tring to extract the href from the second element. The following code only extracts the first link it finds. The only difference between these cards is a aria-posinset attribute with the values "1", "2", etc.
response.css("li.a-carousel-card a::attr(href)").extract_first()

I'm very unsure about how I extract the href from the second element in the list.
Something like response.css("li.a-carousel-card a[aria-posinset="2"] a::attr(href)").extract_first(), but this gives me a syntax error at "2".
The first element is

,
while the other is

The only difference between the two are the value in aria-posinset: "1" and "2".
How would I accomplish this?
Answer: You either need to escape the double quotes inside string or you need to use single quotes. You need to use below
response.css("li.a-carousel-card[aria-posinset='2'] a::attr(href)").extract_first()

Comment: The attribute is on li and not a, so you should check it on li. please see updated answer
Comment: Thank you for your answer. I've edited my question, as I'm getting `None`. Are you able to look at it again, please?


Knowledge required to build your own integer class?

Question: Upon reaching a brick wall with the .Net framework's lack of a BigInteger class (yet), I've decided I'd like to develop my own as an exercise (I realize open source alternatives exist).  What hoops do I need to jump through to be able to develop this?  Is there any particuliar knowledge pieces that I probably wouldn't have?
edit: side question.  Which data type would you use to represent the numbers inside of your new big integer class?
Comment: F# has a big int, don't know how it's implemented underneath.
Answer: Arbitrary precision arithmetic?
Edit: To represent your numbers you will probably want a resizeable array of integers.
Comment: Good call!  Some interesting facts on the side in that article, too.
Answer: I would brush up on your basic math skills.  When I wrote a Big Int class I had to remember how to add, multiply and divide by hand like in Elementary school.
Next if you are going to create a new class I would try to follow the standards that have been set up for the Framework.  So it looks like any other .Net class.
I would follow TDD so you know your class works the way it is designed.
Comment: Is it suggested that for this class I mock the algorithms after the way I'd perform these calculations on paper?  If so, what data type do you start with/
Answer: You need to have a very good understanding of number systems. You could choose to represent the bignum in base 10, base 2  or any base x. This choice would affect your class performance a lot. You also have to choose the algorithms you want to implement. In general, great libraries like GMP for example, choose the algorithm based on the size of the operands. There are a lot of topics you have to be aware of, but in the end you should be convinced that you can't produce something really interesting. As a learning topic it is very valuable, but as producing something useful consider NOT reinventing the wheel!
Comment: Representing the number in base 10 might be good for displaying the numbers, but it's a nightmare if you need to make operation on it.
Comment: Reinventing the wheel for an end product is definitely not my goal.  This is entirely educational.  I'm thinking it would be smartest to implement this in only base 10 for my first try at this, for simplicity sake, no?
Comment: What would make it a nightmare for operations?
Comment: @jpbochi While I agree that base 2^n is the natural choice. Many good libraries like MAPM represents *big float* in base **100**. It is not a nightmare, it is a trade off between goals you want to achieve.
Comment: Your base type is in base 2, and you want to work in base 10.
Answer: If you want to dive really deep into the math of it, you need to read Donald Knuth.
Answer: .Net 3.5 has a BigInteger class, but it's scoped internal to the CLR.  You can see the code using Reflector.  Open System.Core.dll and look in the System.Numeric namespace.  BigInteger is the only class in that namespace.
If you want to see the code for the F# BigInteger class, look in the [F# install folder]\source\fsharp\FSharp.Core\math\z.fs file.
Answer: Maybe studying an already implemented BigInteger class might help?
Comment: This was my first instinct.  I realized there's a lot of hex and bit pushing going on, which I'm fairly dusty with.  That's why I asked!
Answer: If you use elementary algorithms, your BigInts will be unusable for very large integers, for example like Mersenne Primes.
If this is ok for you, use a simple 32 bit int as the basic data type. You need to handle 64 results in this case. If you don't care about speed at all, use some radix-10 number as base, lets say 10000, which will be very easy to implement.
This is mainly because the multiplication in a naive implementation has O(n^2) runtime. Advanced algorithms, based on fourier transforms, have O(n(log(n)) runtime.
This requires some mathematical skills and knowledge.


Issues with stochastic gradient descent

Question: I am using stochastic gradient descent to learn a model. Here is the plot of the objective function for the iterations. I am trying to maximize the function value.

Taking the average of 500 iterations, I have this next plot

As you can see the function value is increasing and we can say the algorithm is converging. However, looking at the first plot, we can see that the function never actually went past a certain threshold. Even though the minimum value it could reach went on converging with the iterations, the maximum value that it could attain remained almost the same.
So can we say the algorithm is converging?
Answer: Yes, you can say that the algorithm is converging because it is increasing the objective value on average.
The most tricky part of stochastic gradient descent (SGD) is the 'learning rate'. Common choices are 1/t, 1/sqrt(t), D/(G*t) where t is the iteration number, D is the max diameter of your feasible set, and G is the infinity-norm of the current gradient. You should experiment with these. You can even split your data into two for cross validation of the learning rate.
Another thing you can try is mini-batch SGD. In this variant, instead of using a single data point to compute the gradient, you use a batch of points like 10,20. This way, the objective-versus-trial plot (the first plot) will be smoother and will look like the second plot you have.
Answer: The right way to monitor convergence is actually to measure the very objective you are optimizing. In your case, this is the average of the error over the whole training set. So the correct way would be to do a pass over the training set evere $k$ iterations only for the purpose of calculating your loss.
This is of course terribly inefficient for big data sets, but everything else is basically a heuristic. Here are some that I use:

Calculcate the loss on a fixed batch every $k$ iterations (use as many samples as you can afford computation time wise). This removes the stochasticity. Ideally, you would do this on a held out validation set that you do not use for estimation of the gradient and which also tells you when to stop optimizing. (That is, when that error rises).
Take a moving average (similar to you second plot).
Fit an exponential to your error curve and see whether the gradient of that fit is low.
Check the absolute values of your gradients and stop if they fall below some threshold.
Answer: Yes, it's converging, but difficult to see (or measure programmatically) from the first plot. You can try averaged SGD, where you use the average of the usual noisy SGD-trained parameters as the true model parameters. See Xu, 2011, "Towards Optimal One Pass Large Scale Learning with Averaged Stochastic Gradient Descent." The averaged parameters should converge faster, and it should make your plots look much smoother.

Issues with stochastic gradient descent


django why getting this error 'RelatedManager' object has no attribute 'email_confirmed'?

Question: When I am using user.email_confirmed I am not getting any error but when using user.userprofile.email_confirmed getting RelatedManager error. Why I am getting this error when trying to get user details from userprofile model?
here is my code:
class UserManagement(AbstractUser):
          is_blog_author = models.BooleanField(default=False)
          is_editor = models.BooleanField(default=False)
          is_subscriber = models.BooleanField(default=False)
          is_customer = models.BooleanField(default=False)
          email_confirmed = models.BooleanField(default=False) #there is no error when obtaining email_confirmed object from abstract user model.

class UserProfile(models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE,related_name="userprofile")
      email_confirmed = models.BooleanField(default=False)

#I am using this for email verification
class AccountActivationTokenGenerator(PasswordResetTokenGenerator):
    def _make_hash_value(self, user, timestamp):
        return (
            six.text_type(user.pk) + six.text_type(timestamp) +
            six.text_type(user.userprofile.email_confirmed) #error rising for this line
            #six.text_type(user.email_confirmed) #I am not getting error if I use this line
        )

account_activation_token = AccountActivationTokenGenerator()

views.py
....others code
if user is not None and account_activation_token.check_token(user, token):
            user.userprofile.email_confirmed = True #why it's not working and rising error?
            #user.email_confirmed = True #it's working
            user.save()
            .....others code

Comment: UserProfile uses a ForeignKey, rather than a OneToOneField, so it is possible for each user to have multiple UserProfile objects. You therefore need to filter the `user.userprofile` queryset down to a single object before you can use it. See also: https://stackoverflow.com/questions/5870537/whats-the-difference-between-django-onetoonefield-and-foreignkey
Comment: @Nick ODell should I use user.userprofile.filter(email_confirmed = True) for six??? can you please show me which query set will be appropriate for  `user.userprofile.email_confirmed` and `user.userprofile.email_confirmed = True`
Answer: as @Nick ODell told me I need to be use filter.
The problem was occurring for this two queryset:
user.userprofile.email_confirmed and user.userprofile.email_confirmed = True after I changed theme
user.userprofile.filter(email_confirmed=False) and  user.userprofile.filter(email_confirmed=False).update(email_confirmed=True) my problem solved.