Undefined ao tentar utilizar o JSON válido recebido

Question: Estou com um problema chato de encontrar o erro, já estou horas procurando aqui. Estou recebendo um JSON do PHP utilizando JQuery, eu consigo visualizar ele como pode ver abaixo o resultado da resposta "data":
{
    "sucesso": 1,
    "dados": {
        "BTC_YAMRUB": {
            "result": 500000,
            "url_redirect": "https:\/\/mysite.com\/?rid=1229109",
            "https": 1,
            "link_permanente": "mysite",
            "nome": "MySite",
            "exchange_rates": 500000,
            "idade": "3 anos e 1 m\u00eas",
            "wmid": null,
            "pais_nome": "Brasil",
            "moeda_from": "Bitcoin BTC",
            "moeda_to": "Yandex money RUB",
            "rank_from": "14",
            "rank_to": "38",
            "reviews": [{
                "cliente_site": "52",
                "positivo": "0",
                "comentario": "0",
                "negativo": "0"
            }],
            "offer": {
                "from": 0,
                "to": 0,
                "in": 1,
                "out": 500000,
                "amount": 121436.1859,
                "minfee": 0,
                "fromfee": 0,
                "tofee": 0,
                "minamount": 0,
                "param": "manual"
            }
        }
     }
}

porém ao tentar qualquer umas das linhas abaixo eu recebo undefined.
console.log(data[0].length);
console.log(data.length);
console.log(data.dados.length);

O código javascript:
function getRates()
{
    $("#gif_load").show();

    $.post(URL_SITE + '/api/exchangers', {from: $("#from").val(), to: $("#to").val()}, function(data, textStatus, xhr) {

        if(textStatus == "success") {

            $("#exchangers tbody tr").remove();

            console.log(data.length); // undefined
            console.log(Object.keys(data).length); // 2

            if(data.dados.length > 0)
            {
                  $.each(data.dados, function(index, el) {
                      console.log(el.result);
                  });
            }
          }

     });

}

O código do PHP:
<?php
ini_set('display_errors', 1);
include_once(dirname(__FILE__)."/../includes/_conect.php");

$limit_blocktraill = 300;

header('Content-Type: application/json');
$url_invalid  = URL_SITE . '/';
$url_valid = str_replace(":80", "", $url_invalid);

if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest' && strpos($_SERVER["HTTP_REFERER"], $url_valid) !== false)
{
    if(isset($_POST["from"]) && isset($_POST["to"]))
    {
        $from = mysqli_real_escape_string($_POST["from"]);
        $to = mysqli_real_escape_string($_POST["to"]);

        #--------------------MemCached-----------------------------------------
        $memCached = new Memcached();
        $memCached->addServer('localhost', 11211);

        if ($dados = $memCached->get('rank_moeda')) {
            if ($memCached->getResultCode() == Memcached::RES_NOTFOUND) {
                $exchangers = 0;
            }else{
                $exchangers = $dados;
            }
        }

        if(count($exchangers) > 0)
        {
            echo json_encode(array("sucesso" => 1, "dados" => $exchangers));

        }else{
            echo json_encode(array("sucesso1" => 1, "dados" => array()));
        }

    }else{
        echo json_encode(array("sucesso2" => 0, "Erro" => "Error"));
    }

}else{
    echo json_encode(array("sucesso3" => 0, "Erro" => "Error"));
}

Verifiquei toda a resposta no https://jsonlint.com/ e está OK. A algum outro teste que posso fazer para encontrar o que está acontecendo?
Comment: Tem como colocar o código JS que faz e trata a requisição?
Comment: Pra já, editei a pergunta com o código JS.
Comment: Editei com o código PHP também.
Answer: Acontece que o JavaScript não retorna o tamanho do objeto, apenas de arrays. Por isso está dando o erro undefined.
Lembrando que toda vez que você retornar (observar os colchetes no exemplo abaixo):
{
    "sucesso": 1,
    "dados": [{
        ...
    }]
}

O JavaScript irá interpretar como um JSON Array e automaticamente adicionará a propriedade length.
E toda vez que você retornar:
{
    "sucesso": 1,
    "dados": {
        ...
    }
}

O JavaScript irá interpretar como um JSON Object e não adicionará a propriedade length
Mas há uma forma de percorrer um objeto. Basta retornar todas as keys do objeto e depois executar um for..of.
Exemplo:
$.post('SUA-URL', {}, function(data, textStatus, xhr) {

    if(textStatus == "success") {

        $("#exchangers tbody tr").remove();

        /* Captura as keys */
        let keys = Object.keys(data.dados);

        /* Exibe a quantidade */
        console.log( keys.length );

        /* Verifica se há keys */
        if ( keys ) {

            /* Percorre os valores através da key */
            for (let d of keys) {
                console.log( data.dados[d]);
            }
        }
      }

 });

Ou você pode retornar todos os valores com Object.values.
Exemplo:
$.post('SUA-URL', {}, function(data, textStatus, xhr) {

    if(textStatus == "success") {

        $("#exchangers tbody tr").remove();

        /* Captura todos os valores */
        let values = Object.values(data.dados);

        /* Exibe a quantidade de valores */
        console.log( values.length );

        /* Verifica se há valores disponíveis */
        if ( values ) {

            /* Percorre todos os valores */
            for (let v of values) {
                console.log( v );
            }
        }
      }

 });

Comment: @PerduGames com o código (PHP) postado não tem como saber muita coisa, mas você deve remover os valores `BTC_YAMRUB` quando salvar os valores da variável. Seria mais ou menos como fazer: ` $dados[] = $dados_da_moeda ` ao invés de `$dados[ $id ] = $dados_da_moeda;`
Comment: E como eu faria para retornar assim `[{
    "sucesso": 1,
    "dados": {
        ...
    }
}]` ?
Comment: Entendi, muito boa sua resposta, marcando como resolvido, agradeço a ajuda, salvou a madrugada da dor de cabeça que iria ser para descobrir que era isso kkkkkk
Comment: Eu tento converter para array com (array) o "offer", porém não consigo também.
Comment: @PerduGames se possível edita sua pergunta posta o código como você está armazenando esses valores na variável. Ou pode postar no https://pastebin.com
Comment: Está correto, é a variável "offer" que está com sendo atribuída errada por algum motivo. Ao invés da string estou recebendo 0.
Comment: Eu estava convertendo ela para float sem querer por causa desse problema aqui https://pt.stackoverflow.com/questions/278176/porque-o-php-retorna-zero-ao-subtrair-elementos-de-um-objeto que acabei fazendo um (float) em tudo, mas me esqueci das strings kkkk, agora está correto.
Answer: Olha, os dados devem ser contados assim:
Object.keys(data).length // retorna 2

Dados:
Object.keys(data.dados).length // retorna 1

Pra simplificar pode fazer assim:
var tmp = Object.keys(data);
console.log(tmp.length);
console.log(tmp.dados.length);

Comment: os ... é só explicando que tem mais dados, desconsidere ele.
Comment: Eu imaginei que fosse, editei a resposta com mais exemplos,
Comment: Fiz o teste e está OK.
Comment: Desculpa, eu salvei sem terminar de por os detalhes da explicação. Espero ter ajudado
Comment: Mas como utilizo os dados? e porque tem que ser assim? Sempre fiz do jeito que está acima e funcionou. Acho que o problema ser outra coisa.
Comment: Pra ser franco eu nunca vi ninguém medir o tamanho das chaves de um **Json** sem ser da maneira que eu mostrei, eu fiz o teste com o seu e funcionou, mas da maneira que você mostrou só consegui com **Arrays**: `[1,['a',b],'teste']`
Comment: console.log(tmp); me retorna `(2) ["sucesso", "dados"]
0
:
"sucesso"
1
:
"dados"
length
:
2
__proto__
:
Array(0)` porém console.log(tmp.dados.length); me retorna indefinido também.
Comment: Você fez o teste direto no console ou chamando a função?
Comment: chamando a função.
Comment: Tem razão, nem fez sentido o ultimo exemplo que eu fiz. Devo estar com sono mesmo


When doing a MERGE in Oracle SQL, how can I update rows that aren't matched in the SOURCE?

Question: I have a main database and a report database, and I need to sync a table from main into report.
However, when an item gets deleted in the main database, I only want to set an IsDeleted flag in the report database.
What is an elegant way to do this?
I'm currently using a MERGE statement, like this:
MERGE INTO report.TEST target
USING (SELECT * FROM main.TEST) source
   ON (target.ID = source.ID)
WHEN MATCHED THEN
    UPDATE SET (target... = source...)
WHEN NOT MATCHED THEN
    INSERT (...) VALUES (source...)
;

The WHEN NOT MATCHED statement gives me all NEW values from main, but I also want to update all OLD values from report.
I'm using Oracle PL/SQL.
Comment: So, is `MERGE` similar to an `LEFT OUTER JOIN`?  I guess I was hoping that  might have a `FULL OUTER JOIN` option.
Comment: I think that SQL Server 2008 has a `WHEN NOT MATCHED ON SOURCE` clause that does a `FULL OUTER JOIN`!  I can't find much documentation on it, but I tried it in Oracle with no success, so I guess I'll look at other options.
Comment: With which values do you want to update `main.test`? Where would you get them from?
Comment: If the row is deleted from `main.test`, then the corresponding `report.test` row will be unmatched.  I want to set the `report.test.IsDeleted` flag for all unmatched rows.
Comment: I don't think that will be possible as the result of the underlying JOIN (`using (...)`) will not contain that row. So where should that data come from?
Answer: You can do it with a separate UPDATE statement
UPDATE report.TEST target
SET    is Deleted = 'Y'
WHERE  NOT EXISTS (SELECT 1
                   FROM   main.TEST source
                   WHERE  source.ID = target.ID);

I don't know of any way to integrate this into your MERGE statement.
Comment: Thank you so much, that link was very helpful  What I learned: if `MERGE` only has `WHEN MATCHED THEN`, it uses a regular `JOIN`.  If there's a `WHEN NOT MATCHED THEN`, it uses a `LEFT OUTER JOIN`.  Now, I'm wishing for a feature such as `WHEN NOT MATCHED ON SOURCE THEN`, which will do a `FULL OUTER JOIN`.  But this might only exist for SQL Server, not Oracle.
Comment: There's a related question here  http://stackoverflow.com/questions/4863960/could-somebody-explain-what-the-merge-statement-really-does-in-oracle, I think it'll do an outer join, not a full outer join, so I don't think what you've suggested will work.
Comment: It seems weird that I can't do this with MERGE.  I'll consider this answer.
Comment: Would it be any more "elegant"/efficient if I did an `OUTER JOIN`, and updated where `main.test is null`?
Answer: The following answer is to merge data into same table
MERGE INTO YOUR_TABLE d
USING (SELECT 1 FROM DUAL) m
    ON ( d.USER_ID = '123' AND d.USER_NAME= 'itszaif')
WHEN NOT MATCHED THEN
        INSERT ( d.USERS_ID, d.USER_NAME)
        VALUES ('123','itszaif');

