Cython exetension class __getattr__ not doing the same behavoir with python's class counter part

Question: Edit: the problem is more complicated than the first question I asked, so I deleted everything and re-edit the question.
I tried to make a class in python, the following code works:
From my test_loop.pyd file
class mockClass:
    def __init__(self,val):
        self._val = val
    def __getattr__(self,attrName):
        print('Getattr:',attrName)
        print('This work on python:',self.__dict__)
        try:
            return self.__dict__[attrName]
        except:
            raise AttributeError("Unknow ",attrName)
    def __add__(self,val):
        return mockClass(self._val+val)
    def __str__(self):
        return str(self._val)
def test_func():
    print('In test func')
    myList = [1,2,3]
    for ii,item in enumerate(myList):
        if (ii==0):
            out = mockClass(item)
        else:
            print('Add:',item)
            out += item

    return out

And the module works, my test.py file:
import test_loop
a = test_loop.test_func()
print(a)

But when I change the python class to cython class I got stuck in the recursive loop: the getattr (I tried getattribute too) get stuck because it try to find dict, which is, again, require function getattr.
cdef class mockClass:
    cdef int _val
    def __init__(self,val):
        self._val = val
    def __getattr__(self,attrName):
        print('Getattr:',attrName)
        print('This work on python:',self.__dict__)
        try:
            return self.__dict__[attrName]
        except:
            raise AttributeError("Unknow ",attrName)
    def __add__(self,val):
        return mockClass(self._val+val)
    def __str__(self):
        return str(self._val)

I can't find any functional getattr example of cython extension class.
Comment: Your original code gets cythonized (obviously). ` mySum += item` isn't cython syntax, so it doesn't work. Please provide [mcve]
Comment: [cdef classes do not have a `__dict__` by default](https://cython.readthedocs.io/en/latest/src/userguide/extension_types.html#dynamic-attributes) - the documentation isn't explicitly clear on this but I've linked to the bit that shows how to add it.
Comment: Why not just do `mySum = sum(myList)` and move on?
Comment: @ead: I know, what's I'm trying to say is I'm looking for a syntax that allow me to tell the compiler that please assume that the variable mySum is already initialized somewhere else and I know what I'm doing
Comment: @Booboo: because I provide the sum function as a simplified version of what I actually want. I actually wanted:
```
mySum.mySpecialAppend(item)
```
Comment: @mqnguyen1988, still the code you have provided gets cythonized. The code you have problems with must be different. Thus, please provide [mcve].
Comment: @ead: you are right! I'm working on a minimal reproducible example, while doing so I realized that the problem isn't come from what I'm think of. I just copied and paste the code on cython and it's not working anymore so I jumped too fast in the conclusion. I'm working on this, may be it's completely irrelevant to the title.
Comment: "I'm looking for a syntax that allow me to tell the compiler that please assume that the variable mySum is already initialized somewhere else and I know what I'm doing" - `global mySum`?
Comment: @ead: sorry I can't get the minimal reproductive code to function because I got another error on the way. I'll try to work on it. I posted my problem here anyway.
Comment: @DavidW: thank you for your answer. So do you know how to make an implementation of __getattr__ that doesn't stuck in an infinite recursive? I seem can't find an example anywhere.
Comment: `__getattr__` is only called if the attribute hasn't been found by normal means. Therefore there's _never_ any point in looking in `__dict__` because if the attribute was in `__dict__` then `__getattr__` would not have been called.
Comment: So to clarify: your Python `__getattr__` is pointless (it always fails). Your Cython `__getattr__` is broken. In both cases the right thing to do is to delete them.
Answer: Why don't you use a the built-in sum function?
mySym = sum(myList)

Comment: Because the sum function is just an reduced problem. I actually wanted to use a custom function : mySum.mySpecialAppend(item)
Comment: Then you should really think about updating your question and telling the *whole* story so there is a chance somebody can give you an answer that will satisfy you.
Comment: @Booboo: yes my problem is not that easy to explain, so while working on simplify the problem, I discover another problem. I did edit my post so you can follow what I have tested. Sorry I jumped too fast to the conclusion.


how to check if the following function is $A/B$ measurable.

Question: I have been working with measurable function etc, but i get quite confused if we look at a function which goes from a propability space to say the borel sifma algebra. For example:
$f: (\Omega,P(\Omega)) \rightarrow (\mathbb{R},B(\mathbb{R}))$.
$\Omega = \{((j,k): 1 \leq j, k\leq 6\}$, So we describe here throwing two dices.
suppose $f(j,k) = j + k$. how do we check this is a measurable map?
I thought of taking a generator in B(\mathbb{R}) and checking whether the inverse lies in $P(\Omega)$.
So $f^{-1}(a,b) = \emptyset$ if $2,3,....,12 \notin (a,b)$.
If we have that one or more elements of {2,.....,12} is in (a,b), the inverse is just the union of all sets in the form $(j,k)$ where $j+k = c \in(a,b)$. This is in the power set of $\Omega$, so this funtion is measurable.
Is this the right way to prove that the function is measurable or have i forgotten something?
Kees
Answer: For your map to be measurable, the preimage of any Borel set $B$ should be in the $\sigma$-algebra $P(\Omega)$. But this $\sigma$-algebra is the power set, which contains any subset of $\Omega$, so your map is automatically measurable.
Comment: @KeesTil yes, that is correct.
Comment: So any well defined functiuon between these sigma algebras is measurable?


Is the group $U(8)$ cyclic?

Question: Referring to the group of units.
My first thought is yes, since $1$ would be the generator.
Although I think I'm getting confused between the generator and the identity element in this case. $1$ is definitely the latter, is it also a generator?
I believe I'm doing the operation incorrectly. For example, $3 \cdot 3 =1$ correct? $3$ couldn't be the generator because if I kept doing this operation I would start repeating the same elements, but not all the elements ($1,3,5,7)$
Comment: @CameronWilliams But 1 is indeed the identity in this case. I have the Cayley table in front of me and anything (1,3,5,7) operated with 1 will result in the operated element (ie 1,3,5,7)
Comment: Note that $3^2=5^2=7^2=1$ so there is no single generator.
Comment: @DerekHolt but none of those elements will produce all the other elements in the group?
Comment: NO @Mukr....how could it? All the non-unit elements haver order two, so none has order four. In fact, $\;U_8\cong C_2\times C_2\;$
Answer: I guess you are mixing $\mathbb{Z_8}$ and $U(8)$. $1$ is identity in $U(8)$ as operation is multiplication here. But in $\mathbb{Z_8}$ operation is addition, so $0$ is the identity and $1$ is the generator in $\mathbb{Z_8}$ as you can have any elements less than $8$ by adding $1$. No $U(8)$ is not cyclic. To see it pick an element of $U(8)$ and keep multiplying it with itself. If you find one with order 4, that is your generator. but every element here is of order 2.
$\textbf{Theorem-}$ $U(n)$ is cyclic iff $n$= $2,4, p^k,2p^k $ where $p$ is an odd prime.
Try to prove it.
Answer: $U(8)$ is not cyclic because it has more than one element of order $2$ namely $3,5,7$ and in general $U((2^n)$ is not cyclic for $n>2$.

Is the group $U(8)$ cyclic?


How to check if Windows login screen is displayed (in .NET)

Question: Is there any way to recognize if login screen is displayed ?
I trued to use OpenInputDesktop function but it not reliable (sometime it works but sometimes not)
<code>[DllImport("user32.dll", SetLastError = true)]
static extern IntPtr OpenInputDesktop(uint dwFlags, bool fInherit, uint dwDesiredAccess);

var handle = OpenInputDesktop(0, false, 0);
var locked = handle == null || handle == 0;
</code>
My exact case is:
Windows 10 starts all previously ran programs with user session after OS reboot.
I dont want my program to do anything until Windows login screen is displayed / user unlock  his session
Comment: You can listen for [lock and unlock events](https://stackoverflow.com/a/12293351/219933) and act on it
Comment: This will only if my app will be run after real user login (user login to OS then locks session). My issue is app starts when session is already locked –
Answer: Try
<code>using Microsoft.Win32;

SystemEvents.SessionSwitch += (s, e) =>
        {
            if (e.Reason == SessionSwitchReason.SessionLock)
            {
                // Do what you want here as the system is locked
            }
            else
            {
                Console.WriteLine("Unlocked by: {0}", Environment.UserName);
            }
        };
</code>
Comment: This will only if my app will be run after real user login (user login to OS then locks session). My issue is app starts when session is already locked


how to insert simple gmaps in a block

Question: How can I insert a simple google map in a block?
I have a contact page with a contact-form (that one can fill in and send),
and I want to add to this page a google map.
thanks alot in advance!
Comment: Hello. Have you tried to Google it and use search on Drupal.org? There are modules to do things like that, aren't they? There is even one simply called GMap Module.
Comment: Go through this article, Hope this will help http://webwash.net/tutorials/how-display-maps-using-gmap-views-and-location-drupal-7
Answer: There are many ways you can do this.

Go to maps.google.com, type in the address, get the link, then click the customize and preview embedded view. A popup should appear. Select the map size you want. Copy the html code and go to structure -> blocks -> add block, paste your code and select full html filter. And add your block to where you want it
Download the gmaps module and use it. By default is has a block created called location map

The GMap module provides an interface to the Google Maps API within
  Drupal. It integrates with the Location module to provide users a
  clickable map for entering latitude and longitude, as well as to
  display maps of Drupal nodes and users. GMap can be used to create
  interactive maps with various map markers and content in map bubbles,
  taking advantage of Drupal's other content management features. The
  module also provides a Views display plugin which allows users to
  display the results of a view on a Google map.
Comment: Thank you so much for the quick reply!                                              I tried number 1 and it shows me the html code on the website.  (number 2 I thought maybe its stupid to add a module for one map, is it true,)
Comment: I would go with number 1 since that's your only need for maps. Did you change your filter to full html.
Comment: yes i changed my filter to full html
Comment: Do you have wysiwyg on the body field of your block?
Comment: yes I think so because I can add pictures and change font...
Comment: At the bottom of the field, click on disable rich text before pasting the code
Comment: thanks, I did it and I saw the map but after 1 second it disapears and u see only a link:  View Larger Map
Comment: have a nice day!
Answer: With regards to the previous answer above;
There has been some changes to the Google maps GUI, thus in other to access the "embed link" option, you will have to navigate as follows;

Click the little gear option to the right had corner of the screen
Then you will see the option "share and embed maps" option
Answer: I'm not sure if you can do this with a block, but I have an iframe field attached to my basic page. Then adding the Google Maps API is easy with this doc: https://developers.google.com/maps/documentation/embed/guide. Copy the line with your API key https://www.google.com/maps/embed/v1/place?key=YOUR_API_KEY&q=Space+Needle,Seattle+WA to the Iframe URL, and it should work!

how to insert simple gmaps in a block


Manipulation of (rather) simple linear algebra expression.

Question: Given the following expression: $$(x-\mu)^T \Sigma^{-1} (x-\mu) + (\mu-\mu_0)^T S^{-1} (\mu-\mu_0),$$ where $x, \mu, \mu_0$ are vectors and $\Sigma, S$ are invertible square matrices.
Expand the expression so that there are only quadratic terms. How do I do this?
Comment: So what is your question?
Answer: Formally expand this by "FOILing" each product:
$$
(x-\mu)^T \Sigma^{-1} (x-\mu) + (\mu-\mu_0)^T S^{-1} (\mu-\mu_0) = \\
x^T \Sigma^{-1} x -
\mu^T \Sigma^{-1} x -
x^T \Sigma^{-1} \mu +
\mu^T \Sigma^{-1} \mu + \\
\mu^T S^{-1} \mu -
\mu_0^T S^{-1} \mu -
\mu^T S^{-1} \mu_0 +
\mu_0^T S^{-1} \mu_0
$$
Comment: But where are the quadratic terms?
Comment: What is your definition of a quadratic term?  I expanded because the question said "expand"; this is the most you can expand it.  The way I see it, the original form already has quadratic terms.


Unresolved metas in for run in Agda hello-world

Question: I tried to compile the hello-world example with Agda 126.96.36.199 and Agda stdlib 1.5. Below is the code:
module hello-world where

open import IO

main = run (putStrLn "Hello, World!")

When compiling with Agda (agda --compile hello-world.agda), the following error is reported:
Unsolved metas at the following locations:
  $HOME/hello-world.agda:5,8-11

The reported position (5,8-11) corresponds to token run.
I did not find any related information in both Agda and Agda-stdlib Issues, nor on SO or other websites. Is the documentation out-dated, or did I make any mistakes?

Note:

The Agda compiler is installed with stack install Agda with resolver lts-17.5.
I also tried manually compiling from GitHub sources (branch release-18.104.22.168).
In $HOME/.agda/libraries I have:
$HOME/agda-stdlib/standard-library.agda-lib

In $HOME/.agda/defaults I have:
standard-library

Answer: This is the problem described in the comment at https://github.com/agda/agda/issues/4250#issuecomment-771806949. The current workaround is to add an implicit argument to run as follows:
module hello-world where

open import IO
open import Level

main = run {0ℓ} (putStrLn "Hello, World!")

This issue will be fixed in the upcoming release of Agda 2.6.2 and the next version of the standard library.
Comment: Ah, thanks! In that issue, the error message is presented as a screenshot. That's probably why my searching on GitHub gave no results.
Comment: To import `0ℓ` only, use `open import Level using (0ℓ)`. It messed with other imports for me.


How do I get a double top boostrap nav with bootstrap template?

Question: I want a secondary bootstrap navbar on my site, a black one on top of the blue one.
Now when resizing, there is a hamburger menu and so on, so stacking 2 bootstrap menus on top of each other, even of different colors may cause problems.
How do I have a double bootstrap menu with 2 colors?
Answer: You can create a region in yourtheme.info or use Block Group Module.
If you're using Bootstrap theme for Drupal, you can simply write code for your Top Links Navbar in page.tpl.php and use CSS to design it as you wish. Now in the template code, include your navbar if not empty:
<code>if (!empty(primary_nav)||!empty(top_links)||!empty(user_nav)||!empty(navigation))
{ //..Code to include your top_links navbar .. /}
</code>
You can also hard-code your menu in page template of your theme but it's not the best practice.
Plus: Always use the child theme.
If you want to add hamburger menu then use JQuery pluggin for same and remove the default responsive behavior of bootstrap from the menu you want to display hamburger on smaller screen. I advice JQuery plugin as it's open source, clean and very beautiful.
Play here.


Posicionamento de div

Question: Tou a tentar fazer uma brincadeira com css e html5 deste tipo.

Só que esta a dar varios problemas porque

A div (content)principar nao está a ocupar toda a altura e largura da pagina.
O Posicionamento da div (central)  aparenta estar no meio mas quando passa para ecrãs maiores isso não acontece .
Codigo

* {
  margin: 0px;
  padding: 0px;
}
body {
  background-color: #FF0000;
}
#centro {
  position: relative;
  margin-top: 20%;
  margin-bottom: 15%;
  width: 100%;
  height: 200px;
  margin-right: 0;
  margin-left: 0;
  background: rgba(255,255,255,0.3);
  box-sizing: border-box;
}
section p {
  padding: 10px;
  font-family: Comic Sans MS;
  font-size: 40px;
  width: 100%;
  height: 80%;
  box-sizing: border-box;
  text-align: center;
}
footer {
  box-sizing: border-box;
  padding: 10px;
  text-align: center;
}
#content {
  width: 100%;
  height: 100%;
  border: 2px solid #8AC007;
  box-sizing: border-box;
}

      Teste

    Teste

Obrigado.
Comment: Cole seu código aqui também, para facilitar a análise do pessoal.
Comment: Já meti obrigado pela dica
Answer: Amigo, para conseguir centralizar a div (central) na pagina, você terá que aplicar um position: absolute na mesma, então necessariamente a div (content) não pode ter um position: static, neste caso terá de trabalhar com relative, absolute ou fixed
Para fazer a div (central) ocupar toda a pagina, então você deve fazer o html e o body também ocuparem toda a pagina, afinal o height: 100%é relativo ao tamanho do elemento pai.

html, body {
  position: relative;
  width: 100%;
  height: 100%;
  margin: 0px;
  padding: 0px;
}

#content {
  background-color: gainsboro;
  width: 100%;
  height: 100%;
}

#central {
  position: absolute;
  top: 0px;
  bottom: 0px;
  width: 100%;
  height: 120px;
  margin: auto;
  background-color: white;
  box-shadow: 0px 0px 10px black;
}

#central p {
  margin: 0px;
  height: 120px;
  line-height: 120px;
  text-align: center;
  font-weight: bold;
  font-size: 36px;
}

