Como posso pausar e dar play em um gif?

Question: Quero colocar no meu site, um sistema igual o do 9gag, onde as pessoas podem pausar e dar play em um .gif. Eu sei que tenho que usar duas imagens, um .jpg e um .gif, mas tentei algumas funções e não consegui.
Achei essa função :
    function is_gif_image(i) {
        return /^(?!data:).*\.gif/i.test(i.src);
    }

    function freeze_gif(i) {
        var c = document.createElement('canvas');
        var w = c.width = i.width;
        var h = c.height = i.height;
        c.getContext('2d').drawImage(i, 0, 0, w, h);
        try {
            i.src = c.toDataURL("image/gif"); // if possible, retain all css aspects
        } catch(e) { // cross-domain -- mimic original with all its tag attributes
            for (var j = 0, a; a = i.attributes[j]; j++)
                c.setAttribute(a.name, a.value);
            i.parentNode.replaceChild(c, i);
        }
    }

    function unfreeze_gif(id, src) {
     i = document.getElementById(id);
        i.src = src;
    }

Mas eu não sei o que passar por parâmetro e nem como usá-las no HTML.
Answer: Eu gostaria de sugerir uma solução alternativa. Ela dá um pouco mais de trabalho, mas te dá mais controle sobre a animação (permitindo que você não apenas pause, mas altere a a velocidade ou até mesmo reverta a direção frente/atrás). Ela utiliza uma excelente biblioteca chamada EaselJS.
O primeiro passo é converter o arquivo Gif para um formato de "folha de animação" (sprite sheet). Vou usar como exemplo esse Gif do Homer Simpson saltitando (fonte: We Love Animated Gifs):

O Gif animado contém uma série de imagens que são substituidas continuamente produzindo o efeito de animação. Nesse exemplo, a animação se dá pela intercalação de 10 imagens. Se você abrí-la em um editor como o Gimp (recomendadíssimo!), verá cada imagem em uma camada (layer) diferente:

A ideia é produzir a partir dessas camadas uma única imagem com cada camada disposta em uma matriz. Como são só 10 quadros, pode-se colocar uma ao lado da outra, produzindo o seguinte sprite sheet:

Bom, dá pra fazer isso com várias ferramentas (existem até algumas comerciais bacanas como o Texture Packer) ou até programando você mesmo alguma coisa, mas eu uso o Gimp mesmo (de graça!). :) Ah, com a ajuda de um ótimo plugin chamado G'MIC.
Funciona assim:

Após abrir o arquivo Gif no Gimp, inverta as camadas (senão o empacotamento do G'MIC vai colocar os quadros de forma invertida do original). Para isso, execute a opção de menu CAMADA -> PILHA -> REVERTER ORDEM DAS CAMADAS.
Então, com o G'MIC previamente instalado (na página do plugin a informações sobre como instalar), acesse-o por meio da opção de menu FILTROS -> G'MIC.
Nos filtros disponíveis (conforme ilustração a seguir), encontre a opção "Layers to tiles" dentro da pasta "Layers" (selecionado em cinza no meio). Configure para utilizar uma linha no campo Y-TILES (indicado em vermelho na direita) e para processar todos as camadas e gerar uma nova imagem (indicados em vermelho na esquerda). Então, clique em OK.

Será gerada uma nova imagem com o sprite sheet desejado. Exporte-a para um png e construa o código como no exemplo a seguir:
<!DOCTYPE html>

    <canvas id="myCanvas" width="300" height="300">
        Aqui deveria haver um canvas! :)
    </canvas>
    <button id="toggleButton" onclick="togglePause();">Pausar</button>

O código pode ser testado online no JSFiddle.
O código funciona assim:

Na função init o palco (stage) é criado para representar o canvas na biblioteca createJS (o EaselJS faz parte desse pacote). Então, a imagem com o sprite sheet é carregada, com a indicação de uma função de tratamento do evento de término handleImageLoad.
Na função handleImageLoad o sprite sheet é criado e utilizado como parâmetro para o objeto Sprite que é adicionado ao palco. O JSON com a definição do sprite sheet é bastante simples: ele indica a(s) imagem(ns) a ser(em) utilizada(s), configura os quadros (frames) da animação em termos de seu tamanho em pixels e da posição de registro (qual é o ponto que representa o x e y do objeto) e detalha as animações. As animações são construídas indicando um nome qualquer (no exemplo, "run"), o quadro de início (no exemplo, 0), o quadro de fim (no exemplo, 9 - lembrando que são 10 quadros), qual é a próxima animação a ser executada após o final desta (no exemplo, executa run novamente) e um percentual de atualização relativo à taxa de atualização de 30 quadros por segundo (configurada no ticker). Esse último valor pode ser ajustado para tornar a animação mais rápida (valores maiores) ou mais lenta (valores menores).
A função gotoAndPlay executa uma animação com o nome dado (há a opção gotoAndStop que executa uma única vez) e as funções stop e play respectivamente param e reiniciam a animação.

Por curiosidade, a reversão do sentido de animação pode ser realizada com a ajuda de um método chamado createjs.SpriteSheetUtils.addFlippedFrames. Veja um exemplo neste link.
P.S.: Depois de tudo isso, pensei que talvez você não seja o produtor do Gif e por isso não consiga manipulá-lo previamente para gerar o sprite sheet. Bom, nesse caso, talvez seja possível utilizar algum outro código para converter online a imagem Gif em um sprite sheet (acho que vale uma pesquisa a respeito, mas a tarefa fica pra você ou pra outra pessoa que quiser/puder ajudar). :)
EDIT: O usuário @MisaelBraga excluiu sua resposta, mas nela ele citou uma fonte bacana em que o mesmo efeito (sprites em HTML5) é obtido diretamente com o uso do canvas, isto é, sem a necessidade de se utilizar a biblioteca EaselJS. A fonte pode ser acessada aqui. Se ele recriar a resposta com mais detalhes (pode até copiar o que eu estou escrevendo aqui, sem problemas), eu removo essa edição (por favor me avise para que eu o faça).
O princípio dessa solução é mesmo:

Inicialmente ele cria um "palco" com o canvas e carrega a imagem do sprite sheet (função onload);
Então, define um relógio de atualização (função update) com a ajuda da função setTimeout do Javascript.
Na função update está incluída a renderização (chamada para a função redraw), onde o "sprite" é desenhado com a copia de um "pedaço" atual da imagem, ou seja, um quadro. A variável frame controla o quadro atual, e a chamada de ctx.drawImage indicando a posição inicial de cópia da imagem original com base no valor de frame faz a "mágica". O tamanho do sprite é fixo em 96x54.

O sprite sheet utilizado no exemplo é o seguinte (reproduzido da fonte original):

E o código final (também reproduzido da fonte original) é esse:
<!doctype html>

  </script>

<canvas id="gameCanvas"></canvas>

Também disponível no JSFiddle do autor.
Utilizando esse código, a "pausa" pode ser implementada facilmente evitando-se a atualização da variável frame enquanto a pausa estiver ativada.
Answer: +1 por uma pergunta interessante.
Essa(s) funções que você colocou funcionam bem. Não é de facto possivel parar um .gif que é por natureza animado.
As outras soluções que conheço são:

substituír o gif por uma imagem estática (que você referiu)
repôr a cada milisegundo o img.src para o gif estar sempre na primeira frame. Desaconselho pois tem custos altos de performance.

Deixo aqui um exemplo e código comentado:
Exemplo
Javascript comentado:
window.onload = function () { // quando a página carregar, fazer o que está dentro da função
    document.body.appendChild(i); // juntei ao meu documento a imagem criada em baixo
    var parar = document.getElementById('parar');         // botão exemplo
    var continuar = document.getElementById('continuar'); // botão exemplo
    parar.addEventListener('click', function () {  // chamar a função freeze_gif() quando carrego no botão parar
        freeze_gif(i)
    });
    continuar.addEventListener('click', function () {
        unfreeze_gif('minhaImagem', src)   // chamar a função unfreeze_gif() quando carrego no botão continuar
    });
}

function is_gif_image(i) { // verificar se o elemento i tem um src válido
    return /^(?!data:).*\.gif/i.test(i.src);
}

function freeze_gif(i) {
    var c = document.createElement('canvas'); // criar um elemento canvas (que na verdade nunca se usa na página)
    var w = c.width = i.width;   // dar a mesma largura que a imagem
    var h = c.height = i.height; // dar a mesma altura que a imagem
    c.getContext('2d').drawImage(i, 0, 0, w, h); // desenhar a imagem nesse canvas que está na memória
    try {
        // este método do canvas permite guardar o estado/imagem actual do canvas numa imagem
        // assim atribui à imagem (src do elemento i) o conteudo retornado por .toDataURL()
        i.src = c.toDataURL("image/gif");
    } catch (e) {
        console.log('Erro: ',e); // adicionei este log para a console. Aqui dispara um erro no caso de a imagem estar num dominio diferente. Isso não é aceite.
        for (var j = 0, a; a = i.attributes[j]; j++)
        c.setAttribute(a.name, a.value);
        i.parentNode.replaceChild(c, i);
    }
}

function unfreeze_gif(id, src) {
    i = document.getElementById(id); // ir buscar o elemento passado a ID, aqui você pode modificar para passar o proprio elemento, depende de como vai usar depois
    i.src = src;  // voltar a atribuir a imagem original, que é animada, ao elemento img. Aqui a imagem começa da primeira frame
}

var i = document.createElement('img'); // crio um elemento img
i.id = 'minhaImagem';  // dou-lhe um ID para poder chamar mais tarde
var src = 'http://www.thisiscolossal.com/wp-content/uploads/2013/01/1.gif'; // aqui usei em vez deste link, a mesma imagem mas em Base64. Assim conseguí fazer a demo sem ter problemas de CORS
i.src = src; // atribuir o link ao src da img

Comment: Que interessante ! +1 - muito legal isto, não sabia que dava de fazer

Como posso pausar e dar play em um gif?


Filtering a collection of objects by ID

Question: Teaching myself some c# and my problem is that I have a class which creates Person objects and adds them to a List (myPersonList). I also have a PartyGroup class which takes a PersonList as one of its properties. My issue is that myPersonList contains the whole results set so at the moment each time it creates a new PartyGroup it adds all the values in myPersonList. Is there a way to tell it to only add those values in myPersonList where the Person.PartyGroupId matches the current PartyGroup groupID we are dealing with. Hope that makes sense. Thanks.
//Person
using (AseDataReader reader = commandPerson.ExecuteReader())

        {
            while (reader.Read())
            {
                Person person = new Person();
                person.PersonID = Convert.ToInt32(reader["person_id"]);
                person.PartyGroupID = Convert.ToInt32(reader["party_group_id"]);
                person.FullName = reader["full_name"].ToString();

                myPersonList.Add(person);
            }
        }

//PartyGroup
using (AseDataReader reader = commandPartyGroup.ExecuteReader())

        {
            while (reader.Read())
            {
                int groupId = Convert.ToInt32(reader["party_group_id"]);

                if (myPartyGroupList.Where(partyGroup => partyGroup.PartyGroupID == groupId).Any() == false)
                {
                    PartyGroup partyGroup = new PartyGroup()
                    {
                        PartyGroupID = groupId,
                        PartyGroupName = reader["party_group_name"].ToString(),
                        PersonList = myPersonList//where PersonList objects contain this groupId???

                    };

                    myPartyGroupList.Add(partyGroup);

                }

            }

        }

