Java: Hazelcast : java.io.EOFException: Cannot read 4 bytes

Question: For my web application ,I have 2 instance that I have defined in hazelcast xml. When I start one server, it started properly but when I start second server i am getting following error :

SEVERE: [192.168.1.32]:5701 [dev] [3.5] java.io.EOFException: Cannot
  read 4 bytes! 2015-07-31 18:08:49
  com.hazelcast.nio.serialization.HazelcastSerializationException:
  java.io.EOFException: Cannot read 4 bytes! 2015-07-31 18:08:49    at
  com.hazelcast.nio.serialization.SerializationServiceImpl.handleException(SerializationServiceImpl.java:380)
  2015-07-31 18:08:49   at
  com.hazelcast.nio.serialization.SerializationServiceImpl.toObject(SerializationServiceImpl.java:282)
  2015-07-31 18:08:49   at
  com.hazelcast.spi.impl.NodeEngineImpl.toObject(NodeEngineImpl.java:200)
  2015-07-31 18:08:49   at
  com.hazelcast.spi.impl.operationservice.impl.OperationRunnerImpl.run(OperationRunnerImpl.java:294)
  2015-07-31 18:08:49   at
  com.hazelcast.spi.impl.operationexecutor.classic.OperationThread.processPacket(OperationThread.java:142)
  2015-07-31 18:08:49   at
  com.hazelcast.spi.impl.operationexecutor.classic.OperationThread.process(OperationThread.java:115)
  2015-07-31 18:08:49   at
  com.hazelcast.spi.impl.operationexecutor.classic.OperationThread.doRun(OperationThread.java:101)
  2015-07-31 18:08:49   at
  com.hazelcast.spi.impl.operationexecutor.classic.OperationThread.run(OperationThread.java:76)
  2015-07-31 18:08:49 Caused by: java.io.EOFException: Cannot read 4
  bytes! 2015-07-31 18:08:49    at
  com.hazelcast.nio.serialization.ByteArrayObjectDataInput.checkAvailable(ByteArrayObjectDataInput.java:543)
  2015-07-31 18:08:49   at
  com.hazelcast.nio.serialization.ByteArrayObjectDataInput.readInt(ByteArrayObjectDataInput.java:255)
  2015-07-31 18:08:49   at
  com.hazelcast.nio.serialization.ByteArrayObjectDataInput.readInt(ByteArrayObjectDataInput.java:249)
  2015-07-31 18:08:49   at
  com.hazelcast.cluster.impl.ConfigCheck.readData(ConfigCheck.java:217)
  2015-07-31 18:08:49   at
  com.hazelcast.cluster.impl.JoinMessage.readData(JoinMessage.java:80)
  2015-07-31 18:08:49   at
  com.hazelcast.cluster.impl.operations.MasterDiscoveryOperation.readInternal(MasterDiscoveryOperation.java:46)
  2015-07-31 18:08:49   at
  com.hazelcast.spi.Operation.readData(Operation.java:451) 2015-07-31
  18:08:49  at
  com.hazelcast.nio.serialization.DataSerializer.read(DataSerializer.java:111)
  2015-07-31 18:08:49   at
  com.hazelcast.nio.serialization.DataSerializer.read(DataSerializer.java:39)
  2015-07-31 18:08:49   at
  com.hazelcast.nio.serialization.StreamSerializerAdapter.read(StreamSerializerAdapter.java:41)
  2015-07-31 18:08:49   at
  com.hazelcast.nio.serialization.SerializationServiceImpl.toObject(SerializationServiceImpl.java:276)
  2015-07-31 18:08:49   ... 6 more