footer {
  position: absolute;
  text-align: center;
  width: 100%;
  bottom: 0px;
}

Texto

    Texto

O truque para centralizar a div(central) é ancorar ela no topo e no final, para isto você vai precisar do top: 0px e bottom: 0px, mas ao fazer isto e deixar o height: auto, a div(central) vai ocupar todo o espaço da div(content), um efeito semelhante a um height: 100%, então se especificamos um height e colocamos margin: auto, as margens irão crescer até a posição do top: 0px e o bottom: 0px;
Comment: deu certo mas o problema e que o `footer` fica em cima não no lugar dele em baixo
Comment: Tenta colocar o footer com `position: absolute` e `bottom: 0px`
Comment: O exemplo que coloquei acima, o footer está na parte de baixo.

Posicionamento de div


Read XML and create objects using LINQ in VB.NET

Question: Com o seguinte código abaixo:
<code><?xml version="1.0" encoding="UTF-8" standalone="yes"?>
    <escuelas>
    <escuela>
    <estudiante>noe</estudiante>
    <fechaCreacion>2017-11-21T00:11:26.748-05:00</fechaCreacion>
    <idE>1</idE>
    <nombre>joao</nombre>
    <profesor>maria</profesor>
    </escuela>
    </escuelas>
</code>

Obs: Estou trabalhando com REST em um Serviço Web, então ao agregar um
  novo objeto o serviço me retorna um xml com todos os objetos, porém,
  ainda não encontrei uma forma de ler esses dados.
Answer: Para trabalhar com XML vc tem algumas ferramentas disponíveis no .Net Framework.

O XPath e o XmlSerializer.
No XmlSerializer vc cria uma estrutura de classes que corresponde à estrutura do XML que vc está carregando, usando anotations para determinar se os valores estão em elementos ou atributos e chama o método Deserialize da classe para carregar todas as informações para a estrutura que vc definiu.

Se o que vc quer é simplesmente buscar um ou mais valores específicos dentro do Xml, XPath é o mais indicado.
O Link abaixo explica como usá-lo:
https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/linq/how-to-filter-on-an-attribute-xpath-linq-to-xml
Abs e bom trabalho!
Comment: Obrigado meu caro, já consegui resolver meu problema! Desculpe o atraso, era um projeto de faculdade portanto aqueles que verem essa pergunta e quiser saber como eu resolvi, só me chamar ! Abraços


How can I have different serialization options for DocumentDB and BLOB storage?

Question: I've a class and I need to save it both in DocumentDB and in BLOB storage.
public class MessagesSetType
{
    public DateTime CreatedAt { get; set; }
    public virtual string CustomerSubscriptionId { get; set; }
    public virtual string DefaultLanguage { get; set; }
    public MessageSetTypeCollection Messages { get; set; }
    public DateTime ModifiedAt { get; set; }
    public virtual string Name { get; set; }
    public virtual string[] Tags { get; set; }
}

In DocumentDB I have to save all properties EXCEPT Messages then in BLOB storage I must save all properties included Messages.
So my question is: how is the prettiest way to exclude the Messages property from DocumentDB and not from BLOB?
I've tought to create a clone of this class without the Messages property then save it to DocumentDB and save the original class to BLOB but this solution doesn't satisfy me..
Comment: Can you use a different contract resolver for each, along the lines of [Conditional member serialization based on query parameter?](https://stackoverflow.com/questions/29713847/conditional-member-serialization-based-on-query-parameter) ?
Answer: I would not use the same class. Simply because we can re-use does not mean it's a good idea. The purpose and usage of each store differs, which means that they may very well diverge further. How do you know if it's the same item from different stores or if it is different items? Instead of having clean and explicit implementations you may very well find yourself with a some implicit monster of assumptions.
The storage and usage is different. What you store and retrieve from blob and DocumentDB is not the same thing. Be explicit.
Comment: I agree with hsulriksen. Consider creating sperate classes for `MessagesMetaData` (to be stored in DocumentDB) and `Messages` (to be stored in Blob Storage). For the `MessagesMetaData` class, you can create an "attachment" that is simply a reference to the URI for the messages in blob store.


WCF initialization on local network hangs for 20 secs

Question: I have WCF service using basicHttpBinding.
When client and server are on same network they initial call hangs for about 30 secs than it goes smooth.
When I do the same call from client over internet with DNS than it works nicely with no hanging.
Client and server are both console applications. Server is running windows 7 and problematic client is running Windows Server 2008. Both computers on same network are using their local security policies so there is no Domain controller.
Turning off all firewalls and antivirus did not solve my problem.
This is log from setup with boxes next to each other
09:33:05,252 [1] DEBUG ChannelFactoryManager: Created ClientChannel http://192.168.1.11:18762/DiagnosticService
09:33:05,263 [1] INFO  Program: WcfAppender.InitializeWcfAppender: 08:33:05
09:33:05,274 [1] INFO  Program: File.Copy(C:temptest.txt, O:test.txt, true): 08:33:05
09:33:05,298 [1] INFO  Program: GETTING DomainFactory.LoggingDiagnosticService.GetMonitoringLevel: 08:33:05
09:33:32,661 [1] INFO  Program: GOT DomainFactory.LoggingDiagnosticService.GetMonitoringLevel: 08:33:32
09:33:32,668 [1] INFO  Program: GETTING DomainFactory.LoggingDiagnosticService.GetMonitoringLevel: 08:33:32
09:33:32,680 [1] INFO  Program: GOT DomainFactory.LoggingDiagnosticService.GetMonitoringLevel: 08:33:32
09:33:32,693 [1] INFO  Program: File.Copy(C:temptest.txt, O:test.txt, true): 08:33:32

This is log when I hit same server over the internet from different network (no delays):
09:36:56,500 [1] DEBUG ChannelFactoryManager: Created ClientChannel http://mydomain.com:18762/DiagnosticService
09:36:56,501 [1] INFO  Program: WcfAppender.InitializeWcfAppender: 08:36:56
09:36:56,501 [1] INFO  Program: File.Copy(C:temptest.txt, O:test.txt, true): 08:36:56
09:36:56,501 [1] INFO  Program: GETTING DomainFactory.LoggingDiagnosticService.GetMonitoringLevel: 08:36:56
09:36:56,680 [1] INFO  Program: GOT DomainFactory.LoggingDiagnosticService.GetMonitoringLevel: 08:36:56
09:36:56,680 [1] INFO  Program: GETTING DomainFactory.LoggingDiagnosticService.GetMonitoringLevel: 08:36:56
09:36:56,705 [1] INFO  Program: GOT DomainFactory.LoggingDiagnosticService.GetMonitoringLevel: 08:36:56

I have also tried copying test.txt file between boxes to see if I get same connectivity issue for
Comment: I had a simular problem very long time ago. We solved it with setting the proxy to null. Sometimes, if you set nothing the connection try to use the default network proxy
Comment: useDefaultWebProxy="false" solved it.
thanks a lot. you should answer it as answer so I can mark it.
Answer: This type of error can occure when a default proxy is defined: Disable the use of the default-proxy by adding this to your app.config
<system.net>
    <defaultProxy enabled="false" useDefaultCredentials="false">
        <proxy />
        <bypasslist />
        <module />
    </defaultProxy>
</system.net>

or use useDefaultWebProxy="false" :-) as you already said in your comment


