Programmatically show field in different regions depending on content

Question: I'm creating an Omega sub theme & three regions ("Sidebar 1", "Content" & "Sidebar 2") inside of the "Content zone". "Sidebar 1" & "Content" are both set to always show, "Sidebar 2" however is set to only show if there's content inside of it.
I also have a field which contains links related to the page, this is output programmatically into all three regions but CSS hides all but one. This is done so it can be shown in the "Sidebar 1" region which stacks above the "Content" region on small screens but on larger screens it'll be hidden in the "Sidebar 1" region & shown in the "Sidebar 2" region instead, on the right hand side. If "Sidebar 2" doesn't exist it'll then be shown in "Content."
"Sidebar 1" pretty much only contains a menu, only on some pages though, which is again programmatically output. The reason being that I want to label / title of the menu to be set to the name of the currently active page and it was the best way I could see of doing it.
I've almost got it all working as I have a class set on the content zone div which states how many regions are inside of it (2 means no "Sidebar 2", 3 means it's there) & the first sidebar now adds a class stating if it's empty or not.
I've attempted to add a class to the "Sidebar 2" region by using drupal_get_region_content("sidebar_1") to detect if the "Sidebar 1" region is empty of not and add a class to the "Sidebar 2" region based on this will CSS selectors will use. Problem is no mater what I try or what region I try to output drupal_get_region_content always returns NULL.
The basics of what I'm trying to do
I'll try and write here what I'm wanting in a more concise manor, above I've also included how I'm trying to do it.
I have some pages with three regions in the content zone, I want to output a field in all three regions so they can be shown & hidden at different screen sizes with CSS.
The left sidebar might have a menu in which is added programatically. If it does not have this then the second sidebar doesn't need to the field I'm outputting programmatically will just be shown in the first sidebar & main content area.
I realise this is very long, appreciate anyone who's read it and any help you can offer.
Comment: I'm not sure I understand what you are trying to do. So, what do you mean by "field" here, do you mean a "block"?
Comment: Sorry, I thought this would be a bit confusing to explain. By field I mean a field which is completed by the user when creating a node, not a block. It's a field actually added to the content type. It's being programmatically added so it can appear in all content zone regions and shown / hidden depending on screen size to get it to appear in the correct location.
Comment: So, basically, you have 3 columns inside your content area. And you want to show / hide the third one depending on whether a node field is empty or not?
Comment: Close, I want to show & hide the third one based on if the first one has a menu in it or not. If it doesn't have a menu then I want the third one hidden, if it does have a menu I want it to show.
Comment: Perfect. Check my answer below and let me know.
Answer:
"I have some pages with three regions in the content zone, I want to
  output a field in all three regions so they can be shown & hidden at
  different screen sizes with CSS..."

If this is the case, you could solve this entirely in CSS, by using media queries to show / hide areas -or your field -depending on the browser size. And you don't even need to have the same field in all the three regions.
However, if what you want is to show / hide columns inside your content depending on a field value, you might be looking for the Display Suite module, which allows you to easily create different layouts and view modes. For example, you could:

Create one view mode with 2 columns and another one with 3 columns.
Add the fields you want to display in each one of those view modes.
If you want to switch the view mode, depending on whether a field has a value or not, you could use hook_entity_view_mode_alter() like this:
<code>function YOUR_MODULE_entity_view_mode_alter(&$view_mode, $context) {
  // If viewing a node in the two_columns view mode...
  if ($context['entity_type'] == 'node' && $view_mode == 'two_columns') {

    // If your field 'something' has a value, change the view mode to 'three_columns'.
    if (!empty($context['entity']->field_something)) {
      $view_mode = 'three_columns';
    }
  }
}
</code>

Or you could also use the Contextal View Mode module to change the view mode for a node based off of a context.


Why will drupal not recognize my configuration?

Question: I am trying to import configuration from one site to another.  I have copied the directory full of config files from an older site to my new site.  When I try to run Drush cim, the files all show up as they will be created.  However, after answering yes to the prompt I get
<code>This import is empty and if applied would delete all of your configuration, so has been rejected. in Drupal\Core\Config\ConfigImporter->validate() (line 756 of
/home/vagrant/code/indigo-signs-pantheon/web/core/lib/Drupal/Core/Config/ConfigImporter.php).
The import failed due for the following reasons:                                                                                [error]
This import is empty and if applied would delete all of your configuration, so has been rejected
</code>
I found this question and tried changing the UUID like suggested, but it didnt change anything I still get the same error.
Any suggestions
Answer:
This import is empty

This error might occurs when the config directory is not configured in the settings.php.
Check for the config directory settings in new site. It will mostly have a different directory configured.
Change to the same folder path as in the old site.
Comment: This was it.  When i copied my directory to the new site i copied the whole directory into the new location not contents of the directory into the new location


Run python script from bash into Terminal not running

Question: I'm trying to run the following bash script on my raspberry pi:
#!/bin/bash

python Testing.py