Answer: If I understand your problem correctly, you just need:
PersonList = myPersonList.Where(p => p.PartyGroupID == groupId).ToList();

Comment: Yes that line of code makes sense but I am still getting strange results. So I have 3 partyGroups and each should be 10 rows. My select query is sorted by GroupID. What I am seeing is that if I select the first 10 rows my first partyGroup gets populated but not the other 2 which is fine. When I select the first 20 rows it adds 20 rows to the first partyGroup, 20 to the second partygroup and nothing to the third partyGroup instead of adding only the next 10 to the second partyGroup. And same when I add all 30 rows - it adds everything to all partyGroups. Any ideas?
Comment: Mmmh, seeing just the code you posted it should work. Did you try to debug it step by step ?
Comment: I'm doing that now - thinking its something to do with the GROUP BY in my SQL query. Thanks for your help

Filtering a collection of objects by ID


Disable Fast User Switching

Question: On Windows 10 Pro Desktop I'm looking for a local setting to limit the number of user sessions allowed to be running to 1.
This is not through use of remote desktop client.  It's physical access to the desktop and multiple users accessing it.
For example, when the desktop is locked for User A then User B may sign into the workstation at its keyboard. User A's session is still active in the background using memory/disk resources and can be switched back to, as seen on the Task Manager Users tab (can click Signout there), or by Windows Start Switch User icon to switch back to a session. A number of users can be logged in and switch between their sessions.
A number of users eventually eat up too many resources slowing the machine. Users don't bother to log off. This is the core of the issue. I want to automate it rather than teach it.
I'm looking for a way to tell the machine to not keep other user sessions, or to limit the total to 1 (the current) effectively causing the others to be logged off instead of sit in the background. Either way the outcome would be no pile-up of user sessions on the machine.
It's for a boardroom computer which suffers the issue of too many user sessions over time.  I'm looking to limit only shared boardroom computers to 1 session.
An Active Directory server is available on premises.
Answer: What you are asking to do is to disable "Fast User Switching."
It can be done with GPO, or registry tweaks.
Set the "Hide entry points for fast user switching" GPO in Computer Configuration\Administrative Templates\System\Logon.
Or, create the following DWORD in the registry: HKLM\Software\Microsoft\Windows\CurrentVersion\Policies\System\HideFastUserSwitching=1
Comment: The next logical bit is how to forcibly log off the user who locked the screen and left, so that the machine is usable by the next user. I expect the OP won't consider this a complete solution without it.
Comment: @MichaelHampton it's been a long time since I used this. I remember a time where I was prompted to log off the other user when I logged in. Is that not the case any more?
Comment: You could combine this with a scheduled task to query session, filter for 'disc' and logoff [session#].

Disable Fast User Switching


Fetch all emails across all Gmail contact groups

Question: I am trying to fetch all the emails from the user contacts using JS library.
Setup
1.) Initialised the gapi client using
gapi.client.init({
      apiKey: config['google']['apiKey'],
      discoveryDocs:
     ["https://www.googleapis.com/discovery/v1/apis/people/v1/rest"],
      clientId: config['google']['appId'],
      scope: "https://www.googleapis.com/auth/contacts.readonly"
})

2.) After the user grants permission, I try to fetch the contact details
gapi.client.people.people.connections.list({
         'resourceName': 'people/me',
         'pageSize': 500,
         'personFields': 'names,emailAddresses'
       }).then((response) => {
         let connections = response.result.connections;
         console.warn(connections);
})

3.) From step 2, I get zero connections.
However, when I perform
gapi.client.people.contactGroups.list()

I get following response
{
  "contactGroups": [
    {
      "resourceName": "contactGroups/all",
      "groupType": "SYSTEM_CONTACT_GROUP",
      "name": "all",
      "formattedName": "All Contacts",
      "memberCount": 13
    },
    ...
  ],
  "totalItems": 9,
  "nextSyncToken": "EJjRiq3lnNYC"
}

From the response, I can see that in contactGroups/all group, I have 13 contacts and in my account i can see the same number of contacts.
So, what is the proper way to get all the contacts across all the contact groups using JS library?
Answer: I've tried using gapi.client.people.people.connections.list and successfully got 200 response. I also don't get equal values.
Using gapi.client.people.people.connections.list, here is the response:
....
],
 "nextSyncToken": "^***",
  "totalPeople": 19,
  "totalItems": 19
}

While in gapi.client.people.contactGroups.list(),
{
  "resourceName": "contactGroups/all",
  "groupType": "SYSTEM_CONTACT_GROUP",
  "name": "all",
  "formattedName": "All Contacts",
  "memberCount": 155
},

Be noted that people.connections.list only provides a list of the authenticated user's contacts merged with any connected profiles. While contactGroups.list lists all contact groups owned by the authenticated user. Members of the contact groups are not populated.
Comment: i was checking the `Import contacts` feature of airbnb and when i allow permission they fetch all my emails from contacts but with the JS library I get none. I wonder how do they do it


How to switch Authentication from one user to another using Laravel

Question: Firstly, I login as user X, and I have a function like:
public function loginAs($userId)
{
    Auth::loginUsingId($userId); // now use Y user
    return response()->json(['logged' => Auth::check(), 'user' => Auth::user()]);

}

and when I try to print out Auth::check() it returns TRUE which is fine so far I am logged now as user Y, the thing is that I do first login as an X user and then switch to another Y user but when I do call some other functoins it seems that the current user logged is still X, and I want to be Y the current user logged... This might have to do something with session or I dont know exactly how to do this thing, would be grateful if someone has any sample or have any idea how to achieve such things in Laravel 5.
Comment: Did you try `Auth::logout()` before `Auth::loginUsingId($userId)`?
Comment: Are you saying that after logging in with user Y, `Auth::user()` is still returning the X user? What is the result of `dump(Auth::loginUsingId($userId));`?
Comment: Try this one http://laravel-tricks.com/tricks/temporary-user-switching
Comment: Did you switched user without logging out first one?
Answer: Can you elaborate? I was able to switch users using the following:
use Auth;

class TempController extends Controller
{

    public function index() {
        $user = User::find(1);
        Auth::login($user);
        var_dump(Auth::user()->id); // returns 1
        Auth::logout();

        var_dump(Auth::user()); // returns null

        $user = User::find(2);
        Auth::login($user);
        var_dump(Auth::user()->id); // returns 2
        Auth::logout();

    }
}

routes.php
Route::get('/temp', 'TempController@index');

If you run this, you can see the logged in user's id changes.
Comment: Good solution. You can also make it have a parameter so u can choose which account to switch too: `Route::get('debug/hopacc/{id}', 'ProfileController@debughop')->name('debug.hop');`
`public function debughop($id)
    {
        $user = User::find($id);
        Auth::login($user);
        return redirect('costumer/account/edit')->with('user');
    }` edit: make sure to check if the user exists first :)
Answer: You should use impersonating
There is a weblog post about that
http://blog.mauriziobonani.com/easily-impersonate-any-user-in-a-laravel-application/


Permission needed to use ScriptDb in new project

Question: I try to use ScriptDb in a new project which is run as a GAS in the web-site. As soon as the row var stored = db.save(ob); is added, even as commented!, to the code the GAS does not work anymore. It try's to load the GAS but instead on the screen appears "You need permission to do this" <-- free translation from my language! :-) In the old project the DB works fine.
Actually I noticed that for Example var results = db.query({employee_id: 1}); causes the same. So it seems that no DB related is allowed...
I use this same code in both projects:
var db = ScriptDb.getMyDb();
var ob = {type: "employee",
            employee_id: 1,
            department_id: 52};
var stored = db.save(ob);

Any advices?
Answer: Each time you add a new service that needs authorization, you will have to explicitly authorize the script from the Script Editor.
Open the script editor, run any function, you will be prompted for authorization. Complete the authorization process.
Comment: Thank you Srik, your answer was perfect!


Get the index of a non-alphanumeric-string in a list containing non-alphanumeric elements in python

Question: I have a file (test.txt) like this:
[06/Oct/2017:20:18:47 +0200] [pool-2-thread-7] http://10.12.214.20
[06/Oct/2017:20:19:38 +0200] [pool-2-thread-4] http://10.12.214.18
[06/Oct/2017:20:19:38 +0200] [pool-2-thread-4] http://10.12.214.18
[06/Oct/2017:20:19:49 +0200] [pool-2-thread-8] http://10.12.214.18
[06/Oct/2017:20:19:59 +0200] [pool-2-thread-7] ends.
[06/Oct/2017:20:20:47 +0200] [pool-2-thread-7] http://10.12.214.20
[06/Oct/2017:20:21:24 +0200] [pool-2-thread-4] ends.
[06/Oct/2017:20:21:34 +0200] [pool-2-thread-8] ends.

As a python-beginner i wanted to get the linenumber of a specific line, so i searched for a solution and found this post:
Finding the index of an item given a list containing it in Python.
I am using the answer of @tanzil, because later on it is possible, that i do look for elements not in the list.
This is what i do:
Save the lines of the original file in a list:
with open(test.txt) as f:
    content = [line.rstrip('\n') for line in f]
    print len(content)
index = [x for x in range(len(content))]

Iterate through the original file:
with open(test.txt, "r") as file:
    for line in file:
        print find_element_in_list(index, line.rstrip('\n'))

Find the index of each line of the original file:
def find_element_in_list(index_list, list_element):
    try:
        index_element = index_list.index(list_element)
        return index_element
    except ValueError:
        return None