Can someone help me?  I am not able to find anything :(
Here is my hazelcast xml:

<code>- no hazelcast.xml if present
</code>
-->

        dev
        dev-pass

    http://localhost:8080/mancenter

        5701

            0

                22.214.171.124
                54327

                192.168.1.67
                192.168.1.75

                my-access-key
                my-secret-key

                us-west-1

                ec2.amazonaws.com

                hazelcast-sg
                type
                hz-nodes

            10.10.1.*

            PBEWithMD5AndDES

            thesalt

            thepass

            19

        16

        0

        0

        1
<code>    <!--
        Number of async backups. 0 means no backup.
    -->
    <async-backup-count>0</async-backup-count>

    <empty-queue-ttl>-1</empty-queue-ttl>
</queue>
 <map name="persistent.*">
    <!--
       Data type that will be used for storing recordMap.
       Possible values:
       BINARY (default): keys and values will be stored as binary data
       OBJECT : values will be stored in their object forms
       NATIVE : values will be stored in non-heap region of JVM
    -->
    <in-memory-format>BINARY</in-memory-format>

    <!--
        Number of backups. If 1 is set as the backup-count for example,
        then all entries of the map will be copied to another JVM for
        fail-safety. 0 means no backup.
    -->
    <backup-count>1</backup-count>
    <!--
        Number of async backups. 0 means no backup.
    -->
    <async-backup-count>0</async-backup-count>
    <!--
        Maximum number of seconds for each entry to stay in the map. Entries that are
        older than <time-to-live-seconds> and not updated for <time-to-live-seconds>
        will get automatically evicted from the map.
        Any integer between 0 and Integer.MAX_VALUE. 0 means infinite. Default is 0.
    -->
    <time-to-live-seconds>0</time-to-live-seconds>
    <!--
        Maximum number of seconds for each entry to stay idle in the map. Entries that are
        idle(not touched) for more than <max-idle-seconds> will get
        automatically evicted from the map. Entry is touched if get, put or containsKey is called.
        Any integer between 0 and Integer.MAX_VALUE. 0 means infinite. Default is 0.
    -->
    <max-idle-seconds>0</max-idle-seconds>
    <!--
        Valid values are:
        NONE (no eviction),
        LRU (Least Recently Used),
        LFU (Least Frequently Used).
        NONE is the default.
    -->
    <eviction-policy>NONE</eviction-policy>
    <!--
        Maximum size of the map. When max size is reached,
        map is evicted based on the policy defined.
        Any integer between 0 and Integer.MAX_VALUE. 0 means
        Integer.MAX_VALUE. Default is 0.
    -->
    <max-size policy="PER_NODE">0</max-size>
    <!--
        When max. size is reached, specified percentage of
        the map will be evicted. Any integer between 0 and 100.
        If 25 is set for example, 25% of the entries will
        get evicted.
    -->
    <eviction-percentage>25</eviction-percentage>
    <!--
        Minimum time in milliseconds which should pass before checking
        if a partition of this map is evictable or not.
        Default value is 100 millis.
    -->
    <min-eviction-check-millis>100</min-eviction-check-millis>
    <!--
        While recovering from split-brain (network partitioning),
        map entries in the small cluster will merge into the bigger cluster
        based on the policy set here. When an entry merge into the
        cluster, there might an existing entry with the same key already.
        Values of these entries might be different for that same key.
        Which value should be set for the key? Conflict is resolved by
        the policy set here. Default policy is PutIfAbsentMapMergePolicy

        There are built-in merge policies such as
        com.hazelcast.map.merge.PassThroughMergePolicy; entry will be overwritten if merging entry exists for the key.
        com.hazelcast.map.merge.PutIfAbsentMapMergePolicy ; entry will be added if the merging entry doesn't exist in the cluster.
        com.hazelcast.map.merge.HigherHitsMapMergePolicy ; entry with the higher hits wins.
        com.hazelcast.map.merge.LatestUpdateMapMergePolicy ; entry with the latest update wins.
    -->
  <merge-policy>com.hazelcast.map.merge.PutIfAbsentMapMergePolicy</merge-policy>
     <map-store enabled="true">
        <factory-class-name>com.adeptia.indigo.services.hazelcast.PersistentMapStoreFactory</factory-class-name>
        <write-delay-seconds>0</write-delay-seconds>
    </map-store>

</map>

<multimap name="default">
    <backup-count>1</backup-count>
    <value-collection-type>SET</value-collection-type>
</multimap>

<list name="default">
    <backup-count>1</backup-count>
</list>

<set name="default">
    <backup-count>1</backup-count>
</set>

<jobtracker name="default">
    <max-thread-size>0</max-thread-size>
    <!-- Queue size 0 means number of partitions * 2 -->
    <queue-size>0</queue-size>
    <retry-count>0</retry-count>
    <chunk-size>1000</chunk-size>
    <communicate-stats>true</communicate-stats>
    <topology-changed-strategy>CANCEL_RUNNING_OPERATION</topology-changed-strategy>
</jobtracker>

<semaphore name="default">
    <initial-permits>0</initial-permits>
    <backup-count>1</backup-count>
    <async-backup-count>0</async-backup-count>
</semaphore>

<reliable-topic name="default">
    <read-batch-size>10</read-batch-size>
    <topic-overload-policy>BLOCK</topic-overload-policy>
    <statistics-enabled>true</statistics-enabled>
</reliable-topic>

<ringbuffer name="default">
    <capacity>10000</capacity>
    <backup-count>1</backup-count>
    <async-backup-count>0</async-backup-count>
    <time-to-live-seconds>30</time-to-live-seconds>
    <in-memory-format>BINARY</in-memory-format>
</ringbuffer>

<serialization>
    <portable-version>0</portable-version>
</serialization>

<services enable-defaults="true"/>
</code>
Answer: I had the same probelm. I tried to store the following data structure into Hazelcast using portables (row and cell are different portable impl.):
row { cell { 'name' : 'cell_0_0', 'value' : 'cell_value_0_0' },
      cell { 'name' : 'cell_0_1', 'value' : 1} },
...
The problem is that for the first cell hazelcast stores for the field name 'value' a field type of UTF, but during the storing of the second cell, hazelcast retrieves stored field definition for the field name 'value' and this was UTF. So the field type is not Int but UTF and during reading of stored portables from map readUTF was used and that caused the exception for me, because stored field value and stored field type do not correspond to each other.
EDIT: In your case after starting the second instance stored objects are exchanged and of course read. Perhaps the problem lies at this point.


What it's the easiest way to add a flash frontpage without alter Views node page?

Question: I'm using Views to render content in frontpage, but now, I want create a single flash presentation page as frontpage that links to the current frontpage.
Answer: Try using Themekey if its a different look and feel altogether... or Frontpage. Although you can create a node and have that node set as the frontpage in the sites configuration page. You have to use jQuery to have the page render the flash in drupal. As for redirection, what you will have to do is create a jQuery or actionscript that gets redirected at the end of the presentation or use the rule module that gets the page redirected after your particular condition is met. That is what I used on a previous project.
Answer: Why not just embed the flash in a normal html page and when the animation finishes have a link at the end that links to your drupal site. I know splash pages are a bit dated now but then again so is having a flash intro.
Answer: Create a block and enable the block on Front Page...
Comment: Sorry, it's not I looking for..
I want a single page that only shows my flash presentation as frontpage, and after flash ends the page go to current/real frontpage.
Comment: You may need to write a Javascript or Action in flash that redirects user to the link once flash is completed... If you don't have access to the flash piece then write a jQuery or Javascript timer to redirect after certain time...
Comment: Yes, I know that, but if I set flash presentation as frontpage in drupal settings, Views doesn't render content in '/nodes'
Comment: You can have only one front page in Drupal Instance that will be treated as "Home" page... You can set a cookie or session to redirect user to flash screen if cookie or session is not set when user is in Home Page.. Set cookie or session after flash presentation and redirect user to Home Page.. That should solve what you are looking for i guess...


Mapear dois arrays e deletar o item não encontrado

Question: Eu tenho uma api em node e estou com a seguinte situação:
Eu sou o usuário master e crio um usuário A  para um funcionário qualquer. Esse usuário A possui as permissões
Permissões usuário A
[criar_usuario,editar_usuario,receber_contas,editar_contas,ver_clientes]
Então, esse usuário A cria um  outro usuário B no sistema com as permissões
Permissões usuário B
[criar_usuario,deletar_usuario,deletar_contas,enviar_sms,excluir_registro]
o que eu quero é mapear as permissões do usuário A e, caso ele crie ou edite o usuário B, o usuário B pode ter as mesmas permissões que o usuário A ou menos, mas nunca ter permissões que o usuário A não tem.
No exemplo acima, o usuário B pode ter:
[criar_usuario,editar_usuario,ver_clientes]
Mas nunca:
[deletar_usuario,receber_contas,editar_clientes,ver_clientes]
Tentei isso
let p = usuarioLogado.permissions; // permissões do usuário logado
let up = req.body.permissoes; // permissões do usuário que será criado ou editado

up.map((o, index) => {
     if (p.indexOf(o) <= -1) {
         up.splice(index, 1)
     }
})

mas não funciona, ficam resquícios das permissões q não podem ser aplicadas
Answer: O método Array.map() aplica uma função em um array e retorna um novo array onde cada elemento deste novo array é o resultado da função aplicada aos elementos do array anterior.
O que você parece estar querendo é utilizar o método Array.filter(), que retornará um novo array contendo apenas os elementos que passarem na "função de teste", ou seja, apenas os elementos cujo retorno da função foi true estarão no array de resultado.
Então para que você garanta que todas as permissões do usuário B estejam contidas nas permissões do usuário A, você pode usar o método Array.includes() para testar se a permissão B está contido nas permissões A.
Exemplo:

let perm_A = [
    "criar_usuario",
    "editar_usuario",
    "receber_contas",
    "editar_contas",
    "ver_clientes"
];

let perm_B_OK = [
    "criar_usuario",
    "editar_usuario",
    "ver_clientes"
];

let perm_B_Errado = [
    "deletar_usuario",
    "receber_contas",
    "editar_clientes",  // Essa permissão não pode
    "ver_clientes"
]

let allowed_perms_OK = perm_B_OK.filter(perm => perm_A.includes(perm));
console.log(allowed_perms_OK);

let allowed_perms_Errado = perm_B_OK.filter(perm => perm_A.includes(perm));
console.log(allowed_perms_Errado);

Se por algum motivo alguém for utilizar estes métodos no navegador, vale lembrar que o método Array.includes() é relativamente recente (ou seja, problemas com IE). Verifique aqui a compatibilidade antes de usar no seu projeto e considere usar Array.indexOf() para garantir a compatibilidade no browser.
Comment: fernandosavio, era exatamente isso. Mto obrigado!!!
Answer: Você pode utilizar  Array.filter e Array.indexOf em conjunto para verificar se as permições do usuário logado p já está em up.
Assim:
let p = usuarioLogado.permissions; // permissões do usuário logado
let up = req.body.permissoes; // permissões do usuário que será criado ou editado

let permissoes_up = p.filter((permicao) => (up.indexOf(permicao) !== -1))

console.log(permissoes_up)

Answer: O erro no seu código está na comparação, acredito que se você trocar o <= por >= irá funcionar, o indexOf retorna a posição do elemento no array quando esse existe e retorna -1 quando não, então quando existir sempre será um valor maior que -1.
Eu fiz da seguinte forma
const usuarioA = ['criar_usuario', 'editar_usuario', 'receber_contas', 'editar_contas', 'ver_clientes']
let usuarioB = ['criar_usuario', 'deletar_usuario', 'deletar_contas', 'enviar_sms', 'excluir_registro']

usuarioB = usuarioB.filter(permissao => usuarioA.indexOf(permissao) !== -1)

Ai é só adaptar para a sua realidade.
Obs: Dei uma pequena refatora me baseando na resposta do outro rapaz.


How do I stop muting nearby strings or will my fingers reshape after some practice?

Question: I recently started learning to play guitar. I cut my nails completely, so I can press the strings. Often I need to endlessly re-arrange my fingers because I'm muting nearby strings. I correct one finger with a lot of effort, but mute some other string. :(
I don't have big fingers or anything; it's just that there is this pointy meaty part (marked in red) on each finger that lays slightly on nearby string. No matter how much I move finger up or try to bend finger away from it, it very soon touches the string.
Will this change if I continue to practice?
Comment: I'd remark that this is substantially easier to get right on classical guitar than on steelstring.
Comment: Something I see in the picture unrelated to your question: make sure you play as close to the fretbar as possible (without touching it) instead of in the middle of the space.
Comment: Use the 3 smallest fingers if you have to play all three notes with a finger each. Otherwise, try using a couple of fingers instead, over the three strings, all adjacent on an open A. Some players only use one finger for all three, and still have the top string sounding open. Almost what you are doing already, but using something bad to make something good!
Comment: @JunJun try to make the fingers as close together as possible. My teacher explains it as making them "hug". If this is hard, make sure your fingers are curved.
Comment: @OldBunny2800 I realized sound is clearer near the fret bar, as you said without touching it. What is a good practice when playing for example A or E major ? there is little space for three fingers to fit in there so each finger gets further from the fret bar.
Comment: I have the same problem! LONG fingers, yet they are too large in the tips! I think it the result of 30+years using KEYBOARDS most of the day!!! the tip is constantly pressed... Now i'm trying to learn guitar and it's very hard to avoid touching the near string! And i'm using a classic guitar!
Answer: You're not going to mutate significantly. In time, you'll learn to place your fingers more precisely.
In some cases, this might mean placing the finger to one side rather than in the middle, because you might not need to worry about fouling the string on one side (e.g. if you're fretting it higher)
Another important thing is to put your fingers close to the fret you're playing. This allows you to press down less hard, which makes the fingers 'squish' less.
You'll also get better at feeling and hearing when you're accidentally muting a string, and be able to correct faster with less conscious thought - so your mistakes will matter less.
You'll also anticipate where you need to put your fingers further into the future, which will help you make fewer mistakes.
Sometimes I even have to 'cheat' a little by bending one string a little away from a potentially interfering finger! It takes a little time to get the co-ordination to do this.
Having said all that, you may well find that your fingers harden up a little, which may help you press a little less hard (which again avoids some of the squishing). It's probably only a tiny effect, but all these factors add up.
Comment: +1 for _press down less hard,_ which is a big part of developing skill with the guitar. Not only will you be able to play more precisely, but you will also pull the strings less out of tune, and you will be able to play more effortlessly.
Comment: "*Sometimes I even have to 'cheat' a little by bending one string a little away from a potentially interfering finger!*" At some point my ear developed enough that if I accidentally bend a string slightly and make the chord out of tune it bothers me, so this technique should be applied sparingly, if at all.
Comment: @ToddWilcox true. Thinking about it a little more, It's probably something I do when I'm lining up for a string bend anyway, and hence a) pressing harder (and more likely to accidentally mute another string) and b) in a musical situation where I've already decided that coming off the note is OK. Not all that uncommon in bluesy soloing situations though!
Answer: To add to Todd and Topo's excellent answers - I will add my voice to assure you that it will get better over time with practice.  I actually have short fat fingers and I have learned to compensate.
In addition to finger placement and angle of attack, the other thing you might need to adjust is your thumb position on the back of the neck.  I find that to cleanly play certain chords without muting strings I am constantly readjusting my thumb position on the back of the neck.  Every chord formation gets its own thumb position.  It will eventually become very intuitive to include the thumb position for certain chords as part of the finger position for that formation.
For example, I know when I play an open E major chord I need to shift my thumb to the treble side of the back of the neck to get my fingers oriented perpendicular to the fretboard.  So while my fingers are forming the correct position in mid air - my wrist is rotating so my thumb can slide closer to the treble side of the neck.  When I play an open D major chord, my thumb is pointed straight up at the ceiling and the tip of my thumb is not even on the back of the neck.  The C chord finds my thumb more parallel with the neck of the guitar.
Try different thumb positions and thumb orientations with the chords that are giving you trouble and you may find that a shift in thumb position or angle might make it easier to get your fingers where they need to be.
Good luck.
Comment: Excellent point mentioning the thumb and wrist.... and of course to get the wrist in the right place, you have to get your elbow in the right place, which can mean getting your strap and posture right.... more of your body goes into it than you might think!
Comment: @topomorto yes it's a whole body experience.  Unless you are one of the YouTube vid tutorial guitarist who play that guitar that is suspended statically in mid air ;-)
Comment: @topomorto Totally agree.  That's why I have learned to use a strap - even if I am sitting on a stool during a live performance.  Otherwise I will constantly be exerting at least a small degree of muscle tension resisting the guitar's proclivity to want to slide down my leg from the sheer force of gravity.
Answer: It will change, but not because your fingers will change, because you'll get better at perfect finger placement. First, your minor finger corrections will come more and more quickly. Then, you'll start to put your fingers in the right place in the first place.
With daily practice, you should have much improved finger placement after 1-2 years. You don't have to wait that long to learn interesting techniques or challenging songs, it just means that at that time your playing will start to sound pretty good in a subtle way.
Answer: I'm skeptical about writing this as a full answer - this is mostly an addition to the excellent answers others have already posted.
As a young and amateur guitarist I had the same issues (obviously). What helped was... cutting my fingernails short.
With shorter fingernails I was able to place my fingers at a better angle without having the nail hit the fret board, and this also means less "squishing" and less accidental muting.
Since I'm a male having short fingernails doesn't concern me at all. That said, I have no idea how do female guitarists manage it (if they want to keep more "feminine" hands). ;)
Comment: Banjo player here, but short fingernails has also been very helpful for me.
Answer: Once I started playing banjo a great deal, my fingertips developed callouses that were significantly harder than my fingertips were before I started playing.  With these callouses, my fingertips don't flatten out as much when pressing against a string.  This does help to keep from muting adjacent strings.
This is not the only thing that helped.  Short fingernails (as mentioned by @Shaamaan) helped.  Good finger placement helped.  Practice was the key to developing all of these things.
Answer: Maybe so obvious that no one says it but make sure your Truss Rod is adjusted correctly so your strings are not too far away from the frets.  If you have to push a string down far the strings next to it is going to be high and easy to touch.


Restringir o __setattr__ quando o atributo não existir dentro da instância em Python

Question: Olá, preciso saber como posso montar uma classe que não possa ter atributos implementados após a instância. Ex:
class Foo(object)

    def __init__(self, a='hello', b='world')
        self.a = a
        self.b = b

    __setattr__(self, key, value)
        if hasattr(self, key):
            super().__setattr__(key, value)
        else:
            pass