This command checks if USER_ID and USER_NAME are matched, if not matched then it will insert.
Answer: MERGE INTO target
USING
(
    --Source data
    SELECT id, some_value, 0 deleteMe FROM source
    --And anything that has been deleted from the source
    UNION ALL
    SELECT id, null some_value, 1 deleteMe
    FROM
    (
        SELECT id FROM target
        MINUS
        SELECT id FROM source
    )
) source
   ON (target.ID = source.ID)
WHEN MATCHED THEN
    --Requires a lot of ugly CASE statements, to prevent updating deleted data
    UPDATE SET target.some_value =
        CASE WHEN deleteMe=1 THEN target.some_value ELSE source.some_value end
    ,isDeleted = deleteMe
WHEN NOT MATCHED THEN
    INSERT (id, some_value, isDeleted) VALUES (source.id, source.some_value, 0)

--Test data
create table target as
select 1 ID, 'old value 1' some_value, 0 isDeleted from dual union all
select 2 ID, 'old value 2' some_value, 0 isDeleted from dual;

create table source as
select 1 ID, 'new value 1' some_value, 0 isDeleted from dual union all
select 3 ID, 'new value 3' some_value, 0 isDeleted from dual;

--Results:
select * from target;

ID  SOME_VALUE   ISDELETED
1   new value 1  0
2   old value 2  1
3   new value 3  0

Comment: Thanks for being creative!  I'm not gonna do this, but it does get the job done.
Answer: merge into x as target using y as Source on target.ID = Source.ID
when not matched by target then insert
when matched then update
when not matched by source and target.ID is not null then
update whatevercolumn = 'isdeleted' ;