It gives me two options: "Execute" and "Execute in Terminal".  Execute works no problem, it produces a CSV that I'm testing.   When I use "Execute in Terminal" though, the script doesn't run (I also have some print statements in there that don't print).  The terminal window is titled "LXTerminal".
Am I missing something?  My goal is to launch the script in a terminal window so it can produce print statements etc.
Thanks!
Comment: Why cant you call the python script directly?
Comment: i guess I could?  how do I do that...?  I'm trying to make this super simple for someone else, so they can simply double click something..
Comment: Yeah, he means why not just execute `python Testing.py` in a terminal.  Seems like the best option, only thing is that it's not as simple for the other person -- they need to know what to do other than just double clicking an executable file.

Things to check: Are both scripts executable?  And I assume they're both  in the same directory, like both on the Desktop?  What is your shebang on your python script?  Might as well make it `#!/usr/bin/env python`
Comment: Just out of curiosity, because I've never done such a thing on a raspberry pi, what happens when you execute this command:
`lxterminal -l -e 'python Testing.py ; /usr/bin/python '`

If it opens a terminal and executes the python script, perhaps you can put that in the bash script.
Comment: See the answer provided here: https://superuser.com/questions/906479/how-to-keep-the-terminal-open-after-executing-a-c-program
Answer: Try chmod 755 "file path/filename. I think this should help as it is used to change the file permissions.
Answer: This works for me:
xterm -e 'python /path/to/my/script.py'
or if xfce
xfce4-terminal -e '/path/to/my/script.py'
I just can't figure out how to keep terminal open when the scipt is complete.
Terminal is closed after script run.
Answer: I ran into the same issue and the problem was that my python command was an alias to the executable. When I replaced it with python3, it worked.


Como criar um autorun?

Question: Fiz um programa pelo Visual Studio e estou tentando criar um autorun para executá-lo, porém, o executável do programa fica em \programa\programa\bin\Debug\programa.exe e o autorun deve ficar na pasta raiz do CD ou imagem.
Este é o problema, como eu poderia fazer o autorun funcionar, já que o executável está em outra pasta?
Comment: Importante ressaltar que as versões atuais do Windows só respeitam Auto Run para mídias ópticas. Autorun em HD ou PenDrive será solenemente ignorado.
Comment: já tentou: open=programa\programa\bin\Debug\programa.exe ?
Comment: Esse caminho `\programa\programa\bin\Debug\programa.exe` é dentro do CD?
Comment: @bfavaretto, sim.
Comment: @alacerda, já, mas deu problema, disse que o windows não pode abrir esse tipo de arquivo.
Comment: @Patrick se certificou de usar o caminho relativo?
Comment: Ah, consegui, estava a colocar uma barra antes do caminho... `\programa\programa\bin\Debug\programa.exe`
Comment: @Patrick considere adicionar uma resposta a sua pergunta.
Answer: Respondendo um pouco mais do que perguntado, vou apontar algumas opções que tem ao usar o arquivo autorun.inf:
Principais atributos

action=texto opcional: texto do item da execução automática, tanto no menu de contexto, como na janela de execução automática da mídia.
icon=caminho caminho do ícone a ser usado para representar a mídia
É possível fazer referência a um ícone dentro de um pacode de ícones, executável ou dll, colocando uma vírgula + o índice do ícone dentro do arquivo:
app\ConsoleApplication.exe,0
label=texto título da mídia que aparece no Explorer
open=caminho caminho para execução automática

Atributos para adição de itens ao menu de contexto

shell=nome_comando_primario indica qual é o menu primário, que aparece em negrito no menu de contexto, e será usado no duplo clique
shell\nome_comando=texto representa o título da opção de menu nome_comando... podem haver vários títulos para nome_comando`s distintos:
shell\comandoA=Título comando A
shell\comandoB=Título comando B
shell\nome_comando\command=caminho caminho do executável que deve ser disparado ao clicar no comando específico. Deve haver um para cada título de comando especificado:
shell\comandoA\command=app\ConsoleApplication.exe
shell\comandoB\command=notepad.exe arquivos/leiame.txt

Mapa das partes do arquivo Autorun.inf
Abaixo um mapa que mostra onde devem aparecer os textos colocados no arquivo Autorun.inf, assim como a relação entre as propriedades. Usei cores para indicar os elementos relacionados em várias partes.

Exemplo completo
[autorun]
action=Executar ConsoleApplication.exe (action)
open=app\ConsoleApplication.exe %0
icon=app\ConsoleApplication.exe,0
label=Título do CD (label)

shell=iniciar

shell\iniciar=Lançar a aplicação (shell\iniciar)
shell\iniciar\command=app\ConsoleApplication.exe %0

shell\leiame=&Ler o aqruivo leiame.txt (shell\leiame)
shell\leiame\command=notepad.exe arquivos/leiame.txt

Aplicação
using System;
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(string.Join(" ", args));
            Console.WriteLine("Olá mundo!");
            Console.ReadKey();
        }
    }
}

Como adicionar um ícone na sua aplicação
Vá nas propriedades do seu projeto executável, na guia Application, daí é só selecionar um arquivo de ícone:

Referência
Autorun.inf Entries (MSDN)
http://en.wikipedia.org/wiki/Autorun.inf
Answer: Crie um  autorun.inf na Pasta raiz do CD
contendo um conteúdo semelhante a este:
[autorun]
open=programa\programa\bin\Debug\programa.exe
icon=Autorun.ico

Explicação:

"open=" mostra ao Windows o comando que deve ser executado.
"icon=" mostra ao Windows que ícone será utilizado para fazer a represnetação da mídia (CD, DVD ou Pen Drive) em Meu Computador ou no Windows Explorer.

A primeira linha "[autorun]" é apenas pra identificar que é um arquivo de autorun e deve ser especificada em todos os arquivos autorun.inf criados.
Fonte:
http://www.oficinadanet.com.br/artigo/1077/criando_um_arquivo_autorun.inf

Como criar um autorun?


Difference between dissonance and clashing notes

Question: Wikipedia describes dissonance as the quality of sounds that seems "unstable" and has an aural "need" to "resolve" to a "stable" consonance
Which basically means it hurts your ears and you want it to go away.
In the band pieces I have played, there is often dissonance written into the piece. And it sounds good if the instruments that are playing the opposing notes are in tune. But then there is just times when there is an instrument playing a wrong note. And it sticks out. So my question is why does dissonance sound good at times, when it doesn't at other times?
I think that this has something to do with the context that it is played within. For example, I played "Aquarium" from "The Carnival of the Animals" as a percussion ensemble piece. I had a vibraphone part, and it called for an alternating E and F with the pedal down. And it didn't sound too bad when we played it together. But if I played alone, it sounded awful. Why is that?
Answer: Dissonance is highly subjective and relative to musical context.
It is also commonly used as a source of tension in various kinds of music. Take, for example, a V7 - I chord progression. The dissonance between the 3rd and the 7th of the V7 chord (forming a tritone) creates a tension that we expect to hear a resolution for, by "relaxing" in the next, "stable" chord. This feeling of tension is mostly based in one's cultural upbringing.
Consider, also, the difference between a Maj7 chord as used in a slow jazz ballad vs. being played as a wrong note in baroque music. When we listen to different kinds of music, our ear is contextualized into the kinds of sounds we would expect to hear from that music. Hence, wrong notes are much easier to pick out in baroque music than they are in atonal music.
So, there's really no such thing as absolute dissonance (or consonance) in practice, but the relative terms with which we describe different collections of pitches come from an inspection of the harmonic series. You can read all about it on Wikipedia if you're not familiar, but the way it is applied here is that intervals near the beginning of the harmonic series can always be described as more consonant than intervals occurring later in the series.
So, to wrap up and come back to the last part of your question, when you were playing vibes in Carnival of the Animals, the part was occurring in the larger context of a piece of music with lots of textural elements, and the less-restrictive harmonic context of Saint-Saëns's French Romanticism. However, when you were practicing on your own, you were just hearing two notes in isolation that form an interval occurring quite high up in the harmonic series.
Comment: @CodyGuldner Playing a dominant 7th chord and then a root chord.
Comment: What is a v7-I chord progression?
Comment: Dissonance between two notes can be defined as a property of the sound. I don't know how, but it is not completely clear to me that the same cannot be done for larger number of simultaneous notes. How consonance and dissonance are interpreted as pleasant or not, for example, is a different story.
Comment: @FranklinVP Dissonance and consonance are descriptive words used on a continuum of relativity. Two notes at a time are just easier to explain the concept with; of course you can apply it to any number of notes played simultaneously.
Comment: keyword: progression


Delete 'CATALINA_HOME' user variable or update the 'CATALINA_HOME' name to 'CATALINA_HOME_1' using java code

Question: I would like to delete the 'CATALINA_HOME' using java code. Please let me know if someone know this type of problem.
Suppose already set 'CATALINA_HOME' = C:\Program Files\Apache
While installing the software, my software should use the my customize tomcat7
and that store in different location.
'CATALINA_HOME' = D:\Installer\Apache
while running the software it find the tomcat this location 'CATALINA_HOME' = C:\Program Files\Apache but my location is
'CATALINA_HOME' = D:\Installer\Apache
Comment: Why you need to do so?
Comment: Delete the entry in file in which you want to modify.
Comment: CATALINA_HOME is defined in a file, generally on catalina.sh. You can modify it as any other regular file if you have access to it.
Comment: What _is_ the question exactly?
Comment: look at this thread http://stackoverflow.com/questions/318239/how-do-i-set-environment-variables-from-java
Answer:
I would like to delete the 'CATALINA_HOME' using java code.

Sorry, but you can't.  A program (at least on Linux / Unix / Solaris) cannot modify the environment of its parent shell.  At most, a program only sees a snapshot of its parent's environment variables ... as they were when the parent forks the child process.
(Windows variables work a bit differently, but I think the same restriction applies ...)
The only thing that a Java can do (reliably / portably) is to change the environment variables that a child process of your Java process will inherit.  You can do that using ProcessBuilder.

Now in theory, a program could attempt to modify the source of the variables' values:

On a Unix like system, they often come from one of the shell's RC files; e.g. $HOME/.profile, $HOME/.bashrc and so on ... depending on the shell.  Or the variable may have been set in the "init" script that launches Tomcat.
On a Windows system, the may have come from the registry, or a BAT file or ...

The problem is two-fold:

It is impossible to be entirely sure where the value really comes from.
Even if you can be sure, changing the source of the value won't affect the respective shell's current value for the variable.

Note: this is not a shortcoming of Java.  You would have the same problem when coding in C, C++, Python ...


Group columns SQL

Question: I have the table clients:
client_id   name   class_id
101      Mark     2
132      David    3
199      Anna     1
199      Anna     1

and the table class:
class_id   name
1          Bronze
2          Gold
3          Platinum

how can I display in 2 columns with nicknames Class and Clients the number of customers that belong
in each of the three categories (Gold, Platinum, Bronze).
Class       Clients
Gold           1
Platinum       1
Bronze         2

and finally how can I display the details of all customers (except class_id) grouped based on the class category (ie Golden, Platinum, Bronze)?
Comment: Welcome to SO! I suggest you read over [how to ask](https://stackoverflow.com/help/how-to-ask) and edit your question to show us what you have attempted so far. In short, you're looking for `JOIN` to combine table data, `GROUP BY` to aggregate your resultset, and `COUNT()` to get the number of clients. Also, to clarify your data, is Anna (client_id 199) supposed to exist twice in the `clients` table?
Comment: No sry it was a typo. Clients ids are unique
Answer: Try the following, you need count and group by.
select
    cl.name as class,
    count(c.*) as clients
from class cl
join clients c
on cl.class_id = c.class_id

group by
    cl.name

order by
    clients,
    class;

Output:
| class    | clients |
| -------- | ------- |
| Gold     | 1       |
| Platinum | 1       |
| Bronze   | 2       |

Group columns SQL


How to sort view by the weight of referenced nodes?

Question: I'd like to display the list of studies and their authors in a view. Authors are stored in a node reference field. It's very important to keep the original order of referenced authors in the view which is repredented by their weight.
I looked through View UI for a solution for this problem but didn't find any useful option.
Answer: I found out that the :delta component of the field (e.g. field_authors:delta) can do this trick.
-- EDIT--
Some more explanation: Let's say field_authors contains the reference to connected authors. Among the sorting options there's a field_authors:delta which contains numbers for each referenced node (0, 1, 2...) and represnts their actual order.


Products containing a hyphen or numbers not shown or wrong relevance

Question: I have an external Apache Solr Server, with Search API and Search API Views.
When we search for ordinary products, they are shown correctly, with the correct descending relevance order.
When we search for a product with the exact name: "Productx-123W"
it is showing in this order (with highlighted terms by search function):

Productx-123D
Productx-123S
Productx-123
Productx-123W

So the exact product name is only shown on the 4th place, while all other products with no hyphens or - in them have the correct displayed order in the results.
It is like the hyphen splits the word in two.
Secondly, I have a product: Product20001w
When I look for this search term: "2000" nothing is shown. It's like the numbers on the end confuse the server.
When I look for "2001w", it shows the right products which have partially this "2001w" in their name.
Anyone knows how to fix this?
Comment: Do you have any custom configuration in your Solr? Can you post it?
Comment: Hi, I just received the config files from "Hosted Apache Solr" https://hostedapachesolr.com/
Here you can download the files: (thanks)
http://www.omegaservers.be/config-apache-solr.zip
Comment: I think Search API Solr module should have a tab where you can see the content of loaded config files as well.
Comment: You are right. there are a bunch of config files there. I didn't change anything there. Can I tweak something to make hyphens in a word be seen as real letters and treated as such ?
Answer: It is basically a feature of Word Delimiter Filter to allow matching of words on case-change, alphanumeric boundaries, and non-alphanumeric chars, so when typing "wifi", "wi fi" could match documents containing "Wi-Fi". That is why Product-123A is split to match more products. See: Intra-Word Delimiters.
So you can either disable WordDelimiterFilter, or customize it. For example:
<filter class="solr.WordDelimiterFilterFactory"
        protected="protwords.txt"
        generateWordParts="1"
        generateNumberParts="1"
        catenateWords="0"
        catenateNumbers="0"
        catenateAll="0"
        splitOnCaseChange="0"
        preserveOriginal="1"/>

Since the second part of your word consist number (e.g. 123W), you may try to enable catenateWords and catenateNumbers (set to 1) in your schema.xml file and apply the changes to your hosted Solr server.
You can also provide some customization usingwdftypes.txt file, see: SOLR-2059.
However, if you want to keep the feature as it is (without modifying any Solr config files), you can also consider increasing the score for certain fields, such as titles (e.g. a product name). So your Productx-123W phrase after a word split will match higher on documents with partial matches such as 123W in specific fields.
Related posts:

Search with various combinations of space, hyphen, casing and punctuations
Quering numbers containing hyphens with SOLR WordDelimiterFilterFactory isn't working?


Why do I have to enter a recipient after selecting users in the VBO send emails operation?

Question: I'm using VBO module in D7. I created a table view listing users by some filter criteria. I want to send a mass mail to selected users. I'm using the VBO field bulk operations: user and selected the send email functionality. The view looks like that:

Selecting multiple users and hitting the send email execute button brings me to this form:

Why do I have to enter a recipient after selecting users in the view? What does that send email operation do if not sending emails to the selected users?
Is it my fault and I messed up the installation or did I miss some settings or configurations?
Comment: Are you sure you have a view displaying *users* and not *nodes*?
Comment: Yes. I added a new view and selected *Show: Users*.
Answer: VBO does not provide the "send email" function. It is provided by core actions and it really doesn't know the context that it is being used in. Therefore, you need to insert a token in the "Recipient" field as mentioned in the help text just below the field e.g. user:mail , node:author:mail etc.  I can't tell for sure what the base table  your view is using based on your screenshot but it looks like you can use the token [user:mail].
If you would like to have this info prepopulated you need to use the views send module. It used to support VBO but it now provides it's own UI. It's a pain if you want to combine it with a VBO view as you get double checkboxes etc...
See http://drupal.org/node/575980 for more info
Comment: Yes [user:mail] worked for a view of users.
Answer: I think it is so that you can select which address to use. all tokens are available.
you probably want to enter [user:mail] in most cases. works fine with vbo


Editing a comma-separated list of path,size pairs

Question: I have lines of the form
parts=/a,1mb,/b/c,2gb,/zee/last,-1 #general form on next line
parts=path1,size1,...,lastPath,-1

I want to replace all path1,size1 except lastplace,-1 with newPath,newSize so that it looks like
parts=newPathX,newSizeX,lastPath,-1

I figured how to do it using at least one instance of ',' char as follows
sed 's|^parts=.*,\(.*,-1\)$|parts=newPathX,newSizeX,\1|gi'

but this breaks if the list only has the last path and size. For example, I want
parts=lastPath,-1

to be transformed to
parts=newPathX,newSize,lastPath,-1

So I tried to fix this with a conditional in bash:
egrep -i '^parts=.*,.*,-1$' $file
if [[ $? -eq 0 ]] ; then
    sed 's|^parts=.*,\(.*,-1\)$|parts='$new',\1|gi' $inp
else
    sed -i -e 's|^parts=|parts='$new',_gi' $file
fi

I would like to know a pure sed solution as I can quickly understand it, but awk will do too.
Comment: You might be able to make this work using `sed`, but anchored regexes and the `g` modifier aren't going to do it. You'd have to do some looping and splitting with some swaps between pattern space and hold space. Your title, question and data are all such a mess I'm not going to attempt it. It would be pretty hairy anyway.
Comment: I attempted to fix the format, but quickly gave up :(. @Some n00b - please format your code so we dont have to hire codebreakers.
Comment: puthere_new=/a,1kb,/b,2mb,/c,-1 will be change to what when newplace is /dd, and size is /2gb?
Comment: should I paste my bash quick as answer ? though I still want a combined 'regex magic' to solve this one ??
Comment: puthere_new=/dd,2gb,/c,-1 @Gadolin
Comment: @Dennis : sorry, 1st timer here.. getting used to stack overflow.. so no clue how people go about Qs and providing Data
Answer: Try using awk:
$ var='puthere=$place1,$size1,$place2,$size2,(..and so on..),$lastplace,-1'
$ echo "$var" | awk -F"[=,]" -vnp="$newplace" -vns="$newsize" '/puthere/{print "puthere="np,ns,$(NF-1),$NF}' OFS=","
puthere=test1,size1,$lastplace,-1

Comment: there are times when things can be done simpler by not using sed.
Comment: thank you very much for the nice 'awk' script, guess i'll have to start digging awk now :) But will it be too much to ask for single line sed magic ?
Thanks again !
Comment: I ask because the pattern comes as a line in a text file, can someone tell me how to convert above into something that will take $1=filename as argument and do the rest ?
Comment: hmm, I think I better customize your awk solution to my bash script, looks quite elegant :)
I give up on sed :( !
Answer: sed '/^parts=.*,.*,-1$/ s|=.*,\([^,]*,-1\)$|=newPathX,newSizeX,\1|gi'

Sometimes, its also very simple in sed ;-). Just add a filter before to avoid your exception case


Android: Create a background thread that runs periodically and does UI tasks?

Question: OK, so I know how to do a backround task, I know how to do a periodic task (using handle postdelayed and runnable), I also know how to do UI task from background thread (via handler) but I am not able to execute a periodic background task that does some action on the UI thread.
I am trying to execute some background task every minute in which I have to make a network call. After the call is over, depending on the output I have to update the UI. I tried to do something like this
private void DoTask() {
        Thread thread = new Thread() {
            public void run() {
                Looper.prepare();
                final Handler handler = new Handler();
                handler.post(netRunnable);
                Looper.loop();
            }
        };
        thread.start();
}

Runnable netRunnable = new Runnable() {
    @Override
    public void run() {
        handler.getLooper().prepare();
        final Handler handler1 = new Handler(Looper.getMainLooper());
        if ( do background work and check result){
            handler1.post(new Runnable() {
                @Override
                public void run() {
                    //Do UI Task
                }
            });
        }
        handler.getLooper().loop();
        handler.postDelayed(netRunnable, 60000);
    }
}

I understand that there might be some fundamental flaws with my implementation but I do not know how to do this task properly. Right now it is giving the error that Only one Looper may be created per thread.I get what it is trying to say. But can anyone please suggest to do this the right way.
Comment: check out this post: http://stackoverflow.com/a/15472594/4516174
Answer: You could use Async Tasks. These are designed for it :
http://developer.android.com/reference/android/os/AsyncTask.html
It allows you to execute a network call in the background, then when you get the result, execute an action on the UI thread
Declaration :
 private class MyTask extends AsyncTask<Input, Void, Output> {
 protected Output doInBackground(Input... inputs) {
       // do something on the network
       return myOutput;// use this to transmit your result
 }

 protected void onPostExecute(Output result) {
     // do something on UI thread with the result
 }

}
If you want to repeat it, just create a runnable to launch it, and after every call, schedule the next one :
MyTask myTask;
Handler handler = new Handler();

    Runnable myRunnable = new Runnable() {
            @Override
            public void run() {
                MyTask myTask = new MyTask();
                myTask.execute(myArg);
                handler.postDelayed(netRunnable, 60000); // schedule next call
            }
        }

To launch it for the first time :
handler.postDelayed(myRunnable, 60000);

Or, if you want to launch it immediately :
handler.post(myRunnable);

Do not forget to cancel the Task when your activity is destroyed :
myTask.cancel(true);

Comment: What if you rotate the phone while asyncTask is running?
Comment: It depends whether a configuration change event is triggered. If so, the activity is destroyed and the AsyncTask needs to be cancelled. If there is no configuration change, activity is not destroyed, so I think it is OK.
Comment: If I look at [this](http://stackoverflow.com/q/4748964/4791726), I think the task will not be cancelled that easily. You might also loose the reference to a valid activity. Cancelling network task might also not be the best idea.
Comment: I tdo not think that is really what the link means.  Whether or not this will actually cancel anything is dependent a bit upon what you are doing. You remain free to check whether the task has been cancelled. Also, if you want it, the network task can continue on its own.
Comment: What I mean: You can not simply call `myTask.cancel(true)` and the task stops automatically. You have to handle this condition in the doInBackground of the Task. And because you could loose the reference to your Activity, you have to check that aswell. Just some points that you should be aware of, when using AsyncTasks.
Comment: That is not exact. If you handle it correctly, you will never lose (and not "loose") the reference to your activity.
Comment: As I stated before, and it is explained in the link you posted : "Whether or not this will actually cancel anything is dependent a bit upon what you are doing". Please do not be confused between the background task and the UI task. If you want to cancel the background task, you have to check it regularly. Any way, if you call cancel(), the PostExecute() method will not be called, so potential activity reference loss, is not dangerous
Comment: @YvesDelerm Thanks for the response but during these tasks there might be swithing of activities. As such I do not think AsyncTask will be the ight way to go in that case !!
Comment: OK, I understand. My answer is more for general cases. Maybe you should precise it in your question, in order to have more specific answers.
Answer: Maybe you are better of, creating a seperate (Intent)Service and calling it periodically with postDelayed. Create a BroadcastReceiver in your Activity and handle UI changes there.
Another hint for handling UI changes from other threads: It is not possible. Therefore you need to call runOnUiThread. Here is how to use it
Comment: Intent service is an option but there are two reasons i do not want to use it. Firstly I don't need to do the task while the app is in the background which is the main reason for using IntentService. Secondly my need is something that self runs periodically, and I think it can be done in a simpler way. Thanks for the response anyways.
Answer: If activities are frequently switching, why not reversing  the responsibilities. You might create a service which executes a periodic network task.
Then,
 - either your activities periodically call this service to get the value.
 - or you use a listener system : you create an interface that your activities must implement in order to get notified from the task completion


$\text{Aut}(G) \cong \text{Out}(G)$ when $G$ is abelian

Question: I would appreciate if you could please evaluate my proof and point out any mistakes I made.
Proof:
Define a homomorphism $\Phi: \text{Aut}(G)\to \text{Out}(G)$, such that all elements of $\text{Out}(G) \leq \text{Aut}(G)$ are sent to $\text{Out}(G)$ (identically), and all elements of $\text{Inn}(G) \leq \text{Aut}(G)$ are sent to $1$. Thus $\Phi$ is surjective. Now let $\phi_a$ be an element of $\text{Inn}(G)$. Then $\phi_a(g) = aga^{-1}=aa^{-1}g=g \implies \phi_a = id_G \implies \text{Inn}(G)=\{id_G\}$. This implies that $\ker(\Phi)$ is empty, and hence $\Phi$ is injective. Therefore, $\Phi$ is an isomoprhism $\implies$ $\text{Aut}(G)\cong \text{Aut}(G)$.
Comment: How are you defining $Out(G)$? If it is the subset of $Aut(G)$ consisting of the outer (non-inner) automorphisms, then $Out(G)$ is not a subgroup of $Aut(G)$. The usual definition is $Out(G) = Aut(G)/Inn(G)$, and that is also not a subgroup of $Aut(G)$. So your definition of $\Phi$ doesn't make sense. Perhaps more straightforward: note that if $G$ is abelian, then $Inn(G)$ is trivial (why?)
Comment: You shouldn't define your homomorphism the way you did. The map you want is the quotient map $\mathrm{Aut}(G) \to \mathrm{Aut}(G) / \mathrm{Inn}(G) = \mathrm{Out}(G)$. This is better because first of all it's a very natural definition for your context and second of all $\mathrm{Out}(G)$ is not a subgroup of $\mathrm{Aut}(G)$, so you cannot map to $\mathrm{Out}(G) "identically" like you just did. You can map it "canonically" however, using the canonical projection map, which is already given to you.
Comment: @sequence : Sometimes math is easy and you don't need to make it harder than it has to be.

In the mean time, in your computation of the kernel you should be more careful. The kernel it certainly not empty since it contains the inner automorphism group of $G$, which in particular contains the identity element of $\mathrm{Aut}(G)$. What you need to show is that this is the only element of $\mathrm{Aut}(G)$ in the kernel, which is what you did. But it doesn't prove that your map is the identity, it proves that it is an isomorphism. $\mathrm{Aut}(G)$ is not a subset of $\mathrm{Out}(G)$..
Comment: @sequence : The reason why $\mathrm{Out}(G)$ is not a subgroup of $\mathrm{Aut}(G)$ is because it's not even a subset of it.
Comment: @Bungo Yes, I noted this in my proof above, but I thought that would be too easy.
Comment: @PatrickDaSilva Thanks for pointing out that $Out(G)$ is not a subgroup of $Aut(G)$. I'm wondering, however, if $\Phi$ could be defined in such a way as to map all elements of $Out(G) \subseteq Aut(G)$ to $Aut(G)$?
Answer: Your proof does not seem to be true because as mentioned in comments $Out(G)$ is not even a subset of $Aut(G)$ in general. On the other hand, the proof of your result is very obvious. Indeed $Out(G)$ is just defined to be $Aut(G) / Inn(G)$. You proved that $Inn(G)  = 1$. So  we have $Aut(G) = Out(G)$.


Remove user account completely from a server?

Question: We use desktop-folder and user-folder redirection on our terminal servers, so that user settings are remembered when moving between servers.
When we were configuring and testing this setup, my user account was logged into a particular server, time passed, settings were changed, folders were moved, and now, weeks later, I get weird bugs on that server. Mostly this is confined to Windows Explorer crashing when accessing certain folders, and completely taking out whatever program had created the Explorer window (in OpenFileDialogs, and such).
I've looked at the registry settings for folder redirection for that user account on that server and they are a mess of different versions and folder locations and the like, from back when we were still changing settings. On our newer servers, this user account is completely fine; it's only on this server which I've been using for some time that the problem occurs.
My question is: How can I completely remove all record of my user account from that server so that I can go in clean, and the server will think that this is the first time I've ever logged on to it?
Answer: Log on using an alternative administrator account.
Go to Start, right click on "Computer" and select "Properties"
You'll now be at the System page.
Click on "Advanced system settings", then go to the "Advanced" tab and click on the "Settings" button underneath "User Profiles"
This may take some time to populate. Find your username in the list and click "Delete"
Do NOT, just delete the folder in C:\Users
Answer: Delete the user from Active Directory, check each server to see that there's no reference to them locally on the profiles tab of the machine, delete (or rename) every top-level folder in which you put their home directory/profile, and do a search through the registry for references to the user's username and rename those instances on the local servers that aren't AD servers.
Or change the user's username to something else and they'll have a whole new login that would be brand new.
When we get login glitches, often it's registry corruption for the profile. I'll rename just the profile with an _1 and have them log in and it'll usually give them a new profile to start fresh without interference from the broken login; we didn't do folder redirection, but we taught our users to save to the home directory for things they wanted saved (Which is a file share) and then manually recover favorites or desktop items from their old profile folder. Renaming the profile keeps most of the account intact and the user doesn't need to worry about most of the items in it.
Your best strategy to approach this depends on how you were doing redirection, what exactly you redirected, and how you were saving profiles over how many servers. Nine times out of ten with us it is just a matter of changing the profile, not the account, and making sure the user was logged off while making the change (and changing or deleting cached profiles on the servers so the new jdoe account doesn't get a cached, corrupted account on the other machines that ends up contaminating the newly created jdoe_1 profile on the server)
Answer: Profiles now have a corresponding reg key you also need to remove if you are manually deleting profiles
There is some new way of handling user profiles in Server 2008 R2 / Windows 7, which requires you to either use the method decribed by Dan (if you haven't already deleted the profile) or if you make the mistake and deleted the profile already from the C:\Users folder you will likely get a temp profile next time you logon and everything you save in that profile will be deleted when you log off. Happened to me twice during the Win7 beta's. ;(
If you already deleted the profile and need to finish the job!
The profile related reg keys are located:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList

Find the key that match the SID of the account you are wanting to delete. And your done. This is the hackesh way of doing it, but I never heard of the method above until today.
Here is a blog post that talks more about it -
http://www.sepago.de/d/helge/2008/10/16/deleting-a-local-user-profile-not-as-easy-as-one-might-assume
Note: Posting is for completeness and offers a way to fix a botched profile removal, I understand the original poster has marked this as solved.


Condição if and else com data no crystal report

Question: Estou realizando uma condição no meu relatório com o objetivo de inserir <code>"-"</code> quando a data Vencimento vier nula, porém ocorre erro quando a data vem diferente de nulo. Abaixo está a imagem que mostra o erro quando preencho a data vencimento:

Foi utilizado a seguinte expressão no relatório report:
<code>=IIf(Fields!DataVencimentoPago.Value <> "",Format(Fields!DataVencimentoPago.Value,"dd/MM/yyyy"),"-")
</code>
Tentei também de outra forma, porém sem sucesso:
<code>=IIf(Fields!DataVencimentoPago.Value <> "", Fields!DataVencimentoPago.Value,"-")
</code>
Answer: Identificado o problema o componente utilizado que report não aceita valores nulos no campo, assim foi realizado a seguinte alteração :
=IIf(Fields!DataPagamento.Value <> "01/01/0001 00:00:00",FormatDateTime(Fields!DataPagamento.Value,DateFormat.ShortDate),"-")
problema resolvido com sucesso!


what exactly does correlation mean

Question: what exactly is a correlation of zero meant to be, does that mean that changes in x does not affect y, if that is the case, from the scatter plot

That is completely false, as sometimes as x increases, y decreases or increases
Comment: $X \perp Y \implies \text{R}[X,Y] = 0$ but the converse is does not hold.
Comment: The typical example of that reverse implication not holding is a parabola like $y=x^2$.
Comment: Correlation is the measure of how random variables are related to one another. There are some coefficients trying to measure the degree of correlation. If you are talking about  Pearson correlation coefficient it gives information about linear relationships, so if it is zero it means that there is no linear relationship between $x$ and $y$. For nonlinear relationship  Pearson correlation coefficient is noninformative, as an example consider this relation $x^2+y^2=1$, here correlation coefficient is zero.
Answer: From JMP: Introduction to Statistics: Correlation:

What is correlation?
Correlation is a statistical measure that expresses the extent to
which two variables are linearly related (meaning they change together
at a constant rate). It's a common tool for describing simple
relationships without making a statement about cause and effect.

Key points to highlight from that is that a correlation describes the relationship between two variables, assumes the relationship is linear, and it does not make any assumptions about cause and effect.
Thus, firstly addressing what you stated, we can never say whether x does or does not affect y. If we say "affect," we would be implying cause and effect, where x is a cause to effect y. A classic example of a correlation-not-causation is the negative relationship between pirates and global warming; the correlation does not mean the reduction of pirates over the years causes an increase in global temperatures.

(Figure from Wikipedia)
The correlation coefficient describes the strength and direction of the relationship between two variables that are linearly related. When the correlation is zero, it means the two variables are not related, assuming the relationship would have been linear. If you have a scatter plot with a perfect U-shape relationship, for example, where y is seen to sometimes increase and sometimes decrease as x increases, you will get a correlation coefficient equal to zero, but it clearly violates the assumption of linearity. The figure below shows a couple of examples that violate the assumption. Practically, the correlation coefficients wouldn't make sense there.

(Figure from JMP)
The further away the correlation coefficient is from zero (towards -1 or +1), the stronger the relationship between two variables is. Generally speaking, when there is a relationship, the relationship is stronger when the x and y values are closer to the line of best fit (least squares) on a scatter plot (see the figure below). In other words, the correlation coefficient can also be interpreted as the "goodness of fit" of the best fit line.

(Figure from QuestionPro)
A more thorough description about correlations can be found at JMP: Introduction to Statistics: Correlation.
Comment: This is a really great start! Perhaps discussing the geometric interpretation of the coefficient would also be beneficial.
Comment: Perhaps it is too arcane anyway. If anyone is interested, [this article](https://www.researchgate.net/publication/256374947_Geometric_interpretation_of_a_correlation) seems to cover what I am referring to.
Comment: Briefly stated, you can think of the correlation as an inner product divided by the product of the 2-norms of the residuals. This leads to an angle, which for arbitrary dimensions is defined to be the cosine of the angle between the vectors.
Comment: Thanks, @Galen. I added something new to the post.
Comment: Nice! I was also thinking about the fact that $\text{Corr}[X,Y] = \cos \theta$ where $\theta$ is the angle between the residual vectors. This speaks to whether the residuals are (anti)parallel, orthogonal, or in between.
Comment: Wow, sorry, that is beyond my understanding. Maybe you can add an answer about it here.

what exactly does correlation mean


Restore From Database not showing database I want to pick

Question: In Management Studio I want to restore to a point in time from an existing database.  However, the databases that I can choose from in the drop down list don't include the one I want to choose.  And oddly, there are databases in the list that have been deleted too.
I closed/re-opened Management Studio in hopes it would refresh but no such luck.
Anyone know what the deal is here?
Answer: First of all, if you restored a database using a full database backup, but specified a new name for the new database, the drop down menu in the Restore Database dialog in SSMS will show the name from the original backup, not the new name you specified
Another situation when a database is not shown in the drop down menu in the Restore Database dialog is when no database backups have been made for the database
Comment: "Another situation when a database is not shown in the drop down menu in the Restore Database dialog is when no database backups have been made for the database" - thank you so much!
Comment: Ok, so let's say I took a backup of a database and restored it to a different computer and named it differently.  Then if I wanted to restore to a point in time from there, I wouldn't be able to do it using SMSS because the drop down would show the original name but I imagine I could still do it from a script.  Does that sound right?
Comment: Yes, you can use the syntax given here http://technet.microsoft.com/en-us/library/ms179451(v=sql.105).aspx  Please note that the database name in the RESTORE DATABASE is the new database name (not the original one)


ativar transparencia total do background png no form

Question: Bom eu tenho um form c# porém eu uso uma render png, que contem uns efeitos sombras e fumaça, a única maneira que achei para dar a transparência foi o key, mas ele não fica totalmente transparente, imagem de exemplo abaixo.

eu queria saber, se tem alguma maneira de deixar totalmente transparente.
Comment: veja se esse link te ajuda: https://stackoverflow.com/questions/4387680/transparent-background-on-winforms
Comment: continua a não funcionar o codigo de solução, fica esse efeito mesmo com o lime
Answer: Você pode cancelar o evento onde o BackGround é pintado e preencher com uma imagem desta forma:
<code>public SeuForm()
{
    InitializeComponent();
    FormBorderStyle = FormBorderStyle.None;
    StartPosition = FormStartPosition.CenterScreen;
}
protected override void OnPaintBackground(PaintEventArgs e)
{
    //Definir sua imagem.
    Image newImage = Properties.Resources
        ._0_cKbBcUPJTfpFwuQi_;

    //Posição e tamanho da imagem
    //Aconselho deixar o seu form do tamanho da imagem já design time, para facilitar o desenvolvimento
    //ou pode setar os tamanhos do form para o da imagem pelo codigo tambem(ex: this.Width = newImage.Width;)

    //Caso deseje centralizar a imagem automaticamente:
    //x = (Width - newImage.Width) / 2; y = (Height - newImage.Height) / 2;
    int x = 100;
    int y = 100;

    //Desenhar imagem
    e.Graphics.DrawImage(newImage, x, y, width, height);
}
</code>

Não é lá uma boa pratica, mas não vejo outra maneira de atingir o resultado que deseja em WF.
Comment: agora o bakcground fira totalmente preto https://imgur.com/a/qR0QG


Silverman Adv. Topics example

Question: I would like to refer you to Silverman's Advanced Topics in the Arithmetic of Elliptic Curves example 10.6:
Let $D$ be a nonzero integer, $E:y^2=x^3+D$ with complex multiplication by $\mathcal{O}_K$ where $K=\mathbb{Q}(\sqrt{-3})$. Let $\mathfrak{p}$ be a prime of $\mathcal{O}_K$ with $\mathfrak{p}\nmid 6D$. Since $\mathcal{O}_K$ is a PID, write $\mathfrak{p}=(\pi)$ and one can check that there is a unique $\pi$ generating $\mathfrak{p}$ which satisfies $\pi\equiv 2 (\text{mod }3)$.
My question is now this, if we let $\mathfrak{p}=(2+\delta)$, where $\delta=\frac{1+\sqrt{-3}}{2}$, then because it has norm 7, it is a prime. So, taking $\pi=2+\delta$ how to we get the result that $\pi\equiv 2 (\text{mod }3)$? I've tried to multiply $\pi$ by units in $\mathcal{O}_K$, but don't seem to get anything useful. Think may be missing something obvious here.
Edit: Are you able to prove in general that there is a unique $\pi$ generating $\mathfrak{p}$ which satisfies $\pi\equiv 2 (\text{mod }3)$?
Thanks for the help!
Answer: The short answer is...it isn't true for $\pi$.
It is the ideal that possesses such a generator. This doesn't mean all generators satisfy the congruence.
In fact $\pi \equiv -\bar{\delta} \bmod 3$ so you should find that $\pi\delta \equiv -\bar{\delta}\delta \equiv -1 \equiv 2 \bmod 3$.
Since $\delta$ is a unit in $\mathfrak{O}_K$ we find that $\mathfrak{p}=(\pi) = (\pi\delta)$ and so you have found the right generator.
Comment: Hi Fretty, thanks for your help. Didn't notice that $\pi\cong -\overline{\delta}$. Are you able to prove the result in general? See edited question. Thanks once again!
Comment: From what I see it boils down to noticing that there are $6$ possible generators since $|\mathfrak{O}_K^{\times}|=6$. Reducing each mod $3\mathfrak{O}_K$ gives a different unit and there are exactly $6$ of them in $\mathfrak{O}_K/3\mathfrak{O}_K$. In particular $2$ is a unit so a unique generator must produce this.
Comment: So to put it into perspective I didn't just see that $\pi \equiv -\delta \bmod 3$ in my head...I knew beforehand that whatever it is mod $3$ it would be a unit and that the units in $\mathfrak{O}_K/3\mathfrak{O}_K$ would form a group including $2$...hence there would be some unit multiplying to give $2$. By basic group theory this multiplier would be unique.
Comment: Please accept the answer if you feel it has answered your question thoroughly...
Answer: In general, notice that the units of $\mathcal{O}_K$ are
$$\{1,-1,\delta,-\delta,\delta^2,-\delta^2\}=\left\{1,-1,\frac{1+\sqrt{-3}}{2},-\frac{1+\sqrt{-3}}{2},\frac{-1+\sqrt{-3}}{2},\frac{1-\sqrt{-3}}{2}\right\}.$$
Therefore, the units $\mathcal{O}_K^\times$ modulo $3\mathcal{O}_K$ are the classes
$$\{1,-1,\delta,-\delta,\delta^2,-\delta^2\}\equiv \left\{1,2,2+2\sqrt{-3},1+\sqrt{-3},1+2\sqrt{-3},2+\sqrt{-3}\right\} \bmod 3\mathcal{O}_K,$$
which form a complete system of representatives for $(\mathcal{O}_K/3\mathcal{O}_K)^\times$, which has size $\varphi(9)=3\cdot 2=6$. Now let $\mathfrak{P}$ be an ideal generated by $\pi$, such that $\mathfrak{P}$ does not divide $3$. Then, $\pi \bmod 3\mathcal{O}_K$ is a unit in $(\mathcal{O}_K/3\mathcal{O}_K)^\times$. Then, there is a unit $u$ in $\mathcal{O}_K^\times$ which is the inverse of $\pi$ modulo $3\mathcal{O}_K$, so that $\pi\cdot u \equiv 1 \bmod 3\mathcal{O}_K$. Finally,
$$\pi\cdot(-u)\equiv - \pi\cdot u \equiv -1\equiv 2 \bmod 3\mathcal{O}_K,$$
as desired, because $-u$ is also a unit in $\mathcal{O}_K$.
Example: Take $\mathfrak{P}=(2+\delta)$. Then $$\pi = 2+\delta\equiv 2+(2+2\sqrt{-3})\equiv 4+2\sqrt{-3}\equiv 1+2\sqrt{-3}\equiv \delta^2 \bmod 3\mathcal{O}_K.$$
The multiplicative inverse $u$ of $\delta^2$ is $-\delta$. Hence, $\pi\cdot (-\delta)\equiv 1 \bmod 3\mathcal{O}_K$. And therefore $\pi\cdot \delta\equiv 2 \bmod 3\mathcal{O}_K$. Indeed:
$$(2+\delta)\cdot(\delta)=-1+3\delta.$$ Clearly $\mathfrak{P}=(-1+3\delta)$ because $\delta$ is a unit. Moreover,
$$(-1+3\delta)-2 = -3+3\delta=3(-1+\delta).$$
Hence $-1+3\delta\equiv 2 \bmod 3\mathcal{O}_K$.
Comment: Thanks Alvaro! That helped as well. Like the example too.

Silverman Adv. Topics example


What happens to URL alias when a node is unpublished?

Question: We have many pages where we set "Generate automatic URL alias" to true and false. Then we will eventually unpublish some of the pages. Looking at Webmaster tools, we have found the URLs are still indexed and cached so when any unpublished page is crawled again it is generating a 404.
Given that in the Path settings we have set the Update action set to "Create new alias. Delete old alias", we need assistance in figuring out what happens to url aliases once the page is unpublished in the scenario where "Generate automatic URL alias" is set to true or false.
Answer: Nothing happens and nothing should.
An alias only exists on the URL level. It simply aliases "/blog/2018-01-23/my-awesome-article" to "/node/27", does a lookup for what when a request is coming in and that's it. After that, the routing and entity (access) systems are taking over to figure out what to display and who is allowed to see it.
If you unpublished node 27, then it still exists and admins can still access it, using that alias. In theory, it wouldn't even care if node 27 is deleted, it would still de-alias it to "/node/27" and then the routing system would return a 404 page as there is no node 27 anymore. This actually doesn't happen with nodes because there is code that listens on nodes being deleted and deletes aliases pointing to them as well.
It also doesn't matter if you use a manual alias or generated one using pathauto, that only differs while saving the node and telling pathauto if it should generate one dynamically or not.
But that's actually not your question, because what you're really asking is how  google updates its index when you unpublish content. And what you describe is exactly what should happen, eventually google will re-index your content, see that it no longer exists and removes it from its index. There isn't really anything else you can do directly. You could use a sitemap.xml to tell Google index your content more or less frequently but that's about it.
Comment: that makes sense, the Generate Automatic Path is only for pathauto and routing system will take care of the 404 page.


Graphing has several solutions?

Question: I have a simple graph question, but I can see a few potential answers.
The graph of $y = x^2 + px + q$ has a turning point at $(2,5)$. Find the values of $p$ and $q$.
Can someone explain why the correct answer is $p = -4 \text{ and } q = 9$?
The answer I got was $p = 0, q = 1$ and another answer I got was $p = -1, q = 3$.
Comment: with $p=0,q=1$ we have $y=x^2+1$ so that if $x=1$ we have $y=2$ and since $2 < 5$ then $(2,5)$ cannot be a turning point. With $p=-1,q=3$ we have $y=x^2-x+3$ and again with $x=1$ we see that $y=3 < 5$ so it is also not correct.
Comment: @securityauditor think about the shape of the parabola. The turning point is the minimum value of the function. This means at any other points the $y$ value must be larger than at the turning point. So this motivated me to check some values of $x$ near $2$ to see if they were smaller than $5$ as a way to check your answers. You can see for $y=x^2+1$ that if we set $x=1$ this gives $y=1^2+1=2 < 5$. Likewise for $y=x^2-x+3$ you get $y=1^2-1+3 = 3 < 5$. This means both of them fail to have a turning point at $(2,5)$.
Comment: Can you show your try?
Comment: @CyclotomicField Are you saying that the (2,5) are x,y but are different to the x-squared at the beginning of the equation after equal sign? :-O
Comment: I still do not understand why you are playing with the x value when the question clearly stated x=2 and y=5. Unless you are saying, the values of p and q must be such that any value of x like x=0, x=1, x=2, x=3 etc... must satisfy the equation by equalling 5?
Answer: We are told that the turning point is at $(2,5)$.
We are given the leading coefficient is $1$,  the quadratic curve is $$(x-2)^2+5=x^2-4x+9$$
$p$ and $q$ are unique.
In general if the turning point is $(x_0, y_0)$ with the leading coefficient being $1$, the quadratic curve is
$$(x-x_0)^2+y_0=x^2+(-2x_0)x + (x_0^2+y_0)$$
The $p$ that you proposed doesn't satisfy the formula.
Answer: $y=x^2+px+q$
$5=4+2p+q$
So $p$ and $q$ where $2p+q=1$ will have $(2,5)$ on the curve. It isn't a turning point though unless $2x+p=0 $ and $x=2 \implies p=-4$
Not a vertex:
Comment: In the 2 where did the 2 come from?! I know the x=2 from the (2,5).
Comment: $x^2+px+q=0.  $x^2+px+q= (x+p/2)^2 +q -p^2/4$ reaches a minimum when $x+p/2=0$ That's from completing the square. You can get the same result using calculus.  If $y=x^2+px+q$ then $y'=2x+p$. You get your turning points where $y'=0$ so $2x+p=0$.

Graphing has several solutions?


Hearing the difference between VIIdim7 - Im and Vm - Im

Question: I've been using EarMaster to practice hearing progressions. For most of them, I can pick out a certain interval and slowly improve my accuracy.

Major against Minor triads — I try to pick out the 3rd
VIIdim7 - I against V7 - I — I try to pick out the root movement
VIIdim7 - Im against Vm-Im — I'm having a hard time figuring out what exactly to listen for to tell the difference.

Right now, it feels like I'm stabbing in the dark with this. What should I be trying to pay attention to here?
Answer: The vii(dim 7) will have a more dissonant sound that the v, also there will be four different pitches in the seventh chord than in the basic triad. Finally, vii(dim 7) has no tones in common with i, whereas v has one pitch in common with i. Finally, vii contains the leading tone, while v does not (i.e., in vii-i, ^7 moves to ^1 by half step, but in v-i, ^7 moves to ^1 by whole step).
So four things you could listen for:

relative level of dissonance
four distinct pitches vs. three
common tone with the following chord
half-step versus whole-step motion to the tonic

In scale-degree terms:

viio7: #7 2 4 b6
        \     /
i    :   1 3 5
        /    |
Vm   : b7 2  5   (shown in first inversion
                  to emphasize common-tone)

And visualized in A minor:
Comment: I didn't even realize I was dealing with 4 note vs 3 note chords. That helps a lot.
Answer: I may be a bit prejudiced because I'm a bass player by trade but I think one of the most important things to develop in harmonic ear training is picking out the bass motion. Once you can establish the bass motion it makes it easier to figure out what is going on above it. For that reason you're taking a good approach to your bullet point #2
As for bullet point #3, by VIIdim7 I am going to assume you are talking about a diminished chord a half step below the tonic, so say   Bdim7-Cm in the key of Cm. This should be pretty easy to pick out by two methods, one is the bass movement of a 5th down (or a 4th up) should be pretty easy to distinguish from the bass moving up a half step. The other distinguishing factor is Vm-Im is not a cadence and there is no dissonance of b5 intervals in the Vm chord so that is another thing you can listen for.
Comment: Yes, I was referring to Vm - Im.
Comment: OK, I edited my answer based on your comment.
Comment: Have a look at a previous question - 'Can we have a perfect cadence in a minor key' - I wasn't sure that v>i was, but now think it is.
Comment: @Tim it doesn't fit the definition but I hear resolution in it.
Answer: Surprised that no-one has yet mentioned that VIIdim7 is a rootless (roll eyes) V7b9 chord. Many jazz players would consider that functionally there is no difference between V7 - I and VIIdim7 - I – if you have a functional cadence then any and all alterations are on the cards, to taste. Picking out whether the root is actually present or not seems like a somewhat unnecessary endeavour to my mind (perhaps I could be convinced otherwise) as musically I would say V7 - I and VIIdim7 - I are the same.
(eta: of course, one has the b9 alteration and the other doesn't, so it's that that I would focus on picking out. It should be quite clear as a jarring/jazzy/clashing/'cool' note)
That however provides an easy resolution to your third query, since in VIIdim7 - Imin, which I'm claiming is V7 - Im, the five chord is a dominant7, so has a major third (indeed this is the VII) whereas in Vm - Im the five chord has a minor third. As covered in other answers, if it sounds just like two minor chords one after the other, it's the Vm - Im. If it sounds like "dramatic tension! resolution to a minor chord" it's the VIIdim7 - Im.
Answer: I don't know EarMaster, but I'll try to answer anyway.

Yes, major and minor triads differ by the third, and this gives them a different color. It should become quite natural for you after a while
Listening to root is a good idea. I'm not sure what do you mean by VIIdim7. Is it a diminished chord (e.g. Bo7 B-D-F-Ab in the key of C) or half diminished (Bm7b5 B-D-F-A). In the first case the Ab note is very distinguishable. In the latter you have A note, which is missing in V7 (G7 G-B-D-F), so half-dimished has more rich sound.
It is actually more difficult to distinguish Bo7 vs G7b9 and Bm7b5 vs G9, but it is possible with practice.
Again, not sure what do you mean by VIIdim7, but either diminished or half-diminished chord sound quite different (more dissonant) from a minor one, so you should be able to distinguish it just by listening to the sound of first chord.
Comment: I'd be referring to a diminished chord. Bdim7 = B D F Ab
Comment: Alright, then it should be quite clear difference. Diminished chord is much more dissonant. It has two tritones, as opposed to one in a dominant seventh chord, and none in a minor triad. I'd advice you to focus on distinguishing the sound of these chords.


Ant design Modal remove or change the black background

Question: EDIT:
Hi, Thank You so much for your answer, it helps me a lot.  but do you know how to remove the lines background?
Comment: Can you provide more information on the implementation you've done ?
Comment: You've edited your original question out, this Q&A pair no longer makes sense! Please edit your question to make sure someone coming here in the future will find useful information in the form of both a question and its answer(s).
Answer: To hide the mask (background)
mask={false}
To change the style of mask(Background)
 maskStyle={{ backgroundColor: "red" }}

A complete example for experiment

<Modal mask={true} maskStyle={{ backgroundColor: "red" }} title="Basic Modal" visible={isModalVisible} onOk={handleOk} onCancel={handleCancel}>

Some contents...

Some contents...

Some contents...

</Modal>
Comment: Hi, Thank You so much for your answer, it helps me a lot. but do you know how to remove the lines background? see this pic https://i.stack.imgur.com/8gZjj.png
Comment: You can mark this answer and. try to replicate in the linked code sandbox. looks like a custom css /theme in your environment. so it needs to be available for debugging.
Comment: Not sure if you are using some background image
Comment: Hi, I don't use background image, when I change the size of the modal, it's not removing. see this pic https://i.stack.imgur.com/snfEh.png
Comment: It is hard to guess from an image.


Why doesn't std::sort doesn't work on std::list?

Question: Due to std::sort on a std::list, I receive the following errors:

line 44         : instantiated from here
line 5258 : error: no match for 'operator-' in '_last -__first'
line 179 : note: candidates are: ptrdiff_t std::operator-(const std::_Bit_iterator_base&, const std::_Bit_iterator_base&)

From the following code:
int main()
{
    std::list<Student_info> students;
    Student_info record;
    string::size_type maxlen = 0;   // the length of the longest name

    // read and store all the students data.
    while (read(cin, record))
    {
        // find length of longest name
        maxlen = max(maxlen, record.name.size());
        students.push_back(record);
    }

    // alphabetize the student records
    std::sort(students.begin(), students.end(), compare);

    return 0;
}

What causes these errors? How can I sort this list?
Answer: Your error means that the sort function was trying to use subtraction on the iterators.  Only random access iterators support this operation.  std::list has Bi-Directional iterators.  std::sort only works with random access iterators.  Luckily, std::list has it's own sort function.
students.sort(compare);

Comment: understandable answer, thought so, there something that I don't understand(personal base knowledge), I can figure out later after learning more from the book thought, so no problem about it, whatsoever, tq for answer...
Answer: use list member function sort
students.sort(compare);


Handling Multiple Input : Array vs Loop, Which Is Low Resource Consuming?

Question: I have multiple input tag submitted from previous page, say step1.php like this :
<input type="hidden" name="block01" value="001"/>
<input type="hidden" name="block02" value="012"/>
<input type="hidden" name="block03" value="002"/>
<input type="hidden" name="block04" value="005"/>
<input type="hidden" name="block05" value="008"/>
<input type="hidden" name="block06" value="015"/>

now I want to process those inputs in the step2.php and I have 2 options to do it, either using Array or Loop.
If I'm using array, those inputs will be appended like this :
<?php
$stack = array(""); //empty array declared

// I assume I have some codes here to 'catch' those inputs and put it as array_push
array_push($stack, "001", "012", "002", "005", "008", "015");
print_r($stack);
?>

compare to array, I have this LOOP option too :
<?php
$i = 1;
$x = 'block0'.$i;
$webBlock = $_POST[$x];

while (!empty($webBlock)){
    $x = 'block0'.$i;
    $webBlock = $_POST[$x];
    echo $webBlock . "
";
    $i++;
}

?>

both are solutions of my problem on step2.php. I just need your opinion which is more less memory / cpu consuming? that's all...
thanks!
Answer: In first case, you are using array_push() and print_r(). The first function uses a loop to push arguments passed onto a stack. The second function that is print_r() also uses a loop to print all the values of the array. So, basically you are running loop twice to do the task.
Where as in second case, you have written a code to handle both things at once. So, this method just needs to loop once. Moreover, looking into the working of print_r() and echo, if you run echo X times and use print_r() to print X values, the echo is bit faster than print_r. Read php documentation for more info about all these function.
So, the second way is better.


How to Insert values to strongly typed DataSet from code and then show it from RDLC reporting page?

Question: I have created an aspx page and added a Report viewer to it and script manager. I have also added a strongly typed DataSet file DataSet1.xsd in which there is a DataTable having 2 coloumns - Name and Designation.
I have also used rdlc file which I have binded it with dataset1.
Now I want to put values to the data set from my code and then show it to report viewer.
aspx.cs code -
DataSet1 ds = new DataSet1();
DataRow dr = ds.DataTable1.NewRow();
ds.DataTable1.AddDataTable1Row("x","y");
this.ReportViewer1.LocalReport.Refresh();

I am not getting the values to the report.
Answer: You can add the DataSource to the Reportviewer from code behind. Try the following code.
ReportDataSource datasource = new ReportDataSource("TableName", ds.Tables[0]);
ReportViewer1.LocalReport.DataSources.Clear();
ReportViewer1.LocalReport.DataSources.Add(datasource);


'return false' statement outside function error

Question: I've been trying to implement the following Javascript code into the head of a Wordpress project. I found the original method here: jQuery isotope query filtering results for url but the last 'return false;' keeps throwing the error 'return not in function'. Admittedly, I had to update the script to use jQuery instead of the $'s in the original script & have included the jquery.cookie.js as they had it in their working example (as think it's old) but wondered if anyone could suggest a workaround for the return false error so I can get this concept to work with jQuery? Thanks

Comment: Well the error is ok. The return shouldn't be there at all. Why do you need it there?
Comment: you dont need to include html, head or script tags to the post.
Comment: I have no idea why they originally used it. I just copied the JS verbatim & then had to change the $ to jQuery to get it to work. I thought the return had something to do with killing the cookie generated?
Comment: ..if I remove the last return false I then get an error: $ is undefined 'if ( $.cookie("listfilter") ) {'
Answer: The error is correct. Your "return false" occurs outside a function, which is not allowed.


If $p : E \to B$ is a covering map and $E$ is simply connected, then each fiber of $p$ has the cardinality of that of $\pi_1(B)$.

Question: Can anyone provide a source or a proof of the following fact:
If $p : E \to B$ is a covering map and $E$ is simply connected, then each fiber of $p$ has the cardinality of that of $\pi_1(B)$?
Answer: Check out $\S$1.3 in Hatcher's book for a full exposition, but here's the idea:
Since $E$ is simply-connected, any two paths between points $e,e'$ in a fiber $p^{-1}(b)$ are homotopic rel endpoints (i.e. if $\gamma_0,\gamma_1: [0,1]\to E$ satisfy $\gamma_0(0)=\gamma_1(0)=e$ and $\gamma_0(1)=\gamma_1(1)=e'$, then they are homotopic through a family of paths $\gamma_t:[0,1]\to E$ such that $\gamma_t(0)=e$ and $\gamma_t(1)=e'$ for all $t$.) Thus there are $|p^{-1}(b)|$ paths in $E$ that start at a chosen basepoint $e \in p^{-1}(b)$ and end at another point in $p^{-1}(b)$, up to homotopy rel endpoints. Any path $\gamma:[0,1] \to B$ representing an element of $\pi_1(B,b)$ can be lifted to a path $\tilde \gamma:[0,1] \to E$ with starting point $\tilde \gamma(0)$ equaling any chosen $e \in p^{-1}(b)$. Since $\gamma(0)=\gamma(1)=b$, the condition $p \circ \tilde \gamma = \gamma$ implies that $\tilde \gamma(1)$ must also lie in $p^{-1}(b)$. Using the homotopy lifting property, we see that any other path $\gamma'$ in $B$ representing the same class as $\gamma$ in $\pi_1(B,b)$ lifts to a path $\tilde \gamma'$ in $E$ (starting at $e$) that is homotopic rel endpoints to $\tilde \gamma$. This gives us a one-to-one correspondence between elements of $\pi_1(B,b)$ and homotopy (rel endpoint) classes of paths starting at $e \in E$ and ending at some other point in $p^{-1}(B)$. As mentioned above, this latter set has cardinality $|p^{-1}(B)|$.
Answer: I like the view that algebraic topology is about modelling topology by algebra; in these terms, a useful model of a covering map  $p: E \to B$,  given in Topology and Groupoids,  and, following earlier editions of that book,  to some extent in Peter May's "Concise ...." book, is the "covering morphism" of fundamental groupoids  $\pi_1 p: \pi_1 E \to \pi_1 B$.
A morphism $q: H \to G$ of groupoids is a covering morphism if for each object $x$ of $H$ and element $g: q(x) \to y$ in $G$ there is a unique element $h$ in $H$ starting at $x$ such that $q(h)=g$. It is helpful to draw pictures of this.
The traditional arguments show that a covering map determines a covering morphism, and a version of traditional arguments show that if the space $B$ has appropriate local conditions then a covering morphism $H \to \pi_1 B$ determines a topology on $E= Ob(H)$ so that $Ob(q) :E \to B$ is a covering map with $\pi_1 E \cong H$.
The standard argument can now be given in the algebraic model, as explained in the books and by squirrel,  to show the result required.


Opengl compressed texture with lwjgl

Question: I have a DXT1 texture loaded in a ByteBuffer and I'm trying to load it with Opengl
<code>int tID = glGenTextures();
glBindTexture(GL_TEXTURE_2D, tID);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glCompressedTexImage2D(GL_TEXTURE_2D, 0, GL_COMPRESSED_RGB_S3TC_DXT1_EXT, w, h, 0, imageData);
System.out.println(gluErrorString(glGetError()));
</code>
It's giving me the error "Invalid Operation" on the glCompressedTexImage2D call. Can't seem to figure out why.
Answer: Ok i figured out what the problem was.
The size of imageData was incorrect.
Since DXT1 is 4 bits per pixel, i kept thinking it should be w * h * 4.
It should have been w * h * 1/2 (4 bits being 1/2 a byte).

Opengl compressed texture with lwjgl


Processo Assíncrono em Ruby on Rails

Question: Tenho um processo que faz um match entre os itens[livros, filmes, musicas e jogos] de um determinado usuário no Facebook com os itens cadastrados na minha base. O problema é que o processo todo demora em torno de 18~25 segundos e não gostaria de deixar o usuário esperando esse tempo.
Estava pensando em assim que o usuário logar com a sua conta do Facebook, disparar tipo uma thread(nem sei se é possível em RoR) e redireciona-lo para o root_path e quando o processo terminasse apresentar em uma div alguma mensagem.
Como isto deve ser feito em Ruby On Rails, ou seja, há alguma gem para esse propósito ou alguma boa prática para isso?
Agradeço desde já..
Comment: Por que não usa ajax? Já é assíncrono (client-side), e no lado do servidor representa só mais uma requisição.
Comment: Eu poderia até usar Ajax, mas não sei como ele funciona quando acontece troca de paginas...
Answer: Existem varias alternativas para processos em back end. De uma olhada no https://github.com/mperham/sidekiq acredito q deve resolver e enquanto o usuario espera vc faz chamadas em ajax p saber se a thread  ja foi concluida. Existem uma gem q so verifica os status do job no sidekiq
Answer: Aqui uma lista das possíveis gems para isso:
https://www.ruby-toolbox.com/categories/Background_Jobs
Comment: @josuetex Por favor, tente elaborar melhor sua resposta. Embora ela possa ajudar quem fez a pergunta, respostas que contém somente links são complicadas porque a URL pode deixar de funcionar a qualquer momento. Se quiser entender um pouco melhor o motivo do que estou escrevendo acesse a questão do meta [*Queremos respostas que contenham somente links?*](http://meta.pt.stackoverflow.com/questions/42/queremos-respostas-que-contenham-somente-links)

Processo Assíncrono em Ruby on Rails


Save scraped list object text as column to pandas dataframe

Question: I want to scrape text from webpages and put it in to pandas dataframe. If I can scrape a table I get no problem but this here is no table and make me much trouble.
driver = webdriver.Firefox()

driver.get('https://example.com/')
time.sleep(3)

number = driver.find_elements_by_xpath("//span[@class='blaaal']")
name = driver.find_elements_by_xpath("//span[@class='blaaal2']")
for count in number:
    print(count.text)

for names in name:
    print(names.text)

df = pd.DataFrame(columns=['name','number'])

In that way I can print the data but if I use the count names definition without for in loop in dataframe I get error list object got no text or something like that.
I don't know how to put it to dataframe I think I have to append to define the for in loop as a column right? I don't find any post here on stack or any other learn tutorials on google.
Answer: Create list first for both number and name and then pass into pandas.
number =[count.text for count in driver.find_elements_by_xpath("//span[@class='blaaal']")]
name = [names.text for names in driver.find_elements_by_xpath("//span[@class='blaaal2']")]

df = pd.DataFrame({"name":name,"number":number})


What AWS cloud service to use for short term storage?

Question: I have a service that will listen to a stream via a websocket and compute some temporary information (say, number of busses currently on the network). This number would change every few seconds.
I don't want to store this information indefinitely, I just need other services to access the most recent version of this information (number of busses currently on the public transport) at any point.
What type of storage would you recommend for this short term non presistent type of information.
I've been thinking about simply storing a json file to S3 and then overriding it when information changes. The other option was using DynamoDB.
I'm wondering what would be the simplest and most cost effective option for this?
Comment: Does this temporary file even need to be shared among instances?
Comment: Redis (via ElastiCache) sounds appropriate here.
Comment: yes this information needs to be shared
Comment: I'd go with Redis too. It changes too frequently for S3 to work well.
Comment: how about dynamodb? would it be too expensive to write so often?
Comment: How are you doing compute? EC2, Lambda, or something else? That would influence how / where data is stored. Running an elasticache server / cluster seems like it would be an expensive solution compared with something like DynamoDB or S3.
Comment: It'll be written from a lambda function
Answer: If in case you're not specifically looking for AWS service. I will suggest you go with MongoDB Atlas. With this service, you can setup TTLs on your collections. Changing the data often won't be an issue and you can use a free cluster i.e. M0 which looking at your needs would be more than enough. This also obliviates from you all the dependency as to from which service you are writing and accessing the data. Latencies are low and at any point in time you can always take a backup and use point in time restore to go back to any point.
Other than this if you want to use AWS service specifically I will suggest you go with DynamoDB that is, in my opinion, one of the best services for your use case.
Hope it helps!


Hi, Do you know how to display an object over other objects on the app screen in Android Studio? (java)

Question: For example, I have a list on the screen and I want a certain action to bounce an image in the center of the screen (like a dialog) but the image does not appear when the app is running , it seems to be hiding behind the list. Do you know if there is a command that will cause the image to appear in front of the screen (above all other objects on the screen)?
Comment: Without any code it's difficult to see what you're doing. I would recommend taking a look at [ask] for details on how to ask a great question!
Answer: You can use View.bringToFront()
or from the view's parent ParentView.bringToFront(childView)
Here is the function documantion:

Change the view's z order in the tree, so it's on top of other sibling views. This ordering change may affect layout, if the parent container uses an order-dependent layout scheme (e.g., LinearLayout). Prior to Build.VERSION_CODES.KITKAT this method should be followed by calls to requestLayout() and invalidate() on the view's parent to force the parent to redraw with the new child ordering.


Qual o atalho no NetBeans para fechar todas os "+" das funções?

Question: Eu lembro que tinha essa função no NetBeans. É um atalho que fecha todos os (+) das funções ou divs.
Comment: Collapse all? Seria isso?
Answer: Boa parte dos atalhos podem ser obtidos em PDF criado pela comunidade. Mas não tem o que precisa. Tem uma página da Wiki de versão mais antiga com todos os atalhos. Não deve ter mudado muito. Especificamente o que deseja para PC/Mac:

Ação
PC
Mac

Collapse (hide) a block
Ctrl + Minus
Cmd + Minus

Collapse (hide) a block
Ctrl + NumPad Minus

Collapse (hide) all code blocks
Ctrl + Shift + NumPad Minus
Cmd + Shift + Minus

Expand a Collapsed Block (expand-fold)
Ctrl + Plus
Cmd + Plus

Expand a Collapsed Block (expand-fold)
Ctrl + NumPad Plus

Expand a Collapsed Block (expand-fold)
Ctrl + Equals                Cmd + Equals

Expand all code blocks (expand-all-folds)
Ctrl + Shift + NumPad Plus

Expand all code blocks (expand-all-folds)
Ctrl + Shift + Plus
Cmd + Shift + Plus

Expand all code blocks (expand-all-folds)
Ctrl + Shift + Equals
Cmd + Shift + Equals

Coloquei no GitHub para referência futura.
Answer: O padrão é CTRL+SHIFT+-. Mas você pode ajustar em Ferramentas -> Opções -> Mapeamento de tecla.
Referência: Resposta para a pergunta Netbeans shortcut to minimise all functions? no superuser


The styled image is not displaying

Question: I have created a thumbnail like image style in Drupal 7 (glossy_footer_sublogo).Also i have coded a module that has a block to display the 'logo.png' file that comes with my theme and converted by 'glossy_footer_sublogo' style. after enabling the block and clearing cache no image is displayed although the 'sites/all/themes/glossy/' path created in my style directory.
Following are the codes that i used to display the block:
/**
 * Implementation of hook_block_view().
 */
function glossy_helper_block_view($delta = '') {
  switch ($delta) {
    case 'glossy_footer_sublogo':
            $img_url = 'public://sites/all/themes/glossy/logo.png';
            $style = 'footer_sublogo';

            return array(
                'subject' => '',
                'content' => "",
            );
      break;
  }
}

Can anyone point me to what is the problem?
Thanks!
Answer: If you go to admin/config/media/file-system what is your public path set as?
If your public path is set as sites/default/files then I think your code is generating the following link:

http://yourdomain/sites/default/files/sites/all/themes/glossy/logo.png

Try changing your $img_url to the following

$img_url = drupal_get_path('theme', 'glossy') . '/logo.png';

On another note, is the block rendering at all (just without the image)?  Your implementation of hook_block_view looks incorrect.
I think it should be more like the following:
/**
 * Implementation of hook_block_view().
 */
function glossy_helper_block_view($delta = '') {
  $block = array();

    switch ($delta) {
      case 'glossy_footer_sublogo':
              $img_url = 'public://sites/all/themes/glossy/logo.png';
              $style = 'footer_sublogo';

              $block['subject'] = ''
              $block['content'] = "",

              );
       break;
    }

  return $block
}

Edit
Change $img_url as I previously mentioned, but rewrite your block content as follows:
$block['content'] = '';

There aren't any quote marks around the image URL that is being returned by the function.
Comment: Thanks for answering, The implementation of hook_block_view is totally correct. after changing the $img_url path nothing changes.
Comment: The implementation you have probably does work, but it is not structured the way that the Drupal docs recommends.

I have adjusted my answer to fit with what I've just realised the problem could be!
Comment: problem solved: the 'image_style_url($style, $img_url)' function can only accept images that are placed in public folder not out of it.
Comment: You could answer the question yourself and mark it as the correct answer so that other's can find it as a resource.
Answer: The public:// stream wrapper maps to your site's public files directory: trying to access themes outside of it isn't going to work. That is, this will never work:
$img_url = 'public://sites/all/themes/glossy/logo.png';

Because it gets expanded to:
$img_url = DRUPAL_ROOT . '/sites/<sitename>/files/sites/all/themes/glossy/logo.png';

Instead, to build the correct path to your theme's file, you need to use drupal_get_path() like Chapabu mentioned:
$img_url = drupal_get_path('theme', 'glossy') . '/logo.png';

However, as you noted in the comments, image_style_url() requires a stream wrapper URL, and more specifically, a public:// stream wrapper URL.
Creating a styled version of your theme's logo by copying the logo
So, the easiest way to do what you want is to copy your theme's logo to your public files directory and use image_style_url() that way:
$img_path = file_unmanaged_copy($img_url, 'public://', FILE_EXISTS_REPLACE);
$block['content'] = theme('image', array('path' => image_style_url($style, $img_path)));

Creating a styled version of your theme's logo without copying the logo
Alternatively, you could manually create the derivative using image_style_create_derivative():
$img_destination = 'public://logo-' . $style . '.png';
image_style_create_derivative($style, $img_url, $img_destination);

Then reference the file's URL by calling file_stream_wrapper_get_instance_by_uri():
$image = file_stream_wrapper_get_instance_by_uri($img_destination);
$block['content'] = theme('image', array('path' => $image->getExternalUrl()));

In either case, you want to make sure at some point you add some logic to deal with repeatedly copying the logo (or generating the derivative) every time someone accesses the block uncached.
Answer: Use below two function to create images based on image style.
//new_style is image style
//image_uri is public path of existing image
 $new_image_destination=image_style_path('new_style',$image_uri);
    $new_image_path=image_style_create_derivative(image_style_load('new_style'),$image_uri,$new_image_destination);

//use drupal_realpath to get public uri as below
//$new_image_public_uri= drupal_realpath($new_image_destination);

The styled image is not displaying


How to change front page title?

Question: The front page title in the menu is Home or Startseite in german. I would like to give it another name. How can I do this?
The question is asked multiple times over the internet (fore example here) but no clear answer... Thank you
Comment: Have you seen [this link](https://www.drupal.org/node/1268204)? Is there what you need?
Comment: Yes I did, but i hoped there is a slimmer solution. I'll try it out and post here, if i don't get anything else.
Comment: What do you mean by "slimmer" and what's wrong with using settings page?
Comment: The provided link contains two answers. One referring to the module Page Title which i considered being to much. The other answer was refering to: /admin/settings/page-title which did not work or I didn't understand. The mentioned link is not present.
Answer: Just deactivate the predefined menu link and add a new one - use
<front>

as path.
In Drupal 7 and 8 go to
Home > Administration > Structure > Menus > Main menu > Add link

Your German version will say something like
Startseite > Verwaltung > Struktur > Menüs > Hauptmenü > Hinzufügen

Drupal 7

See tooltip for details (using Rubik Theme)

Drupal 8 (German version)
Comment: Perfect! I was not even necessary to add a new menu link. I could edit the existing one.
In the end i will create the site in spanish. Just because of thinking that the page should support multiple languages, It looks like it would be hard to have the menu in different languages not? I see that it would be possible to create multiple menu's and the content is assigned to a language. But best practice to tie everything together one would have to read about. But thats another question :).
Comment: I made two multi-language sites one with two languages, one with three. I used menu translations at first, but I was better off making one menu Item in every single language rather than using the translate function - since you can have different orders and other stuff that way.

How to change front page title?