Fancybox2 api open() ignores options?

Question: The fancybox2 docs for the API call open() says
<code>$.fancybox.open( [group], [options] )
</code>
However the docs go into detail about [ group ] and say nothing about the format expected for the  [ options ]
Furthermore the options seem to be ignored.
When I use
$.fancybox.open([{ href : '#popup_panel' }], [ { 'title' : 'Title Two', 'minWidth' : 500  }] );
or
$.fancybox.open([{ href : '#popup_panel' }], [ { title : 'Title Two', minWidth : 500  }] );
Fancybox seems to ignore the options... it opens, but there is no title and the minWidth is ignored.
I'm using v2.1.5 if the fancybox javascript.
Answer: The fancybox documentation is wrong; options go inside the [group] apparently:
$.fancybox.open([{ href : '#popup_panel',  title : 'Title Two', minWidth : 500 }], [] );
Comment: Well, I don't think the documentation is wrong, I think you misinterpreted it. Check http://fancyapps.com/fancybox/#useful ==>No. 10 ==> "Method two - Open fancyBox manually" for a how-to example
Comment: The issue I have with the docs is that that there is a tab (next to Api) called "Options" and then the API docs for open() says the arguments are ([group], [options]) BUT (a) the API docs do not say WHAT "options" can go in the [options] arg, and more to the point, the Options under the Options tab apparently are supposed to go in the [group] arg NOT the [options] argument. That seems like wrong docs to me.

Fancybox2 api open() ignores options?


Concurrent map with multiple values for one key and auto-remove on timeout

Question: I'm newcomer in concurrency. I read about Guava Cache and MultiMap. I look for something that can combine some possibilities of both:

From Cache I want auto-removal after ACCESS_TIMEOUT and WRITE_TIMEOUT has been expired.
From Multimap I want multiple values associated with one key.
All that must be concurrent.
I has multiple writers and multiple readers. I want to add values with rundom keys and remove them.

Question: Is there map implementation that fits my needs?
UPDATED: Striped<Lock> solution
More I read about Striped<Lock> - more attractive that seems to me. But it arose even more questions in my head:

If I use something like Striped<Lock> with Guava Cache which already uses ConcurrentHashMap I can face the problems with deadlocks or performance decline. Am I wrong?
If I use  Striped<Lock> over Cache it still doesn't remove the question linked with multiple values per key.
Does Striped<Lock> eliminate the need of using concurrent map in my case? (I suppose the answer is YES) but in GitHub a saw the contrary.
Answer: You could start with a Cache<SomeKey, Collection<SomeValue>> (so you still get the expiration) and use synchronized collections (Collections.synchronized*()) as the values.
But what's really the question here is the type of concurrent access you need on the collections:

Is it enough that the operations are synchronized so the collections don't get corrupted, or do you need higher-level semantics like what ConcurrentMap.putIfAbsent() offers?
Do you need to do multiple operations on the collections of values in an atomic way? Like if you need to do
if (c.contains(v)) {
    c.remove(v);
} else {
    c.add(v);
}

you usually want to put that into a synchronized(c) { } block.

If so, you'll probably want to wrap the collection inside a class exposing those higher-level semantics and managing the lock around multiple operations to get the atomicity you need, and use that class as the value: Cache<SomeKey, SomeValuesContainer>.