Estou tentando criar uma classe como essa mas não funciona porque mesmo eu verificando se o atributo existe na classe a instancia ainda define um novo atributo, ao invés de apenas ignorar...
Answer: Talvez você não precise declarar o __setattr__ -
O modelo de objetos do Python define o atributo especial
__slots__ que, estando declarado numa classe e e em todas
as superclasses, restringe os atributos que os objetos da classe
poderão ter. (https://docs.python.org/3/reference/datamodel.html#slots)
Além da restrição desejada, o atributo __slots__ tem a vantagem de que o Python não precisa criar uma instância de um dicionário para cada instância da classe (essa é sua finalidade principal na verdade) - assim fazendo objetos que teriam o papel de uma pequena estrutura de dados terem um footprint de memória bem reduzido.
class Foo(object):

    __slots__ = ('a', 'b')

    def __init__(self, a='hello', b='world'):
        self.a = a
        self.b = b

E no ambiente interativo:
>>> f= Foo()
>>> f.c = 5

    AttributeError                            Traceback (most recent call last)
    <ipython-input-82-6ce08c4facb1> in <module>()
    ----> 1 f.c = 5

AttributeError: 'Foo' object has no attribute 'c'

Comment: Antes eu usava uma variavel de condicao e executava uma funcao que obrigava o `__setattr__` a ler se a variavel estava true e então travava o objeto para novos atributos... usando o __slots__ realmente ficou menos "recurso-técnico" rs
Comment: um problema que identifiquei em relação ao `__slots__` é que se eu tiver "nested classes" definidas dentro da classe onde elas servem para complementar uma lista, o elemento __slots__ conflita com o da classe pai
Answer: Você estava no caminho certo, acredito que seja mais um problema de erro de syntax do que outra coisa, veja esse exemplo:
class Foo:

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __setattr__(self, key, value):
        if not hasattr(self, key):
            return
        super().__setattr__(key, value)

if __name__ == '__main__':
    f = Foo('a', 'b')
    f.c = 'c'
    print(f.c)

Basicamente é o mesmo código que você escreveu, com a diferença que o método __setattr__ está escrito como um método corretamente.
Ao executar esse código, acontece um AttributeError::
Traceback (most recent call last):
  File "attr.py", line 15, in <module>
    print(f.c)
AttributeError: 'Foo' object has no attribute 'c'

Ou seja, o atributo c não foi criado no objeto, ele foi ignorado.
Porém, existe um efeito colateral, ao sobrescrever o método __setattr__ com esse comportamento, nenhum atributo passa a ser aceito pela classe, ou seja, nem mesmo os declarados no método __init__ (a e b).
Uma possível solução seria declarar um lista de atributos permitidos e se basear nessa lista, ao invés de verificar os atributos que o objeto possui:
class Foo:

    attributes = ('a', 'b')

    def __init__(self, a, b):
        self.a = a
        self.b = b

    def __setattr__(self, key, value):
        if key not in self.attributes:
            return
        super().__setattr__(key, value)

Comment: Muito boa respoosta,  mas de uma olhada no `__slots__`
Comment: Vi sua resposta @jsbueno realmente muito melhor e mais assertiva. Já usei slots no intuito de diminuir o uso de memória na criação de milhares de objetos iguais, mas nunca pensei em usar para restringir os atributos de uma classe.


Taking a full screenshot of only my desktop icons using python/ PIL

Question: I'm currently able to take a screenshot of my desktop using this code
from PIL import Image, ImageGrab
x =ImageGrab.grab()
x.show()

but the problem is, this captures the python script/idle dialog(box) which is running the script as well.
I want to take a clean screenshot of my desktop screen, caputuring all the desktop icons,background screen and taskbar etc via a script.
Is there a way to automate it so the script can automatically do this?
Thanks.
Comment: Did you manage to get it working?
Comment: Hi Eddie, I haven't a chance to test it out yet. I'm finishing up a couple of other scripts, first. I don' t have much experience using web servers, so I want  to do a some  reading on the subject and go through a few tutorials, just to get a basic understanding. I will let you know how it goes once I play around with it. Really appreciate the tips and insights.
Answer: One of the solutions would be to use a Python web server (tornado or whatever).
Take a look at the following code (Python 3 version):
pip install tornado
from PIL import ImageGrab
import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        x = ImageGrab.grab()
        x.show()
        self.write("Hello, world")

def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(8888)
    tornado.ioloop.IOLoop.current().start()

Minimise the IDLE window when the script is running.
Open a browser from your phone or another computer and navigate to:
http://[your IP address]:8888
I cannot test this script because ImageGrab.grab() only works on Mac and Windows but unfortunately not on Linux.
Comment: Thanks. I will read a bit more on python servers as I'm not too familiar with them.
Comment: It should be pretty easy. Once you `pip install tornado` from the terminal window, you can literally copy, paste and run the code above. When you navigate to the link above, the code inside the get function executes. If you want to learn more about Tornado here is the docs (http://www.tornadoweb.org/en/stable/). It is relatively straight forward. I strongly recommend you to use a proper IDE like PyCharm (if you haven't already) and run your app in a debug mode with a bunch of break points. It will make your life easier.
Answer: I tried out this code:
from PIL import ImageGrab
import time
import cv2

time.sleep(5)
x = ImageGrab.grab()
x.save('Screenshot.jpg')
x.show()

I delayed the execution of ImageGrab.grab() by 5 seconds, in the meantime I minimized my workspace and switched to my Desktop. After 5 seconds it captured a screenshot of my desktop and saved it.
I am still figuring out a way to automatically capture the Desktop.
Comment: You can check [THIS POST](http://stackoverflow.com/questions/24129253/screen-capture-with-opencv-and-python-2-7/24213099#24213099) as well.


Why do we have to assume normality for a one-sample t-test?

Question: As a consequence of the central limit theorem the sampling distribution of the sample means will always be normal whatever is the distribution of the variable we measure.
From our sample we can calculate the standard deviation of the sampling distribution (i.e. standard error) and we can therefore calculate a 95% confidence interval ($\bar x ± 1.96\cdot SE$) in order to accept or reject the null hypothesis.
So, why do we have to assume that the variable is normally distributed? It seems to me that the only thing that has to be normal is the sampling distribution that is approximatively normal given a large enough sample size, isn't it?
Comment: [This post](http://stats.stackexchange.com/questions/94764/why-does-non-normally-distributed-errors-compromise-the-validity-of-our-signific/94806#94806) shows an example that indicates the difficulties that arise with non-normal distributions at a sample size that is often supposed to be "big enough" (n=30). [This post](http://stats.stackexchange.com/a/111597/805) shows problems at n=50. It's not difficult to generate data where neither the t-distribution nor the normal distribution are suitable at very large sample sizes (greater than n=1000, say). So how do you decide what's "large enough"?
Answer: The central limit theorem certainly does not guarantee that "the sampling distribution of the sample means will always be normal whatever is the distribution of the variable we measure" in the short run. @Macro has a nice demonstration of how long it can take for the CLT to kick in here: Regression when OLS residuals are not normally distributed.  It may help you to read that (remember that a $t$-test is a simple case of regression).  In short, you need the data to be normal to guarantee that your $p$-values are accurate with your given sample size.  If the data are not normal, your sample size may be adequate, but it may not and it may be difficult for you to know which is true.
Comment: I don't have time to watch the video right now, but the gist of it is that the 'further' your dist is from normal, the larger N has to be for the sampling dist to be adequately normal. *EDIT:* yes, once your sampling dist is normal, you are OK.
Comment: Just to be clear: You typically have no idea what N is required for your sampling dist to be normal, so the whole issue is sneakier than most people realize. However, once your sampling dist is normal, you're done; that was the point.
Comment: So, is it true to say that the sampling distribution is close to a normal distribution only when the sample size is large enough or when the original variable is normally distributed? [This video](https://www.khanacademy.org/math/probability/statistics-inferential/sampling_distribution/v/standard-error-of-the-mean) from Khan Academy was my reference. If the sampling distribution is normal with a large enough sample size, does it mean that if we have a large enough sample size we don't have to care about the distribution of our variable? Thanks @gung!
Answer: Your first sentence might be better written as "As a consequence of the central limit theorem the sampling distribution of the sample means will always approach normality whatever is the distribution of the variable we measure, assuming the variable is distributed finitely and i.i.d.."
A Bernoulli-distributed variable with $p\le0.1$ is pretty much extremely not normal for a finite i.i.d variable (i.e. it takes zero or one as discrete values, rather than any real between $-\infty$ and $\infty$, and is hella skew). Playing with $N$ and decreasing $p$ in the following code may prove instructive about the rate at which the distribution of sampling means approaches normality:
N <- 250
x.bars <- 1:N
for (i in 1:N) {
  x.bars[i] <- rbinom(1,N,0.25)/N
  }
hist(x.bars, breaks=N/10)

In this code, the i.i.d. assumption is given by rbinom(1,N,0.25) so that all "observations" are Bernoulli with $p=0.25$ (i.e. $p$ is constant, and we don't switch distributions depending on the observation), that the possible values are 0s and 1s means we have finite sample distribution, that plus i.i.d. insures we have a finite population distribution.
Here are a series of histograms for $N \in 25, 250, 2500, 25000, 250000, 2500000$ and $p=0.25$:
N=25 (added more bins: N/4)

N=250

N=2500

N=25000

N=250000

N=2500000

There is something really beautiful about that last plot ($N=2.5$m): we can see that there's very much a smooth bell distribution in there... and yet it is also plain that there's something not quite smooth, not perfectly bell about it.


Copy excel (2007) sheet to new workbook without formulas referencing original workbook

Question: I have a workbook with two sheets. The first is full of data and calculations, the second is mostly cells with references to the first sheet. The second sheet also concatenates strings, and references to cells in the sheet, to form SQL commands used elsewhere.
There is also a second workbook (soon to be more). It has a sheet identical to the first sheet of the other workbook, except with different data. The problem I'm having is that the new workbook needs a sheet similar to the second of the original workbook (sorry if this is sounding confusing). I would like to simply duplicate the sheet and its formulas, which I tried using the 'move or copy...' option. Unfortunately, the formulas in the cells reference the first sheet from the old workbook, like this: =[foobar.xlsx]data!A1. Way too much data to remove them by hand. I can't just redo the formulas because I had to remove a lot of specific lines from the second sheet, so dragging the formula would not match up correctly. I'm currently trying to hack this together with REPLACE but if anyone can offer help it would be greatly appreciated.
CLARIFICATION:
When I copy the sheet, a formula will appear as =[foobar.xlsx]data!A1. I want it to just be data!A1.
Thanks :)
Answer: I hope this answers your problem, but I am a little unclear on your need!!!
Highlight all cells in the worksheet.
Perform a replace to replace = with say '=
This stops the formulas "being formulas"
Copy the sheet.
Perform another replace on the new sheet to replace '= with =
This converts back to formulas, referring to cells in your new workbook.
Comment: Highlight the whole range (or sheet), press CTRL+H, and do replace all


random factor structure for diversity surveys with repeat visits

Question: I'm involved in a project where we surveyed native insect communities across a large spatial gradient. Each site was surveyed twice over two summers for a total of 4 visits. We are hoping to analyze patterns in the abundance and richness of these communities across different land use types, regions, and management regimes. We are currently using both glmmPQL  and lmer depending on the distribution of each variable and are struggling to build an effective structure for our random effects.
Our data is currently structured such that each visit to a site is its own row, such that each site is listed multiple times.
We have two questions regarding how to structure our random effects.

First, do we need to include both SITE and VISIT as random effects to address the repeated measures, or is it sufficient to just include SITE?
Secondly, if we have 1 predictor variable that was measured only once per year and another that was measured twice per year, how would this change our random effect structure?
Answer:
do we need to include both SITE and VISIT as random effects to address the repeated measures, or is it sufficient to just include SITE?

tl;dr use just 1|SITE for linear mixed models; 1|SITE/VISIT if you want to allow for overdispersion in GLMMs, otherwise 1|SITE.
Typically one would include this as 1|SITE/VISIT ("VISIT nested within SITE", equivalent to 1|SITE+SITE:VISIT or "main effect of SITE plus the interaction between 1|SITE and 1|VISIT") in the model, but since you have only a single observation at each VISIT for each SITE, the 1|SITE:VISIT term is an observation-level random effect. You definitely don't want to include it in your linear mixed models (i.e. lmer); if you include it in your generalized linear mixed models it will act as a model of overdispersion. If your data are not overdispersed (i.e. the conditional distribution of counts at a particular site has variance less than or equal to the mean), then you might not need the overdispersion term.

Secondly, if we have 1 predictor variable that was measured only once per year and another that was measured twice per year, how would this change our random effect structure?

In general, you don't have to worry about the levels at which fixed-effect predictors get measured; this gets handled automatically. I assume you're going to do something like assuming that the once-measured variable is constant across the two visits within a year?
In general I would recommend glmer over glmmPQL unless you have a particular reason to use the latter.
Comment: We started using glmmPQL because we were getting convergence issues with glmer. We did try rescaling and adding in control code to specify number of iterations but the convergence warning still came up. @Ben Bolker do you have any suggestions for another way to deal with this? Thank you again for your help =D
Comment: did you look at `?convergence`? the gold standard is to try with another optimizer and see if you get the same results (coefficients, likelihood, etc.)


Can you give me an example of constant onto function

Question: What I think is a  function which is constant but onto should just have the single value in codomain which the function takes
Comment: yes, you are correct
Answer: So the codomain must have only $1$ element:   $f:C\to D$, where $D=\{x_0\}$.  $C$, the domain, on the other hand,  can be any nonempty set.  So $f(x)=x_0\,,\forall x\in C$.
Answer: Let $A=\mathbb{Z}$ and $B=\{2\},$ and define $f:A \to B$ by $f(x)=2$ for any integer $x.$


Arrange 6 adults and 12 children in 5 rooms, with at least 1 adult in each room

Question: Problem: How many ways can you arrange 6 adults and 12 children in 5 rooms of max 4 people such that there is at least 1 adult per room. Every person and room is distinguishable.
My take from the problem is the following:

There are 2 distinct ways to place 18 people in room of 4: $\{4, 4, 4, 4, 2\}$ and $\{4,4,4,3,3\}$
For the first sequence, I can start by fixing all the adults in every room in the following manner: $\binom{6}{2} \times \binom{4}{1} \times \binom{3}{1} \times \binom{2}{1} \times \binom{1}{1}$
Now there are 2 cases:

The room with 2 adults is the one with 2 people $\binom{12}{0} \times \binom{12}{3} \times \binom{9}{3} \times \binom{6}{3} \times \binom{3}{3}$
The room where 2 adults is among one that contains 4 people $\binom{12}{2} \times \binom{10}{3} \times \binom{7}{3} \times \binom{4}{3} \times \binom{1}{1}$

There are $5!$ ways to shuffle the rooms around since they are distinguishable

Adding the 2 cases in (3) and multiplying it with (2) and (4) should in my opinion give me the answer with the sequence $\{4, 4, 4, 4, 2\}$. Is there anything wrong with my reasoning?
Comment: Your reasoning is correct.
Answer: You could drive your consideration under 1. even further: you would have the following patterns (using a = adult, c = child):
$A = \{aacc, accc, accc, accc, ac\}$,
$B = \{accc, accc, accc, accc, aa\}$,
$C = \{aacc, accc, accc, acc, acc\}$,
$D = \{accc, accc, accc, aac, acc\}$.
Now let us consider first the rooms to be undistinguishable. Thus the filling pattern can be considered fixed in the above order.
Then we get groupings:
$gA = (\binom{6}{2}\cdot\binom{12}{2})\times(\binom{6-2}{1}\cdot\binom{12-2}{3})\times(\binom{6-3}{1}\cdot\binom{12-5}{3})\times(\binom{6-4}{1}\cdot\binom{12-8}{3})\times(\binom{6-5}{1}\cdot\binom{12-11}{1})$,
$gB = (\binom{6}{1}\cdot\binom{12}{3})\times(\binom{6-1}{1}\cdot\binom{12-3}{3})\times(\binom{6-2}{1}\cdot\binom{12-6}{3})\times(\binom{6-3}{1}\cdot\binom{12-9}{3})\times(\binom{6-4}{2}\cdot\binom{12-12}{0})$,
$gC = (\binom{6}{2}\cdot\binom{12}{2})\times(\binom{6-2}{1}\cdot\binom{12-2}{3})\times(\binom{6-3}{1}\cdot\binom{12-5}{3})\times(\binom{6-4}{1}\cdot\binom{12-8}{2})\times(\binom{6-5}{1}\cdot\binom{12-10}{2})$,
$gD = (\binom{6}{1}\cdot\binom{12}{3})\times(\binom{6-1}{1}\cdot\binom{12-3}{3})\times(\binom{6-2}{1}\cdot\binom{12-6}{3})\times(\binom{6-3}{2}\cdot\binom{12-9}{1})\times(\binom{6-5}{1}\cdot\binom{12-10}{2})$.
Finally you can mix up the room numbers as well, thus you get the sequence counts:
$sA = \frac{5!}{1! \cdot 3! \cdot 1!}$,
$sB = \frac{5!}{4! \cdot 1!}$,
$sC = \frac{5!}{1! \cdot 2! \cdot 2!}$,
$sD = \frac{5!}{3! \cdot 1! \cdot 1!}$.
Thus you get as individual possibilities:
$pA = gA \cdot sA$,
$pB = gB \cdot sB$,
$pC = gC \cdot sC$,
$pD = gD \cdot sD$.
Or finally as total possibility count:
$P = pA + pB + pC + pD$.
(The actual calculation is kept for you.)
---rk
Comment: May you explain the reason of the divisors in $sX$?
Comment: (+1) I've only checked $pA$ but I reckon this answer checks out. Those terms $gA,gB,gC$ and $gD$ simplify significantly.
Comment: @BinyuanSun: There are 5 rooms to be swapped. One of them e.g. in $A$ is of type $aacc$ (unique) and one of them is of type $ac$ (unique too), but all other three all are of type $accc$, thus interchangeable. This gives $\frac{5!}[1! 3! 1!}$, as was mentioned. (The others are analogue.)
Answer: Just for fun let's look at how we might solve this with generating functions.
Firstly, a room must have at most $2$ adults due to the pigeonhole principle. If it has $1$ adult then it can have $0,1,2$ or $3$ children, and if it has $2$ adults then it can have $0,1$ or $2$ children due to restricted capacity of $4$ people. We can express these possibilities for each room with the finite $2$-variable exponential series
$$x\left(1+y+\frac{1}{2!}y^2+\frac{1}{3!}y^3\right)+\frac{1}{2!}x^2\left(1+y+\frac{1}{2!}y^2\right)$$
$x$ is the enumerator for the number of adults and $y$ is the enumerator for number of children.
There are $5$ rooms, so to combine all possibilities for the rooms we must raise this to the power $5$:
$$\left(x\left(1+y+\frac{1}{2!}y^2+\frac{1}{3!}y^3\right)+\frac{1}{2!}x^2\left(1+y+\frac{1}{2!}y^2\right)\right)^5$$
and we want, as our answer, the coefficient of $x^6y^{12}/(6!12!)$ in this double exponential generating function.
Well, that can be done manually by considering cases (hint: there are only $4$) but I will use the online free open source computer algebra system "sage" with the following input:
<code>y=var('y')
show(factorial(6)*factorial(12)*expand((x*(1+y+y^2/2+y^3/6)+x^2/2*(1+y+y^2/2))^5).coefficient(x^6).coefficient(y^12))
</code>
and sage outputs (in MathJax format):

$$34\,594\,560\,000\tag{Answer}$$

Does that agree with your answer? If not, please double check as I have done so with this one.

Okay, so if you are not acquainted with generating functions here is how to count the $4$ cases manually:
The $4$ types of room filling are:
$$\begin{array}{cccccc}\text{type 1}&(2,0) & (1,3) & (1,3) & (1,3) & (1,3)\\
\text{type 2}&(2,1) & (1,2) & (1,3) & (1,3) & (1,3)\\
\text{type 3}&(2,2) & (1,1) & (1,3) & (1,3) & (1,3)\\
\text{type 4}&(2,2) & (1,2) & (1,2) & (1,3) & (1,3)\\\end{array}$$
where $(\text{adults},\text{children})$ tells us how a room is to be filled with adults and children.
We can count each type by first choosing the room with $2$ adults in $\binom{5}{1}$ ways then distributing adults to rooms in $\frac{6!}{2!1!^4}$ ways. Then, for each type we distribute children to the rooms  using a similar logic to the adult fillings:
$$\begin{align}\text{type 1}&=\binom{5}{1}\frac{6!}{2!1!^4}\frac{12!}{3!^4}\\[1ex]
\text{type 2}&=\binom{5}{1}\frac{6!}{2!1!^4}\binom{4}{1}\frac{12!}{1!2!3!^3}\\[1ex]
\text{type 3}&=\binom{5}{1}\frac{6!}{2!1!^4}\binom{4}{1}\frac{12!}{2!1!3!^3}\\[1ex]
\text{type 4}&=\binom{5}{1}\frac{6!}{2!1!^4}\binom{4}{2}\frac{12!}{2!^33!^2}\end{align}$$
giving:
$$\begin{align}\text{type 1}&=665\,280\,000\\
\text{type 2}&=7\,983\,360\,000\\
\text{type 3}&=7\,983\,360\,000\\
\text{type 4}&=17\,962\,560\,000\\
\text{total}&=34\,594\,560\,000\tag{Answer}\end{align}$$
Comment: @BinyuanSun, yes. Specifically by looking at the ways *up to* 3 children can fit once the adults have already taken a room. It is encouraging that our answers are the same! With regards to generating functions, they sometimes help give an answer quicker (sadly not the case here) but at the very least they give a clear insight in to the structures we are trying to count and how to enumerate more systematically. See if you can see how the answer arises from the coefficient of $x^6y^{12}/(6!12!)$ in the expansion, you'll hopefully see that it gives the same 4 types as when counting manually.
Comment: I haven't learned the generating function yet but it is quite interesting nonetheless. As for the manual method, it was quite different from my method but it seems to arrive at the same result. Just to be sure, in your method,  the way of you distribute the children is by looking at the ways 3 children can fit in the room right?


How to set a field value from parent template in Twig?

Question: I have node--article--teaser.html.twig which calls image-formatter.html.twig to printout the field_image. Everything works fine except that I don't want the field_image itself to be a linked. i.e image-formatter.html.twig should not find a url to only print an img tag.
I have tried the following in node--article--teaser.html.twig:
{#{ content }#}
  {% set content.field_image[0]['#url'] = null %}{% endset %}
  {{ content.field_image }}
    {{ label }}

The second line causing the following error:

Twig_Error_Syntax: Unexpected token "punctuation" of value "." ("end
  of statement block" expected) in
  "themes/saidbakr/templates/node--article--teaser.html.twig" at line
  78. in Twig_TokenStream->expect() (line 87 of vendor\twig\twig\lib\Twig\TokenStream.php).

While {{ content.field_image[0]['#url'] }} prints the url without any problems!
The image-formatter.html.twig code is as the following:
{% if url %}
  {{ image }}
{% else %}
  {{ image }}
{% endif %}

There is no any suggestion from twig debug about any alternative template for image-formatter.html.twig
Also using Theme Hook image_formatter as saidbakr_preprocess_image_formatter will not be an option because it is not possible to know the view context, i.e teaser or full, or content types to restrict this interaction for articles type. I think that the most simple way is from Twig, but how?!
Answer: There should be no reason to change any code for this, as you are using the default image formatter. You should be able to remove the link by going to /admin/structure/types/manage/article/display/teaser and change your field's formatter settings using the cogwheel-button and then select "None" for "Link image to".
Should the teaser view mode configuration page not be available, got to /admin/structure/types/manage/article/display and activate its checkbox on the far bottom of the page, then save and try again.
Answer: I think that you have to think otherwise but this code will help you :
node--article--teaser.html.twig
{{ content.field_image | merge ({ 'url' : value }) }}


Por que o ponto de entrada das aplicações é um método estático?

Question: Um método declarado estático significa que ele pertença ao tipo e não a instância de um objeto.
Em uma aplicação console C#, o ponto de entrada é estático:
static void Main(string[] args) { ...  }

Isso não é só do C#, no Java é o mesmo conceito:
public static void main(String[] args) { ... }

Também não se limita a aplicativos console. Um projeto WPF tem um ponto de entrada estático.
Nas perguntas que já existem sobre o assunto não se explana sobre o static além da sua obrigatoriedade sem justificativa e definição:

O que significa public static void main(String[] args)?
Por que é obrigatório implementar "public static void main (String [] args)"?

Por que os pontos de entrada dos aplicativos são estáticos?
A aplicação em si, inicialmente, não é uma instância de objeto do tipo Application ou ConsoleApplication (ou seja lá o nome que eu dei para a classe que contém o método de entrada), por exemplo?
Comment: Se o `main` não fosse estático, como você lidaria com os construtores da classe? E se o construtor tiver parâmetros? E se a classe tiver múltiplos construtores? Acredito que o ponto dos *designers* dessas linguagens foi definir um "contrato" simples para o ponto de entrada da aplicação.
Comment: Em java, que eu saiba, o fato de receber um array já significa que você pode passar quantos parametros quiser, agora o tipo, é somente string mesmo, se precisar de outro tipo, tem que fazer cast no main após recuperar os parametros.
Comment: Não em Java (e que eu saiba também não em C#). Mas o ponto do meu comentário inicial vai além do tipo e quantidade de parâmetros. Quando introduzimos OO na equação temos que resolver todos os problemas de construtores, destrutores, *overloading*, *overriding*, etc, etc, etc. Java não possui um tipo *singleton* (`object`) bem comportado ou funções *standalone*. Um método `static` me parece ser a maneira mais conveniente de garantir esse contrato (basicamente procedural) em uma linguagem OO que não possui mecanismos mais modernos.
Comment: Acredito que seja por conveniência e, possivelmente, por semântica. O `main` é apenas o ponto de entrada do programa e pertence à uma classe que (geralmente) não tem representatividade real: ela só existe para ter o método (poderia ser apenas uma função). E se a classe ter representatividade, a instância pode ser feita dentro deste método sem problemas.
Comment: O `main` não pode ter mais parâmetros como `static main(String[] args, int x)`? @AnthonyAccioly
Comment: Relacionada: [O que significa public static void main(String\[\] args)?](https://pt.stackoverflow.com/q/93048/5878)
Answer: Inicialmente a aplicação não é instância de nada. E de certa forma isso explica porque o método é estático.
Poderia ser um método de instância, não há nada tecnicamente que impeça fazer dessa forma, só foi assim que escolheram, talvez porque sempre foi assim em outras linguagens existentes antes do C#, a maioria que sequer possuem o conceito de classes e instanciação de objetos.
Poderia mais, poderia deixar definir outro método, talvez até com outra assinatura, deixando até passar outros argumentos. Lembre-se que precisa dizer qual é o tipo que deve usar como entry point. E pode ter Main() em qualquer tipo sem que seja um ponto de entrada.
O Android instancia objetos e faz o que precisa. Para o modelo do sistema operacional é mais interessante. Mas os sistemas operacionais tradicionais sempre tiveram uma única forma de iniciar uma aplicação. Então eu diria que escolheram assim até por razões históricas, todo mundo estava acostumado fazer assim.
Em linguagens não orientadas a objeto uma função é usada como ponto de entrada e o método estático é o mesmo que uma função.
Acho que entender o uso do método estático ajuda entender essa decisão. Ao contrário do que pregam os ideólogos de OOP, um método estático é sempre mais simples de lidar e ele deveria ser preferido sempre onde couber (não cabe em um monte de situação). O Main() é um caso que cabe como uma luva.
Não vejo tanta dificuldade assim quanto disseram nos comentários, mas faz algum sentido. A simplificação me parece o melhor argumento para evitar esta funcionalidade que traria pouca ou nenhuma vantagem. Desenvolvedores de linguagens são pragmáticos e analisam os custos de implementar algo, de complicar a linguagem e os benefícios que isso trará.
Um ponto que acho que pode levar em consideração é que você pode querer chamar este Main() dentro da sua aplicação. Aí precisa instanciar outro objeto, porque o objeto que iniciou a aplicação é de propriedade do CLR (a não ser que fique passando ele pra lá e pra cá na aplicação). Se é outra instância, embora fisicamente chamará o mesmo método, está acessando outro objeto, com dados possivelmente diferentes, pode não ser o que deseja.
Em C# pode usar 4 assinaturas diferentes (não simultaneamente):
static void Main();
static void Main(string[] args);
static int Main();
static int Main(string[] args);

Coloquei no GitHub para referência futura.
Em C# 7.1 pode até mais porque o Main() pode ser assíncrono.
Em C# 9 não precisa ter esse método explicitado para scripts simples. Não é que ele deixou de ser necessário, o compilador coloca para você. Só faça isso para código throw away.


Moderation-analysis with a hierarchical multiple regression analysis

Question: For my thesis I perform a moderation analysis via a hierarchical multiple regression analysis. More specifically, I want to investigate whether closeness in the parent-child relationship is a moderator in the association between conflict in the teacher-student relationship and the working memory performance of primary school children. In the analysis I work with two models (model 1 without interaction and model 2 with interaction as in this file: https://www.sheffield.ac.uk/polopoly_fs/1.885172!/file/90_Moderation_Meditation.pdf)
I would like a good example of another thesis or paper that works with the same analysis as me, but I haven't found one yet.
In addition, with the second model I do not arrive at a statistically significant R2 change after adding the interaction. Can I continue with a moderation analysis or should I stop? According to my promoter, there are articles that use less strict criteria and that do continue with moderation analysis, but I haven't found them yet.
Thank you in advance!
Regards,
Elise
Answer: In brief, if the change in the coefficient of determination $R^2$ from the parsimonious model (without interaction) to the more complex model (with interaction) is not statistically significantly different, then you are not justified in using the more complex model.  The "rule of parsimony" applies here: if the simpler approach is just as good as the complicate approach...then stick with the simpler approach.
However, this does not mean you do not have valuable information that should be reported.  There still may be a difference in the relationship with regard to the intercepts of the models (the main effects) even if the slopes of the models can be constrained to be equal.
Additionally, you may be able to report on the effect size of the interaction effect, even if you do not actually use the more complicated model for further/follow-up analyses.
Comment: Thank you very much!


The Affine Tangent Cone

Question: I'm failing to see how exactly is the tangent cone at a singular point on a curve picking out all the different tangent lines through this singular point (say the origin in $\mathbb{A}^2$)?
Could someone explain this, or at least redirect me to a source I could read about? I tried to look online, but at most places they are just taking this as a known fact!
Thanks!
Answer: Initial remark. Suppose someone gives you a continuous function of two variables, and asks you to calculate the Taylor series in $(0,0)$. If we happen to notice that the first derivatives vanish at the origin, we will call it a critical point.
The idea of the tangent cone is that we are doing exactly this: taking the Taylor series of the simplest continuous function: a polynomial. And if the first derivatives vanish, we call $(0,0)$ a singular point.

We have a curve $X=V(f)\subset \mathbb A^2$ passing through the origin.
Even if the origin is a nonsingular point of the curve, you do have a tangent cone at the origin: it is also called the tangent line! (and this is precisely encoded in the corresponding first terms of the "Taylor series" of $f$).
However, the tangent cone is constructed starting from the leading form of $f\in k[x,y]$, which is the homogeneous form $\tilde f$ of smallest degree appearing in the decomposition of $f$; it is again in two variables. For instance, the leading form of $f=2x+y-8y^2x$ is $\tilde f=2x+y$, the term of smallest degree. The tangent cone is the zero set $V(\tilde f)$. So the origin is nonsingular if and only if $f$ has leading form of degree one. In that case, $V(\tilde f)$ is exactly the tangent line.
In general, the leading form will be a product of linear factors, each appearing with some exponent. So the scheme $V(\tilde f)$ is a union of lines, where some of them are possibly nonreduced.
If $f$ starts, say, with degree $2$, then for instance $(0,0)$ will be a node in case the (degree $2$) leading form is a product of two distinct linear forms, i.e. something of the kind $$(ax+by)\cdot (cx+dy).$$ If, instead, the leading form has the shape $(ax+by)^2$, something else happens (example: the cusp $f=y^2-x^3$, whose tangent cone which is a double line).

Reference. All this is beautifully explained in Mumford's The red book of varieties and schemes.
Comment: I guess my question then $\bf{really}$ is how should I go about understanding that when I write $f=f_0+f_1+...+f_d$ where $f_i$ are homogeneous polynomials of degree $i$ in $x,y$, then why is the smallest such $f_r$ picking out all these different tangent lines at the singular point? Because, I think, I can see how it is working, I just don't seem to understand why. I'm not sure if I'm making sense? Thanks for the reference, by the way, I will definitely check that out!
Comment: You call them *tangents* because you are selecting the *least* degree in the homogeneous decomposition of $f$. You have them *all* just by definition (you take the *entire* homogeneous part). You actually *see* them one by one writing down the product decomposition of $\tilde f$ into linear factors. Sorry for being unclear on that.
Comment: My question might be more ignorant than I thought. Here is my confusion: Say that the leading form of $f$ factors into linear factors. Then, these two lines seem to be precisely the tangents at the singular point, of the two branches of $f$ respectively. For example take $f=y^2-x^2-x^3$. The leading form factors as $(x-y)(x+y)$ and these are precisely the tangent lines through the origin of the two branches of $f$. I don't see how this is happening in general. How are the other terms irrelevant? I might be missing something more fundamental.
Comment: It seems to me, like somehow we are writing $f$ as a product of some formal power series, and then these are defining each branch of $f$, and then in turn the linear term of these formal power series is representing the 'tangent' of the corresponding branch through this singular point of $f$. But, also, I'm not sure if we can always write $f$ as a product of these formal power series.
Comment: As for your first comment: I do not get what you mean when you say the other terms are "irrelevant". Also, I do not see power series hidden as factors of the polynomial $f$, but it is probably something I am missing myself. Indeed, the study of singularities is very much related to power series (maybe, those you mention), in particular to the *completions* of the local rings at the singular points. Sorry for not being able to say more on this.
Comment: As a concrete example, I reconsider the one in the previous comment: $f=y^2-x^2(x+1)=(y-x\sqrt{x+1})(y+x\sqrt{x+1})$, this factorization is valid over the completion of the local ring of $\{f=0\}$ around the origin. So, we can expand $\sqrt{x+1}$ in $\mathbb{C}[[x,y,]]$. This argument seems to hold in more generality. This is what i meant by the power series being hidden in the background. I talked to my professor today, and this seems to be a general result, with some restrictions. Then, the factors of $f$ (which are formal power series) give you the branches of $f$ around the singular point.
Answer: For anyone interested I will write a reference for the 'answer' to this question: It turns out that this is a problem in Hartshorne, namely Problem 5.14 (b) of Chapter 1. I will write the statement here, and maybe at some point post a solution as well.
If $f=f_r+f_{r+1}+\cdots \in k[[ x, y]]$, and if the leading form $f_r$ factors as $f_r=g_sh_t$, where $g_s,h_t$ are homogeneous of degrees $s$ and $t$ respectively, and have no common linear factors, then there are formal power series
$$g=g_s+g_{s+1}+\cdots$$
$$h=h_t+h_{t+1}+\cdots$$ in $k[[x,y]]$ such that $f=gh.$

The Affine Tangent Cone


Entailment of two formulae

Question: If I have two statement, say $A$ and $B$. From which, I formed two formulae:
$F_1$: ~$A$ $\&$ ~$B$
$F_2$: ~$A$ $\mid$ ~$B$
Do $F_1$ and $F_2$ entail each other?
Comment: If $|$ is the [Sheffer stroke](https://en.wikipedia.org/wiki/Sheffer_stroke), than $\lnot A \mid \lnot B$ is simply : $A \land B$. Thus : $F_2 \nvDash F_1$, because otherwise $A \land B \vDash \lnot A \land \lnot B$, which is not.
Answer: I assume that your $|$ is meant for 'or' (in programming it often is), and an inclusive or at that (again, in programming it often is used as such).
So, using more 'standard' logical symbols, the statements are:
$F_1: \neg A \land \neg B$
$F_2: \neg A \lor \neg B$
Now, a statement $\phi$ entails a statement $\psi$ if and only if $\psi$ has to be true if we assume $\phi$ is true.
So in this case:
$F_1$ entails $F_2$, because if we assume that $F_1$ is true, then $\neg A \land \neg B$ is true, hence in particular $\neg A$, and that means that $\neg A \lor \neg B$ is true (think about it: if $P$ is true, then of course $P \lor Q$ will be true as well)
On the other hand, $F_2$ does not entail $F_1$, since we could have a situation where $A$ is true, and $B$ is false: that would mean that $\neg B$ is true, and hence $\neg A \lor \neg B$ (i.e. $F_2$) is true, but since $A$ is true, clearly $\neg A \land \neg B$ (i.e. $F_1$) is false. So this shows that it is possible for $F_2$ to be true but $F_1$ to be false, so $F_2$ does not entail $F_1$.
Comment: Very informative. I had the second confusion. Thank you sir.

Entailment of two formulae


Removing White Space in a Palindrome String

Question: I'm trying to modify the code to ignore white spaces in a Palindrome String. For example, the code should mark Do Geese See God as Palindrome. I've been trying to use .replace(" ", ""), but either an error pops up or the Palindrome is returned as False.
stk = Stack()

for i in range(len(sentence)):
    stk.push(sentence[i])

    for i in range(stk.size()):
        stk.replace(" ","")

        if sentence[i] != stk.pop():
           return False;

    return True;

I'm trying to not use stk.item[-1] or stk.item == stk.item[::-1] in Stack, by the way.
Comment: On a side note, your test phrase is not a Palindrome. Change `Does` to `Do` perhaps?
Comment: Then define a white space in your replacement. So it should be `.replace(" ","")`.
Answer: I would recommend just stripping all whitespace with a RegEx:
input = "  A man a plan a canal Panama "
input = re.sub(r'\s+', '', input)

This would also handle the cases of leading and trailing whitespace, which you probably also want to ignore.
Comment: Thank you, I thought about using a regex but the code will take user input and then decided if it's a palindrome or not, I'll edit the question to reflect this.
Answer: It may be a cut and paste error but you don't actually have a space in what you are replacing.
stk.replace(' ', '')

Answer: I've modified the code to make this work:
def isPalindrome(sentence):
   sentence = sentence.replace (' '. '')
   stk = Stack()
   for i in range(len(sentence)):
      stk.push(sentence[i])
   for i in range(stk.size()):
      stk.replace(' ','')
      if sentence[i] != stk.pop():
          return False;
   return True;

Comment: It seems that `stk.replace(' ','')` is not necessary


How to access date value from a datelist form element for validation?

Question: I have a simple form element using datelist as the type. I need to validate this to make sure the date is in the future. But I cannot work out how to access the date itself in the validation method.
Form:
public function buildForm(array $form, FormStateInterface $form_state) {

  $form['date_field'] = array(
    '#title' => $this->t('Expiry'),
    '#type' => 'datelist',
    '#date_part_order' => array('month', 'year'),
    '#date_year_range' => '2017:2027',
    '#date_increment' => 1
  );

  return $form;
}

Validation:
public function validateForm(array &$form, FormStateInterface $form_state) {

  $date_input = $form_state->getValue('date_field');

  if(strtotime(date($date_input)) < strtotime(date('now'))) {
    $form_state->setErrorByName('date_field', $this->t('The date must be in the future.'));
  }
}

From the above, $date_input currently returns an object (see below). Essentially, I want to access $date_input->dateTimeObject->date; but doing exactly that will return a fatal error.

Fatal error: Cannot access protected property
  Drupal\Core\Datetime\DrupalDateTime::$dateTimeObject

$date_input object:
stdClass Object
(
    [__CLASS__] => Drupal\Core\Datetime\DrupalDateTime
    [formatTranslationCache] =>
    [dateParts] => Array
        (
            [0] => year
            [1] => month
            [2] => day
            [3] => hour
            [4] => minute
            [5] => second
        )

    [inputTimeRaw] =>
    [inputTimeAdjusted] =>
    [inputTimeZoneRaw] =>
    [inputTimeZoneAdjusted] =>
    [inputFormatRaw] =>
    [inputFormatAdjusted] =>
    [langcode] => en
    [errors] => Array
        (
        )

    [dateTimeObject] => stdClass Object
        (
            [__CLASS__] => DateTime
            [date] => 2027-12-01T00:00:00+11:00
            [timezone] => Australia/Sydney
        )

    [stringTranslation] =>
)

I could do something like:
$form_state->getValue('date_field')->format('d m Y');

But I suspect there is a better way?
Answer: Yes, to compare the date it's better to use the unix timestamp. You can get it by using the method getTimeStamp() and compare it to the current date:
      $value = $form_state->getValue('date_field');
      if ($value->getTimeStamp() > REQUEST_TIME) {
        drupal_set_message('Time is in the future');
      }


Questions about ARIMA

Question: I am estimating this model:

But I want to do some analysis of the variables before. In particular, I am interested in fitting some ARIMA models. First, I am doing it for the inflation rate in Mexico.

For the ARIMA model, do I need to take into account the other variables or only the values of variation of inflation in previous periods?
When I look at the ACF graph it looks like this:

What does it mean to have a lag at 0.5 ? Since I cannot introduce an MA(.5), should I care about it or only take into account lags at t=1 and t=2?
When I look at the PACF it looks like this:

Again, what does it mean to have considerable autocorrelation at t=.5 and t=.8? Since I cannot have an AR(.5), should I pay attention to this lags or only to lags at t=1 and t=2? Why?

When I use the auto.arima function in R, it produces a model ARIMA(0,0,2), so that is no AR term, but is this not a contradiction with the PACF graph? What should I do? Why?
In order to evaluate the goodness of fit I am using Box.test(fit_resid,lag=10,type="Ljung-Box"), but that gives me a p-value of very small, then is that a good fit or not?
Finally, should I repeat that for every variable in the model or not? Why?
Answer:
ARIMA only considers one variable and its own lags.
The lags in the plots reflect periodicity of your data. You probably have monthly data with 12 months making up one period. Then in the plots, a lag of 1 means a lag of 1 year (12 months). Thus 0.5 is 6 months. In modelling, you would use AR(12) or MA(12) and AR(6) or MA(6) components in place of AR(1) or MA(1) and AR(0.5) or MA(0.5).
See 2.
I suggest posting this as a separate question. The implicit role of ACF and PACF in the algorithm of auto.arima is nontrivial (and there is no explicit role for them).
A small p-value suggests low support for the null hypothesis of no serial correlation in model residuals. Therefore, a low p-value is bad.
Depends on why you are doing "some analysis of the variables".
Comment: But how to model that AR(6) in R.The code arima(x,order=c(1,0,1)) would be for AR(12) and MA(12), what is the code for AR(6)?
Comment: @CarlosN, the code `arima(x,order=c(1,0,1))` would be for ARIMA(1,0,1), so AR(1) and MA(1). Code for ARIMA(12,0,12) would be `arima(x,order=c(12,0,12))` and for ARIMA(6,0,6) would be `arima(x,order=c(6,0,6))`. Some coefficients (e.g. lags between 1 to 5) can be restricted to zero by the argument `fixed`.

Questions about ARIMA


Perpendicular Vectors find x

Question: My Higher maths question booklet has this question and I am rather stuck with it. I have done one similar before I just cannot remember and have no idea now.
<code>      Two vectors **a** and **b** are perpendicular.
      **a** = i – 2j + xk and **b** = xi + 3j + xk
      Find and verify any possible values of x.
</code>
Comment: Welcome to MSE. Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference).
Answer: Hint:
$\vec a \perp \vec b \Leftrightarrow \vec a \cdot \vec b = a_x b_x + a_y b_y + a_z c_z = 0$
Answer: compute the dot-product:$$(i-2j+xk)\cdot
 (xi+3j+xk)=x-6+x^2$$
Comment: yes that is what i meant

Perpendicular Vectors find x


Cohomology Groups of Projective Space and Sphere

Question: I am stuck on the following question from Switzer's Algebraic Topology: Homotopy & Homology:
Describe the cohomology groups of $\mathbb{R}P^2 \times \mathbb{R}P^2$ and $\mathbb{S}^m \times \mathbb{C}P^n$ for any integers $m,n$ greater than or equal to 1.
I have been thinking hard about it since last two days, but I cannot think about cohomology groups of the product space of 2-dimensional real projective spaces nor the product of m-dimensional sphere and complex projective space...Could you help me out?
Comment: Have you tried using the [Künneth theorem](https://topospaces.subwiki.org/wiki/Kunneth_formula_for_cohomology)?
Answer: Here's the roadmap you'll want to take for calculating these groups. If you have any questions about the details (for example, about why the tensor product or Tor groups are what they are) feel free to follow up in the comments.
The Künneth formula for cohomology (linked by William in a comment) gives us that
$$H^k(\mathbb RP^2 \times \mathbb RP^2) \cong \left(\bigoplus_{i+j=k} H^i(\mathbb RP^2) \otimes H^j(\mathbb RP^2)\right) \oplus \left(\bigoplus_{i+j=k+1} \text{Tor}(H^i(\mathbb RP^2), H^j(\mathbb RP^2))\right).$$
When $k \geq 3$ all of the summands will be $0$. When $k = 2$ the left big summand is $\mathbb Z/2\mathbb Z$, and the right is $0$. When $k = 1$ the left big summand is $\mathbb Z/2\mathbb Z \oplus \mathbb Z/2\mathbb Z$, and the right big summand is $\mathbb Z/2\mathbb Z$, so the whole thing is $(\mathbb Z/2\mathbb Z)^{\oplus 3}$. Finally when $k = 0$ you obviously just get $\mathbb Z$.
For the other space I'll start with a slightly more general fact, namely that for any space $X$ we have
$$H^k(S^m \times X) \cong H^{k-m}(X) \oplus H^k(X).$$
You can show this by just writing out the formula again:
$$H^k(S^m \times X) \cong \left(\bigoplus_{i+j=k} H^i(S^m) \otimes H^j(X)\right) \oplus \left(\bigoplus_{i+j=k+1} \text{Tor}(H^i(S^m), H^j(X))\right).$$
Now, $H^i(S^m)$ is $\mathbb Z$ when $i = 0, m$ and $0$ otherwise, so the summands on the left are non-zero exactly $i = 0, m$, and then it simplifies to what I wrote above (note that the whole right summand will become $0$ since the cohomology of $S^m$ is always free).
So $H^k(S^m \times \mathbb CP^n) \cong H^{k-m}(\mathbb CP^n) \oplus H^k(\mathbb CP^n)$. The cohomology of $\mathbb CP^n$ is not too bad (see here), but it will be a little bit obnoxious to write out all the possible cases for $k, m, n$. Let me know if you need some more clarification.
Comment: Regarding your last paragraph : it would actually be a lot easier to write down the cohomology algebra than the specific cohomology groups (as you point out, writing out all the cases is very likely to be annoying). Of course OP asked for the cohomology groups, but I guess it's worth a mention (it's actually an additional motivation for the cohomology ring : nice packaging which makes things easier to write down)
Comment: Dear fish, thank you very much for your explanation.  Are they really cohomology groups of both product spaces?  I have hard time trying to understand how the cohomology of m-sphere and CP you derived is indeed cohomology group.


Should I be submitting my compositions to multiple publishers?

Question: I submitted several choral scores to a publishing company for consideration.  They were initially very interested in seeing them, but since I've sent them ... big surprise, I haven't heard anything.  I have been patient and have written them only twice in the more than a year since I've submitted the music to them.
This publisher is one with which I would like to work, or at the very least, not offend.  They are connected to a major choral ensemble and burning bridges wouldn't be prudent.  That said, I can only wait so long before moving on to another publisher.
Here are my questions...

Is it against any established etiquette or convention to submit a score to multiple publishers at once?
If it is, how long is reasonable to wait before assuming that they simply aren't interested?

Finally,

Should I tell them that I am submitting the scores to another publisher?
Comment: I would start with option 4.: write to the publisher and ask their guidelines. "Dear ..., I submitted my score on DAY MONTH YEAR, but so far have not received a reply regarding whether you would like to publish it. Since it has been more than a year, I would like to approach other publishers. Please advise as to your policy in this regard." Something along those lines.
Comment: Alternatively: "Please let me know whether my score is still under consideration." If they say "yes", then you can inquire about when you might expect a decision. If "no", then you're free to submit elsewhere.
Answer: Submit to as many as you like, all in one mailing round.
Wait a month or so, to see if you get any replies. Don't nag. No-one will appreciate being chased.
Compare offers - or start over with new material.
I'm surprised they haven't said anything at all after first displaying interest*, but you never will know what's happened in the intervening period. The person with the main interest may have moved on. Policy on new material may have changed.
If you've written twice more & still heard nothing, just move on. Don't nag them, they've already as much as said they don't care.
*There's a caveat on this - you said they displayed interest in seeing the work… that's different from displaying interest in it once they'd seen it. I'm still surprised they didn't bother even with a standard 'thanks but no thanks' letter of some sort.
Above all, don't be discouraged. I have a friend who waited 20 years to get his first choral work published. Most bizarrely, when it finally was, it became part of a two composer release… with another friend of mine, who'd been at the premier of that piece 20 years earlier.
Life's like that.
Answer: I'm answering my own question to supplement Tetsukin's excellent answer.  A few hours spent viewing the submission guidelines for several publishers of choral music taught me that...

Most publishers have very specific guidelines on their submission process, and
Some publishers include in these guidelines a request to be the only publisher reviewing a piece.

So, the answer is that there's no reason not to submit to multiple publishers unless they request you not to ... so far all of these publishers give an estimate of their review time, so that you'll know that if you haven't heard from ABC Music Press after their 5 months (even though they want to be the only publisher reviewing your work), you can submit to others then.
Comment: They request to be the only reviewer to give them a chance to be the only one in the line if they really want you. That's an instruction you really ought to ignore. Bidding wars make for good business sense. There is absolutely no reason [or compulsion] to follow that instruction.


Sync Drupal commerce order information

Question: Sync Drupal commerce order information between several drupal instances.
Here is my use case.
A business has a Drupal commerce website.
It also has several internal commerce sites.
Each of these has to have the ability to work independently of each other for certain periods of time.
At a later date there will be a mobile app doing the same thing.
So any sales information or orders need to be synced at later points throughout the day.
What is the recommended way to do that securely and also avoid and order related conflicts such as order number customer name changes etc?
I realize this is a fairly broad question but Im not looking for a specific answer,  Any general information or recommendations would be great.
Answer: Some general advice:
I had a similar situation on a project. I first tried various options for importing orders from the separate sites into a central site using modules like:

commerce_order_ftp_export
commerce_export
commerce_export_csv
commerce_feeds with patch for orders

But you will need custom code to resolve order IDs etc. Depending on the number of sites, this may be workable.
However, I eventually opted for a solution as follows:

Using a mobile POS app for sales
Sending sales from each instance of the app into a central drupal installation running maceij's version of commerce_marketplace
This way,sales can be separated and/or aggregated by location, POS, etc.
Comment: Could you provide some more information as to how you achieved this?
Comment: I am using a mobile app called Tabshop and used its API to write drupal module for sync with commerce. All in drupal 7. Difficult to explain everything here - better offline.
Comment: Ah ok thanks I will look into that, im using drupal 7 myself. Not sure if im skilled enough to make a module to sync with commerce but I will give it a go. Any other advice you could give would be great
Comment: Not sure we can chat offline here... But if you send me skype or whatsapp contact, we can discuss in detail.
Comment: Hi. Have you now resolved this?

Sync Drupal commerce order information


How to initialize arrays and vectors in old extension clang and gcc compilers in macOS?

Question: I have a code in c++. It works in windows, Ubuntu and Fedora.
Now I want to compile it for macOS. I encountered some errors like
error: expected expression
error: variable-sized object may not be initialized

I have many lines like
int A[n][2] = {{2, 5},{2, 6},{3, 4},{3, 7},{4, 3},{5, 2},{6, 2},{7, 3}};
int B[n][2] = {{8, 15},{8, 16},{9, 14},{9, 17},{10, 13},{10, 14},{10, 17},{11, 12},{11, 15},{11, 16},{12, 11},{13, 10},{14, 9},{14, 10},{15, 8},{15, 11},{16, 8},{16, 11},{17, 9},{17, 10}};

I searched it is because of the old installed clang and gcc extension in macOS (I am using Mojave 10.14.0)
I do not know what can I do to resolve this problem.
Comment: What is `n` defined as here? Those two lists are different lengths, they can't have the same type.
Answer: You can define these instead like this:
int A[][2] = {{2, 5},{2, 6},{3, 4},{3, 7},{4, 3},{5, 2},{6, 2},{7, 3}};
int B[][2] = {{8, 15},{8, 16},{9, 14},{9, 17},{10, 13},{10, 14},{10, 17},{11, 12},{11, 15},{11, 16},{12, 11},{13, 10},{14, 9},{14, 10},{15, 8},{15, 11},{16, 8},{16, 11},{17, 9},{17, 10}};

Where clang is then happy.
If you specify n then you need to ensure the initializer list can fit in the defined structure.


Getting Imports/Exports from an PE using a Ghidra Script

Question: I'm using ghidra to Reverse Engineer an EXE file. I want to extract the imports and exports from the symbol tree.
I've Written this script but it doesn't return anything.
sm = currentProgram.getSymbolTable()
symb = sm.getSymbolIterator("Imports")
for s in symb:
     print(s)

but when i use this script to get all the functions from the symbol tree, it works
symb = sm.getSymbolIterator()
for s in symb:
     print(s)

What am I missing?
Answer: Does solves your issue?
sm = currentProgram.getSymbolTable()
symb = sm.getExternalSymbols()
for s in symb:
     print(s)

Comment: Yes it does!.
Thank you so much.


How a header file knows where the implementation of a function prototype is?

Question: I have the following files:
main.c
#include <stdio.h>
#include "my_math.h"

int main()
{
    int a = 10, b = 5;
    add(a, b);
    return 0;
}

my_math.h
int add(int a, int b);

my_math.c
#include "my_math.h"
int add(int a, int b)
{
    return a + b;
}

I know that using #include "my_math.h" copies the content of my_math.h file within the file where it is called. However, how does main.c file where the implementation of add() function is?
At the beginning I thought that my_math.h and my_math.c should match the name, but not the extension, but I have changed the name from my_math.c to my_matho.c and everything is working as previously, so how the heck C know where the implementation of the function is?
I am using the following command to compile:
gcc -g -O0 -Wall main.c my_math.c -o main

One more question is it the same the previous command than:
gcc -g -O0 -Wall my_math.c main.c -o main

so it means that the order in which I indicate the files to be compiled does not matter?
Answer: There are two different stages, compilation and linking.

During compilation, compiler only needs to know the prototype of the function.
During linking, the object files are actually linked together.

So, during compilation, the where part is not required. However, while linking, the function should be present in one of the object files which are being linked together.
To elaborate, that is why we see that, even with a missing header file (forward declaration of a function) but with all required object files, the compilation and linking can happen (with warnings, obviously) (and linker can actually find and link the required function implementation), but even if with the proper header file, if you don't supply the required object file which contains the actual definition, the linker will scream at you throw error.
Comment: @lmiguelvargasf [hope this helps](https://en.wikipedia.org/wiki/Forward_declaration). basically what you've done in `my_math.h`. :)
Comment: Oh this is a really good and clear explanation. I thought that while compiling the where mattered. Thank you.
Comment: @SouravGhosh What do you mean by forward declaration of a function?
Answer: The compiler does not know. The linker does.
Each source file is compiled to a object file:
main.c becomes main.o and my_math.c becomes my_math.o - for example.
When compiling main.c The function prototype in my_math.h, tells the compiler that there will be a function int add(int a, int b); which it can call but it has no extra knowledge about this function.
When the linker links main.o and my_math.o into the executable it performs the necessary relocation.


"Push chord". What's that?

Question: I came across this post the other day that referenced a "push chord". What does "push chord" mean in that context? Is that a term specific to Bossa Nova (a latin jazz genre), or is it just a term I haven't heard before?
Answer: It's not the chord so much as the rhythm that gets pushed. Nothing much to do with bossa, but it happens all the time in a lot of pieces,
The emphasis is expected to come on the 1st beat of the next bar, but instead, comes a little earlier, usually on the & of 4 of the bar before (in 4/4).
It effectively puts the emphasis where the next heavy beat comes a little earlier than anticipated - `a quaver before we expect it. instead of actually on the beat of the next bar, it's on the quaver before. Been around for at least 60 years and so is nothing new!
Answer: I was wondering too, when I read this term in the other question about the Bossa Nova.
Then I've found this link (s.below) that confirms what Tim explains.
It says: Rhythm is also defined by chords and where they fall, a little earlier or later - I would say similar or the same as off-beat:
I thought, the push chord must be what I know from the big band sound in the final chord (or final 2 chords) of a big band piece, off-beat or - in German we would say "vorgezogen" that means actually the opposite of push: PULL!): the final chord, the POLY-Chord, which is often "vorgezogen" (pushed down, or later.
Well, here is the link. It explains it perfect and better than I could:
https://www.musicradar.com/tuition/tech/how-to-add-interest-using-pushed-chords-640295
a good example must be SMOKE ON THE WATER

"Push chord". What's that?


linux cron job isn't running

Question: I have a Ubuntu Server 10.
At the root cron I have a script to run every day at the same hour.
Running the script manually it's run fine, but in the cron it doesn't run.
At the syslog I got this:
Aug 23 09:22:01 database CRON[6884]: (root) CMD (./bkp.sh >> /tmp/bkp.log)
Aug 23 09:22:01 database CRON[6883]: (CRON) error (grandchild #6884 failed with exit status 2)

I found the possible source of the problem, I added some LOGs (echo) in the script...
During script execution, it exits on a "function" definition...
It seems that I have no access to command "function"
How can I solve this?
Comment: The cron environment isn't the same as your login shell environment. System environment variables are different for one, like PATH and library search path. Your script is probably using something that's not available when ran from cron.
Comment: How can I solve this? Can I specify the user for run the job?
Comment: See also http://stackoverflow.com/questions/819944/proper-way-to-run-a-script-using-cron
Comment: Another think... recently I have tryied to change the su password with "sudo su" and "passwd".... after run this commands, I noticed that had no effect.... can this be the cause of my cron job problem?
Comment: Doesn't sound like a programming problem to me. This is a job for Server Fault.
Answer: Shell scripts launched by cron must carefully specify the environment that they're running in. Shells run within cron will be non-interactive, meaning that they will not read /etc/profile, where $PATH is typically set. This means that you will need to specify the paths to all executables called in your script.
If you run a lot of cron scripts, it may be worth your time to write a small shell script which will define and export environment variables to be used inside your script, starting with $PATH.
Answer: Here's a link i got while googling for 'cron environment variables'. It may help. There are many others like it :)
Comment: The cron was working 100%, but....
Recently I have tryied to change the su password with "sudo su" and "passwd"... after run this commands, I noticed that had no effect the su password continues the same... I ignored this and now I having problems with it...
Answer: Place you script inside following directory then it should run everyday.
/etc/cron.daily/

linux cron job isn't running


Windows Server 2008: how to switch license of retail version to MAPS and vice-versa?

Question: Is there any way to take an existing VMware virtual Windows Server 2008 machine that was installed with a retail product key, and switch it to a MAPS key? And/or vice-versa? It would be nice to clone our production Web servers to dev ones with the exact same setup (using MAPS).
I've heard they're completely different so it can't be done, but...
Answer: Seems like if it doesn't work from the official interface there's an alternate using a script that's installed in system32:
http://forevergeeks.com/change-product-key-on-windows-server-2008
Comment: I'll have to try this and will post what I find out. Again, the issue is with a MAPS key.
Comment: Just did a re-install so don't know whether it worked or not.


How to get All the elements of the entity in spring-boot ?

Question: I'm sending a GET request from angular5 to spring-boot to get all the elements of the entity Contrat below  .
This is the entity :
<code>@Entity
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Contrat implements Serializable{

        @Id @GeneratedValue
        private Long id;
        private Date dateDebut ;
        private Date dateFin ;
        @ManyToOne
        @JoinColumn(name = "Id_Project")
        @JsonBackReference(value="projet-contrat")
        private Project project;

        @ManyToOne
        @JoinColumn(name = "Id_AppUser")
        @JsonBackReference(value="appuser-contrat")
        private AppUser appUser;
}
</code>
This is the repository :
<code>  public interface ContratRepo extends JpaRepository<Contrat,Long> {

    @Query("select from Contrat c where c.appUser = :userApp")
    public Page<Contrat> chercherContrat(@Param("userApp") AppUser userApp
   , Pageable pageable);

   }
</code>
In Angular5 the console.log(data) returns this result for exemple:
<code> {id: 1, dateDebut: 1526083200000, dateFin: 1526083200000}
</code>
So as you can see there is not the project element (that i need in front-end) .
I want to show in angular the contrat elements plus some information of the project related to .
Any idea ?
Comment: You will have to excuse me if I'm being over zealous, but you are breaking one of the OWASP top-ten rules, so hopefully you are not putting this code on the internet. You should never expose primary keys from a database in the front-end, and especially when they are auto generated by the database. In OWASP 2013 this was known as **Insecure Direct Object References** in OWASP 2017 you can find it as **A5-2017: Broken Access Control**. Personally I always use a DTO when transporting data to the front-end. There are a lot of SO posts on DTOs and entities that you can read for more details.
Comment: Thank you for these useful interesting information , i will absolutely read about that , so you mean when we see number column in web app table or any others , it doesnt mean the one in database right ? I was always using the one in database
Answer: In place of jpaRepositiry you could use PagingAndSorting repository to get all the related entity details via findAll api .
Comment: can you please explaine more?
Comment: Please refer spring boot documentation .


Double values (products) in Commerce cart form

Question: I use Drupal Commerce version 8.x-2.15. I have a multilingual Drupal site with multiple languages based on domain.
mystic.com -> EN language
mystic.eu -> NL language
etc
I added relationships:
(order_items: Order item) Product variation
(Product variation) Product

To get the image_field available to show a thumbnail in my cart form. This works fine.
After I added those relationships and I add one product to my shopping cart and I see now the number of times that I translated my product back in the shopping cart, like:
My product
My product
My product
My product
(so above product is translated into 4 languages).
I've fixed this by adding a filter to the view:
Product: Translation language Is one of Content language selected for page

It looks like this is working but I see now 2 values (see screenshot)

It doubled the added product. But the price and quantity shows 1.
Comment: Did you add any contextual filters? You've checked that you're combining variations in the cart?
Comment: @TonyTheFerg I have a contextual filter `Order: ID`. How do I check combining variations in the cart?
Comment: Make sure to check that the product variation is set to Combine order items containing the same product variation.. This is under Manage Displayfor the product-type in question. @ admin/commerce/config/product-types/YOUR-PRODUCT-TYPE/edit/display.

For the Variations field, click the settings icon to the right, and ensure that Combine order items containing the same product variation. is checked.
Answer: In the commerce_cart _form view under Advanced, edit the Query Settings, and set it to DISTINCT.
Comment: This is already set in Manage Display...
Comment: Is your contextual filter default as it came?
Comment: Also have you tested removing relationship requirements? (not the relationship itself, but the requirement of it)
Comment: I am not sure. It's set to Provide default value type Fixed
Comment: ok. that should be fine then
Comment: Try requiring relationships for the new relationships you added.
Comment: For all three relationships I have unset Require this relationship. But it doesn't make any difference
Comment: Last guess, try to remove the filter criteria, and set the contextual filter to the language selected. You might want to first save changes and export your config, so that you can import config to revert your changes.
Comment: Let us [continue this discussion in chat](https://chat.stackexchange.com/rooms/101614/discussion-between-meez-and-tonytheferg).
Comment: Answer edited. Please review
Answer: I just ran into the same situation and in my case the solution was to filter the products on the current language or neutral / not applicable language.
The duplicate result was a translation of that related product. Afterwards the "DISTINCT" option could be removed.
So try filtering on current language and language neutral / not applicable.


Image field upload shows a broken preview until I reload the page

Question: When I upload an image it does an AJAX upload and then tries to show the thumbnail but the thumbnail style of that image is not available, so it shows up as a missing image. If I save and come back to the form, then it displays fine.
Comment: Please compare paths in both cases and check the difference?
Comment: The paths are identical
Comment: the image does not exist until the entity is saved
Comment: Have you tried `sudo chmod -R 777 files/`?
Answer: make sure the "image style" of your image field exists. for example to make sure about our "Article" content type, we check the path below:

http://yoursite.com/admin/structure/types/manage/article/fields/field_image

find your "image style" name and then go the path below:

http://yoursite.com/admin/config/media/image-styles

check the image styles name and make sure "Article" image style is here. if it's not, you have to change image style of your content type.


Abrir o Whatsapp em um contato específico através de um web link

Question: estou fazendo uns testes onde através de um link ao ser clicado, abra o whatsapp já em um contato específico.
Qual o cenário?
O cliente que entrar no site pelo smartphone vai aparecer um ícone e quando clicar no ícone, abre o whatsapp para o cliente já na tela para ele conversar conosco.
Depois de algumas pesquisas eu encontrei este exemplo: LINK
No Android até abre o whatsapp na tela para conversar, mas se antes já tiver existido uma conversa e ela estiver salva.
Se não tiver existido um contato anteriormente, mostra uma mensagem dizendo que "provavelmente eu estou tentando enviar uma mensagem para um contato que não tem o whatsapp instalado e dá a sugestão de convidar para usar".
Ou seja, só funciona se tiver havido uma conversa anteriormente. Então eu preciso saber uma forma de chamar um contato específico mesmo sem ter a necessidade de uma prévia conversa.
Fico grato quem poder ajudar. Forte abraço
Answer: Você precisa usar https://api.whatsapp.com/send?phone=seu-numero&text=mensagem-inicial
Isso vai funcionar mesmo sem o contato prévio, tanto para android quanto ios
Caso seu site seja em wordpress o plugin WhatsApp Chat faz isso pra você de forma automática, basta colocar o número e mensagem que deseja.
Já para web e desktop, basta trocar o 'api' da url por 'web'