As a result, there is no match at all.
I only get "None" as output.
I read this post 'is' operator behaves differently when comparing strings with spaces and hoped to get an answer to my question, but couldn't adapt the answers to my problem.
I would apreciate any hints or ideas!
(This is not a dublicate of Get Line Number of certain phrase in file Python because i need to access the indices of different lines multiple times. I am not iterating through the file everytime i need a specific one.)
Comment: Possible duplicate of [Get Line Number of certain phrase in file Python](https://stackoverflow.com/questions/3961265/get-line-number-of-certain-phrase-in-file-python)
Comment: @sunjazz Try printing the exception. It will help you debug the problem.
Comment: @akhilsp i did, but i got some error, saying that "[06/Oct/2017:20:18:47 +0200] [pool-2-thread-7] http://10.12.214.20" is not an element of the list. Your answer is working fine!
Comment: Glad to know that!
Answer: I think you are looking in the wrong list. Instead of looking in the index, try looking in content
with open('test.txt', "r") as file:
    for line in file:
        print find_element_in_list(content, line.rstrip('\n'))

Answer: To get the line number, you can try this:
file = open('filename.txt')
data = file.readlines()
target = "[06/Oct/2017:20:19:49 +0200] [pool-2-thread-8] http://10.12.214.18"
for i, item in enumerate(data, start=1):
    if item == target:
        print('Target is in line: ', str(i))

Comment: tried your solution, but its still printing out None.
I do need the loop over the file later on, so i nested the "target" and "the_index" into the for loop like this:

    content = [i.strip('\n') for i in open(testfile)]
    with open(testfile) as f:
        for line in f:
            target = line
            index = [i for i,a in enumerate(content) if a == target]
            index = None if not index else index[0]
            print index
Comment: @sunjazz I approved the edit, however, the previous solution worked for me when I tested it. Did you use a different target string?
Comment: Change enumerate's argument "start" to 0 (zero).


How do you add captions to each image of Flexslider? (already tried Google!)

Question: First of all, I tried to search the answer in Google, there weren't many results and those who were weren't very informative, clear, stepped, or guiding. I've also checked Youtube, and I found something that seem too general and too long for this purpose.
What I look for is the simplest way to add overlay captions to Flexslider images. The captions should be different per image and I need these captions to contain both a headline and a body texts (That's why I've guessed that the image title field won't be enough by itself and that the solution should come from another place).
Please give me some guidance, for example, where do I even start to get this, what is the logical place to put the text in per image? (I guess it wouldn't be CSS content), what are the ways to do it, etc... And I hope that your good and didactic guidance will endure for all users to come.
Answer: Well, after investigating for a short solution, and one that involves the minimal number of modules, it seems that as of 2/1/2015 there are 2 main ways to give per-images captions, to the images of the slider. It's good to Install Flexslider and creating a working slider-View of images, and right afterwards, implement one of these ways below.
The first way:
Install the module Image Field Caption. It's install is simple but you might have to do about 10 minutes of CSS:
After you have installed the module your images will now have (besides the potential ALT\Title attributes) a third attribute named Caption. You can easily edit it and it can also integrate with CKeditor.
After you have printed the captions you could add some CSS. as of 2/1/2015, the captions appear naturally under the picture, but if you want it to be over the picture (not above, but flying over, in it's bottom for example) with some nice transparent background, just edit the CSS property "Blockquoute" and make sure you give it:
<code>"Position: Absolute; right: 0; left: 0; bottom: 0; rgba(#,#,#,0.#); width: #%; height: auto;</code>. The rest is rather simple...
The second way:
2 CSS guys I spoke seem to would have preferred this option, though bear in mind that it contains 2 modules instead of 1, in the first solution:
Make the images of the Slider appear as CSS backgrounds. This could be achieved via the module CSS Injector. After the images been presented as backgrounds, a way must be found to print a caption attribute below or on the Image. one way to print it is via the module mentioned above - Image Field Caption. The other is to print the image's very own Title attribute via the module image caption formatter.
All luck, Ben.


Sequelize + NestJS: full outer join

Question: Is there a way to return data from db with a condition on a nested object and if the nested object is not present, return the parent anyway?
I have two models Mission and Request:
export class Mission extends Model<Mission> {
...
@HasMany(() => RequestEntity)
  requests: RequestEntity[];
...
}

export class Request extends Model<Request>{
...
  @Column({
    type: DataType.STRING,
  })
  status: string;

  @ForeignKey(() => Mission)
  @Column(DataType.UUID)
  missionId: string;

  @ForeignKey(() => User)
  @Column(DataType.UUID)
  userId: string;
...
}

So the relation between Mission and the Requests is one-to-many (mission can have more than one request). My goal is to filter the missions in the following way:

if the mission has no request associated (so no row in the Request table is present with that given missionId), return the mission
if the mission has one request for a given userId and the status 'pending', return the mission.

I tried looking at the documentation (Eager Loading - Sequelize),  but I don't find the solution. I am now trying this:
    const query: any = {
        limit: payload.limit,
        offset: payload.offset,
        order: [[payload.column, payload.direction]],
        where: {
          status: "open"
        },
        include: [{
          model: RequestEntity,
          where: { userId: user.id, status: 'pending' },
          required: false,
        }],
        transaction,
      };

I tried using required: false, however the result is that if the request is not pending or without the given userId, it does return the mission, just without the nested request. On the other hand, if I do not write required: false (by default it is required: true), all the missions without a requests are not returned.
Answer: You just need to use 2 sub-queries in where conditions in order to filter the parent table mainly because you wish 2 conditions on the same child table and also you use a paging.
const query: any = {
        limit: payload.limit,
        offset: payload.offset,
        order: [[payload.column, payload.direction]],
        where: {
          status: "open",
          [Op.or]: [
            Sequelize.where(Sequelize.literal('(SELECT COUNT(*) FROM "Request" where "Request"."missionId"="Mission".id)'), '=', '0'),
            Sequelize.where(Sequelize.literal(`(SELECT COUNT(*) FROM "Request" where "Request"."missionId"="Mission".id and "Request"."userId"=$userId and "Request".status='pending')`), '>', '0')
          ]
        },
        include: [{
          model: RequestEntity,
          where: { userId: user.id, status: 'pending' },
          required: false,
        }],
        bind: {
          userId: user.id
        },
        transaction,
      };

Comment: Hi Anatoly, thank you. Your solution does not work, the filters are not applied. I can see campaigns with status different from pending...
Comment: If you need to get messions that have only pending requests then you need to change the second `Sequelize.where` to Sequelize.where(Sequelize.literal(`(SELECT COUNT(*) FROM "Request" where "Request"."missionId"="Mission".id and "Request"."userId"=$userId and "Request".status<>'pending')`), '=', '0')
Comment: Still not working...My where is on id with Op.or:

- Sequelize.where(Sequelize.literal('(SELECT COUNT(*) FROM "Requests" JOIN "Missions" ON "Requests"."missionId" = "Missions"."id")'), '=', '0'),

- Sequelize.where(Sequelize.literal(`(SELECT COUNT(*) FROM "Requests" JOIN "Missions" ON "Requests"."missionId" = "Mission"."id" where "Requests"."userId"='${user.id}' AND "Requests".status<>'pending')`), '>', '0')

But I still see the status "selected" for example in the output.
Comment: Because you indicated `>` instead of `=`
Comment: Yes, sorry, my bad. Not working even with '='
Comment: Could you update the post with the latest subqueries and `include` option?

Sequelize + NestJS: full outer join


Modify process name at runtime

Question: I have an JFrame-App with multiple instance functionality and I need change process name (task manager) when started it,  because sometime it's necessary kill the process and It is imposible know which is the process that I want to kill, since all of them has the same name (executable name).
Answer: The name of a process cannot be changed at runtime. You would have to rename or copy the executable and then start it.

Modify process name at runtime


User-created tables are being made as hidden - Unable to delete/amend as Admin

Question: We have an Access 2003 Database (barbaric, I know) that requires users to create their own unique table, and use that table within a query to pull specified data. After which, the table is deleted and made afresh the next time they run the query...
It seems a very small handful (5 users out of 600+) have seemed to make tables that appear almost like system objects, hidden. I had to go through the options and view hidden/system files for them to appear, as at first I couldn't understand why they would get the error to make a new table when the old table wasn't appearing. Due to this those users are no longer able to delete/amend their existing table to run the queries. When they try, they get the below message:
"Run-time error '3033':
    You do not have the necessary permissions to use the 'TABLE_NAME' object. Have your system administrator or the person who created this object establish the appropriate permissions for you."
I've gone into the tables myself and I'm unable to delete these tables or even find a way to gain access permission to delete them.
I have two questions really:-
Firstly, I don't understand how very occasionally these users managed to make their table in this format (as they have made hundreds in the past normally, and just this one time it seems to have been done in this way). I worry that even by removing these stuck tables that the issue will come around again and we'll have to spend time manually going in and changing permissions to delete these tables.
And second, how would I go around finding a way to delete these tables?
Comment: have you tried compacting and repairing the file?
Comment: Does the Access MDB have user-level security applied?
Comment: Does this application consist of a single MDB file on a network share which all 600+ users open directly?  Or are you using a split application where each user has their own copy of a front-end MDB, with the front-ends linked to a shared back-end MDB?
Comment: @Hellow - Yes, compacted several times and nothing gets removed out of that.
Comment: @HansUp - No user-level security, but the database has a password and will automatically lock out 95% of the menu system through VBA on launch. Yes, a single .MDB file on a network share, we're currently unable to give every user their own copy so we thought this may be the best way around the situation.
Answer: In an MDB format database without ULS (user-level security), user operations are performed as the Admin Access security account user.
In your situation, it seems you have a user --- let's call him Fred --- who created a table named tblFred.  But now you are unable to delete that table.
Even though you have not applied ULS, Access still maintains user and group permissions for database objects.  And it sounds like somehow the AdMin user has lost the necessary permissions on tblFred.
In order to delete the table, Admin needs DROP permission for tblFred.  And if the table contains any data, Admin also needs DELETE permission.
Go to the Immediate window (Ctrl+g) and GRANT Admin those permissions.
CurrentProject.Connection.Execute "GRANT DROP ON TABLE tblFred TO Admin;"
CurrentProject.Connection.Execute "GRANT DELETE ON TABLE tblFred TO Admin;"

I'm unsure about precedence for those statements, so repeat them in reverse order if the first attempt doesn't allow you to then delete the table.  And hopefully that effort restores your ability to delete the table using your normal method.
You may want to inspect permissions on other database objects to look for inconsistencies.  (And actually you could use this instead of executing the GRANT statements if you prefer.)
DoCmd.RunCommand acCmdUserAndGroupPermissions

However, even if those suggestions worked, I can't explain why the permissions got broken in the first place.  As only a guess, I'll blame the fact that you have multiple users sharing the same front-end db file.  Although your data is housed in a separate db file, Access still maintains state for operations in the front-end sessions.  So when multiple users have the front-end open, things can get confused, and odd things can happen.  That is why the safest practice is to give each user their own copy of the front-end db file.
I just read the question and comments again.  I had assumed you're using a split application, but you didn't actually say that.  If the users are sharing a single db file which contains the data and the front-end pieces (queries, forms, reports, etc.), the situation is more fragile than I assumed.  Bad things are bound to happen.


How to define a Ruby Struct which accepts its initialization arguments as a hash?

Question: I have a situation where I would like to create a class which accepts many arguments and has setters and getters in the fewest lines of code possible (for maintainability). I thought that using a Struct would be a good idea for this:
Customer = Struct.new(:id, :username, :first_name, :last_name, :address1, ...etc...)

Customer.new(123, 'joe', 'Joe', ...etc...)

However, I don't like having to know the exact order of the attributes. I prefer Ruby 2's keyword arguments feature:
class Customer
  attr_accessor :id, :username, :first_name, ...etc...
  def initialize(id:, username:, first_name:, last_name:, address1:, ...etc...)
    @id = id
    @username = username
    @first_name = first_name
    ...etc...
  end
end

Customer.new(id: 123, username: 'joe', first_name: 'Joe', ...etc...)

However, writing this all out requires a lot more code and is more tedious. Is there a way to achieve the same thing in a short-hand like the Struct?
Comment: Just as a thought, you might prefer an OpenStruct.
Answer: In ruby 2.5 you can do the following:
Customer = Struct.new(
  :id,
  :username,
  :first_name,
  keyword_init: true
)

Customer.new(username: "al1ce", first_name: "alice", id: 123)
=> #<struct Customer id=123, username="al1ce", first_name="alice">

references:

https://ruby-doc.org/core-2.5.0/Struct.html
Comment: I've been waiting for this.
Answer: Cant you just do:
def initialize(hash)
  hash.each do |key, value|
    send("#{key}=", value)
  end
end

UPDATE:
To specify default values you can do:
def initialize(hash)
  default_values = {
    first_name: ''
  }
  default_values.merge(hash).each do |key, value|
    send("#{key}=", value)
  end
end

If you want to specify that given attribute is required, but has no default value you can do:
def initialize(hash)
  requried_keys = [:id, :username]
  default_values = {
    first_name: ''
  }
  raise 'Required param missing' unless (required_keys - hash.keys).empty?
  default_values.merge(hash).each do |key, value|
    send("#{key}=", value)
  end
end

Comment: I think it's **dangerous** to send all keys of the hash as methods using `send`. Use at least `public_send` (which refuses to send to private methods) or validate they keys against a list of allowed attributes.
Comment: If you want to avoid using `send`, you could just use `self[key] = value`
Comment: One drawback is that you don't get required keywords.
Comment: I found myself doing this in every project I worked on, so wrote a gem (https://github.com/rohitpaulk/named_struct) that makes this easier. It defines a `NamedStruct` class that inherits from Struct, and only changes the initialization behavior.
Comment: In addition, you can also call your constructor like this: `def initialize(*args) super(*args) end` that way you avoid the side-affects of named parameters.
Answer:
If you don't care about performance, you can use an OpenStruct.
require 'ostruct'

user = OpenStruct.new(id: 1, username: 'joe', first_name: 'Joe', ...)
user.first_name

=> "Joe"

See this for more details.

It's entirely possible to make it a class and define methods on it:
class Customer < Openstruct
  def hello
    "world"
  end
end

joe = Customer.new(id: 1, username: 'joe', first_name: 'Joe', ...)
joe.hello

=> "world"

But again, because OpenStructs are implemented using method_missing and define_method, they are pretty slow. I would go with BroiSatse's answer. If you care about required parameters, you should so something along the lines of
def initialize(params = {})
    if missing_required_param?(params)
      raise ArgumentError.new("Missing required parameter")
    end
    params.each do |k,v|
      send("#{k}=", v)
    end
end

def missing_required_params?(params)
  ...
end

Comment: That's neat, didn't know this. :)
Comment: This is close to what I want, but can you also make it a class and define methods on it?
Answer: In addition, you can rely on the constructor of Struct itself.
def initialize(*args)
  super(*args)
  # put your magic here!
end

This way you avoid the side-affects of named parameters etc.
Answer: You can use Struct and reduce the amount of code to a minimum by adding a factory method (called build here) and if necessary a validate method to your struct
Struct.new("Example",:a,:b) do
    def build(a:, b:nil)
        s = Struct::Example.new(a,b)
        s.validate
        return s
    end
    def validate
        unless a == 'stuff' || a == 'nonsense'
            raise ValidationError, "broken"
        end
    end
 end

 m = Struct.Example.build(a: 'stuff')

where validate is intended to so something like check strings have certain values, rather than just relying on the required parameters check.
Now you only have to remember the order once, when you write the build method
Answer: Variation on the theme, but a bit more refined, works in any ruby
class Struct
  module HashConstructable
    def from_hash hash
      rv = new
      hash.each do |k, v|
        rv.send("#{k}=", v)
      end
      rv
    end
    # alias_method :[], :from_hash
  end
end

and then
class MyStruct < Struct.new(:foo, :boo)
  extend Struct::HashConstructable
end

and you have best of both worlds this way - no funny name clashes and side-effects and it's clear want you want to do when you do it:
MyStruct.from_hash(foo: 'foo')

does exactly what you think it does. With a bit more possible side-effects but nicer syntax you can add the alias_method :[], :from_hash part, this allows you:
MyStruct[foo: 'foo']

this is also nice because it reminds (me) of the Hash[] constructor which creates a hash out of something that isn't hash.
Answer: This is one approach you could use.
class A
  def initialize(h)
    h.each do |k, v|
      instance_variable_set("@#{k}", v)
      create_method("#{k}=") { |v|instance_variable_set("@#{k}", v ) }
      create_method("#{k}")  { instance_variable_get("@#{k}") }
    end
  end
end

def create_method(name, &block)
  self.class.send(:define_method, name, &block)
end

a = A.new(apple: 1, orange: 2)
a.apple     #=> 1
a.apple = 3
a.apple     #=> 3
a.orange    #=> 2

create_method is straight from the documentation for Module#define_method.


Can't install new pypi packages on Google Cloud Composer

Question: We are using Google Cloud Composer with version composer-1.8.0-airflow-1.10.3 for scheduling our pipelines on GCP.
Lately, when we need to add some new Python packages to the environment (whether using Terraform or Cloud Console), we keep getting a strange error message but Cloud Composer is still up and new packages not installed.
The error message that appears on Cloud Composer UI :

Resource not found (resource=europe-west1-xxxxxxxxxxxxxxxxxxxx-composer-backend-sub-3fb66162-3xxxd-4f43-ba47-xxxxxx)., Http error status code: 400 Http error message: BAD REQUEST Additional errors: {"originalResponse":"{\"paths\":[\"/apis\",\"/apis/\",\"/apis/apiextensions.k8s.io\",\"/apis/apiextensions.k8s.io/v1beta1\",\"/healthz\",\"/healthz/etcd\",\"/healthz/log\",\"/healthz/ping\",\"/healthz/poststarthook/crd-informer-synced\",\"/healthz/poststarthook/generic-apiserver-start-informers\",\"/healthz/poststarthook/start-apiextensions-controllers\",\"/healthz/poststarthook/start-apiextensions-informers\",\"/metrics\",\"/openapi/v2\",\"/version\"]}","reason":"The descriptor url 'https://220.127.116.11/swaggerapi/apis/batch/v1' for type provider 'europe-west1-xxxxxxxxxxxxxxxxxxxx-addons-job-typer' could not be fetched."} , Http error status code: 400 Http error message: BAD REQUEST Additional errors: {"ResourceType":"gcp-types/storage-v1:storage.objects.list","ResourceErrorCode":"403","ResourceErrorMessage":{"code":403,"errors":[{"domain":"global","message":"email@example.com does not have storage.objects.list access to composer-unlistable.","reason":"forbidden"}],"message":"firstname.lastname@example.com does not have storage.objects.list access to composer-unlistable.","statusMessage":"Forbidden","requestPath":"https://www.googleapis.com/storage/v1/b/composer-unlistable/o","httpMethod":"GET","suggestion":"Consider granting permissions to email@example.com"}}

When looking to the Stackdriver logging, we can find this error message which is associated with that environment update:

status: {
     code: 9
     message: "FAILED_PRECONDITION"
    }

Any idea on what causes this behavior and how to resolve it?
EDIT:
Note that email@example.com is the service account used by Google for internal communication which is not manageable on IAM page (see Service Account Documentation).
Also, we noticed that sometimes adding a new package works correctly. But next time we try to add another package it fails with the same error message as above.
Comment: Did you upgrade your airflow version to 1.10.3 soon before you started getting this error? Also, have you manually upgraded the GKE cluster of the environment to version 1.14++?
Answer: I was able to reproduce this error by manually upgrading the GKE cluster of the Composer environment (composer-1.8.2-airflow-1.10.3) to 1.14.8-gke.12:

As mentioned in the documentation, Composer environments not using private IP should not upgrade GKE to 1.14+. These versions have deprecated Swagger in favor of OpenAPI. A future Cloud Composer release will create clusters that use OpenAPI and will enable upgrading existing environments to GKE versions 1.14 and beyond.
Currently, OpenAPI is used only for private IP environments and as a result, there is no issue there.
Unfortunately, there is no way to downgrade your GKE cluster, so the only solution would be to delete and recreate your environment.
Comment: Indeed that was the problem. We recreated the environment with GKE version 1.13. Thank you!
Comment: This is so ridiculous. Would upgrading GKE to `1.15.x` break anything else? I'm now stuck on `1.14.10` with this same issue. I'm trying to scale up the cluster, but get the error above.
Comment: Worse yet: I just created a new Composer environment. There were no options for the GKE version. It defaulted to `1.14.10-gke.17` where I can't install `pandas`. What can one possibly do? On my previous environment (the one that I manually upgraded GKE from 1.13 to 1.14) I tried upgrading to 1.15, and same issue. Is Cloud Composer completely useless now?
Answer: Looks like service email@example.com account does not have the correct permissions. In the IAM section add the 'Storage Object Viewer' role to this service account.
Comment: Actually, this is a google internal service account. https://cloud.google.com/iam/docs/service-accounts?&_ga=2.229816219.-62512895.1568807104#google-managed_service_accounts
Comment: Yes I am aware. You need to make sure those permissions are available to that service account.


Link to latest poll?

Question: I set up my poll tpl file to include the poll fields (form, results, etc) along with a list at the bottom for the previous polls, ordered by date.  What I am trying to do is, from the main menu, link to the latest poll.  In other words, my current latest poll is node/123456/.  I can link to that, obviously.  But when we create a new one, that link needs to be updated.  I'd love to have it so the menu item doesn't need to be edited each time a new poll is created.
Any ideas?
UPDATE
Just so you don't think I'm waiting expecting you to write it for me - this is where I am:

$items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'latest_poll_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );
return $items;
/**
 * Find latest poll and redirect user
 */
function latest_poll_find_poll() {
  $nid = db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = "poll"')->fetchField();
  $latest = is_numeric($nid) ? 'node/' . $nid : '';
  drupal_goto($latest);
}
Answer: Create a small custom module that implements hook_menu() and a custom callback that determines the latest poll and redirects the user.  Something like this perhaps (for D6, D7 will be similar):
Drupal 7

MYMODULE.info
name = "MYMODULE"
description = "Adds a menu item for the most recent poll"
core = 7.x

MYMODULE.module
<?php
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'MYMODULE_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Find latest poll and redirect user
 */
function MYMODULE_find_poll() {
  $nid = db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = :type', array(':type' => 'poll'))->fetchField();
  $latest = is_numeric($nid) ? 'node/' . $nid : '<front>';
  drupal_goto($latest);
}

Drupal 6

MYMODULE.info
name = "MYMODULE"
description = "Adds a menu item for the most recent poll"
core = 6.x

MYMODULE.module
<?php
/**
 * Implementation of hook_menu()
 */
function MYMODULE_menu() {
  $items = array();

  $items['poll/latest'] = array(
    'title' => 'Latest Poll',
    'page callback' => 'MYMODULE_find_poll',
    'access callback' => TRUE,
    'type' => MENU_NORMAL_ITEM,
  );

  return $items;
}

/**
 * Find latest poll and redirect user
 */
function MYMODULE_find_poll() {
  $nid = db_result(db_query('SELECT MAX(nid) AS nid FROM {node} WHERE type = "poll"'));
  $latest = is_numeric($nid) ? 'node/' . $nid : '<front>';
  drupal_goto($latest);
}

Replacing "MYMODULE" with the name of your custom module and placing those files in your site's modules directory in a folder named MYMODULE (replace of course).
Comment: Awesome, will give this a shot.  Always shy away from building my own modules for things, but it doesn't seem too complicated.  Should have mentioned D7, btw.
Comment: OK - so I added that module and enabled it.  Only change I made was what seemed to be a stray "}" under "return $items."

Now, how do I add it to the menu?  I tried directing the menu item to "poll/latest" but that just gives me a list of the polls.
Comment: Ah my bad, some code got cut out... not sure how that happened, edited answer.  You will need to change the database query to be compatible with D7 as the Database API has changed.  The `hook_menu()` function is where it gets added to the menu
Comment: @Mike updated answer for both versions if you needed it. I'm at the point where I need to learn more D7 anyway ;)
Comment: That did it - you are the man!  And now I understand how to use hook_menu.  Thanks a lot!!

Link to latest poll?


Removing all validation on submit

Question: I have a multistep form with two submit handlers (save/submit), when "Save" is clicked I want to remove any validation applied to the node and have it's contents saved.
In my custom validation hook I am checking both the triggering_element and clicked_button for the correct button, I'm then removing  limit_validation_errors however this doesn't work. According to the api documentation it should though.
function test_workflow_form_validate($form, &$form_state) {
  if ($form['#form_id'] != 'test_application_assessment_form') {
    if ($form_state['triggering_element']['#value'] == 'Save') {
      $form_state['triggering_element']['#limit_validation_errors'] = array();
      $form_state['clicked_button']['#limit_validation_errors'] = array();

      $form_state['buttons'][1]['#limit_validation_errors'] = array();
      // Remove validation.
    }
    else {
      // Add in default validation.
      //$node = (object) $form_state['values'];
      //node_validate($node, $form, $form_state);
      //entity_form_field_validate('node', $form, $form_state);
    }
  }
}

I've removed the default node validation so my custom one is the only one present. Is there something else I'm missing?
Comment: `$form['#form_id'] != ` ?! Are you sure it shouldn't be `==` there? Just asking, as it looks like a typo in code.
Answer: Your '#limit_validation_errors' may be set when the form gets built, not when it's processed.
Hence in your custom *_form() function or a hook_form_alter(); not in *_validation() or *_submit().
Answer: Use #limit_validation_errors property. You use it to set:

Values: array indicating sections of the $form_state['values'] which should be validated.

So for a button that's not supposed to trigger any validation, set it to empty array().
Note that this does not prevent validation hooks to be called. They will be called and you cannot do a thing about it. It just tells them to not set errors, but they are able to ignore it, and they will invoke side effects.
Also, setting it when there is already $form_state['triggering_element'] set is too late. It means that user has clicked a button that is supposed to validate everything, as at the moment of clicking there was no #limit_validation_errors set. You need to apply it before user clicks.
Answer: For node edit form, to remove validation on delete submit button just need to write the below code in your custom module for article content type node edit form.
function module_name_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'article_node_form') {
    if (!empty($form['nid']['#value'])) {
      // The nid is required for the delete confirmation form.
      $form['actions']['delete']['#limit_validation_errors'] = array(array('nid'));
    }
  }
}

Removing all validation on submit


Input desalinhado

Question: Estou tentando fazer com que o campo desça e fique debaixo do outro campo como esta no modal. Bem, vou explicar melhor, eu tenho um formulário, nesse formulário tem o botão para adicionar filho, ao clicar é aberto um modal, se a pessoa tiver mais de um filho a pessoa clica em + (que chama o JavaScript).
O problema é que esta desalinhado eu até consegui fazer com que dois campos descesse porém não esta debaixo do outro campo, vou colocar a imagem.

const add = document.getElementById("add");
const childrenContent = document.getElementById("content-children");
const formPersonalData = document.getElementById("formPersonalData");

function addNewInputChildren(e) {
  e.preventDefault();

  let count = childrenContent.children.length;

  const section = document.createElement("section");

  // nome filho
  const DivNomeFilho = document.createElement("div");
  DivNomeFilho.className = "col-md-5";
  const LabelNomeFilho = document.createElement("label");
  LabelNomeFilho.setAttribute("for", "nome_filho" + count);
  LabelNomeFilho.innerHTML = "Nome do Filho";
  const InputNomeFilho = document.createElement("input");
  InputNomeFilho.setAttribute("type", "text");
  InputNomeFilho.setAttribute("class", "form-control");
  InputNomeFilho.setAttribute("id", "nome_filho" + count);
  InputNomeFilho.setAttribute("name", `nome_filho[${count}]`);
  DivNomeFilho.appendChild(LabelNomeFilho);
  DivNomeFilho.appendChild(InputNomeFilho);

  // data nascimento
  const DivDataNasc = document.createElement("div");
  DivDataNasc.className = "col-md-3";
  const LabelDataNasc = document.createElement("label");
  LabelDataNasc.setAttribute("for", "nasc_filho" + count + "BornDate");
  LabelDataNasc.innerHTML = "Data Nasc";
  const InputDataNasc = document.createElement("input");
  InputDataNasc.setAttribute("class", "form-control");
  InputDataNasc.setAttribute("type", "date");
  InputDataNasc.setAttribute("id", "nasc_filho" + count + "BornDate");
  InputDataNasc.setAttribute("name", `nome_filho[${count}]`);
  DivDataNasc.appendChild(LabelDataNasc);
  DivDataNasc.appendChild(InputDataNasc);

  // escolaridade
  const DivEscolaridade = document.createElement("div");
  DivEscolaridade.className = "col-md-4";
  const LabelEscolaridade = document.createElement("label");
  LabelEscolaridade.setAttribute("for", "escolaridade" + count);
  LabelEscolaridade.innerHTML = "Escolaridade";
  const SelectEscolaridade = document.createElement("select");
  SelectEscolaridade.setAttribute("select", "name");
  SelectEscolaridade.setAttribute("class", "form-control");
  SelectEscolaridade.setAttribute("id", "escolaridade" + count);
  SelectEscolaridade.setAttribute("name", `escolaridade[${count}]`);
  DivEscolaridade.appendChild(LabelEscolaridade);
  DivEscolaridade.appendChild(SelectEscolaridade);

  // dependente
  const DivDependente = document.createElement("div");
  DivDependente.className = "col-md-4";
  DivDependente.insertAdjacentHTML("beforeend", "

");
  DivDependente.insertAdjacentHTML("beforeend", "

");
  DivDependente.style.position = "relative";
  const LabelDependente = document.createElement("label");
  LabelDependente.setAttribute("for", "dependente" + count);
  LabelDependente.innerHTML = "Dependente";
  const SelectDependente = document.createElement("select");
  SelectDependente.setAttribute("select", "name");
  SelectDependente.setAttribute("class", "form-control");
  SelectDependente.setAttribute("id", "dependente" + count);
  SelectDependente.setAttribute("name", `dependente[${count}]`);
  DivDependente.appendChild(LabelDependente);
  DivDependente.appendChild(SelectDependente);

  // I.R.
  const DivFir = document.createElement("div");
  DivFir.className = "col-md-4";
  // DivFir.insertAdjacentHTML("beforeend", "

");
  // DivFir.insertAdjacentHTML("beforeend", "

");
  const LabelFir = document.createElement("label");
  LabelFir.setAttribute("for", "fir" + count);
  LabelFir.innerHTML = "Fins para I.R.:";
  const SelectFir = document.createElement("select");
  SelectFir.setAttribute("select", "name");
  SelectFir.setAttribute("class", "form-control");
  SelectFir.setAttribute("id", "fir" + count);
  SelectFir.setAttribute("name", `fir[${count}]`);
  DivFir.appendChild(LabelFir);
  DivFir.appendChild(SelectFir);

  [DivNomeFilho, DivDataNasc, DivEscolaridade, DivDependente, DivFir].map(
    (item) => {
      section.appendChild(item);
    }
  );
  section.style.cssText = "display:flex; flex-direction: row; width:100%;";
  childrenContent.appendChild(section);

  // dependente.style.cssText = "margin-left; 10px;";
  // childrenContent.appendChild(dependente);
}

add.addEventListener("click", addNewInputChildren);

Cadastro de Filhos

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                                        ×
                                    </button>

                Nome Filho

                <input type="text" name="nome_filho[]" id="nome_filho" class="form-control">

                Data Nasc

                <input type="date" name="nasc_filho[]" class="form-control" id="escolaridade">

                Escolaridade
                <select name="escolaridade[]" class="form-control" id="escolaridade">
                  <option value="sel">Selecione</option>
                  <option value="2GC">Segundo Grau Completo</option>
                  <option value="2GI">Segundo Grau Incompleto</option>
                  <option value="CTC">Curso Técnico Completo</option>
                  <option value="CTI">Curso Técnico Incompleto</option>
                  <option value="NSC">Nível Superior Completo</option>
                  <option value="NSI">Nível Superior Incompleto</option>
                  <option value="PGC">Pós Graduação Completo</option>
                  <option value="PGI">Pós Graduação Incompleto</option>
                </select>

                  Dependente:
                  <select name="dependente" class="form-control" id="dependente">
                    <option value="">Selecione</option>
                    <option value="sim">SIM</option>
                    <option value="nao">NÃO</option>
                  </select>

                  Fins para I.R.:
                  <select name="fir" class="form-control" id="fir">
                    <option value="">Selecione</option>
                    <option value="sim">SIM</option>
                    <option value="nao">NÃO</option>
                  </select>

          <button type="button" class="btn btn-success" data-dismiss="modal">Salvar</button>
          <button type="button" class="btn btn-warning">Limpar</button>
          <button type="button" class="btn btn-info" id="add">+</button>

Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Idente o seu código antes de postar, e o JS não tem necessidade de estar aqui para resolver esse problema.
Vou tentar lhe dar uma dica pra resolver da forma que está:
A div da modal imagino que seja fixa ou absoluta, dentro dela crie uma outra div que servirá como um container para todo o conteúdo de sua modal, este container deve ter posição relativa e overflow hidden para evitar estouros de conteúdo como esse que está acontecendo na sua modal, após isso as suas divs que englobam os inputs devem estar todas com display inline block.

Agora as minhas sugestões de mudanças:
Recomendo muito que utilize Grid Layout para organizar melhor o conteúdo de sua modal ou de qualquer outra coisa no seu projeto (até dele como um todo), assim será muito difícil vc ter esse tipo de problema e não passará horas tentando "alinhar" elementos ou corrigir comportamentos inesperados, segue abaixo dois links ótimos com o básico do Grid Layout pra vc dar uma olhada com carinho:
https://www.origamid.com/projetos/css-grid-layout-guia-completo/
https://www.w3schools.com/css/css_grid.asp
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).

Input desalinhado


Use drupal #states to check a radio

Question: I would like to translate some jquery .change functionality to use #states in the form api.
var radio1 = jQuery('input:radio[name=radio_1]');
var radio2 = jQuery('input:radio[name=radio_2]');

radio1.change(function() {
if (radio1.filter(':checked').val() == 0) {
  radio2[1].checked = true;
}
else {
  radio2[0].checked = true;
}
});

radio2.change(function() {
if (radio2.filter(':checked').val() == 0) {
  radio1[1].checked = true;
}
else {
  radio1[0].checked = true;
}
});

Logic:
If radio1 value 0 is selected then radio2 value 1 will be selected.
If radio1 value 1 is selected then radio2 value 0 will be selected.
if radio2 value 0 is selected then radio1 value 1 will be selected.
if radio2 value 1 is selected then radio1 value 0 will be selected.
Looking at form_example_states_form() shows that the syntax is:
'#states' => array(
  'action_to_take_on_this_form_element' => array(
    'jquery_selector_for_another_element' => array(
      'condition_type' => value,
    ),
  ),
),

What's missing for me is "action_to_take_on_this_form_element". I don't know how to select value 0 or 1 of the radio button; all I have in terms of viable options is checked/unchecked (see drupal_process_states() for a list).
What I currently have
'#states' => array(
  'checked' => array(
    ':input[name="radio_2"]' => array(
      'value' => 0,
    ),
  ),
  'unchecked' => array(
    ':input[name="radio_2"]' => array(
      'value' => 1,
    ),
  ),
),

and this doesn't seem to work. I need something like checked[0] in order to select the value 0 radio button.
Edit: Here is the working code. Would like to not use inline js.
function your_form(&$form, $form_state) {
  $form['radios1'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 1',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    ),
    '#default_value' => 0,
  );

  $form['radios2'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 2',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    ),
    '#default_value' => 1,
  );

  $form['#attached']['js'][] = array(
    'data' => "var radio1 = jQuery('input:radio[name=radios1]');
var radio2 = jQuery('input:radio[name=radios2]');

radio1.change(function() {
if (radio1.filter(':checked').val() == 0) {
  radio2[1].checked = true;
}
else {
  radio2[0].checked = true;
}
});

radio2.change(function() {
if (radio2.filter(':checked').val() == 0) {
  radio1[1].checked = true;
}
else {
  radio1[0].checked = true;
}
});",
    'type' => 'inline',
  );

  return $form;
}

Demo video: https://www.youtube.com/watch?v=lXfMFaTTVes
Comment: Is this for `radio` or `radios` ?
Comment: the [radios](https://api.drupal.org/api/drupal/developer%21topics%21forms_api_reference.html/7#radios) type
Answer: You can use the form_api #after_build property to set a callback where you can manipulate the individual radio button elements (not the grouped "radios" element).
function your_form(&$form, $form_state) {
  $form['radios1'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 1',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    )
  );

  $form['radios2'] = array(
    '#type' => 'radios',
    '#title' => 'Radios 2',
    '#options' => array(
      0 => 'zero',
      1 => 'one',
    )
  );

  $form['#after_build'] = array('your_form_after_build_function');

  return $form;
}

function your_form_after_build_function($form) {
  $form['radios1'][0]['#states'] = array(
    'checked' => array(
      ':input[name="radios2"]' => array('value' => 1),
    ),
  );

  $form['radios1'][1]['#states'] = array(
    'checked' => array(
      ':input[name="radios2"]' => array('value' => 0),
    ),
  );

  $form['radios2'][0]['#states'] = array(
    'checked' => array(
      ':input[name="radios1"]' => array('value' => 1),
    ),
  );

  $form['radios2'][1]['#states'] = array(
    'checked' => array(
      ':input[name="radios1"]' => array('value' => 0),
    ),
  );

  return $form;
}

Comment: I've just raised an issue for this on drupal.org: https://www.drupal.org/node/2498791
Comment: Close but this is the result I get: https://www.youtube.com/watch?v=Z5LZDjuqVIY

This is what the original JS gives me: https://www.youtube.com/watch?v=lXfMFaTTVes
Comment: I can confirm that in my testing there is a bug, but not the same one you are encountering in your video.  I'm finding that it works perfectly at first but in some circumstances when you change one of the sets of radio buttons and the following change to the other set of radio buttons doesn't trigger the state change.  It looks like when changing the second radio set it compares the changed state to an incorrect "old value".  I think this may be a bug in core, although it could be that adding states to individual radio form elements in a "radios" element via #after_build isn't supported.
Comment: I'm pretty sure it works fine with normal checkboxes but radios are differents, that could explain why checked state is behaving that way.
Answer: Since #states is bugged for radios at the moment, another option might be to use an #ajax callback, as long as the extra server requests don't cause a problem for you:
function my_form($form, &$form_state) {
  $form = array(
    'radios1' => array(
      '#title' => 'Radios 1',
      '#type' => 'radios',
      '#options' => array(0 => 'Zero', 1 => 'One'),
      '#prefix' => '
',
      '#suffix' => '
',
      '#ajax' => array(
        'callback' => '_my_ajax_callback',
        'wrapper' => 'radios2-ajax-wrapper',
      ),
    ),
    'radios2' => array(
      '#title' => 'Radios 2',
      '#type' => 'radios',
      '#options' => array(0 => 'Zero', 1 => 'One'),
      '#prefix' => '
',
      '#suffix' => '
',
      '#ajax' => array(
        'callback' => '_my_ajax_callback',
        'wrapper' => 'radios1-ajax-wrapper',
      ),
    ),
  );

  if (isset($form_state['triggering_element'])) {
    switch ($form_state['triggering_element']['#name']) {
      case 'radios1':
        unset($form_state['input']['radios2']);
        if ($form_state['values']['radios1'] == 0) {
          $form['radios2']['#default_value'] = 1;
        }
        elseif ($form_state['values']['radios1'] == 1) {
          $form['radios2']['#default_value'] = 0;
        }
        break;

      case 'radios2':
        unset($form_state['input']['radios1']);
        if ($form_state['values']['radios2'] == 0) {
          $form['radios1']['#default_value'] = 1;
        }
        elseif ($form_state['values']['radios2'] == 1) {
          $form['radios1']['#default_value'] = 0;
        }
        break;
    }
  }

  return $form;
}

function _my_ajax_callback($form, &$form_state) {
  switch ($form_state['triggering_element']['#name']) {
    case 'radios1':
      return $form['radios2'];

    case 'radios2':
      return $form['radios1'];
  }
}

I wouldn't recommend this as a long-term solution though.

My original idea below suffers from the same #states bug as encountered when using an #after_build function, hence the strikethrough.
Given that the #after_build method is slightly bugged with the radios type, an alternative method that seems to work for me is to build the form out of individual radio elements and change the radio groupings using #attributes. That way you can set #states in your form constructor without needing an #after_build function:
function my_form($form, &$form_state) {
  $form = array(
    'radios1' => array(
      '#type' => 'container',
      '#prefix' => 'Radios 1',
      '#tree' => TRUE,
      1 => array(
        '#type' => 'radio',
        '#title' => 'One',
        '#return_value' => 1,
        '#attributes' => array(
          'name' => array(
            'radios1',
          ),
        ),
        '#states' => array(
          'checked' => array(
            ':input[name="radios2"]' => array('value' => 2),
          ),
        ),
      ),
      2 => array(
        '#type' => 'radio',
        '#title' => 'Two',
        '#return_value' => 2,
        '#attributes' => array(
          'name' => array(
            'radios1',
          ),
        ),
        '#states' => array(
          'checked' => array(
            ':input[name="radios2"]' => array('value' => 1),
          ),
        ),
      ),
    ),
    'radios2' => array(
      '#type' => 'container',
      '#prefix' => 'Radios 2',
      '#tree' => TRUE,
      1 => array(
        '#type' => 'radio',
        '#title' => 'One',
        '#return_value' => 1,
        '#attributes' => array(
          'name' => array(
            'radios2',
          ),
        ),
        '#states' => array(
          'checked' => array(
            ':input[name="radios1"]' => array('value' => 2),
          ),
        ),
      ),
      2 => array(
        '#type' => 'radio',
        '#title' => 'Two',
        '#return_value' => 2,
        '#attributes' => array(
          'name' => array(
            'radios2',
          ),
        ),
        '#states' => array(
          'checked' => array(
            ':input[name="radios1"]' => array('value' => 1),
          ),
        ),
      ),
    ),
  );

  return $form;
}

Note that I've changed your "Zero or One" radios to "One or Two" for this example because another bug in core means a radio with a value of 0 always gets checked when the form is built. If you absolutely must use a value of 0 then you'll need to work around that bug in some way.
Comment: Hi @mikeytown, yes that's the behaviour that morbiD and I have experienced.  Looks like it's down to the bug in core.  So I'd say your options currently are: 1. Wait for a potential resolution on that bug, 2. Go with it "as-is" (i.e. mostly working but slightly buggy), or 3. go back to the alternative plan of using custom javascript.
Comment: Still no dice; this is a video of that form: https://www.youtube.com/watch?v=HYN6epYIKco
Comment: Hi mikeytown, can I just check if you've still got any of your own javascript modifying the values?  It's just that in your videos you seem to be getting different results to morbiD and I (based on morbiD's comment at https://www.drupal.org/node/2498791#comment-9986937).  It could also be that some other module you have installed is affecting the result.
Comment: [jQuery update](https://www.drupal.org/project/jquery_update) 1.10 appears to be the issue. New video. It still has issues with radio 1 though. https://www.youtube.com/watch?v=VF70Czizbdk Issues start to show up at 1.7, 1.5 seems to work like core
Comment: @PaulQuerol See last comment
Comment: @mikeytown2 I don't know if it's an option for your project but until the bug with #states gets fixed, perhaps you could use an #ajax callback instead?
Answer: Have a look here:
Instead, you must use 'value' => 'name', where 'name' is the name of the radio option that you require to be selected.
In your example it could be '1' instead on 1.

Use drupal #states to check a radio


Question about functions in $L^2$ space

Question: Let $f,g \in L^2 (\mathbb{R})$. For $n \in \mathbb{N}$, define $f_n \in L^2(\mathbb{R})$ as $f_n(x) = f(x-n)$ for all $x \in \mathbb{R}$.
Prove that $\lim_{n \rightarrow \infty} \int_{\mathbb{R}} f_n g dm = 0$. ($m$ is a Lebesgue measure.)
I completely lose my way to solve this problem.
I thought that since we don't what $lim f_n(x)$ is, we need to bound the $\int_\mathbb{R}  f_n g dm$ to solve this problem.
But, how?
Answer: Try this way:

$g \in C^{\infty}_c(\mathbb{R})$, then you should be able to compute this limit
approximate $g \in L^2$ with $g_n \in C^{\infty}_c$ by density
Comment: Could you explain more specifcally?
Comment: Immagine $f$ and $g$ are both $C^{\infty}_c$, then what happens? When $n$ goes to infinity you expect $f_n$ and $g$ to have disjoint support and your integral to be 0. When $f$ is in $L^2$ and $g\in C^{\infty}_c$, approximate $f$ with $f^{\epsilon} \in C^{\infty}_c \,:\, ||f-f^{\epsilon}||_{L^1}< \epsilon $ and write $\lim_{n}\int f_n g$ = $\lim_{n} \int  (f_n - f^{\epsilon}_n )g + \int f^{\epsilon} g$  and so on.

Question about functions in $L^2$ space


Accessing files from a multiple datastores on a VSAN in VMware

Question: I have a VMware 6.7 environment running as a single datacenter, however with two clusters (say A-cluster and a B-cluster), each with 3 esxi hosts. A VSAN is configured on these clusters and has two VSAN datastrores (A-datastore and B-datastore) for A-cluster and B-cluster respectively.
Now, I have a iso file in the A-datastore and I'm trying to deploy a VM in B-cluster and in the process of deploying, I would like to mount the iso file present in the A-datastore. When I try to attach the CD/DVD and choose "Datastore ISO File" option, I only get to browse the B-datastore, but not the A-datastore.
Is this even possible?
Answer: The Virtual SAN datastores are ONLY presented to the hosts that are members of a particular cluster. But you can implement Content Library and store there all templates/iso/ etc.
Here is a detailed guide, how to create it - https://www.starwindsoftware.com/blog/working-with-content-libraries-in-vsphere-6-5
Comment: Yes, the purpose of Library is to share content accross different clusters. Folders are created for "local" usage inside one host/cluster.
Comment: Is the content library different from "Folders" that is typically created under the Hosts?


Java downloading file: "Connection timed out: connect"

Question: When I'm downloading file (35MB) using below code. It gives me the output as:

Connection timed out: connect

Below is my java codes for file downloading process. How can I fix this issue?
<code>//download file
public void download(String url, File destination) throws IOException {
    URL website = new URL(url);
    ReadableByteChannel rbc = Channels.newChannel(website.openStream());
    FileOutputStream fos = new FileOutputStream(destination);
    fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}

public void parserAction() throws Exception {
    // InputStream is = new FileInputStream("en-parser-chunking.bin");
    File modelFile = new File("en-parser-chunking.bin");

    if (!modelFile.exists()) {
        System.out.println("Downloading model.");
        download("file://E:/Final Project/Softwares and tools/en-parser-chunking.bin", modelFile);

    }
    ParserModel model = new ParserModel(modelFile);
    Parser parser = ParserFactory.create(model);
    Parse topParses[] = ParserTool.parseLine(line, parser, 1);
    for (Parse p : topParses) {
        //p.show();
        getNounPhrases(p);
    }
}
</code>
Comment: What kind of server are you trying to connect to?  Which line is giving you the error?
Comment: I'm downloading this file from my hard disk partition to my web application. The uploading task takes too much time and finally it says connection timed out: connect. Is there any way to stop this time out ? or speedup the downloading task ?
Comment: It's a "connection timed out" error, so your problem isn't speed, it's that you can't actually connect to the server.  I think the problem is that you're using a "file" protocol, when it should be http, e.g. http://myserver/en-parser-chunking.bin".
Comment: I'm not clear how to use http for this task. Can you please explain me littlie how to do it in this code ?
Comment: You say you're running a web application, so it should just be a case of changing the URL to where the document is being served by your web server, e.g. "http:..." etc..
Answer: Use following codes to set a time out for the connection manually and see which time will be long enough to let the file being uploaded successfully:
<code>            String url;

         try{
         HttpURLConnection Conn = (HttpURLConnection) new URL( url ).openConnection();

                                      Conn.setConnectTimeout(2000);
                                      Conn.setReadTimeout(2000);

             }
     catch (java.lang.ClassCastException|ConnectException|java.lang.IllegalArgumentException|java.net.MalformedURLException  ex) { }  //catch the possible exception.
     catch (SSLHandshakeException |SocketException | SocketTimeoutException | UnknownHostException ex)
</code>
Times are in milliseconds by the way.
Comment: I set both the connection timeout and read timeout as 60000 (60 seconds). Still the error Connection Timeout is thrown after around 15 seconds. Where did I go wrong?


Get each part of a Java String

Question: Hello guys I'm new to Java and would like to take this challenge myself, since I'm new I need some help from you.
I have a Java string like this:
String strTime = "8:44 PM";
I would like to get the hr, min and am/pm..
How can I do that? I'm also thinking if the hour is 2-digit? What else should I be considering? Thanks for your help.
UPDATE:
  String[] parts[] = strTime.split(":");
  String strHr = parts[0];
  String strMin = parts[1];
  String strAM = parts[2];

But I don't know how to capture for the other to be split like the space, etc.
Comment: You should either parse the String yourself using the functions in the String class, or you can look into regular expressions.
Comment: Have a look at SimpleDateFormat: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Comment: The correct approach of doing this is parse the String to Date and work with the Date API to get the hour/min etc.
Comment: possible duplicate of [How to parse a date?](http://stackoverflow.com/questions/999172/how-to-parse-a-date)
Comment: You may want to try this: http://docs.oracle.com/javase/7/docs/api/java/text/SimpleDateFormat.html
Comment: @hovanessyan can you expound more on that? Thanks
Comment: @user255798 the matter is really hard to explain to new people in Java - first Date's methods are deprecated, you have to use - String - to Date - to Calendar - conversion between objects, it's much easier using 3rd party solutions, but imo it's better to first learn standard language API. In your case the easier solutions will be Guava's Splitter (instead of String split()) and Joda Time (instead of java.util.Date + Calendar)
Comment: to convert the String to Date - check this -http://stackoverflow.com/a/1154990/1007273 - to convert the Date to Calendar - check this - http://www.vogella.com/tutorials/JavaDateTimeAPI/article.html
Answer: What you are doing is very inefficient, however a hardcoded solution:
String[] fistPart = strTime.split(":");
String strHr = firstPart[0];
String[] secondPart = firstPart[1].split(" ");
String strMin = secondPart[0];
String strAM = secondPart[1];

I also suggest looking at regex.
Comment: What can you suggest to improve my approach?
Comment: Why do not use java.util.Date ?
Comment: Depends on how you are gettig the string. If possible, get the time in integer format. If that's not possible, use regular expressions.
Answer: Try this piece of code:
    String strTime = "8:44 PM";
    String[] parts = strTime.split(":");
    String strHr = parts[0];
    String rest = parts[1];
    String[] rest2 = rest.split(" ");
    String strMin = rest2[0];
    String strAM = rest2[1];

In variable parts you wil have two Strings:
8 // strHr
44 PM // rest

Then; in rest you will have:
44 // strMin
PM // strAM

Answer: You can do this :-
String[] fistPart = strTime.split(" ");
String time = firstPart[0];
String strAM = firstPart[1];
String strHr = time.split(":")[0];
String strMin = time.split(":")[1];

8:44  PM
------------
Time| AM/PM

8:44
----
H|Min

Answer: Firstly u have to set a fix time format that it should be in 2 digit or 1 digit. like the time is 08:44 AM or 8:44 AM .
I think u choose the the 2 digit time format for the responsivre programming .
Then u put the logoc for extract the time from time format.
then follow the following code
String strTime = "8:44 PM";
String hour= strTime.split(":")[0];
String remain = strTime.split(":")[1];
String min= remain.split(" ")[0];
String am_pm= remain.split(":")[1];

Get each part of a Java String


How to strip trailing space from keys in a Python Dictionary?

Question: I have the following data in a text file named "user_table.txt":
Jane - valentine4Me
Billy
Billy - slick987
Billy - monica1600Dress
 Jason - jason4evER
Brian - briguy987321CT
Laura - 100LauraSmith
   Charlotte - beutifulGIRL!
  Christoper - chrisjohn

And, the following code to read this data and create a Python dictionary:
users = {}

with open("user_table.txt", 'r') as file:
    for line in file:
        line = line.strip()

        # if there is no password
        if ('-' in line) == False:
            continue

        # otherwise read into a dictionary
        else:
            key, value = line.split('-')
            users[key] = value

k= users.keys()
print(k)

if 'Jane' in k:
    print('she is not in the dict')
if 'Jane ' in k:
    print('she *is* in the dict')

I see that there are trailing spaces in the keys:
dict_keys(['Jane ', 'Billy ', 'Jason ', 'Brian ', 'Laura ', 'Charlotte ', 'Christoper '])
she *is* in the dict

What is the best way to remove the spaces?
Thanks!
Comment: Does this answer your question? [How do I trim whitespace?](https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace)
Answer: try to change:
key, value = line.split('-')

to
key, value = [i.strip() for i in line.split('-')]

Answer: Change key, value = line.split('-') to key, value = line.split(' - ').
Answer: You can replace this:
key, value = line.split('-')
users[key] = value

by this:
k=line.split('-')
users[k[0].strip()]=k[1]

Answer: Just change
users[key] = value

to
users[key.strip()] = value.strip()

This will generalize your code in case there is no space on either or both sides of '-' in split().


Angular 4 unit test get error - Failed: Cannot read property 'map' of undefined

Question: I'm trying to get success on Angular 4 unit test, but I'm getting differents error, I'm getting the error Failed: Cannot read property 'map' of undefined.
I'm using .map() only on service file but I don't know why showing this error
I'd like to know how can I get success for this test, and if, am I on the right way?
Take a look my code:
My Spec

import { TestBed, async, inject } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { of } from 'rxjs/observable/of';
import { fileX } from '../../../models/fileX';
import { fileXService } from '../../../services/fileX.service';
import { fileYfileXComponent } from './fileY-fileX.component';
import { dataService } from '../../../services/data.service';
import { ComponentFixture } from '@angular/core/testing';

describe('fileYfileXComponent', () => {
  let fileXService;
  let myComponent;
  let fixture: any;
  let element;
  let mockHttp: httpClient;

  beforeEach(async(() => {
      mockHttp = jasmine.createSpyObj('http', ['get']);

      TestBed.configureTestingModule({
          declarations: [fileYfileXComponent],
          providers: [
              fileXService,
              dataService,
              { provide: Http, useValue: mockHttp }
          ],
          imports: [HttpModule]
      }).compileComponents();
    }));

  beforeEach(inject([fileXService], s => {
      fileXService = s;
      fixture = TestBed.createComponent(fileYfileXComponent);
      myComponent = fixture.componentInstance;
      element = fixture.nativeElement;
    }));

  it(
    'should get values',
    async(() => {
      const response: fileX[] = [];

      spyOn(fileXService, 'method1').and.returnValue(of(response));

      myComponent.searchdatafileX();

      fixture.detectChanges();

      expect(myComponent.datafileX).toEqual(response);
    })
  );
});
Comment: Are you mocking the http service? Or actually sending requests to your server in a test?
Answer: Currently you are mocking the HubWrapperComponent correctly, such that it will not make a call to your back end every time you invoke get. In order to get this working, you'll need to use Jasmine's Spy utility, returnValue to tell the test what should be returned when http.get is called. Right now, this is not specified so the map is being called on undefined.
In your spec file, after the line:
mockHub = jasmine.createSpyObj('hubWrapperComponent', ['get']);

Add this line:
mockHub.get.and.returnValue(// your test response);

Based on the code in the service, my assumption is that you are expecting an Observable from the get method, so your returnValue call will look something like this:
mockHub.get.and.returnValue(Observable.of(
    {
      json: () => {
        return // object with properties you want to test
      }
    }
  )
);

More information on this method here: https://jasmine.github.io/api/2.7/Spy_and.html.
Comment: I can't tell you without seeing what you tried and what errors you got. The original error you asked about in this question has been solved. Some things to think about for the new error: what does it return in the real program (log it to the console and check)? What properties do you want to test? Since your original problem is solved, please consider accepting and / or upvoting this answer so others know it has been solved. If you are still stuck with the new error, please open a new question. Welcome to Stackoverflow and Good luck to you :)
Comment: I got this error now `Failed: response.json is not a function`
Comment: You will need to add a `json` property to your test response. The `json` property should be a function which returns some JSON object with the data you want. I updated my answer with an example of how this would look. Your original error is solved though! :D
Comment: sorry but what exactly I have to put on `return // object with properties you want to test ` I tried to put somethings but got errors for all
Comment: actually my question is How to get success on this test =/ , but thank you for help me, I'll keep trying with your tips above.
Comment: I created a fakeData array with fake data and put on return, but I got this error `Expected undefined to equal [  ].`
Comment: I wish I could,  but I truly can't help you anymore at this point. The form your data must take is up to you. You can look at this guide: https://angular.io/guide/testing for more general information, but I've helped you as much as I can without being at your desk. And while your goal may be to get success on the test, the question is how to solve the error, which I answered and resolved for you. There is not enough code in your question that would allow me to "get your test working", and that wouldn't actually be a valid Stackoverflow question anyways. I believe you will get it working!


Add roles to user during create and save account

Question: I want to add a custom role to a user during hook_user_create() and hook_user_update(). All goes well during user create, as long as I do $user->save() in the end. The site crashes during hook_user_update() if I do $user->save(). No role is added if I simply add the role with $user->addRole('role_name'), but don't save it.
This is for Drupal 8.
What am I doing wrong?
Answer: Found the answer: hook_user_presave() will do the trick.
I.e you add what you want to the user object (and don't save). Drupal will do the rest.
Comment: HOW will it do so?
Comment: You add what you want to the user object (and don't save). Drupal will do the rest.


Help to understand martingale example from Billingsley

Question: I am studying Billingsley's section 35 about martingales and I have some difficulties understanding one of the examples.
This is the example 35.4.
Suppose we have a measurable space $(\Omega,\mathcal F)$ and let $Q$ and $P$ be probability measures on the latter. Let $\mathcal F_n=\sigma (Y_1,\cdots,Y_n)$ be the sigma algebra generated by the random variables $Y_1,\cdots,Y_n$.
Suppose that under  $P$ the distribution of the random vector $(Y_1,\cdots,Y_n)$ has density $p_n(y_1\cdots,y_n)$ with respect to the n-dimensional Lebesgue measure, and under $Q$ it has density $q_n(y_1\cdots,y_n)$. (To avoid technicalities assume that $p_n,q_n$ are everywhere positive.
Then the Radon-Nikodym derivative of $Q$ with respect to $P$ on $\mathcal F_n$ is
$$X_n=\frac{q_n(y_1\cdots,y_n)}{p_n(y_1\cdots,y_n)}$$
So far so good, but the author then concludes that $X_n$ is a martigale under $P$ w.r.t. the filtration $\mathcal F_n$.
How can I see this last point,
why is that the following holds?
$$\int_F X_n dP=\int_F X_{n+1} dP, \forall F\in\mathcal F_n$$
Thanks in advance.
EDIT:
I may have  found a possible solution, but I am not sure about the validity of it.
I can assume that there is a random variable $\Phi\in\mathcal M(\mathcal F)$ such that
$$Q(F)=\int_F \Phi dP,\forall F\in\mathcal F_n$$
(One problem might be that then $Q$ is not a probability measure on $\mathcal F$).
Then I can interpret the Radon-Nikodym derivative $X_n$ as the condition expectation $E[\Phi|\mathcal F_n]$.
Finally I have that
 $$E[X_{n+1}|\mathcal F_n]=E[E[\Phi|\mathcal F_{n+1}]|\mathcal F_n]=E[\Phi|\mathcal F_n]=X_n$$
$$E[X_{n+1}]=E[E[X_{n+1}|\mathcal F_n]]=E[X_n]$$
Comment: A continuous version of this question (with time index "t" over the nonnegative reals rather than the discrete "n" of the present question) is answered on the Maths Exchange sister site here:
https://math.stackexchange.com/questions/2273549/radon-nikodym-derivative-as-a-martingale Note that in the definition of the martingale as a quotient of densities, the lowercase "y" variables appearing in the numerator and demoninator ought to be replaced by capitals "Y", since these are random variables.
Answer: It's a little strange to say that $X_n=\frac{q_n(y_1\cdots,y_n)}{p_n(y_1\cdots,y_n)}$ is the "the Radon-Nikodym derivative of $Q$ with respect to $P$ on $\mathcal{F}_n$."
In general, a Radon-Nikodym derivative $\frac{dQ}{dP}$ is a random variable defined on $(\Omega,\mathcal{F})$, whereas $X_n=\frac{q_n(y_1\cdots,y_n)}{p_n(y_1\cdots,y_n)}$ is defined on $\mathbb{R}^n$.
I will assume a specific $\Omega$ so that $X_n$ is actually $\frac{dQ}{dP}$. Take $\Omega = \mathbb{R}^{\infty}$, with the Borel $\sigma$-algebra given by the product topology, and $Y_n$ is the $n$-th coordinate map. So $\mathcal F_n=\sigma (Y_1,\cdots,Y_n)$ consists of cylinder sets given by the first $n$ coordinates. In this case, $X_n = \frac{q_n(y_1\cdots,y_n)}{p_n(y_1\cdots,y_n)} = \frac{dQ}{dP}$.
The answer to your question now simply follows from the factorization
$$
q_{n+1}(y_1\cdots,y_{n+1}) = q_{n}(y_1\cdots,y_{n}) q_{n+1|n}(y_{n+1}|y_1\cdots,y_{n})
$$
where $q_{n+1|n}(y_{n+1}|y_1\cdots,y_{n})$ is the conditional density of $y_{n+1}$ given $y_1\cdots,y_{n}$.
To be more explicit, a general element of $\mathcal{F}_n$ takes the form
$F_n = B_n \times \mathbb{R} \times \mathbb{R} \cdots$, where $B_n$ is a Borel set in  $\mathbb{R}^n$. So
\begin{align*}
\int_{F_n} X_{n+1} dP &= \int_{B_n \times \mathbb{R}} \frac{q_{n+1}}{p_{n+1}} p_{n+1} dy_1 \cdots dy_{n+1}\\
&= \int_{B_n \times \mathbb{R}} q_{n+1} dy_1 \cdots dy_{n+1}\\
&= \int_{B_n \times \mathbb{R}} q_{n} q_{n+1 | n} dy_1 \cdots dy_{n+1}\\
&= \int_{B_n} (\int_{\mathbb{R}} q_{n+1 | n} ) q_{n}  dy_1 \cdots dy_{n}\\
&= \int_{B_n} q_{n}  dy_1 \cdots dy_{n}\\
&= \int_{B_n} \frac{q_{n}}{p_n} p_n dy_1 \cdots dy_{n}\\
&= \int_{F_n} X_{n} dP.\\
\end{align*}
(This really just a martingale of the form $E[X|\mathcal{F}_n]$ where $X$ is an $L^1$ random variable and $\{ \mathcal{F}_n \}$ is a filtration.)


Violating the assumptions of one sample t-test and wilcoxon's sign test

Question: As far as the background of my research is concerned, I developed a framework for sustainability management in organizations through a systematic review of literature and sustainability reports. That framework was translated into a set of 52 statements. A couple of example of these statements are as follows:

The leadership should inspire other organizational actors through their commitment towards sustainability management.
The organization should define its sustainability vision and mission.

The statements were posted online as a survey and experts in the field were invited to rate each statement on a five-point Likert scale (1 strongly disagree, 5 strongly agree). The survey was sent to 460 experts, 259 of which participated and 131 provided complete responses.
All of the survey statements were considered as hypothesis (the null was to reject the statement, which goes against the literature review) and the primary idea was to run a 1 sample t-test to compare the means against a (self-defined) test score of 3.5. If the results turn out to be significant, the null would have been rejected and the framework (in the form of the statement) would have been validated.
While studying for the 1 sample t-test, I came across its assumptions of normality and equal variance - which led me to its non-parametric alternative, one sample Wilcoxon's sign test. However, the literature suggests that the latter also makes assumptions about the symmetry of data. Since most of the survey respondents (experts) strongly-agree/agree with the statements of the survey (and rightly so, because these are representative of the literature), the data is skewed and has high kurtosis. For example, for the statements I have provided above, the skewness and kurtosis are -2.712 (st. err 0.212) and 5.438 (st. err 0.420) for the first statement and -2.9 (st. err 0.212) and 8.306 (st. err 0.420) for the second statement, respectively. Since my data is non-normal and asymmetric and does not have equal variances what should I do?
I have a few other questions as well:
1- I read in 'discovering statistics through SPSS' that if the sample size is greater than 25, one can go ahead with the one sample t-test. Would that be applicable to my case?
2- Is the Wilcoxon's sign test robust to the violation of the assumption of symmetry? If so, is there any reference I can use? Please note that I am referring to one sample Wilcoxon's sign test only.
3- If the answer to 2 is no, which other nonparametric tests can I use - which should have good power and can be performed in SPSS?
4- In addition to the hypothesis testing, I will be doing a test for non-respondents bais, the reliability of the data, and the effect size. Will these tests be sufficient to achieve the goal of my study and to develop a story for the readers/audience or should I look for some other measures too?
Comment: The Wilcoxon signed-rank test makes no assumptions about the shape of the data or homogeneity.
Comment: but the literature says that the test assumes symmetry of data (not normality though). Can you pease share any scientific reference which says that the Wilcoxon sign test does not make any assumption at all? Would certainly be a great help.
Answer: I think you misunderstood your literature. Similar questions:
Wilcoxon Signed Rank Symmetry Assumption
Appropriateness of Wilcoxon signed rank test
Is Wilcoxon Signed-Rank Test the right test to use?
TL:DR regarding Wilcoxon signed rank test
If you are testing the null hypothesis that the mean (= median) of the paired differences is zero, then the paired differences must all come from a continuous symmetrical distribution. Note that we do not have to assume that the distributions of the original populations are symmetrical - two very positively skewed distributions that differ only by location will produce a set of paired differences that are symmetrical. We also assume that the paired differences all have the same mean (= median). If you are testing the null hypothesis that the Hodges-Lehmann estimate of the median difference is zero, then the assumption of symmetry is not required.
And if this does not hold either, you can use a Sign test.
And before all this, I would check whether a regular t-test is appropriate. The assumptions here are similar in that they refer to the residuals, not the distribution of the data.
Comment: @wnawaz My bad, for a one-sample Wilcoxon test, to be a test of the median, the data need to be relatively symmetrical about their median. If this is not true then a Sign test can save you.
Comment: Thank you for your prompt response and I completely agree with what you have said. However, you have mentioned about two distributions, which give me an impression that we are comparing two samples (regardless - dependent or independent), whereas my original question is about one sample. I have a fixed median value (test score) which I want to compare with all statements (data points) to see if the median is statistically higher (than the fixed median). In such a case, how do I find the pairwise difference? If I treat the fixed value as a pair against each data point, its still skewed.