As mentioned in the comments, Striped<Lock> can be used to synchronize the access to multiple Caches/ConcurrentHashMaps without imposing a single lock and its performance impact in case of even moderate contention.
If you need multiple Caches/ConcurrentHashMaps, that is: why don't the Peers (or a wrapper around it) actually contain that information?
1. Deadlocks, performance
Guava's Cache is similar to ConcurrentHashMap, but it doesn't use it. However, both work in the same way by having segments which can be locked independently, thus reducing contention when accessing the map concurrently (especially when updating). Using a Striped<Lock> around the access to either one cannot cause a deadlock, which only happens if you're not locking multiple locks in a consistent order: that can't happen here, as you'll always lock your Lock obtained from Striped<Lock> before calling the Cache or ConcurrentHashMap, which then locks its segment (invisible to you).
As to performance, yes, locking has a cost but it really depends on the level of contention (and that can be tuned with the number of stripes in a Striped<Lock> or the concurrencyLevel in a Cache). However, you need proper concurrency support anyway since without it you can get invalid results (or corrupt your data), so you have to do something (using either locking or a lock-free algorithm).
2. Multiple values per key
My original answer still stands. It's difficult to get an exact idea of what you're exactly trying to do from your multiple questions (it's better if you can provide a complete, consistent context in one question), but I think you don't need more than concurrent modification of the multiple values per key so the synchronized collections should be enough (but you need at least that). You'll have to reason about your access patterns as you add them to make sure they still fit the model, though: make sure your replaceAll*() methods lock what they need, for example.
3. Is ConcurrentMap still needed with Striped<Lock>?
YES! Especially with Striped<Lock> vs a single Lock, because you'll still get concurrent updates for keys which don't use the same stripe (that's the whole point of Striped<Lock>) so you need data structures which support concurrent modification. If you use a simple HashMap, you have every chance of corrupting it under enough load (and cause infinite loops, for example).
Comment: seems I want all types of concurrent access. I've already posted the code, so hope you'll look at that (only at code) http://stackoverflow.com/questions/22067533/java-map-multithreading-juggler/22068934?noredirect=1#22068934. In that example I want to change ConcurrentHashMap with something I've described in my question
Comment: You don't really describe the access patterns in either this question or the other one, so it's still not clear what level of atomicity you want, especially when manipulating several `ConcurrentMap` or `Cache` at once, which adds another level of complexity. Could you complement your question with specific scenarios and the expected results in a multithreaded context: Thread1 adds this key and these values, Thread2 removes some of the values for the same key, etc.? We need to understand what should happen in each "map" as well as across those.
Comment: I think you could use a [`Striped`](http://docs.guava-libraries.googlecode.com/git/javadoc/index.html?com/google/common/util/concurrent/Striped.html) to avoid a global lock when moving data between the "maps", at least when the data moved is related to a single key.
Comment: Oh, and it's not clear how `MyObj` and the collection of values per key relate: do you actually need to store several `MyObj` per key, or is `MyObj` the class wrapping a collection of values I was writing about?
Comment: `MyObj` (or `Peer`) associates with user's session or to be more precise with user's tab. User can work with my application from multiple tabs, and each tab is proceeded in separate thread. BUT all those tabs have the same `sessionId`. So actually my map looks like `ConcurrentHashMap`. It can contains multiple `Peer` objects for the same `sessionId`.
Comment: look at http://stackoverflow.com/questions/22145321/cachelong-blockingdequepeer-combined-with-stripedreadwritelock-is-it-thr please


Definir coordenadas ao abrir mapa

Question: Preciso abrir um mapa com coordenadas especificas (latitude e longitude). Esses dados eu já tenho, porém não sei como setá-los no mapa.
PS: É possível abrir direto no Maps do Google?
Comment: A sua dúvida é abrir o aplicativo *Google Maps* com esta coordenada específica ou você mesmo implementar o mapa no seu aplicativo? Para a segunda opção, acredito que [esta questão](http://pt.stackoverflow.com/q/54389/4337) irá lhe responder.
Comment: Gostaria de Abrir direto no 'Google Maps', como prossigo? - Paulo Rodrigues
Comment: César, com as respostas abaixo, agora me surgiu uma outra dúvida que parece que não está na sua pergunta. Você quer abrir o Google Maps é a partir do seu aplicativo nativo, certo? Ou você tem um site mobile?
Comment: Aplicativo nativo! (do Android Studio)
Answer: Para abrir o Google Maps diretamente do seu aplicativo com uma determinada coordenada, utilizando Intent mesmo, por exemplo.
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:-19.8516098,-43.9509601?z=15"));
startActivity(intent);

Outros exemplos, você pode ver aqui na documentação. Neste meu exemplo, além da latitude e longitude, também defini o zoom.
Answer: Todo Marker, você tem que inserir via JS.
Como você já tem a posição, é só enviar para o javascript e pegar em uma variavel.
Ou setar direto como neste exemplo da W3Schools.
W3Schools
Este link abaixo é da documentação oficial do google maps.
Google Maps
Answer: Na sua atividade principal, implemente a interface LocationListener e copie o código abaixo na sua atividade principal.
public class BasicMapActivity_new extends Activity implements LocationListener {
        private LocationManager locationManager;
        private String provider;

        LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
        boolean enabledGPS = service
        .isProviderEnabled(LocationManager.GPS_PROVIDER);
        boolean enabledWiFi = service
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        if (!enabledGPS) {
            Toast.makeText(BasicMapActivity_new.this, "GPS signal not found", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
        else if(!enabledWiFi){
            Toast.makeText(BasicMapActivity_new.this, "Network signal not found", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        // Define the criteria how to select the locatioin provider -> use
        // default
        Criteria criteria = new Criteria();
        provider = locationManager.getBestProvider(criteria, false);
        Location location = locationManager.getLastKnownLocation(provider);
        //getCurrentLocation();

        // Initialize the location fields
        if (location != null) {
            // Toast.makeText(BasicMapActivity_new.this, "Selected Provider " + provider,
            //Toast.LENGTH_SHORT).show();
            onLocationChanged(location);
        } else {

            //do something
        }
        initilizeMap();
    }

Em seguida, na implementação dos métodos dessa interface faça o seguinte:
   @Override
    public void onLocationChanged(Location location) {

        double lat =  location.getLatitude();
        double lng = location.getLongitude();

        LatLng coordinate = new LatLng(lat, lng);

        startPerc = mMap.addMarker(new MarkerOptions()
        .position(coordinate)
        .title("Current Location")
        .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE)));

        mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(coordinate, 18.0f));
    }

    @Override
    protected void onPause() {
        super.onPause();
        locationManager.removeUpdates(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        locationManager.requestLocationUpdates(provider, 400, 1, this);
        initilizeMap();
    }

Por ultimo conceda as permissões necessárias no arquivo maninfest:
  <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
  <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

Answer: basta chamar
        CameraUpdateFactory.newLatLng(LatLng)
ao carregar o mapa, ou onde for necessário.
Construa um objeto LatLng que possui o ponto x e y e pronto.

Definir coordenadas ao abrir mapa


Controlling remote Drupal sites with Drush

Question: For a couple of weeks now I have been watching various screencasts and envying those who can operate Drush on their sites, esp. when enabling/disabling of the modules, or clearing cache. The time savings seem to be immense.
However, as a more of a front-end developer, rather than a qualified, fluent console operator, I find myself completely lost as per the usage of Drush with remote sites. Most of the googled readings treat about local sites, they specify paths to local installations, or they assume that a site was created using site-install command. While I am interested in adding Drush to an existing remote site. How do I add Drush into play with that remote site?
Now that I'm trying to get the big picture of using Drush, I think I may have missed some principal knowledge about the environment and tools needed, which I haven't found anywhere.

Apart from having command line Drush installed on my desktop, do I have to install Drush module on my remote site? Or is Drupal core Drush-controllable out-of-the-box (if it is, what is the purpose of Drush module available at drupal.org/project/drush)
Do I have to configure SSH for communicating the server?
Do I need to provide db credentials anywhere (where)?
Do I need to define FTP credentials anywhere (where)?
aliases.drushrc.php: does it live only on my desktop, or should I define anything similar on the remote ftp?

My setup involves staging and production sites, the former also stored on a remote ftp server with its own domain. I would like both to be controllable via Drush. Is that feasible?
It'd be great if someone could shed some light on me.
Answer: You have a lot of questions there, but I'll try to give you the best overview of how to do this easily.
First, note that though Drush is listed as a module on Drupal.org, it is not technically a module as you don't "enable" or "disable" it like other modules.

Yes, Drush must be installed on the remote site.  When you do so, make sure to install the same version that you have installed locally.  It may still work if you're using different versions, but it can also cause strange bugs that are difficult to troubleshoot so always try to keep the same version.
It's certainly easier if you have SSH set up for some of the Drush commands.  Your web host should be able to help you with getting SSH keys set up for your local machine.
Yes, you will need to provide DB credentials.  This can be done by following the example in drush/examples/example.aliases.drushrc.php in the drush folder.
No, I don't think so.
You do not need to set up the alias on your desktop unless you are going to be logging in to your remote server and using aliases there.

Basically, if you have SSH working and have installed Drush on the remote server as well as your local machine, then, once you set up an alias, you can type something like drush @myremote status and it should work.
Comment: Thanks a lot! Your answers explain a lot. I was confused even more by a representative of my hosting comany, who told me that Drush is meant for controlling locally installed sites only.
Answer: I created a write-up on how you can use drush with remote sites if you have FTP and database access to them, but not SSH access. It's a bit of setup, but if you can't live without drush, or work with lots of sites, it's worth it.
My writeup, if your local computer is Linux:
http://eworldproblems.mbaynton.com/2014/07/drush-remote/
The same principle, if your local computer is Windows:
http://classically.me/blogs/drush-synchronization-ftp
Comment: Really like this from your post 'Remote drush with only FTP and database access', quote: "There didn't seem to be much accurate information about how to do it already, with top Google hits saying things like 'you need ssh and drush installed both locally and on the server', 'you can't', and there was really nobody suggesting anything (..). I stubbornly refused to believe them and came up with a method (..)"


File not found exception when running project from Visual Studio

Question: My C# project needs to read a file that is in the same location as the executable. The file is under <PROJECT>/bin/x64/Debug/input.txt and under <PROJECT>/bin/x64/Release/input.txt. In the same folders there is also the program.exe.
When executing manually the program.exe from those directories it reads the file and executes successfully. When trying to run the executable from the visual studio it cannot find the file.
Is there a way to resolve it?
Comment: It would be helpful if you showed the code that reads the file.  Also, is there a slash missing in your `Release` path?
Comment: Does [this](https://stackoverflow.com/questions/1658518/getting-the-absolute-path-of-the-executable-using-c) help?
Comment: @BACON Thanks. It was actually a spelling mistake while writing the question. I fixed it
Answer: I use
System.Environment.CurrentDirectory + @"\input.txt"

which returns a string of "C:\Users\username\source\repos\Solution_name\Project_name\bin\{DEBUG | RELEASE}\input.txt"
Comment: By default, a relative file path (e.g. `File.OpenRead("input.txt");`) would try to open `input.txt` in the same directory as `program.exe`.  Building an absolute path like this works, of course, but it shouldn't be necessary and there simply isn't enough information provided in the question to know why it would be.  Perhaps the working directory was changed in the project settings.


PHP iframe abrindo mais de uma sessao para o mesmo navegador

Question: Estou trabalhando em um sistema de adsense, e na mesma página possui vários iframes chamado, o problema é que preciso limitar a quantidade para cada pagina
só que pelo acesso ser muito rápido ele cria uma sessao para cada iframe, fiz um contador porem não resolve pois para cada sessao ele estará no 0 sempre.Eu uso o cookie do navegador para dar um tempo de vida a sessao, por quando o usuário atualizar a página precisa renovar a quantidade.
<code>$cookie = $this->input->cookie('token');
    $hash_cookie = substr($this->input->get('wg', TRUE), 0,20);
    if(empty($cookie)){
        $this->input->set_cookie(['name' => 'token', 'value' => random_string('alpha', 6),'expire' => 5]);
        unset($_SESSION['hashs']);
        $_SESSION['hashs'] = [];

    }
    if(empty($_SESSION['hashs'][$hash_cookie])){
        $_SESSION['hashs'][$hash_cookie] =  0;
    }
    if($_SESSION['hashs'][$hash_cookie] < 3)
        $_SESSION['hashs'][$hash_cookie] += 1;
    else
        return '';
</code>
Answer: Foi necessário colocar um setTimeout no javascript para fazer as requisições pois minhas sessões estavam sendo salvas em arquivos por isso a lentidão em atualizar.


Is there a module to show a quick message to a user or role?

Question: Is there a module to send a user or users having a role a message like the one that is currently on top of this site (The Drupal Answers 2012 community moderator election is underway — nominations now being accepted.")?
I don't need a message box like the one that Private message module provides, but a quick message.
Answer: See the User Alert Module. This module provides a simple way to show a short-term urgent message on the website. Think of CNN Breaking News, when they show a short message the top of the site (or the 'Welcome!' style messages at StackExchange websites). This module works for both anonymous and authenticated users by using a cookie, and recording actions in the database. This solves the need to show messages independent of the users authenticated status. With User Alerts, you can: Alert users about breaking news, or a special same-day sale for ecommerce. You can also set expiration timers for alerts (1 hour, 3 hours, Never, etc) (Drupal 6 Only, D7 requires Scheduler).
Answer: Not necessarily a module, but VIEWS could be used to do something very similar.  Create a content type, say "motd," and to get fancy, put in a date field.  Then create a view with a block display, filtering on node type motd and the date field equal to today, and displaying the body of the node, then put that block where you want your message of the day to go...


Relative integral basis for a quadratic extension

Question: Let $K,L$ be two number fields such that $L$ is a quadratic extension of $K$, then can we always find an element $\alpha\in \mathcal{O}_L$ such that $\mathcal{O}_L=\mathcal{O}_K[\alpha]$, i.e., $\{1,\alpha\}$ is a relative integral basis for $L/K$?
When $K=\mathbb{Q}$, this assertion is true due to a classical result. But is it always true for general $K$?
Thanks very much!
Comment: There are examples of quadratic extensions of number fields where $\mathcal{O}_L$ is not even a free module over $\mathcal{O}_K$.
Comment: @LordSharktheUnknown Nice! Could you please give a reference?
Comment: I was hoping you wouldn't ask me that .... I don't have a reference to hand, but I'm sure examples aren't very complicated.
Answer: Let $L/K$ be your quadratic extension of number fields, with rings of integers $O_L , O_K$, and denote by $\Delta=\Delta(L/K)$ the ideal discriminant. Then :
1)@Lord Shark the Unknown. $O_L$ is  $O_K$-free iff $\Delta=(D)$ and $L=K(\sqrt D)$, see [M].
2) Let $L=K(\sqrt a)$ and consider the ideal decompositions $(a)=\mathcal A^2.\mathcal B$ and $\Delta=\mathcal C^2.\mathcal D$, where $\mathcal B$ and $\mathcal D$ are integral square free ideals. Then $L/K$ admits an integral basis iff $\mathcal B=\mathcal D$ and $\mathcal A$ and $\mathcal C$ belong to the same ideal class, see [M].
3) In [F], Fröhlich has defined, for any finite extension of number fields $L/K$, a new kind of "idelic" discriminant $\mathfrak D(L/K) \in J_K/{U_K}^2$, where $J_K$ is the group of idèles and $U_K$ the group of unit idèles of $K$. The classical ideal discriminant $\Delta(L/K)$ is then the image of  $\mathfrak D(L/K)$ under the natural map $J_K/{U_K}^2 \to J_K/{U_K}$. The advantage of the new discriminant shows up immediately with the following theorem : $L/K$ admits an integral basis iff $\mathfrak D(L/K)$ is "principal", i.e. is the image of a principal idèle $d$ of $J_K$ under the projection $J_K\to J_K/{U_K}^2$. Back to the quadratic case, suppose that $L/K$ admits an integral basis. Then there exists $b\in K^*$ s.t. $d\equiv b^2$ mod $4$ and $(1, \frac {b+\sqrt d}{2})$ is an integral basis, see [F], p.24.
[F] A. Frohlich, Discriminants of algebraic number fields, Math. Zeit. 74 (1960), 18-28
[M] H. B. Mann, On integral bases, Proc. AMS 9 (1958), 167-172


Recent progress in the irrationality measure of $\pi$

Question: The context.
For any real number $x$, let's define the quantity
$$\mu(x):=\sup\left\{\mu\in\mathbb R_+\, \text{there is an infinity of $(p,q)\in\mathbb Z\times\mathbb N$ such that}\ 0<\left\vert x-\frac pq\right\vert<\frac 1{q^{\mu}}\right\},$$
and let's call it the irrationality measure of $x$.
We know that
$$\mu(\pi)\leqslant 8.016$$
thanks to M. Hata (1992).
The question.
We can read on this Wikipedia page that
\begin{equation}
\mu(\pi)\leqslant 7.6063,
\end{equation}
but this is provided without any reference.

Do you know any article where I could find a mention of this result?

Does this bound have been improved?
Comment: [Mathworld](http://mathworld.wolfram.com/IrrationalityMeasure.html) has a reference for the smaller bound: "Salikhov, V. Kh. "On the Irrationality Measure of pi." Usp. Mat. Nauk 63, 163-164, 2008. English transl. in Russ. Math. Surv 63, 570-572, 2008." I don't know if there's been any progress since 2008.
Comment: @Micah: I don't believe a better value is currently known, because if there were a better value, then I'm sure it would turn up in the google search [Salikhov + "on the irrationality measure of"](https://www.google.com/search?q=Salikhov+%22on+the+irrationality+measure+of%22&filter=0) ([corresponding google scholar search](https://scholar.google.com/scholar?lookup=0&q=Salikhov+%22On+the+Irrationality+Measure+of%22)). Also, this is the best value mentioned in Marko Leinonen's 2017 Ph.D. dissertation [**On Various Irrationality Measures**](http://jultika.oulu.fi/files/isbn9789526217031.pdf).
Comment: @DaveL.Renfro: Thanks! That sounds good enough for an answer to me.
Comment: @Micah That looks like a potential answer to the question to me.
Answer: Salikhov proved the smaller bound in: "Salikhov, V. Kh. "On the Irrationality Measure of pi." Usp. Mat. Nauk 63, 163-164, 2008. English transl. in Russ. Math. Surv 63, 570-572, 2008." as referenced, e.g., on Mathworld.
Zeilberger and Zudlin have improved Salikhov's bound to $7.1032\dots$, here (or the preprint is freely readable here). As of January 2023, this appears to be the best-known result.
Comment: @Micah The 7.1032... paper has now been published: https://msp.org/moscow/2020/9-4/p06.xhtml. Here's the website of an author: https://sites.math.rutgers.edu/~zeilberg/mamarim/mamarimhtml/pimeas.html
Comment: It is now superseded by 7.103205334137..., according to mathworld and this paper: https://arxiv.org/abs/1912.06345
Comment: @GeorgeLowther: Fantastic, thanks!


Change log output to configuration file in linux

Question: basically I have an output from a DHCP server log that looks something like this:
  hardware ethernet 00:16:41:ef:9e:47;
  client-hostname "mo-10";
  hardware ethernet 00:11:25:73:20:a5;
  client-hostname "mo-11";
  hardware ethernet 00:11:25:73:20:a5;
  client-hostname "mo-11";
  hardware ethernet 00:11:25:73:20:a5;
  client-hostname "mo-11";
  hardware ethernet 00:16:41:ef:9e:47;
  client-hostname "mo-10";
  hardware ethernet 00:11:25:73:21:35;
  client-hostname "mo-23";

Each two lines come together - the first is the MAC address of a device on the network and the second is the hostname. I would like to take the list, and put each pair of lines into a config block for my dhcp server like this:
    host mo-10 {
            hardware ethernet 00:16:41:ef:9e:47;
            fixed-address 192.168.1.10;
    }

The part after host should be identical to client-hostname, the hardware ethernet block should be the same and the fixed address should always be 192.168.1.x where x is the number in the host name (so for host mo-10 the ip should be 192.168.1.10, mo-23 would be 192.168.1.23 etc.) Everything should be enclosed in curly brackets.  Additionaly there are many duplicate entries, which I would like to remove. I tried messing around with grep and awk, but I'm not very proficient at manipulating text in bash and this is just too complex for me. I would be glad if somebody could provide a way to accomplish this and explain why it works.
Thank you very much.
Comment: Is the left hand spacing correct?  Does each line in the source start with several spaces?
Answer: Here is one way of doing it:
awk '
NR%2 { eth = $0; next }
{ gsub(/[";]/,""); map[$NF] = eth }
END {
    for (host in map) {
        split (host, t, /-/);
        print "host " host " {\n\t" map[host], RS, "\tfixed-ethernet 192.168.1."t[2]";" RS "}"
    }
}' file
host mo-10 {
    hardware ethernet 00:16:41:ef:9e:47;
    fixed-ethernet 192.168.1.10;
}
host mo-11 {
    hardware ethernet 00:11:25:73:20:a5;
    fixed-ethernet 192.168.1.11;
}
host mo-23 {
    hardware ethernet 00:11:25:73:21:35;
    fixed-ethernet 192.168.1.23;
}

Store the odd lines in a variable eth. For even lines, you remove the quotes and ; and create a hash keyed at hostname with value of line. In the END block you iterate over your hash and split the hostname on -.
Then you just print as your desired output.
Comment: +1 for using `awk`. Having the restriction to remove duplicates, it is more efficient then sed. (At least I don't know an efficient way with sed atm.. will try to find one ;)
Comment: Thank you very much, simple and elegant.
Answer: You can use sed. To remove duplicates I would suggest a pipe:
sed '/hardware/{N;s/\n/ /}' < list | sort -k5 | uniq -f4 | sed -r 's/ *hardware ([^ ]*) ([^;]*); *.*"(.*\-(.*))";/host \3 {\n\thardware \1 \2;\n\tfixed-address 192.178.10.\4;\n}/'

The pipe flattens the two-line records into one line per record, then overhands them to sort/uniq and then to sed for the final formatting again.
Output:
host mo-10 {
    hardware ethernet 00:16:41:ef:9e:47;
    fixed-address 188.8.131.52;
}
host mo-11 {
    hardware ethernet 00:11:25:73:20:a5;
    fixed-address 184.108.40.206;
}
host mo-23 {
    hardware ethernet 00:11:25:73:21:35;
    fixed-address 220.127.116.11;
}

Btw, after all I would prefer the awk solution as it doesn't need to iterate over the data again and again. (Didn't read the remove duplicates restriction when gave the first version of this answer).
Answer: The next:
perl -lanE '
    if(/^\s*$/){$.--;next}  #skip empty lines
    push @v, map {s/[^\da-f:]//ig;$_} $F[$.%2+1] }{ %h=@v;  #process
#print
say qq[host mo-$h{$_} {
    hardware ethernet $_;
    fixed-address 192.168.1.$h{$_};
}] for keys %h

' <<EOF
hardware ethernet 00:16:41:ef:9e:47    ;

client-hostname "mo-10"   ;

hardware ethernet 00:11:25:73:20:a5;

client-hostname "mo-11" ;
hardware ethernet 00:11:25:73:20:a5 ;
client-hostname "mo-11";
hardware ethernet 00:11:25:73:20:a5;
client-hostname "mo-11";
hardware ethernet 00:16:41:ef:9e:47;

client-hostname "mo-10";
hardware ethernet 00:11:25:73:21:35;
client-hostname "mo-23";
EOF

prints
host mo-23 {
    hardware ethernet 00:11:25:73:21:35;
    fixed-address 192.168.1.23;
}
host mo-10 {
    hardware ethernet 00:16:41:ef:9e:47;
    fixed-address 192.168.1.10;
}
host mo-11 {
    hardware ethernet 00:11:25:73:20:a5;
    fixed-address 192.168.1.11;
}

Comment: fixed now - removes duplicates
Answer: In Python:
import re, sys

template='''\
host {} {{
   hardware ethernet {}
   fixed-address 192.168.1.{};
}}'''

pat=re.compile(r'hardware ethernet ([^;]+;)\nclient-hostname ([^;]+;)')

with open(sys.argv[1], 'r') as fin:
    di={k.rstrip(';').strip('"'):v
            for v, k in pat.findall(fin.read())}

for k, v in di.items():
    ip=re.search(r'(\d+)$', k).group(1)
    print template.format(k, v, ip)

From Bash, running python ip.pl log.txt prints:
host mo-23 {
   hardware ethernet 00:11:25:73:21:35;
   fixed-address 192.168.1.23;
}
host mo-11 {
   hardware ethernet 00:11:25:73:20:a5;
   fixed-address 192.168.1.11;
}
host mo-10 {
   hardware ethernet 00:16:41:ef:9e:47;
   fixed-address 192.168.1.10;
}

The duplicate removal is performed by adding the data by host name to a dict, which can only have one value with each key value.


Constructing a topological invariant in discrete space

Question: Consider a $d$-dimensional discrete space with infinitely many cells. The Location of a cell is denoted by $x=(i_1,i_2,\dots,i_d)$ with $i_k \in \mathbb N$. Now I can define a function $\omega(x)$ that can take the values $0$ and
$1$. If a cell is occupied by a "solid Body" then $\omega$ takes value $1$. If there is nothing on a cell with coordinate $y$ then it holds $\omega(y)=0$. With These conventions arbitrary discrete manifolds with "holes" can be constructed.
Now I have the topological invariant "Number of holes in the manifold" and I am tring to find a Connection between the function $\omega$ and the number of holes of arbitrary Dimension $N$. I am assuming that the "solid Body" (more mathematically: manifold) is distributed over the whole space and has no boundary. If $y$ is a cell which is empty and $y+z$ (the neighboring cell) is also empty with $z$ is a vector with one entry $1$ and Zeros elsewhere then cell $y$ belongs to the same hole as $y+z$. Is it possible to find an Expression $N(\omega)$?
Attempt:
I am trying to Count the number of holes by summing over the whole discrete space. Assuming that the holes are only single isolated point defects it holds clearly: $N= \sum_{i_1,\dots,i_d=0}^\infty (1-\omega(i_1,\dots,i_d))$. If there are more General holes then I think I can use also the Summation. However it must be distinguished whether an empty cell has also empty neighbor cells. The product $(1-\omega(y))(1-\omega(y+z))$ is $1$ if $y$ AND $y+z$ are empty cells and $0$ otherwise. These products (and also higher products for more General distinguishing whether multiple cells are ALL empty) must be involved in the sum over the whole disrete space. Also I think that prefactors must be introduced to absorb cells that are counted multiple times (e.g. $\frac{1}{2}$ absorbs cells that are counted twice). But here I am stuck. Any hints would be greatly appreciated.
Comment: Are you assuming that $\omega(x)=0$ for only finitely many $x$? (Otherwise there could be infinitely many "holes".) Also you start out with dimension $d$ (number of coordinates of each point $x$) and later ask about the number of holes of dimension $N.$ Is the dimension of a hole just another term for the number of cells in that hole?
Comment: I am assuming finitely many holes (I have assumed infinit because the manifold should have no boundary). The Dimension $d$ means that one has a grid in $d$ spatial dimensions; a $d$-dimensional space is subdivided into $d$-dimensional lattices.
Answer: The key for solving this Problem is the inclusion-exclusion principle.
Considering a hole in the discrete grid, one can pick a cell of the hole. If the neighbor cells are also in the hole, the neighbors of the neighbor cell can be examined. Here also neighboring cells can belong to the hole. This procedure can be iterated arbitraryly.
Abbreviation: $\sigma(x) = 1- \omega(x)$.
As a simple example one can consider holes that are built up of 2 cells in Maximum. Then, the Expression obtained by the inclusion-exclusion rule $|A \cup B|=|A|+|B|-|A \cap B|$ can be expressed as: $\sigma(y)+\sigma(y+z)-\sigma(y)\sigma(y+z) = \sum_{x \in Hole}(\sigma(x)-\frac{1}{2} \sigma(x)\sigma(x+z(x)))$ ($z$ is the neighborhood function). For only a single cell hole this Expression is also true since $\sigma(y)\sigma(y+z)=0$. The factor $\frac{1}{2}$ arises because the same Expression appears twice when Summation is performed.
Now the General case can be derived analogously by the inclusion-exclusion formula:
$|\cup_{i=1}^n A_i| = \sum_{i=1}^n (-1)^{i+1}|A_{\tau(1)} \cap A_{\tau(2)} \cap \dots \cap A_{\tau(i)}|$.
All caps are equivalent to the Logical Operator AND. By regarding nested neighborhoods, the above formula can be used. Hence:
$\sigma(y) + \sigma(y+z(y)) + \dots + \sigma(y+z(...(z(y)))) - higher-orders$.
Also there can be introduced Summation over the whole hole and symmetry factors for the higher orders.
Am I on the right way? (I will highly appreciate every comments!)


add to variable on radio button click php

Question: i've got the following radio buttons in a form
<input type="radio" name="shipping" value="Shipping($30)">Express Shipping($30)
<input type="radio" name="shipping" value="Shipping($15)">Regular Shipping($15)
<input type="radio" name="shipping" value="Shipping(Free)">Free Shipping

and the variables
$totalNoShip;
$totalWithShip;

The totalNoShip variable holds the total before shipping.
I want the variable totalWithShip to be updated when one of the radio buttons is clicked.
once this is done I want to print the variable in a span  final value here
how do i go about doing this?
Answer: Change your HTML to
<input type="radio" name="shipping" value="30">Express Shipping($30)
<input type="radio" name="shipping" value="15">Regular Shipping($15)
<input type="radio" name="shipping" value="0">Free Shipping

<input type="hidden" name="total" value="0">

Then do something with JS like:
$(document).ready(function(){

    $('input[name="shipping"]').click(function(){

        var $mValue = $(this).val();
        $('.finalPrice').text($mValue);
        $('input[name="total"]').val($mValue);

    });
});

Then after you POST, Validate your total to see if it is related to the selected Shipping type


Is it possible to dynamically adjust the priority of outgoing emails?

Question: This is more of a theoretical question, but is it possible to dynamically, and on an ongoing basis, adjust the priority of emails in the mail queue?
For example, for all mail, set it's priority (p) to 1 (meaning send immediately). If N emails in the last M share similar or identical content, adjust the priority of this email such that it's priority is in the range [0..1] so that p is equal to 1 - N/M and other email can get sent before the similar/identical stuff.
Or, if you have another idea or standard what is it?
Some background: Someone put a mail() call in an infinite loop... And now we have to wait for the mail queue to catch up before anyone can send or receive mail again.
Answer: With exim you can use the -Mf <id> <id>... option to freeze messages. Which MTA are you using?


Redux variable considered null yet appears in console

Question: I am trying to render a homepage depending on user being connected or not.
App.js
  const user = useSelector(selectUser);

    {!user ? <Login></Login> : (

      <Sidebar></Sidebar>
      <Feed></Feed>
      <Widget></Widget>

  )}

userSlice.js
import { createSlice } from '@reduxjs/toolkit';

export const userSlice = createSlice({
  name: 'user',
  initialState: {
    user: null
  },
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
});
export const { login, logout } = userSlice.actions;

export const selectUser = (state) => state.user;

export default userSlice.reducer;

Login.js
function Login() {
const dispatch = useDispatch()

const loginToApp = (e) => {
e.preventDefault();

auth.signInWithEmailAndPassword(email, password).then(userAuth => {
    dispatch(
        login({
            email: userAuth.user.email,
            uid: userAuth.user.uid,
            displayName: userAuth.user.displayName,
            photoUrl: userAuth.user.photoURL,
        })
    )
}).catch(error => alert(error))
}

Though <Login></Login> is always being rendered, even if user is not null, I don't understand as in the redux console, user is not null.
Comment: I removed the angular tag..
Comment: Please share how you're extracting `user` out of the Redux state.
Comment: I've edited my original post, is this what you expected me to show ? ty
Answer: Your screenshot only includes the render part and the problem might not be render, I think. It must be related to the logic. For example, you might defined user as a state and use it.
To get help, I think you should check the part and show them, too.
Answer: Well, not really sure about this. I think the problem is here.
export const selectUser = (state) => state.user;

According to official document you need to use createSelector.
So it should try like this.
export const selectUser = createSelector(
  (state) => state.user
)
...
const user = useSelector(selectUser);

Answer: Ok, my store name was wrong because I've npx created it with redux template and haven't changed store name from counter to user.
import { configureStore } from '@reduxjs/toolkit';
import userReducer from '../features/userSlice';

export const store = configureStore({
  reducer: {
    user: userReducer,
  },
});

It all works now.


Solution to this error

Question: I have written this query:
String sql = "Update db " +
"SET LName = '"+txtLName.getText()+"'," +
"ATC_Code = '"+txtATCcode.getText()+"'," +
"ATC_Name= '"+txtATCname.getText()+"'," +
"Course_Name =  '"+txtCourseName.getText()+"'," +
"Course_Fee = '"+txtCourseFee.getText()+"'," +
"Where FName = '"+txtFName.getText()+"' ";

And I got an error like:
Malformed SQL Statement: Expected ',', found 'Anuja'`.
Statement:Update db SET LName = 'df',ATC_Code = '323',ATC_Name= 'sd',Course_Name =  'd',Course_Fee = '534',Where FName = 'Anuja'

Comment: Can't you show us just the SQL statement? (Much easier to find the problem that way!)
Comment: Please `edit` your `question` title to some `meaningful` title
Answer: Remove last , for Set statement:
String sql = "Update db " +
   "SET LName = '"+txtLName.getText()+"'," +
   "ATC_Code = '"+txtATCcode.getText()+"'," +
   "ATC_Name= '"+txtATCname.getText()+"'," +
   "Course_Name =  '"+txtCourseName.getText()+"'," +
   "Course_Fee = '"+txtCourseFee.getText() + //here does not need '
   "Where FName = '"+txtFName.getText()+"' ";

On a side note, this kind of sql command generation(concatenating strings that contains some values) are suspect to SQL injection attacks, to prevent this type of attacks, use paramaters and set the parameters values instead. See SQL injection for more information.
Answer: Update db
SET LName = 'df',
    ATC_Code = '323',
    ATC_Name= 'sd',
    Course_Name =  'd',
    Course_Fee = '534',
Where FName = 'Anuja'

Only will change remove last comma ','
Update db
SET LName = 'df',
    ATC_Code = '323',
    ATC_Name= 'sd',
    Course_Name =  'd',
    Course_Fee = '534'
Where FName = 'Anuja'

Solution to this error


How do I install missing drivers in the Recovery Console?

Question: I'm testing a backup to a bare metal restore.  The new hardware doesn't have PS2 Mice/Keyboard and needs USB drivers: I can't log into any of the Safe Modes.
I can however, put the original SBS2003 install disks in the machine and jump into Recovery Console.
How do I go about installing board Chip Set drivers and USB drivers?  Is it a simple copy?  If so, what to where?
Comment: You can probably bypass the issue by looking in the system's BIOS and enabling 'USB Legacy Mode'. This may get the keyboard & mouse working in Windows without the drivers.
Comment: that would be on the first menu of the bios as soon as you tap f2 on the intel series to get ot the bios, it is about mid way on the page.
Comment: @dasko: How did you know it was an intel board? ;)
Answer: http://kb.acronis.com/content/8814
Answer: You don't need USB drivers for keyboard and mouse support in SBS2003 or in Windows Server 2003. What happens when you restore the image to the new hardware? Do you ever get the CTRL+ALT+DEL prompt? Does the mouse or keyboard ever intialize?
Comment: In addition the the article that dasko posted, have a look here: http://support.microsoft.com/kb/314634
Comment: Wow, that's a bold statement.  If I stick a live CD in, the mouse and keyboard work perfectly.  Yes, the login dialog comes up, and no they don't initialize.  I see your logic, couldn't be the drivers.
Comment: The link would be useful if the devices in question weren't a keyboard and mouse.
Comment: So your problem is not with a USB mouse or keyboard? How did I miss that? How is my statement bold? W2K3 requires no driver installation for USB mice and keyboards. I thought that was common knowledge. Sorry for being so bold, I guess the boldness of my answer was too much for someone here and they deemed it worthy of a downvote. "Sigh".


Microsoft SQL server backup : restoring data to one table

Question: Is there an easier way to restore data to single table in an MSSQL server, rather taking down the database and restoring the entire database?
Answer: You can restore the database from the backup file to another database name on the same server, or different server, then copy the data over.
If the database was Northwind, something like:
<code>RESTORE DATABASE NorthwindTemporary
FROM DISK="D:\Backups\NorthwindBackup.bak"
WITH MOVE 'Northwind_Log' TO 'D:\SQL\NorthwindTemporary.ldf',
     MOVE 'Northwind_Data' TO 'D:\SQL\NorthwindTemporary.mdf'
</code>
StackOverflow: How do I restore a single table from a SQL Server 2005 backup?
Answer: There is a third party product, LiteSpeed for SQL Server, which offers this capability of object and even row-level recovery.
Comment: If your running SQL 2005 or earlier lightspeed will also compress your backups very nicely. its a great product
Answer: SQL Server cannot do table-level backups or restores, although you can backup and restore files within a database if you want to
You're best bet is probably to restore the entire backup as a temporary database, and then copy the data you need over to the main database.
Tools like RedGate's SQL Data Compare are good for synchronising data.
Answer: A better option would be to Generate Scripts from the first original database, and choose 1 table, and Script Data. Then execute this script on your database (where you wish to restore just 1 table).
If you don't have access to the original database, then restore the backup to a new database, create the Generate Scripts.. script from there, and then remove the new database.


Contemporary Music note group Notation

Question: I am writing an article about Stockhausen's Plus-Minus and I wanted to take this chance to write some snippets in LilyPond. Is there anyone willing to help me to transcribe this image?

This is what I managed to achieve until now:
\version "2.24.1"
\paper { top-margin = 20\mm}
\language italiano

\score {
    \new PianoStaff  = "Subsidiary Notes"  {<<
        \new Staff {
            \clef "treble"
            \autoBeamOff
            \stemUp
            \override Stem.length = 15
            \relative {
                << sold''4 la>>
                s8
                <<
                    \once \override Stem.length = 20
                    \single \override Stem.X-offset = #-2
                    \single \override NoteHead.X-offset = #-3
                    lad,4
                    \single \override NoteHead.X-offset = #-2
                    si
                >>
                <<
                    \once \override Stem.length = 17
                    \single \override Stem.X-offset = #-15
                    \single \override NoteHead.X-offset = #-16
                    re
                    \single \override Stem.X-offset = #-15
                    \single \override NoteHead.X-offset = #-15
                    mib
                >>
                \once \override Stem.length = 10
                \once \override NoteHead.no-ledgers = ##t
                \once \override NoteHead.transparent = ##t
                \once \override Stem.X-offset = #-27
                \once \override Flag.stroke-style = #"grace"
                do''''8

            }
        }
        \new Staff {
            \autoBeamOff
            \override Stem.length = 45
            \clef "bass"
            s16
            \once \override Stem.length = 50 \crossStaff<<fad,,4 sol,,>>
            \crossStaff<<
                \once \override Stem.X-offset = #-4
                \single \override NoteHead.X-offset = #-5
                red,
                \single \override NoteHead.X-offset = #-4
                mi,
                >>
        }
    >>}
    \layout {
        \context {
            \Score
            \override SpacingSpanner.spacing-increment = 5
            \consists #Span_stem_engraver
        }
    }
}

which gives this result:

I am a new LilyPond user so, I hope that it is not to messy. I guess there is a way to templating all these \overrides and to be more congruent in the use of \single and \once.
EDIT:
Probably another approach would be using 1/8th notes and creating a stencil for the beam. This does look way tidier indeed:
\new PianoStaff  = "Subsidiary Notes"  {
        \time 5/8
        <<
        \new Staff = "high" {
            \clef "treble"
               \override Beam.positions = #'(9 . 9)
            \relative {
                <sold'' la>8^[
                \change Staff = "low"
                <fad,,,, sol>
                <red' mi>
                \change Staff = "high"
                <lad''' si>
                <re mib>]
            }
            \revert Beam.positions
        }
        \new Staff = "low" {
            \clef "bass"
            s2
            s8
        }
        >>
    }

UPDATE:
Well I managed to come up with a solution for the Beam!
First I set it higher than the default one and the a make it invisible:
% inside Staff = "high"
\override Beam.positions = #'(9 . 9)
\override Beam.transparent = ##t

then at the end of the note group I draw the lines using a a customized \markup statement that I called samplePath:
% outside the score
samplePath =
    #'(
        (moveto -13.45 6.4)
        (lineto -6 8)
        (moveto -10.95 6.4)
        (lineto -6 8)
        (moveto -6.35 6.4)
        (lineto -6 8)
        (moveto -2.96 6.4)
        (lineto -6 8)
        (moveto 1.25 6.4)
        (lineto -6 8)
        )
...
% the last chord of the group inside the Staff = "high"
<re mib>]^\markup \path #0.1 #samplePath

and I get this:

How would I position the slashed grace note flag above the line? I have been looking into the glyphs but there is no such symbol and I couldn't even align it properly. Maybe an image of it? But how would I position it correctly? Placing it in the next bar does and adding an negative X-offset does not work because it moves the lines.
NOTE:
It would be great to keep the \time 5/8 so that I could even generate a correct MIDI file out of it
Comment: This is the "4"th of 6 groups of what Stockhausen in this score calls "Accidental Notes". They are not supposed to be played as written, but rather to be used for composing a "possible version" of the score. The rules of _Plus-Minus_ are quite complex. To simplify: there are 7 pages of simbols and seven pages of notes. The symbols indicate how to use these "Accidentals Notes" in combination of the rest of the provided material. [This article](https://stockhausenspace.blogspot.com/2015/06/plus-minus.html) gives a more detailed analysis of the piece
Comment: What does this notation mean?  What is the "4" for? Are all these notes meant to be played at the same time or not?
Answer: A general proof of concept of how this could be done:
#(define (grob-extent2 grob ref axis just dir)
   (let* ((cref (ly:grob-common-refpoint grob ref axis))
          (ext (ly:grob-extent grob cref axis))
          (rext (ly:grob-extent ref cref axis))
          (rext2 (ly:grob-extent ref (ly:grob-parent ref axis) axis))
          (just (/ (1+ just) 2))
          (justv1 (+ (* just (cdr rext)) (* (- 1 just) (car rext))))
          (justv2 (if (= dir UP) (car rext2) (cdr rext2)))
          (justv (- justv2 justv1)))
     (cons (+ (car ext) justv) (+ (cdr ext) justv))))

#(define (stem-alignment stem-expr)
   (if (equal? (car stem-expr) 'translate-stencil)
       (let ((offset (list-ref stem-expr 1))
             (align (stem-alignment (list-ref stem-expr 2))))
         (if align
             (+ (car offset) align)
             align))
       (if (equal? (car stem-expr) 'combine-stencil)
           (let ((align (filter (lambda (x) x) (map stem-alignment (cdr stem-expr)))))
             (if (null? align) #f (car align)))
           (if (and (equal? (car stem-expr) 'grob-cause)
                    (member 'stem-interface (ly:grob-interfaces (list-ref stem-expr 1))))
               0
               #f))))

{
  \override Beam.after-line-breaking =
  #(lambda (grob)
     (let* ((stems (ly:grob-array->list (ly:grob-object grob 'stems)))
            (dir (ly:grob-property (car stems) 'direction))
            (exts-x (map (lambda (stem) (grob-extent2 stem grob X LEFT RIGHT)) stems))
            (exts-y (map (lambda (stem) (grob-extent2 stem grob Y CENTER dir)) stems))
            (cy (map (lambda (ext) (if (= DOWN dir) (car ext) (cdr ext))) exts-y))
            (cx (map interval-center exts-x))
            (lx (map interval-length exts-x))
            (bx (/ (+ (first cx) (last cx)) 2))
            (by (+ (/ (apply + cy) (length cy)) (* 0.5 dir)))
            (lines (map (lambda (x y w) (make-line-stencil w x y bx by)) cx cy lx))
            (stem (grob-interpret-markup grob #{
              \markup \rhythm { \omit NoteHead \override Stem.direction = #dir \slashedGrace c8 }
                                         #}))
            (stem (ly:make-stencil (ly:stencil-expr stem) (stencil-true-extent stem X) (stencil-true-extent stem Y)))
            (stem (ly:stencil-translate-axis stem (- ( stem-alignment (ly:stencil-expr stem))) X))
            (stem (ly:stencil-aligned-to stem Y (- dir)))
            (stem (ly:stencil-translate stem (cons bx by))))
       (ly:grob-set-property! grob 'stencil (apply ly:stencil-add stem lines))))
  g'8 c' e' g'
  c'' e'' f'' c''
}

Contemporary Music note group Notation


Can I add a template preprocessor that's more specific than an existing hook?

Question: I have a preprocessor function in my model that runs on the views_view_table hook. I want it to be called only for a specific view. If it were a hook, rather than a preprocessor, I could use, for example views_view_table__myview. Can I do that with just the preprocessor, too, or do I have to register a matching hook? If so, how do I make sure it does exactly what the base hook does?
Comment: No hook is called `view_table`, so it's difficult to understand your question. Anyway, no Views hook is named after the views created, so you have to test the view object properties to know what view a hook is executing on.
Answer: For the Views module, if you want to know its template file suggestions:

Open edit for your view
Click on 'Theme information'
Use whichever template name that meets requirements
Go back to your view and, at the bottom of 'Theme information', click 'Rescan template files'
Your template file should be highlighted in this list


How can a musician determine the sound of different musical artists?

Question: To be more specific about my question; I am currently trying to learn how to best identify the specific sounds of different jazz artists by listening for quantifiable differences in their style and sound. For my purposes I have limited myself to solo pieces with artists strictly using the piano as an instrument. This should help to make the monstrous task at least somewhat easier.
I am quite new to music theory and would appreciate any advice I can get as to what musicians listen for in different artists to identify the "sound" of the artist.
Answer: This is a very wide topic, but think about how you would approach recordings of two of your favourite jazz pianists.

Do they have some favourite runs or chord sequences that crop up again and again?
How do they handle the beat? Tight, or loose? Always ahead of the 3rd beat in a bar?
How about volume, and sustain? Do they generally approach runs in a smooth legato style, or maybe they like a staccato descending run.

You see what I mean? These are just a tiny selection of identifiable traits.
Once you listen to a lot of a particular artist's work, you will start to see sections that stand out as being recognisably theirs.
Comment: Also favorite chord voicings.
Answer: Your question is a good one, but I think you can go about it in a slightly different way and end up with much more meaningful results.
If we acontextually (that is, away from the music itself) try to compile a list of various musical traits, it will never be complete and it will never be specific enough. So instead of trying to list musical traits and then trying to map them onto particular performers, I recommend starting with the performers themselves.
Start small, with a single album from a single performer. Learn it (from an aural standpoint) inside and out. Once you've done this, try to describe general trends in what you hear.
Then, find another album from the same performer from around the same time period, and do the same thing. Now ask yourself: what traits are consistent between albums? (That is, "what traits can you start to say are consistent within this performer?") What traits are different between albums?
Next, find an album from the same performer that was made 30 years after the previous two. What changes can you determine within this single performer? (Almost every great artist changes throughout their career.)
Then go on to other albums from other artists, slowly building up a repertoire of general trends, and soon you'll be able to compare and contrast various styles, composers, performers, etc.
This approach will certainly take more time, but there is one major advantage compared to us listing off some general ideas and you trying to match them with performers: Going with the latter approach, I worry you're more likely to miss major innovations that some performers bring to the table, and your understanding of these styles will correspondingly be a little limited. But when you start with the music itself, in my opinion you'll much more easily spot innovations when they do appear.

To give a stupid example: I want to compare and contrast forms of transportation. I ask for traits to look for, and someone says "number of wheels." By this strategy, I might not recognize what an innovation the first airplanes were compared to the tricycle, or what an innovation the Model T was compared to a horse-pulled wagon. But if I were to start with the modes of transportation themselves, these innovations are impossible to miss.
It's a silly example, but my worry is that the "list of traits" potentially creates some tunnel vision that will blind you to some of the really important features.
This way takes more time, but I think the outcome is far better.


Do sub classes need to implement Interfaces?

Question: This is more of an understanding question.I have an Interface called InterExe1 and it has 2 methods-print1(), print2().
This interface is implemented by a super class-Worker
 public class Worker implements InterExe1

and then I also have 2 subclasses inheriting from the Worker class and also implementing the interface
Public class DayWorker extends Worker implements InterExe1
Public class nightWorker extends Worker implements InterExe1

If the interface is already implemented through the super class do I need to implement it individually through the subclasses as well because I wrote they implement it? I'm not sure because technically they inherit all methods in Worker and Worker implements the Interface, Does it actually make a difference if I wrote in the subclasses that they implement the interface or not what is the difference if I didnt write it? I tried to make these classes and when I didn't implement the Worker class it showed an error-compile error before running it and but it still didn't require me to implement the subclasses although they would have no implementation of the interface. Do you know why?When I did implement only the super class it showed no error  at all.I would be very grateful if you could help I have test on it today and I need to understand the logic.
Answer:
If the interface is already implemented through the super class do I need to implement it individually through the subclasses as well because I wrote they implement it?

No

I'm not sure because technically they inherit all methods in Worker and Worker implements the Interface, Does it actually make a difference if I wrote in the subclasses that they implement the interface or not what is the difference if I didnt write it?

No. Apart from it's redundant

I tried to make these classes and when I didn't implement the Worker class it showed an error-compile error before running it and but it still didn't require me to implement the subclasses although they would have no implementation of the interface. Do you know why?

If a class implements an interface, it has to implement all the methods. If you have implemented in Worker, your subclass inherits there methods from parent class.

To be honest, try IntelliJ Community version, you can easily see the answer.
Per Effective Java, I believe your Worker should be an abstract class. You will find it's very useful.
Answer: You don't need to implement it in the sub-class (derived class).
The derived class inherits all the implementations of the base class, and can override any of the virtual implementations.


Server structure for webapp + db + memcached

Question: I've been checking around but I still have doubts on how to proceed, that's why I'm adding this question.
I want to deploy a number of small (very low usage) apps written in Play Framework to my servers. The stack would be: nginx + play framework servers (one epr app) + mysql + memcached
Although each application has low usage, there are several of them (so the usage piles up) and the idea is to add many more in the few next months.
Memcache should not store too many objects, as the content users see is not personalized in most cases (so a few objects would serve many many users)
What would you recommend and why:
- Everything in one vps box
- 1 vps box for nginx + play servers + mysql and another (smaller) for memcache
- 1 box for nginx + play, 1 for mysql and 1 for memcache
- Another
As a note, optimizing the budget is relevant but I do't have any problem on spending extra bucks in one (relatively cheap) extra box if the gains are significant.
Answer: It all depends on exactly how "low usage" your low usage apps will be, how much resources each app will take up when quiescent, and how big a box you want to get.
I'd be inclined to start with everything in one box, but make sure everything is properly loosely coupled to allow easy separation of services (service CNAMEs for everything, that sort of thing) when/if demand picks up or you realise you underestimated how much resources things would need.


Objects changed rotation jumps to it's original Unity3D

Question: I made input joysticks for mobile game. One that moves the player and other one that changes it's rotation. Both are working fine but only problem is that when I change players rotation and release that joystick it jumps to it's original rotation. Here's my script:
public GameObject player;
private PlayerInput playerInput;

void Update()
{
    Vector2 input = playerInput.actions["Move"].ReadValue<Vector2>();
    Vector3 move = new Vector3(input.x, input.y, 0);
    player.transform.position += move * speed * Time.deltaTime;

    Vector2 look = playerInput.actions["Look"].ReadValue<Vector2>();
    player.transform.rotation = Quaternion.LookRotation(Vector3.forward, look);
}

Comment: Please put a picture of the problem and explain how you want it to be.
Answer: I typically solve this by ignoring rotation values of small magnitude and maintaining the last frame's orientation in said case. You might have to tune the threshold below to filter out the correct values.
public GameObject player;
private PlayerInput playerInput;
private Vector2 look;

void Update()
{
    Vector2 input = playerInput.actions["Move"].ReadValue<Vector2>();
    Vector3 move = new Vector3(input.x, input.y, 0);
    player.transform.position += move * speed * Time.deltaTime;

    var inputLook = playerInput.actions["Look"].ReadValue<Vector2>();
    look = inputLook.magnitude > 0.1f ? inputLook : look;
    player.transform.rotation = Quaternion.LookRotation(Vector3.forward, look);
}


#2002 - No connection could be made

Question: MySQL said: Documentation
2002 - No connection could be made because the target machine actively refused it.
The server is not responding (or the local server's socket is not correctly configured).
help me to solve this...
Comment: possible duplicate of [mysql\_connect(): No connection could be made because the target machine actively refused it](http://stackoverflow.com/questions/21987746/mysql-connect-no-connection-could-be-made-because-the-target-machine-actively)
Comment: Did the answer make some sense to you!!?
Answer: This can occur when connecting using HTTP-tunneling to a MySQL server running on Unix/Linux platforms.
If the directory /var/lib/mysql doesn't exist than create it and chown to user mysql:
<code>"mkdir /var/lib/mysql; chown mysql /var/lib/mysql"
</code>
Then edit the /etc/my.cnf file and specify
<code>[mysqld]
socket=/var/lib/mysql/mysql.socket
[client]
socket=/var/lib/mysql/mysql.socket
</code>
and restart the mysql server ("etc/init.d/mysql restart")
That is enough for MysSQL. However the chances are that php was compiled with a different default mysql socket location (e.g. /tmp/mysql.sock). In which case you have to edit the php.ini file and find the variable "mysql.default_socket". Set this to the above value
<code>mysql.default_socket = /var/lib/mysql/mysql.socket
</code>
and restart Apache to re-read the php.ini file.

#2002 - No connection could be made


A continuous and integrable function has its maximum?

Question: As the title says, $f \in C(\mathbb{R}^n)\cap L^1(\mathbb{R}^n)$, then $f \in L^{\infty}(\mathbb{R}^n)$?
I think it's true, but struggling to prove it. I'd appreciate any help. Thank you.
Comment: Take a function that is zero everywhere except that it has, as you move to infinity, ever increasing bumps that get taller and taller, but narrower too, and they get narrower way faster than they get taller, in such a way that the area of the $n$-th bump is $1/2^n$.
Comment: @conditionalMethod Yes, right... Thank you very much!
Answer: For an explicit construction of the type of function suggested in the comment above take $n=1$ and  $f(x)=\sum_k I_{(k-\frac 1 {k^{3}},k+\frac 1 {k^{3}}) }(x) (k^{4}|x-k|-k)$. This function is continuous and integrable but $|f(k)|=k \to \infty$.
Answer: Counterexample that's easy to write down:
$$f(x) = x\left ( \dfrac{2+\sin x}{3} \right )^{x^5},$$
although it requires some work to verify.


Groups with transitive automorphisms

Question: Let $G$ be a finite group such that for each $a,b \in G \setminus \{e\}$ there is an automorphism $\phi:G \rightarrow G$ with $\phi(a)=b$. Prove that $G$ is isomorphic to $\Bbb Z_p^n$ for some prime $p$ and natural number $n$.
Comment: @user1729 no, not every element need to be a generator.
Comment: First hint: Every element has to be a generator for the group. Also, the automorphisms are transitive. What does this tell you about the order of the elements?
Comment: A good first step would be to show that the groups $\mathbb{Z}_p^n$ have the property in the statement of the question.
Comment: @Tobias: Well, okay, every *non-trivial* element. But that was implicit!
Comment: The non-trivial element (1,0) doesn't generate the group $\mathbb{Z}_2^2$. Infact, $\mathbb{Z}_p^n$ is only generated by a single element if $n=1$.
Comment: @DanielRust: It does generate the group. It generates it along with any other non-trivial element. A generator is an element which can be used to generate the group (as part of a minimal generating set). I do not mean that the group is cyclic.
Comment: @user1729 I have never before seen the term generate used that way. I have seen the term non-generator to refer to an element that can always be removed from a generating set, but calling a non-non-generator a generator seems like a bad idea.
Comment: @Tobias: You're right. However, I did not spend overly long composing my hint, and I believe I still got the point across, nit-picking aside! Also, the term "generator of a group" is used in presentations to mean an element which is part of a given generating set, which is what I am most familiar with, and what I was meaning (although that can be nit-picked about too).
Answer: Hint 1: If $a, b \in G \setminus \{e\}$, then $a$ and $b$ have the same order.
Hint 2: Using the previous hint, show that $G$ has order $p^n$ for some prime $p$ and that every nonidentity element has order $p$.
Hint 3: In a $p$-group, the center is a nontrivial characteristic subgroup.

Groups with transitive automorphisms


Computing using residue $\int_{0}^{\infty}e^{-x^{2}}\cos(x^{2})\mathrm{d}x$ (but not Gaussian way)

Question: I am wondering if there is a residue-trick for computing  $\int_{0}^{\infty}e^{-x^{2}}\cos(x^{2})\mathrm{d}x$ without having to go through computing the Gaussian residue integral.
For practice here is the Gaussian way, any corrections are appreciated. We will prove $\int_{\mathbb{R}} e^{-x^{2}c}\mathrm{d}x=\sqrt{\frac{\pi }{c}}$ with $\text{Re}(c)>0$.
Step 1
Following the same procedure as in http://www.math.uconn.edu/~kconrad/blurbs/analysis/gaussianintegral.pdf
we need a $\tau$ so $e^{2\tau^{2}c}=1$ to ensure $d(0)=d(\tau)$ and thus $f(z)-f(z+\tau)=e^{-z^{2}c}$. Thus, $$\tau=\sqrt{\frac{\pi }{2c}}(1+i).$$
So $e^{-\tau^{2}c}=-1$ and thus $f(z)=\dfrac{e^{-z^{2}c}}{1+e^{-2c\tau z}}$.
Step 2
Because $\tau=\sqrt{\frac{\pi }{2c}}(1+i)=\sqrt{\frac{\pi}{r}}\cos(\frac{\pi }{4}-\frac{\theta}{2})+i\sqrt{\frac{\pi}{r}}\sin(\frac{\pi }{4}-\frac{\theta}{2})$,
where $c=re^{i\theta}$, for the contour we choose height $ib=i\sqrt{\frac{\pi}{r}}\sin(\frac{\pi }{4}-\frac{\theta}{2})$. Then the pole $\frac{\tau}{2}$ is inside it.
Step 3
The residue yields
$$\int_{\text{Rectangle}} \dfrac{e^{-z^{2}c}}{1+e^{-2c\tau z}}\mathrm{d}z=2\pi i \lim_{z\to \frac{\tau}{2}} \dfrac{e^{-z^{2}c}}{(-2c\tau)e^{-2c\tau z}}=\sqrt{\frac{\pi }{c}},$$
which is what we expected.
Step 4
On the other hand,
$$\int_{\mathbb{R}} f(x)\mathrm{d}x-\int_{-\infty+ib}^{\infty+ib}f(z)\mathrm{d}z=\int_{\mathbb{R}} f(x)\mathrm{d}x-\int_{-\infty}^{\infty}f(x+ib)\mathrm{d}x$$
by rewriting $ib=\tau-\text{Re}(\tau)$ and translating we obtain
$$=\int_{\mathbb{R}} f(x)\mathrm{d}x-\int_{-\infty}^{\infty}f(x+\tau)\mathrm{d}x=\int e^{-x^{2}c}\mathrm{d}x.$$
Therefore, in our case $c=1\pm i$ and in turn
$$\int_{0}^{\infty}e^{-x^{2}}\cos(x^{2})\mathrm{d}x=\frac{1}{4}\left(\sqrt{\frac{\pi }{1+i}}+\sqrt{\frac{\pi }{1-i}})=\frac{\sqrt{\pi}}{2\sqrt[4]{2}}(\cos\left(\frac{\pi}{8}\right)\right).$$
Answer: A way simpler approach:
$$ \int_{0}^{+\infty}e^{-x^2}\cos(x^2)\,dx = \text{Re}\int_{0}^{+\infty}e^{(i-1)x^2}\,dx =\text{Re}\left(\frac{\sqrt{\pi}}{2\sqrt{1-i}}\right).$$
$\cos\frac{\pi}{8}=\frac{1}{2}\sqrt{2+\sqrt{2}}$ appears since $1-i=\sqrt{2}\cdot e^{-\pi i/4}$.
Comment: not really, you assumed what I proved. My question is silly because a simpler way, would imply a simpler way for computing the Gaussian integral.


Different density-functions in different books for Exp(a), why?

Question: This is more of a theoretical question, that I hope someone is willing to explain to me.
I have noticed that the density function for the exponential distribution looks different in two of my books.
For Exp(a), why are these two expressions the same (?)?
$$
f_X(x)=ae^{-ax}  \quad\text{and}\quad     f_X(x)=\frac{1}{a}e^{-x/a}
$$
Comment: In the equation on the left, $a$ represents a "rate" and in the equation on the right, $a$ represents and "expected duration". This is really well explained [here](https://en.wikipedia.org/wiki/Exponential_distribution).
Answer: They aren't the same. They are two different commonly used parameterizations of the exponential distribution. One uses the mean as the parameter, and the other uses the rate, which is 1/mean.
Wikipedia, especially the section on "Alternative Parameterization" gives some background.
You simply need to be careful which parameterization you (and your software) are using.


Creating a global delegate class inside AppDelegate

Question: Apologies in advance if the Question titles is accurate. I have outlined below the basic flow of what I want to achieve.
AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate, SomeFrameworkDelegate, OtherFrameworkDelegate>

…other init stuff

AppDelegate.m

Include the SomeFrameworkDelegate and OtherFrameworkDelegate methods.
These methods mainly output messages such as connected/ disconnected from service.

MainViewController

Do stuff with these delegate methods.
Perform UI actions when connected/ disconnected. etc

DetailsViewController

Use the same stuff as in the MainViewController.

NOTES:

I assume I'd be setting global variables in the AppDelegate, then in the other UI code, I'd be creating an instance of the AppDelegate:
AppDelegate *appDelegate=(AppDelegate *)[[UIApplication sharedApplication]delegate];
appDelegate.isConnected = ...
appDelegate.serviceName = ...

How would I detect when a message arrives to the delegate methods? NSNotificationCenter/ NSTimer?
i.e. post a notification once a delegate method is fired or create a timer to poll the variables in appDelegate.
Comment: Do you mean that; you have some variables in your AppDelegate and you want other classes to be notified when they change value? If so then you probably should use KVC.... otherwise I don't fully understand your question.
Comment: Since you are changing the values in the delegate methods, you can post a notification in there. That way any View controllers that are interested, would all be notified about it.
Answer: It sounds like you're trying to handle/manage a connection in your application delegate. The AppDelegate's purpose is to respond to application level events like applicationdidbecomeactive/applicationwillenterforeground. My recommendation is that you create a singleton to manage your connection. This is commonly referred to the sharedInstance pattern. This singleton should implement the managedObject's delegate functions. You have several options after they are implemented.

Key-Value Observing or KVO (http://nshipster.com/key-value-observing/)
NSNotificationCenter (http://nshipster.com/nsnotification-and-nsnotificationcenter/)

In this case, I recommend using NSNotification since you're trying to figure out a connection status change. If you want to be notified of every change to your object's properties, then you should use KVO.
Answer: You've answered your own question really. I would use NSNotificationCenter to post a notification in the delegate method when it is triggered. Then, in your view controller, observe that notification and respond.