Comment: -1 as this is [SQL Server merge](http://msdn.microsoft.com/en-us/library/bb510625.aspx) syntax not [Oracle merge](http://docs.oracle.com/cd/E11882_01/server.112/e26088/statements_9016.htm#SQLRF01606)
Comment: Just for everyone's reference, this is a good answer, but `not matched by target` and `not matched by source` is a feature only supported by MS SQL Server.  This feature would solve my problem, so I wish Oracle SQL supported it.
Comment: where did you found this syntax? (`by target`)
Comment: This is exactly what I'm looking for ... however, as @FlorinGhita said, where did you find this syntax?  Is this MS SQL syntax?


Apache2 VirtualHost on Debian not working

Question: I am having some problems with Apache2 configuration. I have already tried to look for documentation on the web (Apache's site, Debian's site, here on serverfault, etc), but nothing really helps.
I have tried different configurations, but my current configuration is the following (/etc/apache2/sites-available/default):
<VirtualHost *:80>
    ServerAdmin firstname.lastname@example.com
    ServerName mysite.dev
    ServerAlias mysite.dev
    DocumentRoot /var/www/mysite.dev/httpdocs/
    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>
<VirtualHost *:80>
    ServerAdmin email@example.com
    ServerName livesite.com
    ServerAlias www.livesite.com
    DocumentRoot /var/www/livesite.com/httpdocs/
    <Directory /var/www/livesite.com/httpdocs/>
            Options Indexes FollowSymLinks MultiViews
            AllowOverride All
            Order allow,deny
            allow from all
    </Directory>
    ErrorLog ${APACHE_LOG_DIR}/error.log
    LogLevel warn
    CustomLog ${APACHE_LOG_DIR}/access.log combined
</VirtualHost>

mysite.dev it's just an entry in hosts file on my client machine, while livesite.com it's an actual DNS record which would resolve to the same IP as the IP set in hosts file for mysite.dev.
The problem is that when i try to type mysite.dev in my browser, it would automatically go to livesite.com.
I tried to have different /etc/apache2/sites-enabled/ files (/etc/apache2/sites-enabled/mysite.dev , /etc/apache2/sites-enabled/livesite.com ) - and of course with the actual sites-available related files, but achieving the same results. I have tried to have a peak on error.log and access.log but there's nothing I can see.
My httpd.conf contains:
AccessFileName .htaccess

And I have no /etc/apache2/conf.d/virtual.conf file.
Any help would be greatly appreciated - if I did not provide enough info please let me know I will do my best to provide all necessary info.
Thanks
Answer: in your host file try setting mysite.dev to 127.0.0.1 instead of the pc's ip and also make sure that mysite.dev is the first virtualhost defined in apache, hope this resolves your issue
Comment: hosts file is on client machine, so 127.0.0.1 would redirect to my local apache - instead of the intended server's. mysite.dev is the first virtualhost declared.
Comment: btw, i also have an entry in the server's hosts file - with value 127.0.0.1
Answer: This is just a wild guess, but does the Include statement in httpd.conf look something along the lines of:
 Include /etc/apache/sites-enabled/*.conf
If that's the case, rename /etc/apache2/sites-enabled/mysite.dev to /etc/apache2/sites-enabled/mysite.dev.conf and see if that helps.
Alternatively, do you have the "NameVirtualHost *:80" statement anywhere?  I prefer to stick it in httpd.conf or ports.conf on Debian-based Apache installs.
Comment: I have no include line in httpd.conf - I tried to stick all the code in the httpd.conf (including NamevirtualHost *:80 - which was in ports.conf) but no luck there..
Answer: Try to change
<VirtualHost *:80>

to
<VirtualHost mysite.dev:80>

and
<VirtualHost livesite.com:80>

I think two *:80 virtualhosts is an ambiguous configuration for the webserver.
Answer: Thanks to @law and @tristan625 for the answers.
My problem was that Firefox was doing something silly - when i tried the latest configuration (all in httpd.conf) with chrome it just worked (and also FF worked, once I've restarted it).
Silly problem that has wasted a cpl of hours of my life!


non understandable key switches in jazz

Question: I am trying to learn jazz. I got a handbook with some jazz standards. Given a jazz tab, is there a dominant key ? like in classical music. I don't understand the structure of the music. For instance, there are many II, V, I in a same tab but seems to me that have nothing to do with each other
Comment: Jazz standards are typically in a key, but the harmonic structures don't necessarily adhere to the same rules as in classical music. As asked, though, your question is too broad to generate meaningful answers. Consider asking about a specific section of a specific tune that's giving you trouble.
Comment: can you give an example of a `ii V I` pair that isn't making sense? Giving a specific song title and the confusing passage will be much more helpful, than generalizations.
Answer: For many standard there is a dominant key.  Like in classical music there are modulations to other keys, like the IV and the relative minor vi.  But the key is indicated at the start of the piece by a set of flats or sharps that follow the same pattern as in any western musical tradition.
The abundance of ii/V you mention is likely due to what is called a cycle extension.  It is a common practice to take any chord in the "key" and fill in movement with a relative ii-V or some variant based on the circle progression, you may also see iii-vi-ii-V, etc.
For example if one wants to jump from I to IV you would create a richer sound by passing through the I7 (the V7 of the IV degree), I-->I7-->IV.  You could also walk back and cycle with a full ii-V, I-->v-->I7-->IV, etc.  clearly the minor chord on V would be disconcerting but if approached gracefully will add a lot of interesting harmony to the progression.
These devices are all over classical music, renaissance music, etc.  So it's really nothing new.  If you are interested in digging deeper I'd recommend Modulation by Max Reger, but work through a basic harmony book first as Reger is quite dense.
Answer: You've already identified the ii/V/I progressions, so the question is how the Is are related to each other.
Some jazz tunes are pretty straightforward, following a natural harmonic series (the circle of fifths/fourths).  So if the first I is Cmaj7 and the second I is Fmaj7, you're moving counterclockwise around the circle, and if the second is Gmaj7 you're moving clockwise.
Other modulations are harder to see.  A tune like Giant Steps has Bmaj7, Ebmaj7, and Gmaj7 as the I chords.  But if you connect those on a circle of fifths, you'll see they form a triangle.  That's sometimes called a "geometric modulation"
Answer: In almost all cases, jazz tunes are in a particular key. Most tunes will modulate in some way, and then end in the original key (or the relative major/minor).
One of the differences with "classical music" (by which I mean common practice in the Mozart era) is that there are two types of dominant chord - functioning and non-functioning. For a beginner, these can make it very confusing to identify the proper key.
For example, "Our Love is Here to Stay" in the key of Db will start on an Eb7, but then move to Ebm7 - Ab7 - Dbmaj7. The actual key of the piece is Db, but clearly the first Eb7 is not the dominant of that key. Therefore Eb7 is a non-functioning dominant. There are thousands of other examples like this in the Real Book. Functioning dominants will often have alterations (b9, #9, #5, alt) whereas non-functioning dominants will usually have only 7, 9 or occasionally the #11.
There are also cases where the piece will start on a degree other than the tonic - for example "Just Friends" starts on chord IV of the key.
If you try to look for ii-V-Is that resolve to a major (for a piece in a major key), those are usually a good indicator of the key at that point in the piece. If you find something really unusual or that you don't understand then you can post the specific chord sequence as a question on this forum and someone will try to analyze it for you.
Jazz chord progressions are not infinite - there are a limited number of "moves" that commonly occur which make up the majority of the harmony found in standard tunes. A good place to learn these foundational moves is through the book "Harmony with Lego Bricks" by Conrad Cork or the more recent "Insights in Jazz" by John Elliot. Both of these books are aimed at making it easier to understand chord sequences in jazz contexts.

non understandable key switches in jazz


How to filter Data on the basis of id or uuid by Rest API?

Question: I am using Drupal 8 I have installed the poll module.
I created a view with REST export enabled. Now when I get the data by this url
http://localhost/poll/rest/polling

I am getting all the data of polls like this
[{"question":"which is best city","choice_target_id":"Delhi, Mumbai, Chennai","id":"1","choice_target_id_1":["1","2","3"],"uuid":"b0ef150c-bf05-4a25-8ae9-b6864539c080"},{"question":"Where do you work?","choice_target_id":"Flat, Hotel, Factory, Shop","id":"2","choice_target_id_1":["4","5","6","7"],"uuid":"b2145904-fe8b-4ef6-82fa-f069c2e29f3b"}]

But when I get the data on the basis of id or uuid by this url
http://localhost/poll/rest/polling?id=1

then I am still getting all the data without getting filtered as per the id
What am I doing wrong?
Comment: You haven't set up any exposed filters or you're using the wrong filter id on them.
Comment: yes its working now
Comment: please add this as answer so i can mark it as answer
Answer: You haven't set up any exposed filters or you're using the wrong filter id on them. Views needs exposed filters on it by which to limit a query by.


Multiple JLists on one JPanel

Question: I am making a program that prints out the items on a JList and am trying to use the least memory possible. Therefore, I only want to use one JList variable but still have two lists on the screen that I can read from. I have come in to problems in finding how to find values in the first list that I initialize and add to the JPanel.
JPanel initialization method:
public  void run() {
    panel = new JPanel(null);
    //Initalize components

    //List 1
    ArrayList<String> st = new ArrayList<String>();
    for(int i=0;i<10;i++) st.add("Number: " + i);
    jli = new JList(st.toArray());
    jli.setName("MyList1");
    jli.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jli.setLayoutOrientation(JList.VERTICAL);
    jli.setSelectedIndex(-1);
    jli.setVisibleRowCount(-1);
    JScrollPane jsp = new JScrollPane(jli);
    jsp.setSize(new Dimension(120, 130));
    jsp.setLocation(5, 5);
    panel.add(jsp);

    //List 2
    st = new ArrayList<String>();
    for(int i=0;i<10;i++) st.add("#: " + i);
    jli = new JList(st.toArray());
    jli.setName("MyList2");
    jli.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
    jli.setLayoutOrientation(JList.VERTICAL);
    jli.setSelectedIndex(-1);
    jli.setVisibleRowCount(-1);
    jsp = new JScrollPane(jli);
    jsp.setSize(new Dimension(120, 130));
    jsp.setLocation(150, 5);
    panel.add(jsp);

    //Button 1
    jb = new JButton("Print 1");
    jb.addActionListener(this);
    jb.setLocation(5, 140);
    jb.setSize(jb.getPreferredSize());
    panel.add(jb);

    //Button 2
    jb = new JButton("Print 2");
    jb.addActionListener(this);
    jb.setLocation(120, 140);
    jb.setSize(jb.getPreferredSize());
    panel.add(jb);
}

ActionPreformed Method:
public void actionPerformed(ActionEvent e) {
    switch (e.getActionCommand()) {
        case "Print 1":
            //This is where I need help
            break;
        case "Print 2":
            System.out.println(jli.getSelectedValue());
            break;
    }
}

In short, How do I find data from the first JList created and the Second JList created without making two JList variables?
Comment: Using a single "variable" while you have two instances of JList isn't going to save you any memory. You could have 10 variables pointing to the two lists and the increase in memory would insignificant...
Comment: Is the micro amount of memory from an extra JList really that harmful? Why is this a requirement?
Comment: @MadProgrammer the question offtopic is what are you doing awake at 5 am, related to the question use anonymous class then you don't have to do `switch`
Comment: @nachokk 20 month old = early mornings; I don't think the switch is to much of an issue, but I'd prefer to use an Action, but that's me
Comment: I try to code with the minimum number of variables possible because it makes the text look less cluttered. I am looking to keep my "style" and only have one variable for each type of component as opposed to having multiple variables for only one type of component
Answer: Although I find it pretty weird, but if you insist on having only one variable of each type, then you will have no direct access to the first instantiated list. Assuming your panel and jli are defined globally, you can find the list by searching the child components of the panel:
@Override
    public void actionPerformed(ActionEvent e) {
        Component[] components = panel.getComponents();
        for (Component component : components) {
            // child component must be a JList, but not jli
            if(component instanceof JList && !component.equals(jli)) {
                JList firstList = (JList) component;
            }
        }
    }

I would still like to repeat that this code is a complete overhead that can be simply eliminated by introducing another JList variable. Instead of accessing the list directly, you will have to search for it, consuming cpu time. Also, what would you do if you would have a third JList? You couldn't then distinct the two inaccessible JLists from each other. If you still insist on having one variable, consider using a List of JLists:
List<JList> allMyJLists = new LinkedList<>();
JList jli = new JList(); // first JList
allMyJLists.add(jli);
jli = new JList(); // second JList
allMyJLists.add(jli);

Now access first JList with
allMyJLists.get(0);

and the second one with
allMyJLists.get(1);

Comment: Thanks a lot for the help, I like the idea of having a "List of Lists"

Multiple JLists on one JPanel


How to add platform-specific package data in setup.py?

Question: I would need to deploy platform-specific package data in the wheels built with setup.py
For a bit of background, I am trying to create Python bindings for a certain library using pre-built binaries and ctypesgen.
I have a data tree with platform-specific subdirectories that contain a bindings file and a binary each:
data/
    macos-arm64/
        _bindings.py
        binary.dylib
    linux-x64/
        _bindings.py
        binary.so
    windows-x64/
        _bindings.py
        binary.dll
    ...

And I have a source tree:
src/
    package_name/
        __init__.py
        __main__.py
        ...

Question: How can I build platform-specific packages that only contain the one corresponding binary and bindings?
The final directory tree as deployed to the end-user should structurally look like this:
package_name/
    __init__.py
    __main__.py
    _bindings.py
    binary.xyz
    ...

Answer: This is the solution I am currently using for pypdfium2:

Create a class of supported platforms whose values correspond to the data directory names:

class PlatformNames:
    darwin_x64  = "darwin_x64"
    linux_x64   = "linux_x64"
    windows_x64 = "windows_x64"
    # ...
    sourcebuild = "sourcebuild"

Wrap setuptools.setup() with a function that takes the platform name as argument and copies platform-dependent files into the source tree as required:

# A list of non-python file names to consider for inclusion in the installation, e. g.
Libnames = (
    "somelib.so",
    "somelib.dll",
    "somelib.dylib",
)

# _clean() removes possible old binaries/bindings
# _copy_bindings() copies the new stuff into the source tree
# _get_bdist() returns a custom `wheel.bdist_wheel` subclass with the `get_tag()` and `finalize_options()` functions overridden so as to tag the wheels according to their target platform.

def mkwheel(pl_name):
    _clean()
    _copy_bindings(pl_name)
    setuptools.setup(
        package_data = {"": Libnames},
        cmdclass = {"bdist_wheel": _get_bdist(pl_name)},
        # ...
    )
    # not cleaning up afterwards so that editable installs work (`pip3 install -e .`)

In setup.py, query for a custom environment variable defining the target platform (e. g. $PYP_TARGET_PLATFORM).

If set to a value that indicates the need for a source distribution (e. g. sdist), run the raw setuptools.setup() function without copying in any build artifacts.
If set to a platform name, build for the requested platform. This makes packaging platform-independent and avoids the need for native hosts to craft the wheels.
If not set, detect the host platform using sysconfig.get_platform() and call mkwheel() with the corresponding PlatformNames member.

In case the detected platform is not supported, trigger code that performs a source build, moves the created files into data/sourcebuild/ and runs mkwheel(PlatformNames.sourcebuild).

Write a script that iterates through the platform names, sets your environment variable and runs python3 -m build --no-isolation --skip-dependency-check --wheel for each. Also invoke build once with --sdist instead of --wheel and the environment variable set to the value for source distribution.

→ If all goes well, the platform-specific wheels and a source distribution will be written into dist/.
Perhaps this is a lot easier to understand just by looking at pypdfium2's code (especially setup.py, setup_base.py and craft_packages.py).
Disclaimer: I am not experienced with the setup infrastructure of Python and merely wrote this code out of personal need. I acknowledge that the approach is a bit "hacky". If there is a possibility to achieve the same goal while using the setuptools API in a more official sort of way, I'd be interested to hear about it.
Update 1: A negative implication of this concept is that the content wrongly ends up in a purelib folder, although it should be platlib as per PEP 427. I'm not sure how to instruct wheel/setuptools differently. Luckily, this is rather just a cosmetic problem.
Update 2: Found a fix to the purelib problem:
class BinaryDistribution (setuptools.Distribution):
    def has_ext_modules(self):
        return True

setuptools.setup(
    # ...
    distclass = BinaryDistribution,
)

Answer: Not quite what you described, but for simplicity I'd ship a wheel that is built for all supported platforms.
setup.py
import setuptools

setuptools.setup(
    name='package_name',
    packages=[
        'macos-arm64',
        'linux-x64',
        ...
    ],
    include_package_data=True
)

MANIFEST.in
include macos-arm64/binary.dylib
include linux-x64/binary.so
...

You'd need to adjust your import code a bit to import the correct bindings depending on platform.
The setuptools documentation describes in more detail how to do this.
Comment: @mara004 could you post your solution?
Comment: @vitalstatistix Done. Please see my answer below. I hope this helps you. If you have any questions left, feel free to ask.
Comment: Packaging all binaries into a single wheel is not a good solution for several reasons. Depending on how big the library is and how many platforms are supported, this can make your package ridiculously large. Moreover, if someone uses a platform for which you don't have binaries, it will lead to strange errors instead of a coherent report by pip that there's no suitable wheel available.
Anyway, I already found an acceptable solution how to do get the binaries into platform-specific wheels. If I have some more time I can post an answer about it.
Comment: @frampy Also note that your approach isn't actionable if aiming to supporting multiple architectures of one OS (e. g. macOS Intel and ARM64) if the binary loader doesn't offer a smart way to choose the right file. For instance, ctypesgen will correctly distinguish between `.so`/`.dll`/`.dylib` for Linux/Windows/macOS, but it doesn't have a way to choose between two binaries for the same OS, so you'd have to inject custom code into the loader by patch, which is tedious and prone to changes in the bindings generator.
Comment: MANIFEST.in should only include source distribution (sdist) files, not compiled objects


Docker /bin/bash: nodemon: command not found

Question: I am trying to mount my working node code from my host into a docker container and run it using nodemon using docker-compose.
But container doesn't seems to be able to find nodemon.
Note: My host machine does not has node or npm installed on it.
Here are the files in the root folder of my project (test). (This is only a rough draft)
Dockerfile
FROM surenderthakran/nodejs:v4
ADD . /test
WORKDIR /test
RUN make install
CMD make run

Makefile
SHELL:=/bin/bash
PWD:=$(shell pwd)
export PATH:= $(PWD)/node_modules/.bin:$(PWD)/bin:$(PATH)
DOCKER:=$(shell grep docker /proc/1/cgroup)

install:
    @echo Running make install......
    @npm config set unsafe-perm true
    @npm install

run:
    @echo Running make run......
# Check if we are inside docker container
ifdef DOCKER
    @echo We are dockerized!! :D
    @nodemon index.js
else
    @nodemon index.js
endif

.PHONY: install run

docker-compose.yml
app:
    build: .
    command: make run
    volumes:
        - .:/test
    environment:
        NODE_ENV: dev
    ports:
        - "17883:17883"
        - "17884:17884"

package.json
{
  "name": "test",
  "version": "1.0.0",
  "description": "test",
  "main": "index.js",
  "dependencies": {
    "express": "^4.13.3",
    "nodemon": "^1.8.0"
  },
  "devDependencies": {},
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "api",
    "nodejs",
    "express"
  ],
  "author": "test",
  "license": "ISC"
}

index.js
'use strict';

var express = require('express');

I build my image using docker-compose build. It finishes successfully.
But when I try to run it using docker-compose up, I get:
Creating test_app_1...
Attaching to test_app_1
app_1 | Running make run......
app_1 | We are dockerized!! :D
app_1 | /bin/bash: nodemon: command not found
app_1 | make: *** [run] Error 127
test_app_1 exited with code 2
Gracefully stopping... (press Ctrl+C again to force)

Can anyone please advice?
Note: The Dockerfile for my base image surenderthakran/nodejs:v4 can be found here: https://github.com/surenderthakran/dockerfile_nodejs/blob/master/Dockerfile
Comment: @allprog Yes it works interactively
Comment: Sounds like a PATH issue - try using the full path to nodemon: `/path/to/nodemon`
Comment: If you try interactively, does it work?
Comment: @ChrisMcKinnel the issue has been resolved. Feel free to suggest a better solution as mine is not very elegant. Thanks
Comment: @allprog the issue has been resolved. Feel free to suggest a better solution as mine is not very elegant. Thanks
Answer: The issue has been resolved. The issue boiled down to me not having node_modules in the mounted volume.
Basically, while doing docker-compose build the image was build correctly with the actual code being added to the image and creating the node_modules folder by npm install in the project root. But with docker-compose up the code was being mounted in the project root and it was overriding the earlier added code including the newly created node_modules folder.
So as a solution I compromised to install nodejs on my host and do a npm install on my host. So when the code my being mounted I still got my node_modules folder in my project root because it was also getting mounted from my host.
Not a very elegant solution but since it is a development setup I am ready for the compromise. On production I would be setting up using docker build and docker run and won't be using nodemon anyways.
If anyone can suggest me a better solution I will be greatful.
Thanks!!
Comment: I'm not that familiar with npm/node, but I think you could install them to a different url outside of the project root using `npm install -g` and then link to them with `npm link` instead of installing them again locally?  Another alternative might be to install them to a custom path in the container using `npm config set prefix`, then have a symlink in your project directory that points `./node_modules` at that directory. I think that will work with both add and volumes.
Comment: Bullseye solution.
Answer: I believe you should use a preinstall script in your package.json.
So, in the script section, just add script:
 "scritpts": {
     "preinstall": "npm i nodemon -g",
     "start": "nodemon app.js",
 }

And you should good to go :)
Comment: Maybe you'll need to `RUN npm set unsafe-perm true` before `RUN npm install`.
Answer: I've figured out how to do this without a Dockerfile, in case that's useful to anyone...
You can run multiple commands in the docker-compose.yml command line by using sh -c.
  my-server:
    image: node:18-alpine
    build: .
    volumes:
      - .:/usr/src/app
      - /usr/src/app/node_modules
    working_dir: /usr/src/app
    ports:
      - "3100:3100"
    command: sh -c "npm install -g nodemon && npm install && npm run dev "
    environment:
      NODE_ENV: development
      PORT: 3100

Comment: hey it's perfecto ! Here is my Dockerfile ```FROM node:14
WORKDIR /app
COPY package.json /app/
RUN npm install -g nodemon
RUN npm install
COPY . /app
EXPOSE 3000
CMD ["npm", "run",  "dev"]
```
Answer: Pretty late for an answer. But you could use something called as named volumes to mount your node_modules in the docker volumes space. That way it would hide your bind mount.
Answer: You need to set the node_modules as a mounted volume in the docker container.
e.g
docker-compose.yml
app:
build: .
command: make run
volumes:
    - .:/test
    - /test/node_modules
environment:
    NODE_ENV: dev
ports:
    - "17883:17883"
    - "17884:17884"


Delete an index with double quotes

Question: I had a problem with an index. The index name is "dbo.indexname" (including '"') and I cannot delete it. Someone knows how to drop an index with that name?
sp_help table  output:
index_name, index_keys, index_description,  index_max_rows_per_page,       index_fillfactor,    index_reservepagegap,   index_created,  index_local

"dbo.index_name",    id, nonclustered, 0,           0,       0, Nov 27 2015  6:41PM,    Global Index

Output for: select * from sysindexes where name like '%dbo.index_name%'
name    id  indid   doampg  ioampg  oampgtrips  status3 status2 ipgtrips    first   root    distribution    usagecnt    segment status  maxrowsperpage  minlen  maxlen  maxirow keycnt  keys1
"dbo.index_name"    1259148500  3   0   0   0   0   0   0   0   0   0   0   1   0   0   15  15  15  2   81  00  06  00  01  00  00  bf  08  00  00  00  01  00  00  00  81  00  00  00  00  00  00  2d  06  00  00  00  09  00  00  00

Comment: Is this ASE? this is how you drop in ASE: `drop index <>.["indexname"]`
Comment: `drop index ["dbo.indexname"]`?
Comment: DROP INDEX TABLE."dbo.indexname" / or ["dbo.indexname"] or \"dbo.indexname\"

The error is:
DROP INDEX does not allow specifying the database name as a prefix to the object name
ErrorCode: 166
Comment: Meet is right, but just to add - make sure you are running the command as user 'dbo', since the drop index command does not allow you to specify user name, and you may have same table name + index name for multiple users (schemas).
Comment: it didn't work. Same error. I tried: drop index table.["dbo.indexname"] and drop index table.[""dbo.indexname""] with the same result.
Comment: Is "dbo" the database name? Seems the parser is splitting on the "." and complains because the index belongs to a table, not the DB itself.
I'd try drop index '"dbo.indexname"' (single-quoting the quoted index name) because in another page I saw that it's possible to use either single or double quotes.
Comment: http://stackoverflow.com/questions/16019007/escape-double-quote-in-sybase
Comment: Thanks, but it didn't work. "dbo" is a DB user, no DB name. It didn't work with: drop index tablename.["'dbo.indexname'"]. Same error.
Comment: what is the name of your table and your index?  (you should not specify 'dbo' anywhere in command, I realize it's counter intuitive)
Comment: TABLE: table_name
INDEX: "dbo.table_name_index"
USER: dbo
DB: DBName
Comment: can you run this command and add the output to your post (not in comment here, but in original post): sp_help 'dbo.table_name'
Comment: Done. I put sp_help output
Comment: Wow, please post answer if you figure it out.
Comment: a bug in sybase? You can create it but it's not possible to delete it.
Comment: would you please remove `dbo.`!! As already mentioned, you can not have db user preceding index name
Comment: Ignore previous comment (didn't realize dbo. was actually part of the index name). Other workaround may include creating a copy of entire table, truncating and dropping old table, renaming the new table and finally creating a fresh index without `dbo.`
Comment: Can you rename the index first to something else, then drop it?  `sp_rename objname, newname [,"index" | "column"]` http://infocenter.sybase.com/archive/index.jsp?topic=/com.sybase.help.ase_15.0.sprocs/html/sprocs/sprocs185.htm
Comment: if possible; stop all operations, copy data to another table. drop your table, create as you desired. Finally move data to final table. It will rescue you forever. And please give very specific names to your indexex. Plus, you can try dbcc check commands.
Answer: What is the name of the table? Let's assume 'mytab'.
Now do this:
set quoted_identifier on
go
drop index mytab."dbo.indexname"
go
For some background on why this is puzzling, see http://www.sypron.nl/quiz2002a.html#dec02 .
Comment: You need to post your command and the error otherwise this cannot be resolved.
Comment: Also run this and post the output:
SELECT object_name(id), name from sysindexes where name like '%indexname%'
Comment: You did not include the first column, namely 'object_name(id). "select *' does not show the table name.

Delete an index with double quotes


How to make Rcpp find a new module?

Question: After I successfully compiled a new Rcpp module (the example from "Exposing C++ functions and classes with Rcpp modules, Dirk Eddelbuettel Romain Francois")
Following the instructions in the paper,
require( Rcpp )
yada <- Module( "yada" )

R complained about errors:
Error in FUN("_rcpp_module_boot_yada"[[1L]], ...) :
    no such symbol _rcpp_module_boot_yada in package .GlobalEnv

I tried putting ''dyn.load("/path/to/yada.dll")'' before calling ''Module( "yada" )'', still the same error.
There is very little info about the Rcpp's Module online. Does any known how to solve the problem? Should I put compiled module dll in some specifiec folder?
The example code:
const char* hello( std::string who ){
  std::string result( "hello " ) ;
  result += who ;
  return result.c_str() ;
}

RCPP_MODULE(yada){
  using namespace Rcpp ;
  function( "hello", &hello ) ;
}

Answer: To load the module from the external library ("yada.dll"), you must provide the PACKAGE argument to the Module() function:
yada <- Module( "yada", PACKAGE = "yada" )

The complete example looks as follows (tested under Linux, I guess it works analogous under Windows):
C++:
#include <Rcpp.h>

const char* hello( std::string who ){
  std::string result( "hello " ) ;
  result += who ;
  return result.c_str() ;
}

RCPP_MODULE(yada){
  using namespace Rcpp ;
  function( "hello", &hello ) ;
}

R:
require( Rcpp )
dyn.load( "yada.so" )
yada <- Module( "yada", PACKAGE = "yada" )
yada$hello( "world" )

Comment: I just get `> Module("yada","yada")
Uninitialized module named "yada" from package "yada"
> is.loaded("yada")
[1] FALSE`

How to make Rcpp find a new module?


Python: Searching for a RegEx in sys.stdin

Question: I have small python script in which I look for a pattern in the standard input, and output it after some reformatting. I have removed the complex pattern and reformatting code from the example.
Currently my code looks like this.
<code>for line in re.finditer(r"""(.*)\n""", sys.stdin.read(), re.MULTILINE):
    print(line.group(0))
</code>
Notice the "sys.stdin.read()". This causes the script to buffer the whole input before it looks for a pattern.
How can I pass stdin as a buffer to finditer, so stdin will searched as it is inputted to the script instead of having it buffered first?
Comment: The problem here is "when does the regex engine know to try to match against the buffer"? The engine can't match across "blocks" of the buffer, it has to operate on single chunks at a time, so you need to pick how much you want to operate on at once. To specify that, you can give `.read()` a chunk size as an argument.
Comment: Why do you buffer _all_ output from stin? It looks like you want the input processed line by line... Also, you say you want to "output ot after some reformatting" -- do you want to output only the lines which are matches by your regex, or all lines including the ones which didn't match?
Comment: @Amber I disagree, a regex machine is just a state machine that handles one token at a time. If given a stream of data, it can just wait for tokens until the end of stream signal (EOF char).
Comment: @fge, I never said it's a single line pattern, I simplified it a to this single line pattern but the actual number of lines in the original pattern is unknown in advance.
Comment: @Algebra I wasn't saying that regular expressions as a concept couldn't do it - I was saying that *Python's* regex operates on fixed buffers rather than streams.
Answer: Apparently I missed this before I asked my question, It is already answered.
Python regex parse stream
Unfortunately it's an issue with the implementation of regex in python.
See the link for possible workarounds.


Why does TH32CS_SNAPMODULE32 doesn't work alone?

Question: I was experimenting with some stuff in WinAPI. My OS is Win7 x64 P1 Ultimate. When I was trying to list all modules of a process I found out that the module that I wanted is a 32-bit module so I replaced
TH32CS_SNAPMODULE

With
TH32CS_SNAPMODULE32

After this no module was shown. So I decided to try using bitwise operators and looks like if I send the arguments like this
TH32CS_SNAPMODULE32 | TH32CS_SNAPMODULE

It works perfectly fine, listing all 64bit and 32bit modules. So my question here is why it doesn't work alone? Even the docs say it can be used with TH32CS_SNAPMODULE.
Quote from MSDN

TH32CS_SNAPMODULE32
Includes all 32-bit modules of the process specified in th32ProcessID in the snapshot when called from a 64-bit process. This flag can be combined with TH32CS_SNAPMODULE or TH32CS_SNAPALL. If the function fails with ERROR_BAD_LENGTH, retry the function until it succeeds.
Comment: Sounds like the documentation is wrong (or at least poorly worded).
Answer: The documentation is admittedly confusing. What it meant to say is that the TH32CS_SNAPMODULE32 flag must be combined with another flag, but can only be combined with TH32CS_SNAPMODULE or TH32CS_SNAPALL.
It's only slightly better phrased in this official answer TH32CS_SNAPMODULE vs TH32CS_SNAPMODULE32 - note the "extra":

Based on the feedback from the developer team, TH32CS_SNAPMODULE will
  provide you native modules.  You can OR TH32CS_SNAPMODULE32 with
  TH32CS_SNAPMODULE to get 32-bit modules also when on a 64-bit box.  It
  exists to indicate that you want the extra 32-bit module state.


What does the 'version' keyword mean in .libraries.yml?

Question: In theme.libraries.yml, libraries have a version key. It appears to be optional, but Drupal core libraries (core.libraries.yml) set the version key value as version. What does this keyword mean?
so :

Why we use the version keyword ?
When should I change the version keyword?
Comment: You can manually set a version, or if you use `version`, I believe it picks up your theme's current version number.
Answer:
Why should I use it?

It is used as an identifier for your libraries. Just like any project/package is tagged in different versions. For eg: jQuery 3.5.1 is slightly different from 3.0.0. The difference could be anything, from API change, new features, bug fixes, etc. Thus we need a way to identify the changes that happened to our library we created. So that we can make some conscious decisions. Another example. Suppose there is a 3rd party js that is having issues with another library of a specific version. So during the install, we can check if the other library has library greater than required.

When should I change its value?

Ideally after every deployment if any change to the library has occurred.
So what Drupal does is, it happens the version number to each file in that library when attaching that library to any page. For example: if my library has a css file called custom.css and the version number is say 1.0.0. So, the way it will get attached to the page will be like /path/to/theme/css/custom.css?v=1.0.0.
This is so far ok. But ideally on prod environments there are reverse proxies which caches these files. Suppose if we make any new changes to these files and even if we clear the cache, the files will still be served from CDN, thus we also need to make sure if any change has happened on these files, it makes sense to also increase the library version number. Just as you would do with creating a new tag for a new release for any project.
If we give the version as VERSION. Then drupal sets its version = \Drupal::VERSION the current drupal core version.
Comment: Is there an equivalent "VERSION" value to set the version as the current theme version instead of Drupal core version ?


Constant Variance Assumption in Linear Regression

Question: It seems to me that the following plot of "Residuals Vs. Fitted Values" violates the assumption of constant variance, since for lower fitted values, there are fewer points whereas for higher fitted values, there are dense points.
Am I correctly interpreting the plot?
Comment: I don't think there is hetereogeneity here, you have a lot more points on the right so it gives a false impression.
Answer: The non-constant variance is related to the spread of the points along the y axis. So if there's a funnel shape, for example, we would say: "as the fitted values increases, the variance of the residual (along the y axis) increases too".
Look the image below. The x axis represents the fitted values, and the y axis represents the residuals.
The third one is the only with constant variance.
Comment: These funnel shapes can sometimes be difficult to observe when the density along the x-axis is not the same. For instance a plot of two independent normal distributed variables $X,Y \sim N(0,1)$ may have conditional distributions with constant variance, but in a plot it looks like a circular shape and the middle part looks more bulky/wide than the outer edges.
Answer: residual plot telling you about the model fitting . what you have assumed for the model , as if you assumed the pure white noise model constant mean, constant variance, . this plot shows yes model is good fitted for the particular case, however some departure around the mean lines but these are being adjusted at the end . further expertise can judge more the behavior . i guessed it is ok no heterogeneity


Why should I choose a subdomain of my registered domain for AD (besides having to type "www" to access the comapny website?)

Question: Best practice all over the internet would have you believe that the sky will fall on your head if you register company.com as your public domain name and then use that same domain name in Active Directory here, and here for example. Yet in all those dire warnings, the only concrete reason I have ever seen is that users on internal DNS must type www.company.com in order to access the external website instead of just company.com. MS has hinted at some "future compatibility" that will be broken but this wisdom has been around since at least server 2008 judging from forum posts I've read on the subject.
For some reason, it seems that many of these warnings are also assuming that if you are using the same DNS name for AD, that you are exposing your AD zone to the internet and allowing all internal names to be resolved externally. That is most definitely not what I'm asking about.
Let's say I ignore this advice and use company.com as my AD name. Potential issues are:

Typing company.com in a web browser will try to go to a domain controller instead of www.company.com. Not even remotely an issue.
Internal names are all still internal. There is no dc01.company.com A record in our internet accessible zone file. External names like www, vpn, mail are all unrelated to our internal DNS.
This TechNet article warns of things like "less flexible, less automated DNS operations" and "instable[sic] operations and sub-optimal performance" but offers no details or reasons.

Let's say I follow this advice that so many people have taken to heart and use ad.company.com. I now have to deal with the following issues:

have a different NETBIOS name that does not match the domain name. That doesn't really bother me but it's something you have to think of.
The default UPN suffix when creating users in ADUC is @ad.company.com. The user's UPN suffix should match their email address so anyone who creates users has to know which UPN suffix to use and that it is not the default. One more thing to forget.
AD still requires ad.company.com DNS zone to run. If I want computers to be resolvable as computer.company.com I have to manage another DNS zone, as well as the DNS registration suffix and search suffix.

All this so people don't have to type "www" (which is so far from an actual problem for me it's not even on my radar)?
What is the actual danger of using the publicly registered domain name as the AD domain name?
Bonus question: What is the purpose of having company.com point to a domain controller in the first place when AD has a whole _msdcs namespace for AD related information?
Answer:
have a different NETBIOS name that does not match the domain name. That doesn't really bother me but it's something you have to think of.

Not at all, when creating a domain, you are definitely able to specify the NetBIOS name of the domain.

The default UPN suffix when creating users in ADUC is @ad.company.com. The user's UPN suffix should match their email address so anyone who creates users has to know which UPN suffix to use and that it is not the default. One more thing to forget.

If not there already, one should be rapidly approaching the time of automated, or scripted on-boarding of new accounts.  This will alleviate your concerns about what might happen if a user was created with the wrong UPN suffix.
Alternatively, it is a trivial matter to simply have a nightly clean up task that looks for user accounts with the incorrect UPN suffix and updates accordingly.

All this so people don't have to type "www" (which is so far from an actual problem for me it's not even on my radar)?

No; I believe the purpose is to avoid Split-brain DNS where two different DNS infrastructures are responsible for the same namespace.  Though, the fact that it is not a problem for you now does not mean that it will not become a problem in the future for you or your successors - especialy since this is a best practice, so solution vendors may start to design solutions with that in mind.

What is the actual danger of using the publicly registered domain name as the AD domain name?

I don't know that there is a huge "danger" (certainly not one that you would view as a danger - since you have not referenced any of the other potential concerns in the article); however, it has been my experience that when one is presented with a generally accepted (and actual - as defined by the vendor) "Best Practice" one does not deviate from the best practice without a valid business or technical reason.

Edit: For what its worth - in the most respectful way possible - I do not see any valid business or technical reason presented that would justify why Best Practices should be ignored.  So, I would suggest to be kind to your employer and your successors - and start with an environment that is aligned with best practices.
Comment: Especially best practice related to AD is changing with the release so "successors" would be confused anyway in case of upgrade and "new best practice" (like internal /.local/, public, subdomain,...). In general I would say the best practices linked to the specific release are based on some set of "cooperating" options. In case you really know the impact of changes feel free to set it up your own way. In case you don't have so deep technical knowledge the following best practices could help you with "future challenges" you have not idea about so far...
Comment: I'm not sure what you're getting at in regards to best practices changing with the release.  At least not in this case - using a subdomain of the publicly registered domain as the root of an AD forest has been either recommended or a best practice for well over 10 years.
Comment: AD si relatively "young" so public domain was already involved as it is build up on DNS but evolution came from domains where I remember some time ago the .local domain was preferred - and that is really not public domain (or better say for sure it was not at that time)... Not all the stuff is new with AD and some approach is taken from domain env.  / edit: but domains uses netbios so .local was probably from AD beginning.
Comment: @Semicolon "*Not at all, when creating a domain, you are definitely able to specify the NetBIOS name of the domain*"
That's not what I meant. I meant that by default, the NETBIOS name is the same as the AD name, so it's just another change that may cause issues in the future.
Comment: @Semicolon I don't really see how this answers the question though. It's more of the same "you should do it like this or things might break some day". What things? How? Tell me a story about someone who did not follow this practice and gotten bitten. Your answer repeats exactly what I've read online and lead me to ask this question in the first place. My question is not "what should I do?" it's "what can go wrong if I do things this way?". How do I know the things I listed in my cons list are not *more* likely to break something or cause problems in the future?
Comment: @Semicolon And as for your edit, I never said anything about an employer. I never said I was rolling out a new domain. I'm just asking a question. I usually always agree with best practices and follow them diligently because I can see the reasoning behind them, even when they require more work. This is the first time I've ever seen something that is recommended and felt that something was off about it.
Answer:
The user's UPN suffix should match their email address so anyone who
  creates users has to know which UPN suffix to use and that it is not
  the default.

There's no technical reason that the UPN Suffix needs to match the email address.
Microsoft's idea was that users remember their email addresses more readily then they remember their usernames, so using a UPN Suffix/User Principal Name that matches the email address would make the logon process easier and more intuitive for users. The problem is that it never really caught on.
One reason that you might want the UPN Suffix to match the email address is if you're synchronizing your on premises users to Office 365. Again, this isn't a technical requirement, but it makes things easier and more intuitive for the users when accessing Office 365 services, like Exchange Online and Sharepoint Online.
Comment: I don't know much about O365 but while researching I came across a few people who mentioned that the users' UPNs *should* match their email addresses but I don't know what the technical reasons were.
Comment: I don't think this answers the question, it's more of a comment. I wasn't asking specifically about changing UPN suffixes, my question is about the naming of the domain itself.
Comment: I was addressing that specific point in your question.


Sample size of sampling distribution of the sample mean

Question: When people say that the mean of the sampling distribution of the sample mean is equal to the population mean, is this true regardless of how small or large the size of the samples are? I'm having a hard time wrapping my head around how the size of the samples would not make a difference.
Edit: mistake in wording
Answer: It has to do with there being a lack of bias in your samples.  If you were to randomly select samples, even very small ones, from the population, their means will be above and below the population mean an equal number of times.   So, on average, the mean of the sample means should be a good approximation of the true population mean.
Sample size will, however, affect variance of your estimates around the true mean.  If you have a large n, samples will be closer to the true mean; if you have a small n, they will be dispersed widely around the true mean.
Answer: Yes, it is true that the sampling distribution of the mean is equal to the population mean regardless of how small or large the sample sizes are (In other words, the mean is ubiased).
A good way to think about this is to take a small population and study it.  Say for example your population consists of 4 elements having values 2, 4, 6, and 10.   The sampling distribution can be thought of as taking samples of a certain size over and over again from this population.  So for example  you wanted to sample 3 elements.  Then, on average, the mean of the means of a lot of samples of size 3 will be unbiased (e.g. the sample means of the mean will be a good approximation of the true population mean).  To see this note that the population average of 2, 4, 6, and 10 is 5.5.  The following R code shows 100000 samples of size 3 and of size 2 and of size 1.  After each sample is selected, the mean is calculated.  After all 100000 sample means are calculated, we find the sample mean of those means.  Note that this mean is very close to the population mean of 5.5 in every case (the estimates round to 5.5 every time), regardless of how large the sample size is:
x<-c(2,4,6,10)
> #Population Mean
> mean(x)
[1] 5.5
>
> sample.means<-rep(NA, 100000)
>
> set.seed(5)
> #Sample of size n=3
> for (i in 1:100000){
+   sample.means[i]<-mean(sample(x, size=3))
+ }
> mean(sample.means)
[1] 5.4982
>
> #Sample of size n=2
> for (i in 1:100000){
+   sample.means[i]<-mean(sample(x, size=2))
+ }
> mean(sample.means)
[1] 5.49388
>
> #Sample of size n=1
>
> for (i in 1:100000){
+   sample.means[i]<-mean(sample(x, size=2))
+ }
> mean(sample.means)
[1] 5.49419

Comment: @Antoine makes a good point which I did not address in my post.
Answer: The sample mean is sometimes an unbiased estimatorof the population mean, but it only holds for some sampling designs. Under simple random sampling (SRS), it does work, in which case the sample mean is equal to the Horvitz-Thompson estimator :
$
\begin{align*}
\hat{\bar{Y}}_{HT} &= \dfrac{1}{N} \sum_{k \in s} \dfrac{y_k}{\pi_k} \\
 &= \dfrac{1}{N} \sum_{k \in s} \dfrac{N}{n} y_k \\
 &= \dfrac{1}{n} \sum_{k \in s} y_k \\
 &= \bar{y}
\end{align*}
$
In this case, your estimator is unbiased for any sample size. This property may hold for other sampling schemes (systematic sampling with equal probabilities, for example), but it isn't true in general.
But be careful : using an unbiased estimator does not mean your estimator is consistent. Especially for small samples, you could end up with values really far from the true value. See for example : http://www.johndcook.com/blog/bias_consistency/
. Sometimes, using slightly biased estimators (the Hajek estimator for example) gives better results for small sample sizes (and the biais is smaller for larger samples).
Answer: As @Antoine R pointed out the idea is that sample means provide an unbiased estimate of the population mean. If we could sample unlimited samples of one single observation (or subject) (n = 1) we would reproduce the entire population, and its exact mean.
I wanted to contribute some simulations to illustrate the point about consistency: the sample mean converges to the population mean as the number of observations tends to infinity. Conversely, sample means with small number of observations can deviate substantially, perhaps explaining the counterintuitive impression you describe in your question.
If we obtain 10,000 samples out of a standard normal ($N(0,1)$) distribution each sample containing one additional subject than the previous, and we plot the results we get the following plot,
set.seed(50)
sample_means <- NULL
for (i in 1:1000) sample_means[i] <- mean(rnorm(i))
plot(sample_means, cex = 0.2, pch = 19, col = 'red')
lines(sample_means, col='orange')

showing the convergence to the true mean (0) with increasing sample size.
Or, another way of play with the concept would be to obtain 10,000 samples with n = 10, and then 10,000 samples with n = 10,000, plotting the histograms without altering the x axis limits,
set.seed(50)
par(mfrow=c(1,2))
s_means_10 <- NULL
for(i in 1:1e4) s_means_10[i] <- mean(rnorm(10))
hist(s_means_10,col="dark red", border = 'white', main = "Distr. Means of Samples of 10 rand. numbers")
s_means_10k <- NULL
for(i in 1:1e4) s_means_10k[i] <- mean(rnorm(1e4))
hist(s_means_10k,xlim=c(-4,4),border = "dark red",col="dark red", main = "Distr. Means of Samples of 10,000 numbers")

showing again the convergence with sample size, without any shift in the mean, which is always centered at zero.


Given the moment generating function, find the distribution of $X$.

Question: Let $X$ be a random variable with $M_X(t)=\frac{3}{3-t}$ $t \in (-3,3)$.
Now how do I find the distribution of $X$?
Answer: Observe that if $Y$ has an exponential distribution i.e. has density $f(x)=\lambda e^{-\lambda x}$ for $x\geq 0$, then its moment generating function is given by
$$
Ee^{tY}=\int_0^\infty e^{ty} \lambda e^{-\lambda y} \,dy=
\lambda\int_0^\infty e^{-(\lambda-t)y}  \,dy=
\frac{\lambda}{\lambda-t};\quad (t<\lambda).
$$
Now use the uniqueness of moment generating functions to determine the distribution of $X$ in your case.


Is there incremental deployment module for Drupal 7?

Question: I can find Deploy module for Drupal 7 that achieves full deployment. Also, I can find Incremental Deploy module for Drupal 6. Is there incremental deployment module for Drupal 7? or even work around that achieves incremental deployment for Drupal 7?
Comment: What the module for Drupal 6 did you find? This https://www.drupal.org/project/deploy module don't provide needed functionality for you? Wbat you mean when say "incremental deployment"?
Comment: Drupal 6&7 Deploy module is: (https://www.drupal.org/project/deploy). Drupal 6 Incremental Deploy module is: (https://www.drupal.org/project/incremental_deploy). I mean with "Incremental Deployment", continuous synchronization of content and configuration between two Drupal sites.
Answer: There is no Drupal 7 version of Incremental Deploy. In fact, the Drupal 6 version is no longer supported.
You have several options to duplicate the functionality. The closest match is probably Data Export Import -  https://www.drupal.org/project/data_export_import
Other options are the Migrate module - https://www.drupal.org/project/migrate or migrate_d2d - https://www.drupal.org/project/migrate_d2d
Modules for migrating specific content types are also available. For example, for taxonomies, Taxonomy CSV import/export - https://www.drupal.org/project/taxonomy_csv
Answer: Deployment module for Drupal 7 can be combined with Rules to create setup similar to Incremental Deploy. See https://www.drupal.org/node/1406136 for more info about that (you'll neeed to scroll down a bit).


Exchange Server - How to use existing certificate without CSR?

Question: I have some SSL certificates problem.
We have an Exchange 2010 server hosting mailboxes for mydomain.com, otherdomain.com and thirddomain.com. It's internal name is myserver.mydomain.local.
When setup, it came with its self-signed certificate on the name "myserver".
We already have an SSL certificate for mail.mydomain.com (containing the SAN mydomain.com), and want to use it so everyone will connect to OWA / Activesync / Outlook Anywhere etc. using the url : mail.mydomain.com.
The only resources I find searching the web are telling me to create a certificate request using the Exchange MMC, then forward it to the CA to issue a new certificate then complete the request on the Exchange server.
But how can I re-use our existing certificate ? It is fine, it has already the good server names in it, we don't want to re-pay for a new certificate ! (also we should pay for revoking the old one before a new one could be issued).
Answer: Just install the certificate (with private key) on the Exchange Server in the Computer's Personal Store. Then you can select it in Exchange
Comment: You pointed me the right way : "with private key". I had two separate files for certificate and private key. I merged then using openssl command line (see [http://security.stackexchange.com/questions/25996/how-to-import-a-private-key-in-windows]), and then I was able to import it into Exchange MMC and use it for the services. Now that's right !


How to make elements in Bulma box element full width in mobile view

Question: The bulma documentation has this example for a box with media objects:

          John Smith @johnsmith 31m

          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean efficitur sit amet massa fringilla egestas. Nullam condimentum luctus turpis.

I am new to Bulma and cannot figure out how to make the image and the paragraph texts fullwidth and one on top of the other in mobile view. I have tried to use column class but it didn't work. It is showing the image and text side by side regardless of the screen size.
Answer: Class .media, use a flexible rule, and you can independently move content under each other using a media query, setting rule flex-direction: column at breakpoint 480px (but you can specify any breakpoint).

@media (max-width: 480px) {
  .media {
    flex-direction: column;
  }
}
<link rel="stylesheet" href="https://email@example.com/css/bulma.min.css">

          John Smith @johnsmith 31m

          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean efficitur sit amet massa fringilla egestas. Nullam condimentum luctus turpis.


perl: print output of subroutine to file

Question: How to write the output of a subroutine to file?
my $logfile="C:/Test/report_p3.txt";
open(my $tt, ">",$logfile) or die "Can not open file";

foreach (@files)
{
if (($_ ne ".") && ($_ ne ".."))
{
    &getinfo($logdir."/".$_);
    print $tt &getinfo; #Here, I wanna pass the output to the handler
}
}

close $tt;

on standard output, &getinfo prints correctly the output.
Comment: As an aside, calling subroutines using a leading `&` hasn't been necessary since Perl 4.
Answer: Open a filehandle that outputs into a variable, and select it.
After that all output going into STDOUT will be caught in the variable.
Here is an example:
sub output {
    print "test\n";
}

my $out;
open VAROUT, '>', \$out;
select VAROUT;
output();
select STDOUT;
printf "output: %s\n", $out;

Answer: Is it really necesssary, that the subroutine, whose output you want to pass actually prints something?
Usually you should simply make your sub return a string and have the caller decide where to output it.
my $logfile="C:/Test/report_p3.txt";
open(my $tt, ">",$logfile) or die "Can not open file";

sub get_log {
  return "some text to log";
}

sub log_write {
  my $log_fh = shift;

  print $log_fh get_log() . "\n";
}

log_write($tt);       # prints to file handle from $tt
log_write(STDOUT);    # prints to STDOUT


PHP snag when using strange quotes

Question: Copying a mySQL-driven application and its web-pages (in PHP) I spent 2 days of time debugging the problem exemplified by code below. The 2 "didn't work" comment of course do not apply to the source server (where everything works OK) but do apply to the destination server where nothing works!
The web pages make use indiscriminately a mixture of single (hex 27), double (hex 22) and "funny" (hex e2 80 99).
What can I do? "sed'ing" every page would be easy but what about next time when
I have to re-migrate again these pages?
Thank you very much!
<?php

  echo "Welcome to a quote adventure

";

  $_SESSION['number1']=1;
  $_SESSION['number2']=2;
  $_SESSION['number3']=3;

  echo "my number1 (single-to-single quotes) is: ".$_SESSION['number1']."
";
  echo "my number2 (single-to-double quotes) is: ".$_SESSION["number2"]."
";
  echo "my number3 (single-to-funny quotes) is: ".$_SESSION['number3']."-------didn't work!
";

  $_SESSION["number1"]=1;
  $_SESSION["number2"]=2;
  $_SESSION["number3"]=3;

  echo "my number1 (double-to-single quotes) is: ".$_SESSION['number1']."
";
  echo "my number2 (double-to-double quotes) is: ".$_SESSION["number2"]."
";
  echo "my number3 (double-to-funny quotes) is: ".$_SESSION['number3']."-------didn't work!
";

  $_SESSION['number1']=1;
  $_SESSION['number2']=2;
  $_SESSION['number3']=3;

  echo "my number1 (funny-to-single quotes) is: ".$_SESSION['number1']."
";
  echo "my number2 (funny-to-double quotes) is: ".$_SESSION["number2"]."
";
  echo "my number3 (funny-to-funny quotes) is: ".$_SESSION['number3']."-------worked!
";
?>

I was expecting the web pages to work unmodified also on the destination server
Comment: Basically, "strange quotes" **do not** have any meaning an **any** PHP version. You have to get rid of them once for all. They DO NOT "work" in any sensible meaning.
Comment: @ÁlvaroGonzález I suppose these quotes could be already present in the code and it even would "work" in the older PHP versions, although spitting warnings right and left
Comment: What kind of process are you using to copy files that inserts typographic quotes? Pasting them in Microsoft Word?
Comment: How are you copying the mysql databases?  Please provide more info.
Comment: Also, as a programmer, you are supposed to **pay attention to error messages** PHP emits, when it runs your code. Which are quite self-explanatory in your case.
Comment: redwards: the problem is in PHP: I posted a piece of code having nothing to do with any database, and it behaves differently on different servers.
Comment: Your Common Sense: running the php through apache you do not see errors or warning. So I run in PHP directly and I saw them. They appear equally well on the original server where all works. But you are right when you say that I should take them away.
Comment: Sounds like the silent machine has error messages silenced in PHP.
Comment: Of course `$_SESSION['number3']=3;`or `$_SESSION["number3"]=3;` and then `echo $_SESSION['number3'];` won't work - `'number3'` and `"number3"` are text literals with the value `number3`, whereas `'number3'` is an _undefined constant_, and ignoring that it is not defined, PHP will assume you meant the _value_ `'number3'` here. So these are _different_ array keys.
Comment: As pointed out, the right answer was to point my attention to error messages: this pushed me first to run a part of the code in PHP (where they were immedaitely apparent) and next to look for these errors in the apache logfile. Examining the errors finally
Comment: (hate the return ending and publishing comment)
Since warnings about strange accents appeared equally well in the (working)
server machines, I went deeper and deeper and found that the not-working
server did not work for an entirely unrelated point.
That I fixed, and now the transition to the new server is completed. Thanks again!
Answer: If you've changed servers and didn't review PHP settings thoroughly, it's very likely that you're relying on defaults that have changed, in particular the ones related to error reporting. Your code was never fully correct, it worked partially by pure chance, but you've only realised now.
PHP has been hardening some error conditions because they were a source of frustrating bugs and didn't really serve any purpose. In particular, reading from a non-existing constant has been promoted from notice to warning:

Early PHP: assume you missed quotes and actually wanted a string, trigger notice.
PHP/7.2: same assumption, trigger warning.
PHP/8.0: no more guessing, trigger fatal error.

... key difference being that fatal errors abort the script, thus cannot be easily missed or ignored.
How does this non-existing constant issue apply here? Well, turns out that ' is a valid identifier for constants, as long as you don't use it in a location where the parser chokes:
define(''a'', 'example');
$foo = ['example' => 'OK'];
var_dump('a', $foo['a']);

string(7) "example"
string(2) "OK"

Demo

PHP snag when using strange quotes


Gatsby / Wordpress: map not working when getting data from another table

Question: I'm running into an issue with this application (React/Gatsby + Wordpress as backend).
All data are being fetched with GraphQL through gatsby-source-wordpress plugin for Gatsby.
I'm getting all data correctly from Wordpress using Advanced Custom Fields, except when I need to call some data from another table.
productLines.map works properly but not line.prodLineColors.map
These colors (custom post type) are selected in each post and I need to show their content in this loop.
The query seems to be correct and in GraphiQL I'm retrieving all data as wanted.
It doesn't return any error, it returns just an empty loop. The loop is reiterated so much times as much are the selected colors in the post, just without the expected data (i.e. color.colorType). All console.log calls return [object object]
{productLines.map( (line, index) => {
console.log('line.prodLineColors: ' + line.prodLineColors)
return (

{line.prodLineName}

            {line.prodLineColors.map( (color, index) => {

                console.log('colors: ' + color)
                console.log('color: ' + color.farben)

                if(color.colorType === 'img') {
                    ... do some img things
                }

            })}

)

Here's the query:
query($slug: String!) {
  allWpProdukt(filter: { slug: { eq: $slug } }) {
      nodes {
          title
          slug
          productACF {
              prodLines {
                  prodLineColors {
                      ... on WpFarbe {
                          farben {
                              colorHex
                              colorName
                              colorType
                              colorImg {
                                  sourceUrl
                              }
                          }
                      }
                  }
              }
          }
      }
  }

Can someone help me understand this issue? I understand that something is missing between "prodLineColors" and "farben" but I don't know what exactly and I'm not able to find a similar case by searching for issues nor in the documentation.
Any help will be appreciated! Thanks in advance!
Comment: What is `productLines`? `props.data. allWpProdukt.nodes`?
Comment: Nope, allWpProdukt.nodes.productACF.productLines -

This is just one of the custom fields I created for this post type
Answer: It looks you have an issue(s) accessing the data.

All console.log calls return [object object]

This happens when you are not accessing the correct object of the array or your position is not something callable as is (objects, arrays, etc).

Nope, allWpProdukt.nodes.productACF.productLines

As I mentioned, you can't do allWpProdukt.nodes.productACF because nodes is an array, so you must access to a specific position or loop through it to get each node. It looks you have several nested loops you're not doing so start checking how your data structure looks like and iterate each position at a time. Something as dummy as:
{

    allWpProdukt.nodes.map(node =>
{node.title}
)

}

Depending on your structure maybe you can omit the nodes and just access to the first position and keep iterating:
 allWpProdukt.nodes[0].productACF.prodLines

Check which kind of data is an object and which is an array to iterate or not, prodLines is likely to be an array as nodes is, as probably prodLineColors and farben are.


Dropping condition from conditional probability

Question: Consider 3 random variables $X$, $Y$ and $Z$. Under which conditions would we have $P(X\mid Y,Z) = P(X\mid Z)$?
Comment: Your title asks about "dropping" the condition, regardless of the rest of the question, you can drop it by $P(X|Z) = \sum_y P(X|Y = y,Z) P(Y=y)$ by the [law of total probability](https://en.wikipedia.org/wiki/Law_of_total_probability).
Answer: This is equivalent to $X$ and $Y$ being conditionally independent given $Z=z$. We have
$$
f_{X|Y,Z}(x|y,z) = \frac{f_{X,Y,Z}(x,y,z)}{f_{Y,Z}(y,z)}
=\frac{f_{X,Y|Z}(x,y|z)f_Z(z)}{f_{Y|Z}(y|z)f_Z(z)} =\frac{f_{X,Y|Z}(x,y|z)}{f_{Y|Z}(y|z)}
$$
We want this to be equal to $f_{X|Z}(x|z)$, which is equivalent to
$$
f_{X,Y|Z}(x,y|z) =f_{X|Z}(x|z) f_{Y|Z}(y|z) \,,
$$
i.e. conditional independence.
Comment: Thanks.  Yes, that is clear. Is there some condition on pairwise relations between $X$, $Y$, $Z$ implying conditional independence of $X$ and $Y$ given $Z=z$?
Comment: You can often spot this from how the random variables are defined. For example, you could have $X,Y | Z=z  \sim \mathrm{Poisson}(z)$, where $Z \sim \mathrm{Gamma}(\alpha, \beta)$. $X$ and $Y$ are not independent, because their distributions depend on the common (stochastic) parameter $Z$, but they _are_ conditionally independent for a fixed $Z=z$.


How can I change theme?

Question: I tried drush disable theme-name and afterwards drush enable theme-name, but it didn't work.
How do you change theme with Drush?
Answer: For Drush 9.5.2 and Drupal 8.6.5 I use the following:
drush theme:uninstall THEME_MACHINE_NAME
drush theme:enable THEME_MACHINE_NAME
drush config-set system.theme default THEME_MACHINE_NAME

Comment: Best answer. And if you want to set the admin theme, you can replace "default" with "admin" in the third line.
Comment: To set admin theme one can use: `drush config-set system.theme admin THEME_MACHINE_NAME `
Comment: I can also confirm that these commands work with Drush 10.x and Drupal 9.x.
Answer: Commands to be used in theme using drush :
theme-enable        => pm-enable
theme-disable       => pm-disable
theme-info          => pm-info
theme-list          => pm-list --type=theme
theme-list-enabled  => pm-list --type=theme --status=enabled
theme-set-default   => vset theme_default
theme-set-admin     => vset admin_theme
theme-status        => status theme

Comment: This only applies to Drupal 6 and 7.
Comment: I didn't find this worked, I had to then also do this: `drush vset theme_default THEMENAME` and because I had errors relating to my theme not being active, I couldn't access the set default through the admin pages (article I read here: http://pixelthis.gr/blog/drush-enable-theme-and-set-default)
Answer: With Drush 7 and 8, it is no longer necessary to be so verbose. If you want to enable a theme use the alias:
drush en your-theme-name
drush dis your-theme-name

For example:
drush en seven
drush dis bartik

You may want to clear your caches after enabling or disabling themes. For more information please see: DrushCommands.com
Comment: For a theme, it is usually not enough to just enable it. You also have to set it as a default. In Drupal 8, the command is this: `drush config-set system.theme default NAME_OF_YOUR_THEME`
Comment: The question is how to change the theme. If there is already a default, you can't change it until you can set another one as default, and this does not answer that.
Answer: If you want to change the admin theme using Drush, you can use below command.
drush config-set system.theme admin <theme_machine_name>

Eg.
drush config-set system.theme admin seven

If the theme is not installed, first install the theme using below command
drush theme:en seven

Again run the above command to set admin theme.
Comment: This works with drupal 10.  Also useful:  drush config-get system.theme, drush config-set system.theme default olivero
Answer: drush dis and drush disable aren't anymore valid, in Drupal 8. Their Drupal 8 equivalent are the following commands.
drush pm-uninstall THEME_MACHINE_NAME
drush pm-uninstall MODULE_MACHINE_NAME

Comment: This won't work on a theme set as default.

How can I change theme?


javascript loops: restore console after each iteration

Question: I am currently working on code that when runs on Node.js logs only each of the values of the object below, delayed by one second on each iteration and concatenated with the string "you are now watching"
const episodes = [
  { id: 's06e01', title: 'Pilot' },
  { id: 's06e02', title: 'Top Banana' },
  { id: 's06e03', title: 'Charity Drive' },
  { id: 's06e04', title: 'Visiting Ours' },
  { id: 's06e05', title: 'My Mother, the Car' },
  { id: 's06e06', title: 'In God We Trust' },
  { id: 's06e07', title: 'Storming the castle' },
  { id: 's06e08', title: 'Pier Pressure' },
  { id: 's06e09', title: 'Public Relations' },
];
    const finaleEpisode = { id: 's06e10', title: 'Bringing Up Buster' };

const addToPlaylist = episodes.concat(finaleEpisode)

Below is where i managed to do just that but i am aware there is a much simpler way to do this, I intended to use a loop but was unable to find a way to restore the console log after each iteration. Therefore I used Asynchronous JS to delay the printing and clearing functions
console.log("You are Now Watching "  + addToPlaylist[0].id + ' ' + addToPlaylist[0].title);

setTimeout(function(){console.log('\033c'); }, 3000);

setTimeout(function(){console.log("You are Now Watching "  + addToPlaylist[1].id + ' ' + addToPlaylist[1].title); }, 4000);

setTimeout(function(){console.log('\033c'); }, 5000);

setTimeout(function(){console.log("You are Now Watching "  + addToPlaylist[2].id + ' ' + addToPlaylist[2].title); }, 6000);

setTimeout(function(){console.log('\033c'); }, 7000);

setTimeout(function(){console.log("You are Now Watching "  + addToPlaylist[3].id + ' ' + addToPlaylist[3].title); }, 8000);

setTimeout(function(){console.log('\033c'); }, 9000);

setTimeout(function(){console.log("You are Now Watching "  + addToPlaylist[4].id + ' ' + addToPlaylist[4].title); }, 10000);

setTimeout(function(){console.log('\033c'); }, 11000);

setTimeout(function(){console.log("You are Now Watching "  + addToPlaylist[5].id + ' ' + addToPlaylist[5].title); }, 12000);

setTimeout(function(){console.log('\033c'); }, 13000);

setTimeout(function(){console.log("You are Now Watching "  + addToPlaylist[6].id + ' ' + addToPlaylist[6].title); }, 14000);

Comment: What does "restore console log" mean?
Comment: It is not clear to me what the aim of this exercise is -sounds like an X/Y problem or perhaps a duplicate of https://stackoverflow.com/questions/24293376/javascript-for-loop-with-timeout
Answer: function doTask(num, max) {
    console.log("do whatever you want with " + num);
    if(num < max) {
        window.setTimeout(function() {
            doTask(++num, max);
        }, 2000);
    }
}

Ok, this is recursive. Don't do it with max greater than some millions.
Answer: I guess you are looking for something like this:
for (let i = 0; i < addToPlaylist.length; i++) {
    setTimeout(() => {
        // clears all characters printer on previous loop
        process.stdout.clearLine();

        // use \r at the end to return the cursor to the begining
        process.stdout.write("You are Now Watching "  + addToPlaylist[i].id + ' ' + addToPlaylist[i].title + "\r");
    }, i * 2000);
}

Your solution was not really "restoring" the line printed via console.log btw.
Comment: Then what was it that my original code was really doing?
Comment: When I tried that in node, it was printing new lines, they were not visible at first, but then I tried scroll a bit and they were still there.


How create gmail like common control bar in Canjs?

Question: For example we make a Gmail clone in canjs. Consider each item in the sidebar being rendered with a component of its own. Now I want a single control bar just like gmail to control the activities inside the components.
How should I approach it???
At present am looking at the change event of localStorage, is there a better solution to this???
Answer: I would recommend using an appstate Map or a page level component that holds the state for the features of your toolbar.  If using an appstate, you could use can.route.map to bind certain features of the appstate Map to the route, so the state of your app can be controlled by the URL.  A page attribute, for example, would control which main page is displayed (say, the message list or the contacts list.)  You could then listen for certain values of page in your stache template to switch to showing the correct page.  This snippet would show the message-list whenever the page attribute of the appstate is 'messages':  {{#is appstate.page 'messages}}<message-list></message-list>{{/is}}
If you had more specifics of which feature is hardest to figure out how to implement, I might be able to give more specific advice.
Comment: Hi Marshall, thanks for replying, I was loosing hope that anyone would. :D

So at present I have already implemented the menu interface like gmail where if you click on inbox it will go to inbox and if on sent messages and so on. However, as we know they provide different control bars on a common bar. This is what I want to implement.

I have also explored a few things and now betting on having a page level component and then child components and set communication between them. Parent will contain the control bar. What say???
Comment: It sounds like you're on the right track.  Is this for work or for an open-source project?  I have slowly been working on the Postaci-Webmail, open-source email project.  I made the design and the HTML template, but haven't started the app, yet.  https://github.com/Postaci-Webmail/Postaci/tree/next  There's an image on that page. Is the toolbar you're talking about like the tools/icons above the message pane on the right-hand side of the image?
Comment: No Marshall, unfortunately it is a closed source project for my company. www.mywash.in

Since am the Tech Lead in the company I push for CanJS (coz I can do that :D ). It's a lovely piece of work. I wish I had enough spare time though to get involved in some open source project.

Btw, thanks for all the help. Appreciated. :)


webview.goBack() method doesnt invoke shouldOverrideUrlLoading method

Question: I want every page loaded in my app go through the url override method ( where i do some html modifications ). How can i achieve this?.
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // do some html modifcations (myhtml)
    view.loadDataWithBaseURL(url, myhtml, "text/html", "utf-8", url);
    return false;
}

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web1.canGoBack()) {
        web1.goBack(); // go back 1 step
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Comment: I'm also interested in the answer of this question.
Answer: on page finished method you will get the url  and you can reload the url
       @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            _dialog.dismiss();
        }

        @Override
        public void onReceivedError(WebView view, int errorCode,String description, String failingUrl) {
            // TODO Auto-generated method stub
            super.onReceivedError(view, errorCode, description, failingUrl);
            try{
                _dialog.dismiss();
                Toast.makeText(Showwebviewlatestnews.this, "NO Internet Connection Available", Toast.LENGTH_SHORT);
            }catch (Exception e) {

            }
        }

Answer: Try to return shouldOverrideUrlLoading true
Here is an explanation:-
True if the host application wants to leave the current WebView and handle the url itself, otherwise return false. Reference
So this should do the trick,
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    // do some html modifcations (myhtml)
    view.loadDataWithBaseURL(url, myhtml, "text/html", "utf-8", url);
    return true;
}

And handle backPressed() like -
@Override
public void onBackPressed() {
    if (webview != null && webview.canGoBack()) {
        webview.goBack();
    } else {
        super.onBackPressed();
    }
}

Answer: //Replace this
 public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && web1.canGoBack()) {
    web1.goBack(); // go back 1 step
    return true;
}
return super.onKeyDown(keyCode, event);}

With
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK) && web1.canGoBack()) {
    web1.goBack(); // go back 1 step
    web1.goBack();
    return true;
}
return super.onKeyDown(keyCode, event);}


Para que serve o camando adb forward e como usá-lo?

Question: Gostaria de saber o que é o adb forward e como usá-lo. Alguém poderia me explicar?
Answer: Não tem muito o que dizer sobre adb forward, além do que esta na documentação: https://developer.android.com/studio/command-line/adb#forwardports
Ele serve para encaminhar portas do host (seu computador, aonde esta executando o comando adb) para outras portas do "dispositivo" (celular ou emulador), assim terá uma porta do host acessivel por outra porta no dispositivo.
Por exemplo, se tiver um servidor HTTP do qual queira acessar no celular ou emulador, esse comando ajudaria.
Também existe o contrário/reverso, quando desejar acessar a porta de um dispositivo no seu computador deve se usar adb reverse, por exemplo:
adb reverse tcp:80 tcp:8000

Supondo que tenha a porta 80 no dispositivo/emulador/celular, ela ficará acessível no computador conectado na porta 8000.
O exemplo com HTTP é apenas um uso, isso nem é questão de programação, mas sim de redes e dispositivos, que claro pode ajudar em programação como também pode ajudar em outras questões, como sendo funcionalidade que precisem acessar portas de ambos lados (computador ou dispositivo)


Purchase new SSL Certificate before existing one expires

Question: I am currently transferring a new customer onto my virtual private server from their old host. They have an existing SSL certificate but it expires next month so I don't think it is worth the hassle of getting the details from the old host.
Would there be any issue with purchasing a new SSL (even if it's from the same authority) whilst they have an existing, unexpired, SSL?
Answer: You can just request a new certificate, and run both certificates at the same time.
In fact this is quite common for applications that need to be allowed to run without downtime, that require new certificates.
If you install both on one server, the old certificate will be ignored, in favor of the new one.
Datasprings has a nice write-up about certificate renewal.
Answer: Some CAs, I know DigiCert is one, will carry over the remaining time on your existing cert to the new one.
If you're using such a CA, then just go ahead and request the new certificate.
If you're not, then the only issue that would arise is that you paid twice for the left over time. There are no technical issues to take into account.


How to check if a scheduled Rules action set has already been scheduled?

Question: I'm using the Rules Scheduler (sub-module of the Rules module) to schedule an email reminder based on a date field set in the content type. So a user can request a reminder email on a specific date, to update that content.
However, if I invoke the Rules Action on node update, then I end up with lots of emails scheduled for that date.
How can I make sure that the rule is only scheduled once for the given date?
Answer: The answer to this is simple.
In the action of the rule that calls the schedule component evaluation, in the Identifier section, set a unique value, such as:
reminder-[node:title]-[node:nid]
This value will be a unique identifier of the scheduled task. Scheduled tasks with the same ID will simply be replaced. Problem solved.
Comment: It is OK for your scenario. But there will be situations, like I face now, need to check if that scheduled task really exists.
Comment: @Junaid : I'd be interested in more details about such situations that you were facing. Can you add some more details?
Answer: My answer to "Rule to store user's last post date and scheduled rule based 30 day reminder" contains an illustration about how to delete scheduled tasks, using the "schedule_delete": the schedule_delete that is part of this rule is to ensure that previously "scheduled" reminders will get removed when updating the data field (so that it only triggers 1 reminder, and with the most recent date).
Here is a copy of the Rules Action included in that answer (which refers to the Rules Component that is also included in that answer):
..
        "DO" : [
          { "schedule_delete" : {
              "component" : "rules_send_email_notification",
              "task" : "[account:name]"
            }
          },
          { "data_set" : { "data" : [ "account:field-next-article" ], "value" : "+30 day" } },
          { "schedule" : {
              "component" : "rules_send_email_notification",
              "date" : {
                "select" : "account:field-next-article",
                "date_offset" : { "value" : 2592000 }
              },
              "identifier" : "[account:name]",
              "param_user_to_notify" : [ "account" ]
            }
          }
        ]
...

What is crucial in the context of this question here, is that you have to ensure that you give enough thought to the value you'll use for the identifier of the scheduled task.
In my sample the choice was that for each user, at any time, there can only be 1 scheduled task for each user. So using the account name as the key for that identifier is perfect ... to make it unique, and to know exactly which scheduled task should be deleted also.