How to count detail rows on nested categories?

Question: Let us consider that we have Categories (with PK as CategoryId) and Products (with PK as ProductId).  Also, assume that every Category can relate to its parent category (using ParentCategoryId column in Categories).
How can I get Category wise product count?  The parent category should include the count of all products of all of its sub-categories as well.
Any easier way to do?
Answer: sounds like what you are asking for would be a good use for with rollup
select cola, colb, SUM(colc) AS sumc
from table
group by cola, colb
with rollup

This would give a sum for colb and a rollup sum for cola. Example result below. Hope the formatting works. The null values are the rollup sums for the group.
cola    colb    sumc
1       a       1
1       b       4
1       NULL    5
2       c       2
2       d       3
2       NULL    5
NULL    NULL    10

Give it a go and let me know if that has worked.
--EDIT
OK i think ive got this as it is working on a small test set i am using. Ive started to see a place where i need this myself so thanks for asking the question. I will admit this is a bit messy but should work for any number of levels and will only return the sum at the highest level.
I made an assumption that there is a number field in products.
with x
as (
    select c.CategoryID, c.parentid, p.number, cast(c.CategoryID as varchar(8000)) as grp, c.CategoryID as thisid
    from Categories as c
    join Products as p on p.Categoryid = c.CategoryID
union all
    select c.CategoryID, c.parentid, p.number, cast(c.CategoryID as varchar(8000))+'.'+x.grp , x.thisid
    from Categories as c
    join Products as p on p.Categoryid = c.CategoryID
    join x on x.parentid = c.CategoryID
)
select x.CategoryID, SUM(x.number) as Amount
from x
left join Categories a on (a.CategoryID = LEFT(x.grp, case when charindex('.',x.grp)-1 > 0 then charindex('.',x.grp)-1 else 0 end))
                    or (a.CategoryID = x.thisid)
where a.parentid = 0
group by x.CategoryID

Comment: I think I did not frame my question correctly.  I apologize for that.  I simply would need the output with columns "CategoryId, Count(Products)".  The count of products would include all products from the current category and all of its sub-categories.
Comment: Are there multiple levels of category (grandparent-parent-child) or is it just holding one level (parent-child)?
Comment: Yes.  I have multiple levels of Categories.  But products always belong one Category (category could be grand-parent, parent or child).
Comment: The only way i can think of doing this at this moment is by using a cursor which is very inefficient or by joining to the same table as many times as you have levels. How large is the dataset and how often will this need to run?
Answer: Assuming that Products can only point to a subcategory, here's a probable solution to the problem:
SELECT
  cp.CategoryId,
  ProductCount = COUNT(*)
FROM Products p
  INNER JOIN Categories cc ON p.CategoryId = cc.CategoryId
  INNER JOIN Categories cp ON cc.ParentCategoryId = cp.CategoryId
GROUP BY cp.CategoryId

But if the above assumption is wrong and a product can reference a parent category directly as well as a subcategory, then here's how you could count the products in this case:
SELECT
  CategoryId = ISNULL(c2.CategoryId, c1.CategoryId),
  ProductCount = COUNT(*)
FROM Products p
  INNER JOIN Categories c1 ON p.CategoryId = c1.CategoryId
  LEFT JOIN  Categories c2 ON c1.ParentCategoryId = c2.CategoryId
GROUP BY ISNULL(c2.CategoryId, c1.CategoryId)

EDIT
This should work for 3 levels of hierarchy of categories (category, sub-category, sub-sub-category).
SELECT
  CategoryId = COALESCE(c3.CategoryId, c2.CategoryId, c1.CategoryId),
  ProductCount = COUNT(*)
FROM Products p
  INNER JOIN Categories c1 ON p.CategoryId = c1.CategoryId
  LEFT JOIN  Categories c2 ON c1.ParentCategoryId = c2.CategoryId
  LEFT JOIN  Categories c3 ON c2.ParentCategoryId = c3.CategoryId
GROUP BY ISNULL(c3.CategoryId, c2.CategoryId, c1.CategoryId)

COALESCE picks the first non-NULL component. If the category is a child, it picks c3.Category, which is its grand-parent, if a parent, then its parent c2.Category is chosen, otherwise it's a grand-parent (c1.CategoryId).
In the end, it selects only grand-parent categories, and shows product count for them that includes all the subcategories of all levels.
Comment: Product belong to only one category (the category could be a grandparent, parent or child).  Does the first one still work (for nested sub-categories)?
Comment: @user203687: Both solutions were for two levels of hierarchy only. Added another one.


Clusterization a Dataset by Category of Another

Question: I have limited knowledge about Machine Learning unfortunately and I want to clusterize a dataset with attributes of another. I have two different data sets which are users and books. Users have different books and books have different categories:
User1 -> book1, book2, book3
User2 -> book1,book3
User3 -> book4, book1

book1 -> Business, Economy, Finance
book2 -> Music, Creativity
book3 -> Novel, Classics
book4 -> Photography

I want to get a kind of result such as "Finance lovers" or "Music lovers". What are the techniques/ways that I can apply? I searched the techniques but I all find that related to my issue was this. However this solution is only one part of my issue I believe.
Answer: You are not doing clustering, and there is also no suitable data or task here for learning.
What you want to do is categorizarion, probably with a rather simple aggregation statistic.
For every user:

select all his books
select all categoies of his books
return the most frequent book category as user category

By the usual terminology:

Machine learning requires training data, and you want to transfer this information to unlabeled data.
Clustering is when you do not know what classes exist.

You have only one kind of data. For ML you need to have training data, and data to predict for. But at the same time, you have book categories - you don't want a clustering algorithm to do something different. A clustering algorithm will yield Clusters "1", "2" and "3". It cannot tell you what makes the cluster special.
Try above approach (there probably is no "tool" or "algorithm" gor that, you should be able to formulate this as SQL query). It's easy to understand, and predictable. Simple wins.
Comment: Your solution contains no ML but statistics and simple&effective. Thanks for the answer. One final question about your technique, what about the rest of the users? Lets say the normal value for the "society" is having %40 Business of whole categories (average) but my user has %30 Business books which is the top category like you said. Is the user still a business lover in this case?
Comment: Normalizing by the averages is a reasonable improvement.
Answer: You could use the book categories instead of the book label for clustering. For example:
These are the categories:
  B(Business)
  E(Economy)
  F(Finance)
  M(Music)
  N(Novel)
  Cr(Creativity),
  Cl(Classics)
  P(Photography).

Then you can make a vector (B, E, F, M, N, Cr, Cl, P) with the frequency each label appears for each user:
User1 -> (1, 1, 1, 1, 1, 1, 1, 0)
User2 -> (1, 1, 1, 0, 1, 0, 1, 0)
User3 -> (1, 1, 1, 0, 0, 0, 0, 1)

Then you can use just a standard clustering algorithm.


How to create a spoiler feature inside a Moodle course (HTML)?

Question: We create Moodle courses with PHP and the Moodle libraries.
The content comes from our users.
Some users create spoilers (DIVs to be clicked and then they reveal the content).
How could such a spoiler be created in Moodle?
Can Javascript and CSS be implemented directly into the HTML of a course? – It seems so!
Answer: You can basically add javascript and CSS to an HTML element:
$output = '
This is the spoiler content.
';

Then it works as a spoiler.


Perguntas com Checkbox dinâmico com required ou não

Question: Olá, já tentei de tudo com javascript, de tutoriais que encontrei na internet, mas nada me ajuda, acho que é porque meu form é dinâmico, ou seja, o usuário que cadastra as perguntas e alternativas.
No caso assim, esse código pega do banco duas tabelas, uma com a pergunta (nela salva, se a pergunta é obrigatória ou não) e no outro, salva as alternativas (titulo e id). o problema é como faço para deixar os checkboxers obrigatórios? tipo, só os que no banco estiverem com o obrigatório= 1, e também, todas as alternativas, tem que ser com ids dinâmicos, como mostra o código,  alguém que manje de JS e PHP pode dar uma luz? Obrigado!
Edit: Se a pergunta for obrigatória, o usuário tem que selecionar pelo menos um campo, senão não for obrigatória, não precisa selecionar nada.
<form action="envia.php" method="post" class="ac-custom ac-checkbox ac-cross" autocomplete="off">
    <?php
        $i = 1;
        $i2 = 1;
        $sql2 = "SELECT * FROM perguntas WHERE type = '3' ";
        $rs2 = mysqli_query($conn, $sql2);
        while($dados2 = mysqli_fetch_array($rs2)){
    ?>

<?php echo $dados2['title']?>

            <?php
            if(!empty($dados2['imagem'])){
                echo '';
            };
            ?>

                    <?php
                        $sql3 = "SELECT * FROM alternativas WHERE id_de = ".$dados2['id']." ";
                        $rs3 = mysqli_query($conn, $sql3);
                        while($dados3 = mysqli_fetch_array($rs3)){
                    ?>

                        <input id="cb<?php echo $i++?>" value="<?php echo $dados3['alternativa']?>" name="cb<?php echo $dados3['id']?>" type="checkbox" required>
                        <label for="cb<?php echo $i2++?>" style="font-size:2.0em"><?php echo $dados3['alternativa']?>

                    <?php
                        }
                    ?>

    <?php
        }
    ?>

        <button type="submit" class="btn btn-primary">Enviar</button>

</form>

Comment: O que você quis dizer `tem que ser com ids dinâmicos`? Seria algo como `cb + a id da alternativa na tabela` ?
Answer: Vamos por passos.
Primeiramente você deve verificar se a pergunta é obrigatória, para isso dentro do while($dados2 = mysqli_fetch_array($rs2)) crie uma variável ex:
$obrigatorio = "";

Abaixo da variável criada, crie uma condição if que ira verificar se a pergunta é obrigatória, ex:
if ($dados2['obrigatorio']) { // 1 = true
    $obrigatorio = ' required'; // Obrigatório
} else { // 0 = false
    $obrigatorio = ''; // Não é obrigatório
}

Segundo, você deve imprimir a variável $obrigatorio na tela, então na linha
<input id="cb<?php echo $i++?>" value="<?php echo $dados3['alternativa']?>" name="cb<?php echo $dados3['id']?>" type="checkbox" required>

Altere required para <?php echo $obrigatorio; ?>, ficando assim:
<input id="cb<?php echo $i++; ?>" value="<?php echo $dados3['alternativa']; ?>" name="cb<?php echo $dados3['id']; ?>" type="checkbox"<?php echo $obrigatorio; // Retorna se o campo é obrigatório ?>>


Suppose that $\underset{x\rightarrow0}{\lim}\frac{f\left(x\right)}{\left|x\right|}=1$ , may $f$ be differentiable at $0$?

Question: Prove or disprove:
Let $f$ be a function that is defined on a neighbourhood of $0$.
Suppose that $\underset{x\rightarrow0}{\lim}\frac{f\left(x\right)}{\left|x\right|}=1$ , then $f$ is not differentiable at $0$
I somehow think its false but couldn't find a counter example. So I tried proving it and this is my prove of it being true:
let us assume by contradiction, that $f$ is differentiable at $0$. thus:
$\underset{x\rightarrow0}{\lim}\frac{f\left(x\right)-f\left(0\right)}{x}=f'\left(0\right)$
Which implies:
$f'\left(0\right)=\underset{x\rightarrow0^+}{\lim}\frac{f\left(x\right)-f\left(0\right)}{x}=\underset{x\rightarrow0^+}{\lim}\underbrace{\left[\frac{f\left(x\right)}{\left|x\right|}-\frac{f\left(0\right)}{\left|x\right|}\right]}$
and:
$f'\left(0\right)=\underset{x\rightarrow0^-}{\lim}\frac{f\left(x\right)-f\left(0\right)}{x}=\underset{x\rightarrow0^-}{\lim}{\left[\frac{f\left(x\right)}{-\left|x\right|}-\frac{f\left(0\right)}{-\left|x\right|}\right]}=\underset{x\rightarrow0^-}{\lim}-\left[\frac{f\left(x\right)}{\left|x\right|}-\frac{f\left(0\right)}{\left|x\right|}\right]=\underbrace{-\underset{x\rightarrow0^+}{\lim}{\left[\frac{f\left(x\right)}{\left|x\right|}-\frac{f\left(0\right)}{\left|x\right|}\right]}}$
They must be equal, thus:
$\underset{x\rightarrow0}{\lim}{\left[\frac{f\left(x\right)}{\left|x\right|}-\frac{f\left(0\right)}{\left|x\right|}\right]}=0$
As we know $\underset{x\rightarrow0}{\lim}\frac{f\left(x\right)}{\left|x\right|}=1$,
then:
$\underset{x\rightarrow0}{\lim}\frac{f\left(0\right)}{\left|x\right|}=1$
which cant be, because if $f(0)=0$, then the limit is $0$, and
if $f(0)\ne0$, the the lim is $\pm\infty$
Which in both cases, doesn't equal $1$,
Contradiction.
.
.
Was there a problem separating to $0\pm$ and change $x$ to $|x|$ without modifying $f(x)$? Or was there any other problem ?
First post, be gentle.
Thank you!
Comment: Wow, thanks Adam. small world I guess.
I wish he didn't paste it as an img, as I could find it myself.
Comment: The two given conditions have no guarantee about the continuity of $f$.  The limit condition only describe $f$ on a deleted neighborhood of $0$.  The first condition on $f$ only says that $f$ is defined on the whole neighborhood including $0$.  As a result, it's possible that $f$ has a removable discontinuity at $0$.
Answer: No. Take $f(x)=|x|$. Then $f$ is not differentiable at 0.
Comment: Downvoted. This doesn't address the question, which is to prove that no such $f$ exists.
Comment: Don't downvote him, I did edit the post 1min later because I forgot the "not". its not his fault.
Comment: Fine, I've removed my downvote.


How to show mySQL BLOB data

Question: Is there a simple way to look at BLOB data that Drupal 7 stores in some tables?
There is a trick to configure phpmyadmin but apparently it's not working with version 22.214.171.124 that comes with MAMP.
Comment: The free version of [Navicat](http://www.navicat.com/en/products/navicat_mysql/mysql_overview.html) lets you view `BLOB` fields as text very easily...I've been using it for many years now and it plays nicely with MAMP
Comment: If only it _was_ JSON there would be a couple of different ways to browse it, but unfortunately it's a serialised PHP object :/ You might get away with doing something like: `dpm(unserialize('DUMP_BLOB_HERE'));` in code but I haven't tried it out
Comment: This [solution](http://stackoverflow.com/a/12141156/686654) worked for me, there are others mentioned there.
Comment: that worked, thanks! Any way of rendering the json krumo style to be able to inspect it better?
Answer: If you need to peek, say into user->data, which is seralised data array, just use drush sqlc to bring yourself to an sql command line, then type:
 select uid, name data from users where uid = <whateveruidyouwant>;

This works for any data, and if you are brave you can even edit the serialized data via command-line but is not recommended unless you know what you are doing.
Answer: I would json_encode the array into a variable and spit it out via devel.
$var = json_encode($yourarray);
dpm($var);

How to show mySQL BLOB data


What is an ADM Template?

Question: In the context of Windows Group Policy, what is an ADM Template?
Answer: They outline registry changes through group policy in a more readable format, in extremely basic terms. Much more information at wikipedia -> http://en.wikipedia.org/wiki/Administrative_Template
Also a how-to for creating your own; http://www.datacrash.net/howtos/howto/create-your-own-adm-templates.html
Answer: An Administrative Template basically adds new options to Group Policy.
For example, we add an ADM Template to allow control over Outlook Settings through Group Policy Editor.

What is an ADM Template?


Java: NullPointerException 2D array of objects even array is initialized and filled

Question: In a method forest() I create a 2D array of objects then I fill it. I am sure that the array is filled because I can display the content of the array in class Forest in method forest() as well as in class Tree in method setTree() as shown below. Unfortunately, I can't get to this content by method showContentOfTree() or elsewhere. An error apears: NullPointerException
The question is why it happens and what I should change?
public class Forest extends JPanel {
    private LoadImage loadImage;
    private Tree[][] tree;

    public forest(){
        setLayout(null);
        loadImage = new LoadImage();
        loadImage.Image();
        Tree[][] tree = new Tree[16][16];
        for (int y = 0; y < 16; y++){
            for (int x = 0; x < 16; x++){
                tree[x][y] = new Tree();
                tree[x][y].setTree(loadImage.loadForest(x,y));
                System.out.println("Tree species " + tree[x][y].treeSpecies);
                //here System displays loaded treeSpecies successfully
            }
        }
        showContentOfTree();
    }
    public void showContentOfTree(){
    for (int y = 0; y < 16; y++){
        for (int x = 0; x < 16; x++){
            System.out.println("Tree species" + tree[x][y].treeSpecies);
                            //here System DOES NOT displays loaded treeSpecies:
                            //Error apears: java.lang.NullPointerException
                            //at Forest.showContentOfTree(Forest.java:31)
        }
    }
}

public class Tree{
    String treeSpecies;
    public void setTree(String treeSpecies){
        this.treeSpecies = treeSpecies;
        System.out.println("Tree species " + treeSpecies);
                //here System also displays loaded treeSpecies successfully
    }
}

Stack trace:
Exception in thread "main" java.lang.NullPointerException at Forest.showContentOfTree(Forest.java:31)
at Forest.<init>(Forest.java:26)
at Okno.<init>(Okno.java:19)

at Glowny.main(Glowny.java:10)
Comment: can you post a stack trace?
Answer: You are shadowing your tree variable in your forest method.
public forest(){
        setLayout(null);
        loadImage = new LoadImage();
        loadImage.Image();
        tree = new Tree[16][16]; //<-- remove Tree[][]

Comment: +1, very good catch, this can almost count as an exam question :), my eyes just skimmed right over it
Comment: you might say he cant see the `forest` for the `tree`s ...I kill me


On the importance of independence in the central limit theorem

Question: While discussing the central limit theorem, my text makes the following remark:

The independence of the random variables $X_1, X_2, \ldots$ is essential. To see this, take $X_1 = X_2 = \ldots = X$ where $X$ is not normally distributed. Then $$\frac{X_1+\ldots+X_n-nE(X)}{\sigma\sqrt{n}}\xrightarrow{\text{in dist.}}X$$

I don't see why would the LHS converge to $X$. Does the quoted passage make sense?
What if we show the significance of independence in the following way: we take $X_1 = X_2 = \ldots = X\sim N(0,1)$ (contrary to the quoted above). Then $$\frac{X_1+\ldots+X_n-nE(X)}{\sigma\sqrt{n}}=\sqrt{n}X$$
and $\sqrt{n}X$ doesn't converge to $X$ in distribution, since $$F_{\sqrt{n}X}(1)=F_{X}(\frac{1}{\sqrt{n}})\xrightarrow{n\to\infty}F_X(0)\neq F_X(1)$$
Does my proof make sense?
What is the best way to demonstrate the importance of independence in the central limit theorem?
Comment: @Did Thank you, sorry, I have no idea what I was thinking.
Answer: I. The quote doesn't make sense to me. First, it should be $X_1 + \dots X_n - n E[X]$, not $X_1 + \dots X_n + n E[X]$. Then
$$\frac{X_1 + \dots X_n - n E[X]}{\sqrt{n}}$$
diverges when $X_1= \dots = X_n = X$. This example shows that if $X_i = X$ then the Central Limit Theorem doesn't hold for $X_i$.
We can also let $X\sim {\cal N}(0,1)$ and let $X_k = (-1)^k X$. Then each $X_k$ is distributed as ${\cal N}(0,1)$. But
$$\frac{X_1 + \dots X_n}{\sqrt{n}} \to 0$$
in distribution.
II. Your proof is correct.


Calculate hash for signature verification in webauthn

Question: I'm trying to implement webauthn, but am having trouble getting the signature verification to work. According to https://w3c.github.io/webauthn/#verifying-assertion I have to basically verify the signature over the following data:
authData || sha256(clientDataJSON)
The authData and the sha256 hash should be "binary concatenated". I have no idea what they mean with that, exactly, but I assume they just mean to stick the bytes next to each other, no idea what exactly would be "binary" about that though.
So, given a PublicKeyCredential named attestation, I can generate the data over which the signature is generated as follows:
var auth_data = new Uint8Array(attestation.response.authenticatorData);
var data_hash = sha256(new Uint8Array(attestation.response.clientDataJSON));
var signed    = new Uint8Array(auth_data.length + data_hash.length);

signed.set(auth_data);
signed.set(data_hash, auth_data.length);

I have of course tried validating this 'signed' value directly, and I have tried hashing it as well. Neither of them validate. What am I doing wrong in calculating the data which is signed?
I have the equivalent code on the server side (in C++) where I build the same value and then verify it with OpenSSL. This signed calculation is only to show what I'm doing - I won't trust that value server-side of course.
Comment: Having the same problem here is a Gist that shows my attempt to do the same as above. Paste the code in the console to run:

https://gist.github.com/philholden/50120652bfe0498958fd5926694ba354
Answer: The signature format authenticatorData || clientDataJSONHash is only for assertion (authentication) signatures, and navigator.credentials.create() returns an attestation (registration) signature. Your code should work for verifying navigator.credentials.get() responses, but not .create() ones.
Attestation signatures are, in general, not signed with the newly created credential private key, but with the authenticator's attestation private key. In addition, the format of the signed data, and the procedure for verifying it, is determined by the attestation statement format. The purpose of this is that already existing hardware might only support generating signatures in a particular way, so these different attestation formats allow those hardware implementations to work with WebAuthn without a hardware or firmware upgrade.
Verifying an attestation signature always requires parsing the CBOR in both the attestation statement and the authenticator data. This is because the signature is delivered in the CBOR-encoded attestation object, and the credential public key is delivered in the authenticator data. Although credential.response.getPublicKey() also returns the same credential public key, this representation of it is not signed. The authenticator data is covered by the signature, so the credential public key must be parsed from the authenticator data for the signature to be meaningful.
If your application does not care about attestation, you can simply not verify the attestation signature and instead only verify future assertion signatures. You can still store the attestation object in case you change your mind and want to care about attestation in the future.
Answer: Assuming, from the link that you posted, that you are trying to create assertion signature. I found this in the documents -
Let signature be the assertion signature of the concatenation authenticatorData || hash using the privateKey of selectedCredential as shown in Figure 4, below. A simple, undelimited concatenation is safe to use here because the authenticator data describes its own length. The hash of the serialized client data (which potentially has a variable length) is always the last element.
look at the image below Point 11
I think the correct way would be to use JSON serialised string of AuthData and append it to Client Data Hash and sign it using the private key. On the server side you can try to recreate the same structure and verify it using the public key.
I don't know about C++ but in python you can use a package called cryptography and verify the signature like this-
>>> public_key.verify(
...     signature,
...     message,
...     padding.PSS(
...         mgf=padding.MGF1(hashes.SHA256()),
...         salt_length=padding.PSS.MAX_LENGTH
...     ),
...     hashes.SHA256()
... )


Ajax Link In A FAPI tableselect Row

Question: I'm trying to add an ajax link to my tableselect rows and replace part of this form with ajax.
$options = array();
foreach ($result as $camp) {
    $options[$camp->uuid] = array(
        'select_link' => array('data' => array(
            '#type' => 'link',
            '#name' => 'select_link',
            '#title' => t('use'),
            '#href' => 'ajax_use_data_callback/nojs/',
            '#attributes' => array(
                'class'=>array(0=>'use-ajax')
            ),
            '#ajax' => array(
                'wrapper' => 'selected-data-div',
                'method' => 'replace',
            ),
        )),

        ...

    );
}

This triggers an alert with a 404 error and the site's default html. How do I tell this ajax link to be handled like a regular ajax form element?
Answer: This can be solved by building a 'select' element with an option for each row id in the tableselect that gets an ajax link. Then we can add links to the tableselect row with '#markup' and use Drupal.behaviors to attach a function that sets the value of the select element and triggers its 'change' event. In the form building function, if $form_state['triggering_element']['#name'] is the new select element, $form_state['triggering_element']['#value'] is the one we want to process.
The select element could then be hidden and the in-row ajax links are still fairly clean. Of course this won't work if javascript is off.
Answer: you must declare hook_menu() for ajax_use_data_callback/nojs/ path
Comment: Can you elaborate on this?
Comment: @monymirza it might as well be an answer. Or at least part of an answer and the rest was so obvious to Rustam he didn't even mentioned it. I'm sure happened to the best of us sometimes.
Comment: This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post - you can always comment on your own posts, and once you have sufficient [reputation](http://drupal.stackexchange.com/help/whats-reputation) you will be able to [comment on any post](http://drupal.stackexchange.com/help/privileges/comment).

Ajax Link In A FAPI tableselect Row


Microsoft MPEG-2 Encoder & MPEG-2 Video Encoder failed at Windows 8

Question: During building record graph to file from video and audio sources using Microsoft MPEG-2 Encoder at Windows 8 ICaptureGraphBuilder2::SetOutputFileName return failed 80040154 result - class not registred.
<code>    //Adding MPEG2 Encoder Muxer filter to the graph
hr = m_pCapGraphBuilder->SetOutputFileName(&CLSID_CMPEG2EncoderDS, szOutFileName, &pMPEG2EncoderMuxer, &pFileSinkFilter);
</code>
Also at graphedit any attempt to insert at graph MPEG-2 Encoder & MPEG-2 Video Encoder filter failed with description:
"The filter could not be created. Resourses used by this filter may alreadey be in use. (Return code: 0xc004f011) "
Why this happen and how to avoid this problem?
Will be happy for any suggestions
Answer: Are you sure your windows 8 has a MPEG-2 encoder? As I heard from MS, they removed MPEG-2 from Windows 8 and you must buy an encoder by yourself.
Comment: 0xC004F011 = SL_E_LICENSE_FILE_NOT_INSTALLED. Maybe if you buy the MediaCenter pack the License is activated and this filter can be used.
Comment: Thank you for answer, but the fact, what filters are listed how directshow filters at official tool and doesn't work, little suprised me.


Suppressing PHPLint's "operator applied to a value of type mixed"

Question: I am currently in a phase of work to 'bullet-proof' my code (its nice to have the time to do it!). I'm using PHPLint which is doing the job admirably, however does anyone know how to suppress the error "operator applied to a value of type mixed". Below is a sample of a function taken from a class:
<code>protected /*.int.*/ function numRows(/*.string.*/ $sql)
{
    /*.int.*/ $num_rows = 0;
    $result = $this->mysqli->query($sql);

    if ($result instanceof mysqli_result)
    {
        $num_rows = $result->num_rows;
        $result->free();
    }
    return $num_rows;
}
</code>
This gives the following ERRORS:
<code>            $num_rows = $result->num_rows;
                                 \_ HERE
</code>
==== DatabaseObject.class.php:103: ERROR: `->' operator applied to a value of type mixed
<code>            $result->free();
                     \_ HERE
</code>
==== DatabaseObject.class.php:104: ERROR: `->' operator applied to a value of type mixed
Answer: I think you can use the cast function to do this. However, it means installing the lint library as part of your main code. This isn't something I've been willing to do.


Analyzing relationships between ordinal and continuous time series data

Question: I have two sets of time series data - roleTrajectories & normalizedDegree. The former data set contains ordinal rankings of subjects' positions within a network at 13 time periods. The latter data set contains subjects' normalized degree centrality at the same 13 time periods. I am trying to determine whether or not subjects' changes in ordinal rank is correlated with changes in their normalized degree centrality.
What is most appropriate approach to analyzing the relationship between the two data sets?
I plan on using R for the analysis; if possible I would be grateful if someone could point me to the right package to use.
Comment: "How do I analyze a relationship" is not usually a question well answered identifying "which test". That only answers a very specific kind of question (and often not a very revealing one). Considering what your questions of interest are, and what a suitable model for the data could be might be a good place to start. Then - if necessary - what tests will answer questions of interest might become clearer.
Answer: Here are some introductory guides on performing time series analysis in R:

Introduction to R's Time Series Facilities
Working with Financial Time Series Data in R

If you're interested in more detailed exploration of the rich variety of R packages, focused on time series analysis, and their functionality, the corresponding CRAN Task View: Time Series Analysis is IMHO the best place to start. Correspondingly, an excellent and one of the most comprehensive R-focused guides on the topic is the "Time Series Analysis with R" by MacLeod, Yu and Mahdi.
If you're interested in forecasting in regard to your time series data, the following free and also R-based online textbook "Forecasting: Principles and practice" by Hyndman and Athanasopoulos could be very helpful: https://www.otexts.org/fpp.
Bonus / Fun fact: The 2003 Nobel Prize in Economics has been awarded to professors Robert Engle and Clive Granger for their work on economic time series analysis (volatility and trends, correspondingly). Research paper, summarizing their work and implications can be found here.


Using RegEx, How to replace multiple occurrences of the same word with grouping and other pattern criteria

Question: I'm trying to replace some specific word in comments in some VB.NET code using a find/replace GREP tool, which itself is using VB.NET regex matching rules.
For the sake of this example, lets say I have this (note that I don't want to change the code itself):
'*** This day is the day of all days
     '*** This day is the day of all days (there are 4 spaces at the start)
    Dim day as integer
    day=day+1

I would like this:
'*** This night is the night of all nights
     '*** This night is the night of all nights (there are 4 spaces at the start)
    Dim day as integer
    day=day+1

My regex is as follows:
(^\s*'.)day(.)
and I'm replacing it with:
$1night$2
This only finds the last occurrence of day, and replaces it with night, so I see this:
'*** this day is the day of all nights
    '*** this day is the day of all nights
    Dim day as integer
    day=day+1

How to replace it so it looks like this:
'*** this night is the night of all nights
    '*** this night is the night of all nights
    Dim day as integer
    day=day+1

Comment: I'm not sure how to solve your problem, but I recommend two things: one is www.regex101.com for testing regexes, and another is this resource on how to exclude certain patterns using regex: http://www.rexegg.com/regex-best-trick.html
Comment: `^\s*'\*{3}.*(?'match'day).*` creates a named capture group called "match" but only matches the results in your comments.
Answer: Using .NET you could use for example:
(?<!\S)(?<!\bDim\s+)day(s)?(?!\S)

Explanation

(?<!\S) Negative lookabehind, assert a whitespace boundary to the left
(?<!\bDim\s+) Negative lookbehind, assert not Dim followed by whitespace chars to the left
day(s)?Match day and capture an optional s char
(?!\S) Assert a whitespace boundary to the right

See a .NET regex demo.
In the replacement use:
night$1

The output will be:
'*** This night is the night of all nights
     '*** This night is the night of all nights (there are 4 spaces at the start)
    Dim day as integer
    day=day+1

Comment: Thank you for your answer. I provided a simplistic example, and your solution, although not exactly what I wanted, helped me figure out what I needed to do. Specifically, I didn't want to include any of the specific code in the regex (in your provided solution, it had 'dim' hard coded into the regex). Using your example and the one from Cary below, I was able to arrive at a solution that was good enough.
Answer: We can make use of the fact that VB .NET supports variable-length lookbehinds, which allows us to replace matches of "day" with "night" for matches of the following regular expression.
(?<='.*)\bday(?=s\b|\b)

Demo
The regular expression can be broken down as follows.
(?<=   begin a positive lookbehind
  '    match a single quote
  .*   match zero or more characters other than line terminators
)      end the positive lookbehind
(?=    begin a positive lookahead
  s\b  match 's' followed by a word boundary
  |    or
  \b   match a word boundary
)      end the positive lookahead

As shown at the link, this matches "day" as indicated below.
'*** This day is the day of all days
          ^^^        ^^^        ^^^
'    *** This day is the day of all days
              ^^^        ^^^        ^^^
Dim day as integer 'so far so good today but maybe not another day
                                                               ^^^
day=day+1   'a daystar is a planet visible in the east before sunrise

All is not wine and roses, however.
text1.Text = "'day"   'No, no, not there!
               ^^^

Comment: Thank you for your answer. I provided a simplistic example, and used the word 'day' which is 'just a word', but you were too smart and found other examples of 'day' that could cause issues. The actual word I will be looking for is longer and very unique, so I don't think I'll run into other cases where it is being used. But it helped me figure out what I needed to do. Using your example and the one from The Fourth Bird above, I was able to arrive at a solution that was good enough for me.
Comment: I am tempted to respond to your last sentence by saying, "that's all that matters", but of course it's not. Whenever you learn something it will help you solve a problem in future or to learn something else (assuming you are not run over by a bus anytime soon).


Amazon like sort box on taxonomy page

Question: I have a taxonomy term page that lists certain nodes. I would like to include custom sort options like the one on amazon's search results page, at the top. It is a drop down with sort options, unlike the usual clicking on a table column. I have searched but found no resources on implementing this in drupal. Any ideas on how I can implement this?
Thx
Answer: The most easy way to get this taken care of is use the Views module. Set up a view that queries for nodes based on the term as an argument. This will give you what you already have, however, it will also allow you to use exposed filters to get more granular with the results based on the values of the exposed fields.
If you would like to learn more about exposed filteds and views, check out this video, which is not the best video in the world, but highlights using exposed filters in Views, which should hopefully get you on the right track.
As a summary, what your doing is replacing Drupal's built in taxonomy view pages with a view instead and allowing views to handle the querying and filtration of the data respectively.
Happy Programming!
Comment: Hmm....I understand the view part, but how do I hook these views up to a drop down list. And is it possible to ajaxify the requests?

Amazon like sort box on taxonomy page


Solving $28^x \equiv 2 \pmod{43}$

Question:
How do we solve $28^x \equiv 2 \pmod{43}$?

I know there are not generally efficient methods for computing the discrete logarithm which are defined for an invertible $a$ modulo $q$ by $$a \equiv t^x \pmod{q}, \quad 0 \leq x \leq q-1,$$ but I was wondering if there was a way to compute it efficiently here.
Comment: Sorry, did you want a general algorithm or something that works just for this problem, where works is defined as a human can do it easily?
Comment: I don't think so, the order of $28$ is $42$ and the order of $2$ is $21$. So it could really be any even number, and I think each one is as good a guess as any other.
Comment: @Hwai-RayTung A way a human can do it easily.
Comment: @CarryonSmiling The set of all such $x$ can be determined to be $x \equiv 39 \pmod{42}$.
Comment: @JohnRyan I meant every guess is as good as any other before knowing the actual number.
Answer: We try to make $\,2\equiv 45\equiv \color{#c00}5\cdot \color{#0a0}3^2\,$ using factors of $\,3\,$ and $\,5\,$ from small powers of $\,28.\,$
$\qquad\qquad  28^3\equiv 22\equiv -\color{#0a0}3\cdot 7$
$\qquad\qquad  \color{#c00}{28^5}\equiv \color{#c00}5$
$\qquad\qquad 28^7\equiv 7$
So we have $\,\color{#c00}5\,$ and we can make  $\ {-}\color{#0a0}3\equiv 28^3/28^7\equiv \color{#0a0}{28^{-4}}$
Therefore $\ 2\equiv \color{#c00}5\cdot (\color{#0a0}{-3})^2 \equiv  \color{#c00}{28^5}(\color{#0a0}{28^{-4}})^2\equiv 28^{-3}\equiv 28^{39},\ $ by $\,28^{42}\equiv 1\,$ by Fermat.
Comment: @Zack Many algorithms in number theory use this idea. You pick a "basis" of small primes, then you do linear algebra on the exponent vectors of these primes to find a solution once you have enough relations.
Comment: It should also be noted that the order of $28$ modulo $43$ is $42$.
Comment: @JohnRyan But we don't need that above.
Comment: How then can you say this is the set of all possible solutions?
Comment: @JohnRyan If you need all solutions then yes, you could use that
Comment: Your algorithm is excellent but how to generalise it  I mean how to find some other discrete logarithm, such as $28^x \equiv 30 \pmod {42}$.
Comment: This is very nice.
Comment: Yes, this is good. The method is known as [index calculus](https://en.wikipedia.org/wiki/Index_calculus_algorithm), and is one of the techniques in working out discrete log problems. It works equally well in some other finite fields. For example in $\Bbb{F}_2[x]/(p(x))$ you use irreducible low degree polynomials the same way as selected small primes were used here.
Answer: Some enumerating is inevitable:
Notice that
$28^7 \equiv 7 \pmod{43}$
$28^4 \equiv 14 \pmod{43}$
Let $x = 4k+7w$ since Bézout's theorem
Now $28^x \equiv 28^{4k+7w} \equiv  2 ^k 7^{k+w} \equiv 2 \pmod{43}$
$\implies k \equiv 1 \pmod {42}$ and $k+w \equiv 0 \pmod {42}$
$ \implies k \equiv 1 \pmod {42}$ and $w \equiv -1 \equiv 41 \pmod {42}$
$\implies x \equiv 39 \pmod{42}$
EDIT: Why do I come up with such idea?
Firstly, I write a program running all the logarithm with base $28$. Here is my program written in C plus plus:
int u = 1;
for(int i = 1;i<=42;++i)
{
        u*= 28;
        u%=43;
        printf("%d ",u);
}

All the related discrete logarithm  listed here (i.e. the output of my program):
28 10 22 14 5 11 7 24 27 25 12 35 34 6 39 17 3 41 30 23 42 15 33 21 29 38 32 36 19 16 18 31 8 9 37 4 26 40 2 13 20 1

And notice that $28 = 2 \times 7$, so I will try to find the position the least number which can be decomposed into $2$ or $7$ or spontaneous.
And I ascertain that position $7$ and $4$ satisfying the condition.
Answer: We move from $28$ to $5$ to facilitate calculations (btw, both numbers are primitive roots modulo $43$). One has $5^{17}=28$ so we have to solve the equivalent equation $$5^{17x}\equiv 2\pmod{43}$$ Calculating first $$5^w\equiv 2\pmod{43}$$ we find $w=33$ hence $$5^{17x}=5^{33}\Rightarrow  5^{17x}=5^{33}\cdot 5^{42y}\space  (\text{ Fermat's little theorem })$$
We have then the diophantine equation $$17x-42y=33$$ whose general solution is $$(x,y)=(42n+39,17n+15)$$ For $n=0$ one has the answer $\color{red}{x=39}$

Solving $28^x \equiv 2 \pmod{43}$


Read data from Firebase in Swift

Question: This is what my JSON file in FireBase looks like:

I am trying to look in Firebase tutorial in Firebase Web but it dosent work for me:
Comment: Best not to post code as an image and instead paste it into stack overflow.
Comment: Yes, this way one can easily tweak the code and I don't have to write complete method again. And will be able to provide you complete answer with context.
Answer: You have to dig one more level to get the properties you want. Your current dictionary is holding values under persons tree.
<code>(value["Manny"] as? [String:Any])?["Name"] as? String
</code>
Comment: Hi,ive tried to do whats you ask for and dig one more level in JSON but its not help, now i have Persons->Names->["A","B","C"].... and my code is et refe = Database.database().reference().root.child("Persons").child("Names")
        refe.observeSingleEvent(of: .value, with: { (snapshot) in
            // Get user value
            let value = snapshot.value
            print (value)
            // ...
        }) { (error) in
            print(error.localizedDescription)
        }
Comment: What output you are getting in this case??
Answer: <code>let value = snapshot.value as? [String : AnyObject] ?? [:]
                for (_,profile) in value {

          let name = profile["Name"] as? [String : AnyObject] ?? [:]

    }
</code>

Read data from Firebase in Swift


Php that generates XML

Question: <?php

require("phpsqlajax_dbinfo.php");
$dom  = new DOMDocument("1.0");
$dp   = fopen('samp.xml', 'w');
$node = $dom->createElement("Groceries");
fwrite($dp, '$node');
$parnode = $dom->appendChild($node);

$connection = mysql_connect($host, $user, $pass);
if (!$connection) {
    die('Not connected : ' . mysql_error());
}

$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
    die ('Can\'t use db : ' . mysql_error());
}

$query  = "SELECT * FROM tbl_groceryitem";
$result = mysql_query($query);
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

echo "<groceries>";
while ($row = @mysql_fetch_assoc($result)) {

    $node = $dom->createElement("item");
    echo "<echo>";
    fwrite($dp, '$node');
    $newnode = $parnode->appendChild($node);
    $newnode->setAttribute("auto_id", $row['auto_id']);
    echo "<auto_id>", $row[auto_id];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_barcode", $row['Gro_barcode']);
    echo "<Gro_barcode>", $row[Gro_barcode];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_name", $row['Gro_name']);
    echo "<Gro_name>", $row[Gro_name];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_brand", $row['Gro_brand']);
    echo "<Gro_brand>", $row[Gro_brand];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_category", $row['Gro_category']);
    echo "<Gro_category>", $row[Gro_category];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_aisle", $row['Gro_aisle']);
    echo "<Gro_category>", $row[Gro_aisle];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_qty", $row['Gro_qty']);
    echo "<Gro_qty>", $row[Gro_qty];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_netwt", $row['Gro_netwt']);
    echo "<Gro_netwt>", $row[Gro_netwt];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_pic", $row['Gro_pic']);
    echo "<Gro_pic>", $row[Gro_pic];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_price", $row['Gro_price']);
    echo "<Gro_price>", $row[Gro_price];
    fwrite($dp, '$newnode');
    $newnode->setAttribute("Gro_tax", $row['Gro_tax']);
    echo "<Gro_tax>", $row[Gro_tax];
    fwrite($dp, '$newnode');
    echo "</item>";
    fwrite($dp, '</item>');
}
fwrite($dp, '</groceries');
echo $dom->saveXML($xml);

?>

I'm new in php.
I'm creating a php file that can generate xml file with data from myPHPAdmin. Thanks :D. Hope someone can help me.
At first try, the code has been displayed in php and when I open to check for the created XML. the display was '$node', it reflects the exact string a place inside fwrite, when I try to delete the string quote ('') like this  fwrite($dp,$node);. I got error.
And when I try to return the code to  fwrite($dp,'$node');. There was no Display. the XML page is blank.
Comment: OMG, first let me welcome you to the community. Please **note** You do not need to upload all of your code on a question. Please only post that code, that is relevant to the question. Otherwise, we will not be interested on answering them.
Comment: Does phpMyAdmin not allow you to download XML-formatted data directly anyway?
Comment: Why are you using DOM to create a new XML File and also opening an XML file to write. Check my answer for the write way
Comment: first, I think you want to load data from MySQL, instead of from phpMyAdmin. phpMyAdmin is just a web interface of MySQL client. You can also use simple save contents to a variable to generate XML instead of using `DOMDocument` (write the contents of the variables to file at the end).
Comment: Thank you for all the comments and welcome. I have come out with a new set of code. It's better than the other one, the problem now is, error : Extra content at the end of the document.
Comment: My prob is I cant let field from phpmyadmin database appear. Is there a problem in my code?
Comment: '
while ($row = @mysql_fetch_assoc($result)){

  $url = $objDom->createElement("item");
  $root->appendChild($url);'

is there any problem in my code?. i try to use while to display all info in my field. but, still error displays. Thank You.....
Answer: You need to use XML headers when you are creating a XML file with PHP.
<?xml version="1.0" encoding="utf-8"?>

But this is not needed when you are using saveXML() on the end.
Here is an example, picked out from php's manual.
<?php

$doc = new DOMDocument('1.0');
// we want a nice output
$doc->formatOutput = true;

$root = $doc->createElement('book');
$root = $doc->appendChild($root);

$title = $doc->createElement('title');
$title = $root->appendChild($title);

$text = $doc->createTextNode('This is the title');
$text = $title->appendChild($text);

echo "Saving all the document:\n";
echo $doc->saveXML() . "\n";

echo "Saving only the title part:\n";
echo $doc->saveXML($title);
?>

Php that generates XML


Extracting required names from a given format

Question: I have a  text file containing data as shown below. I have to extract some required names from it. I am trying the below code but not getting the required results.
The file contains data as below:
Leader :     Tim Lee ; 34567
Head\Organiser: Sam Mathews; 11:53 am
Head: Alica Mills; 45612
Head\Secretary: Maya Hill; #53190
Captain- Jocey David # 45123
Vice Captain:- Jacob Green;  -65432

The code which I am trying:
import re
pattern = re.compile(r'(Leader|Head\\Organiser|Captain|Vice Captain).*(\w+)',re.I)
matches=pattern.findall(line)
for match in matches:
    print(match)

Expected Output:
Tim Lee
Sam Mathews
Jocey David
Jacob Green

Answer: import re
line = '''
Leader :     Tim Lee ; 34567
Head\Organiser: Sam Mathews; 11:53 am
Head: Alica Mills; 45612
Head\Secretary: Maya Hill; #53190
Captain- Jocey David # 45123
Vice Captain:- Jacob Green;  -65432'''
pattern = re.compile(r'(?:Leader|Head(?:\\Organiser|\\Secretary)?|Captain|Vice Captain)\W+(\w+(?:\s+\w+)?)',re.I)
matches=pattern.findall(line)
for match in matches:
    print(match)

Explanation:
(?:                 : start non capture group
  Leader            : literally
 |                  : OR
  Head              : literally
  (?:               : start non capture group
    \\Organiser     : literally
   |                : OR
    \\Secretary     : literally
  )?                ! end group, optional
 |                  : OR
  Captain           : literally
 |                  : OR
  Vice Captain      : literally
)                   : end group
\W+                 : 1 or more non word character
(                   : start group 1
  \w+               : 1 or more word char
  (?:               : non capture group
    \s+             : 1 or more spaces
    \w+             : 1 or more word char
  )?                : end group, optional
)                   : end group 1

Result for given example:
Tim Lee
Sam Mathews
Alica Mills
Maya Hill
Jocey David
Jacob Green

Comment: Thank you so much. Actually, in the second line, it could be just Head: Sam Mathews; 11:53 am, no 'Organiser', so this code may not work as we are using \W+, is there a way to solve it?
Comment: Sorry for adding some requirements later
Comment: can you please solve my this question:
https://stackoverflow.com/questions/51887141/unable-to-extract-date-of-birth-from-a-given-format
Comment: This is perfect solution to  my question:
pattern = re.compile(r'(?:Leader|Head(?:\\\w+)?|Captain|Vice Captain)\W+(\w+(?:\s+\w+))',re.I)
Answer: Given:
s='''\
Leader :     Tim Lee ; 34567
Head\Organiser: Sam Mathews; 11:53 am
Head: Alica Mills; 45612
Head\Secretary: Maya Hill; #53190
Captain- Jocey David # 45123
Vice Captain:- Jacob Green;  -65432'''

You can get the names like so:
>>> [e.rstrip() for e in re.findall(r'[:-]+[ \t]+(.*?)[;#]',s)]
['Tim Lee', 'Sam Mathews', 'Alica Mills', 'Maya Hill', 'Jocey David', 'Jacob Green']

Or, create a dict of the titles and associated names:
>>> {k:v.rstrip() for k,v in re.findall(r'^\s*(Leader|Head\\Organiser|Head|Head\\Secretary|Captain|Vice Captain)\s*[:-]+[ \t]+(.*?)[;#]',s, re.M)}
{'Leader': 'Tim Lee', 'Head\\Organiser': 'Sam Mathews', 'Head': 'Alica Mills', 'Head\\Secretary': 'Maya Hill', 'Captain': 'Jocey David', 'Vice Captain': 'Jacob Green'}

Which then can be restricted to the titles desired:
>>> {k:v.rstrip() for k,v in re.findall(r'^\s*(Leader|Head\\Organiser|Captain|Vice Captain)\s*[:-]+[ \t]+(.*?)[;#]',s, re.M)}
{'Leader': 'Tim Lee', 'Head\\Organiser': 'Sam Mathews', 'Captain': 'Jocey David', 'Vice Captain': 'Jacob Green'}

And if you just want the names (Python 3.6+ maintains the order, so they will be in string order):
>>> {k:v.rstrip() for k,v in re.findall(r'^\s*(Leader|Head\\Organiser|Captain|Vice Captain)\s*[:-]+[ \t]+(.*?)[;#]',s, re.M)}.values()
dict_values(['Tim Lee', 'Sam Mathews', 'Jocey David', 'Jacob Green'])

Demo and explanation of regex
Comment: Thank you. Yes, it is helpful.


how to bound recurrence?

Question: I am writing a simple library using recursive data structures like BST. How do I bound recursive functions like search, insert or postorder print in an elegant manner.
void print_postorder(BST_NODE* node)
{
     if (node == NULL)
        return;

     print_postorder(node->left);
     print_postorder(node->right);

     cout<<node->key<<endl;
}

Comment: @Misery Recursive functions on recursive data are implicitly bound by the data. If you need an explicit boundary, see the answer below.
Comment: Does your function not work?
Comment: What functionality do you expect when you bound a recursive function?  How is it different from what you've written?
Comment: My interpretation of the question is that you are trying to [map a function to your data structure](https://en.wikipedia.org/wiki/Map_(higher-order_function)). That is, instead of printing each node, you would like to execute an arbitrary function on each node recursively. Is this correct?
Comment: Do you mean "How to print it with indentation reflecting your tree structure instead of printing a 'flat' column of keys?"
Comment: @FrançoisAndrieux My function works. However the requirement for this library is no unbounded recurrence. There is nothing about mapping function recursively. That is a simple lib without such tricks.
Comment: What do you expect it to do when it reaches the limit? Give up with an error? Skip part of the work? Switch to a different algorithm?
Answer: If I understand correctly, you want to limit the depth of your call stack (say, only allow for N recursive calls).
The easiest way to do this would be to simply pass the current depth of your call stack as a const parameter.
Your code would become:
void print_postorder(BST_NODE* node, const unsigned int call_depth)
{
     if (node == NULL || call_depth > SOME_THRESHOLD)
        return;

     print_postorder(node->left, call_depth + 1);
     print_postorder(node->right, call_depth + 1);

     cout<<node->key<<endl;
}

Note that SOME_THRESHOLD must have a value. You can hardcode it in the function (bad) or define it as a static constant (better).
Your first call would go from being print_postorder(node) to print_postorder(node, 0).
Comment: Hmmm... that's another way to see it. Let's see if whoever asked comments my answer to see if it helped.

how to bound recurrence?


What is a single powerplay in ice hockey?

Question: This is a question only about the statistical representation of power plays.
When looking at team statistics (example), there are numbers that describe teams efficiency in power plays and penalty killing.
In the linked example Denmark had an advantage 29 times and scored 10 goals thus having 34.48% powerplay efficiency. But how do they get the "29"? It is clearly not the amount of penalties as in the penalty killing table Canada has had 29 disadvantages while actually having earned 35 penalties.
It is obvious that a 5-man team playing 2 minutes against team that has one player sent off on a minor penalty is a powerplay, but I am concerned about some trickier cases:

Player a (team X) is sent off for 2 minutes. After 1:50 (game time) player b (team X) is sent off. After 1:50 (game time) player c (team X) is sent off etc. Does this all counts as a single disadvantage situation? Can a team play 4v5 for 50 minutes and have only one penalty killed?
Player a (team X) is sent off for 5 minutes. A minute later player b (team Y) is sent off for 2 minutes. Does team X get two disadvantage situations based on a single penalty? It would seem wrong that you have more powerplays just because a 5 minute penalty was split in half by a minor penalty on the opposing team.

Edit
As this question is pretty much a duplicate, I will specify that I am interested to find the interpretation that is used by IIHF as in the linked example. The IIHF rulebook defines some of the statistics, but does not define this one.
I initially asked without specifying IIHF rules because I expected that there would be a common and accepted understanding of the statistic.
I was aware of the NCAA rulebook, I just don't really believe that IIHF tournaments and different national leagues follow the NCAA definitions and there should be either the accepted or at least the IIHF definition of counting advantageous/disadvantageous situations.
Comment: Seems a better, more straightforward metric would indeed just be goals per 2 minutes of 1 man advantage power play time.  If sabermetrics type work has gotten into hockey, I'd be quite convinced they'd be using data like that rather than the quirky nature of the given statistic :-/
Answer: You are considered on a power play when you have the advantage of one player for any time during a game.  Whether it is 1 second, 10 seconds, or 2-full minutes, it does not matter.  So to get back to your example, where Denmark is 10 out of 29 on the power play.  This means they scored 10 goals while the other team had less players than they did on the ice.  6 on 5 does not count as a power play though.
Also, you can earn a penalty but not be considered on a power play.  For example, you can get a major penalty where you fight against an opponent.  Both players will get a penalty in this case and no man-advantage will occur.  Still counts as a penalty.  Two players from each opposition could get minors and the play would go 4-on-4 for two minutes.  In this case, there would not be a power play opportunity.
And no you would not get two power plays because of the split time on power play.  A five minute would typically be because of "Boarding" or "Illegal check".  This would only be counted as one power play.
So the wrap it up, a power play is when you have a man-advantage for any given amount of time during a game.  The NCAA statistics rules define "Teams are on a power play when they have at least a one-player advantage on the ice for any amount of time." (section 8).
Comment: Unfourtunaly, the IIHF rulebook does not define these details. I will try to contact some IIHF officials in hope for an authorative answer.
Comment: Thanks. So what exactly should be counted in the two tricky cases I mentioned? If the "Illegal check" 5 min major is interrupted by 2 minutes of 4-on-4 is it counted as two powerplays or one? And does chained powerplays count as one?
Comment: A major penalty interrupted would be counted as one power play I believe.  This is a tricky case and a rule book or an official would be able to answer that.  Chained power plays count for the number of penalties taken.  The first penalty is a power play as long as it is 5 on 4 for any amount of time.  Then, the second penalty is taken at 1:50 of the first penalty which makes it 5-3 for 10 seconds but 5-4 for the rest of the penalty.  That counts as another power play.  Does that make sense?


window-function to get top rank is not working as properly giving duplicate records

Question: I am using spark-sql-2.4.1v in my project.
To get a unique companies for given time range I am using spark window-function with rank.
But for the same date for the same company id , it is ranking two records as top 1 record.
I am using below code snippet to find unique i.e. rank-1 records.
val ws = Window.partitionBy("company_id").orderBy(desc("created_date"))

val rankDs =  sourceDs.withColumn("rank",rank().over(ws))
                                      .where($"rank".===(lit(1)))
                                      .select("*")

The results it shows is
+-------------+-----------+----+
| created_date| company_id|rank|
+-------------+-----------+----+
|   2018-02-01|   17869354|   1|
|   2018-02-01|   17869354|   1|
|   2018-02-01|   41248792|   1|
|   2018-02-01|   41248792|   1|
|   2018-02-01|   86947653|   1|
|   2018-02-01|   86947653|   1|
--------------------------------

As show above it is giving duplicate records for few source records, so what is wrong here , how to fix this i.e. only give rank-1 records without duplicates ?
Expected Result :
+-------------+-----------+----+
| created_date| company_id|rank|
+-------------+-----------+----+
|   2018-02-01|   17869354|   1|
|   2018-02-01|   41248792|   1|
|   2018-02-01|   86947653|   1|
--------------------------------

Comment: Please include your expected output.
Answer: Instead of rank use row_number() window function to get the unique records without duplicates.
val ws = Window.partitionBy("company_id").orderBy(desc("created_date"))

val rankDs =  sourceDs.withColumn("row_number",row_number().over(ws))
                                      .where($"row_number".===(lit(1)))
                                      .select("*")
//result
//+------------+----------+---+----------+
//|created_date|company_id| no|row_number|
//+------------+----------+---+----------+
//|  2018-02-01|  86947653|  1|         1|
//|  2018-02-01|  41248792|  1|         1|
//|  2018-02-01|  17869354|  1|         1|
//+------------+----------+---+----------+

Comment: any advice how to solve this in spark ... https://stackoverflow.com/questions/62933135/dataframe-look-up-and-optimization


Understanding an Outer Automorphism of $S_6$

Question: In an article (paper), there is a description of an outer automorphism of $S_6$. There are six pentagons, arranged with a rule, with vertices $1,2,3,4,5$. Any permutation of these vertices will permute the six pentagons, hence giving a map (homomorphism) from $S_5$ into $S_6$.
I understood this map as follows: if we interchange the vertices, the pentagons will be permuted. Consider permutation $(2 \,3)$, and its effect on the first pentagone a in the note.
(1) In a, vertices $2,3$ are not joined by a "continuous edge", hence after permuting $2,3$ there should not be continuous edge between $2,3$. Hence image of a after this permutation will be either a,d or f (am I correct?). Also, 5 is joined to both $2,3$ before permutation, hence after permuting $2,3$, vertex $5$ should be adjcent to them. We can conclude that a is mapped to a by permutation $(2\,3)$.
(2) The other way, in a, $2,3$ are not joined by continuous edge before permutation $(2\,3)$. Hence after permuting $2,3$, a  would be mapped into
either a,d or f. Also, $4$ is joined to $2$ but not $3$ before permuting $2,3$; after permuting $2,3$, the vertex $4$ will be  joined to $3$ but not $2$; hence image of a by permutation $(2\,3)$ should be d.
I couldn't find my mistake in understanding, if any.
Can one explain the action of $S_5$ on the six pentagons in the article?
Comment: You've omitted an essential fact without which this is incomprehensible.  The point is that there are six ways to 2-color the vertices.  Without that, I don't see where your six pentagons come from.
Answer: The crucial part you missed is "(up to choices of colors)" (in the third line of the section). If you distinguish between colours, there are twice as many pentagons. Applying $(23)$ to a yields e with colours swapped.
Comment: @jorki: OK; means, given a (ordered) 5-cycle on vertices $\{1,2,3,4,5\}$, there is **unique pentagon** containing the 5-cycle. By permutation of vertices, these 5 cycles (and hence the pentagons) will be permuted; this will be the map (homomorphism) from $S_5$ to $S_6$; am I correct?
Comment: @user28017: Yes, correct!


How can I generate random number in specific range in Android?

Question: I want to generate random number in a specific range. (Ex. Range Between 65 to 80)
I try as per below code, but it is not very use full. It also returns the value greater then max. value(greater then 80).
Random r = new Random();
int i1 = (r.nextInt(80) + 65);

How can I generate random number between a range?
Comment: With [Kotlin](https://stackoverflow.com/a/45687695/8583692) you can do this: `val r = (0..10).random()`
Comment: You can write `val randomNumber = (min..max).random()` where `min` and `max` are the edges of the specified range. Refer [Kotlin – Generate a Random Number in specific Range](https://kotlinandroid.org/kotlin/kotlin-generate-a-random-number-in-specific-range/)
Answer: Random r = new Random();
int i1 = r.nextInt(80 - 65) + 65;

This gives a random integer between 65 (inclusive) and 80 (exclusive), one of 65,66,...,78,79.
Comment: I've been writing Java in one way or another for about 8 years and I still copy and paste this code whenever I need it, cheers
Comment: If you need a negative number, use this and multiply by -1. You need a float, I think.
Comment: it won't work for negative numbers
Comment: simpler as possible: int myRandomInt = new Random().nextInt(80 - 65) + 65;
Comment: @Sirens: He could even generate two more numbers, then count differente between them (it can be negative or positive number ;)), and finaly multiply the original random number ;)
Comment: @TomeeNS that would weaken the randomness .. these arent actual random numbers, dont forget.
Comment: this is just pseudo-random!
Answer: int min = 65;
int max = 80;

Random r = new Random();
int i1 = r.nextInt(max - min + 1) + min;

Note that nextInt(int max) returns an int between 0 inclusive and max exclusive. Hence the +1.


Calculate variable String(010) with integer(1) where outcome is string(011)

Question: The user can insert an random string that can only contains numbers.
But it must been possible to calculate it with an integer.
the problem is the user insert a string like 010 + integer(1) it would result in 11;
but i want to return a string 011
But the user can also enter numbers like 001, 0001, etc
What is the best approach here? I have try to use
String.format("%05d", yournumber); but i does not work with variable strings

I also came across
String str = "abcd1234";
String[] part = str.split("(?<=\\D)(?=\\d)");
System.out.println(part[0]);
System.out.println(part[1]);

If i use it like this i got a new problem.
how to split the number in a right way.
Any idea what i'm missing
Comment: is the string binary?
Comment: How about cutting leading zeros ?
Comment: Sounds logic but can you give an example as answer. I'm Still fairly new to programming.
Comment: how you are taking the input? are you using `nextLine()` o?
Comment: the user can insert the input into a textbox where i check if it only contains numbers.
Answer: Considering you are handling Integer number (not binary )
Try something like this:
String input ="001";//your user input
    /**
     * your check here if input is a  number
     */
    int len=input.length();
    int inputInteger=Integer.parseInt(input);
    inputInteger+=1;

    String output=String.format("%0"+len+"d", inputInteger);
    System.out.println(output);

Comment: great to know it helped , happy coding @user3475722


Subsets - Problem with understanding

Question: If I have two sets $A=\{2\}$ and $B=\{2\}$, can I say that $A$ is a subset of $B$ and vice versa? I am coding in event $B$ and I need to check that $A \nsubseteq B$
Comment: yes. and the other way around. no "proper" subset though.
Comment: @user1552404 yes; for sets, "equals" implies "is a subset of." So A ⊈ B is false.
Comment: They look like the same set to me; care to explain your notation?
Comment: what does $\left\{2\right]$ mean? never seen this notation. if it's a typo then obviously $A=B$.
Comment: Ye they are the same set but I am wondering can I call A a subset of B
Comment: A = {2} donates that A consists of the set 2, anything inside the brackets belongs to the set
Answer: Every element of $A$ is an element of $B$. Therefore $A\subseteq B$.  And every element of $B$ is an element of $A$, so $B\subseteq A$.
The subset relation is a weak inequality, like "less than or equals".  That's why many of us prefer to avoid the symbol "$\subset$", and use "$\subseteq$" instead - both symbols have the same meaning, but the first can be a little confusing.

It's also worth noting that $\subseteq $ is a partial ordering relationship:

Reflexivity holds because $A\subseteq A$.
Transitivity holds since if $A\subseteq B$ and $B\subseteq C$, then $A\subseteq C$.
And antisymmetry holds since if $A\subseteq B$ and $B\subseteq A$, it must be the case that $A=B$.

Furthermore, in many universes (power sets for example), we get a lattice structure: The join (least upper bound) of $A$ and $B$ is just $A\cup B$, and the meet (greatest lower bound) is $A\cap B$. It is not for nothing that the symbols usually used for lattice operations ($\leq,\vee,\wedge$) so closely echo those used for set operations ($\subseteq,\cup,\cap$).

Subsets - Problem with understanding


In the Restricted Boltzmann Machine's free energy function, how can it be simplified to only be a function of v?

Question: I realize this is a copy of this question: How to compute the free energy of a RBM given its energy? however I am unable to comment on the best answer to ask that person to elaborate.
We start with:
$$
F(v) = -b^Tv - log\sum_{h} \prod_{j=1}^{M} e^{c_jh_j + v^TW_jh_j}
$$
In this tutorial http://deeplearning.net/tutorial/rbm.html it simplifies to:
$$
F(v) = -b^Tv - \sum_{j=1}^{M}log\sum_{h_j}e^{c_jh_j + v^TW_jh_j}
$$
And we end up with:
$$
F(v) = -b^Tv - \sum_{j=1}^{M}log(1 + e^{c_j + v^TW_j})
$$
In the first step, what are the prerequisites I need to know to understand why the product can be moved outside the sum?
In the second step, where does the 1 come from? Where does the $ h_j $ go?
Answer: Answering my own question since I figured it out.
First, it helps if you write down the full h.
In simpler terms and only displaying the relevant part:
$$ \sum_{h=\{0, 1\}^M} \prod_{j=1}^M e^{q_jh_j} $$
Suppose we have M=2, h takes in the values {(0, 0), (0, 1), (1, 0), (1, 1)} so then this would be:
$$ e^{q_0 0}e^{q_1 0} + e^{q_0 0}e^{q_1 1} + e^{q_0 1}e^{q_1 0} + e^{q_0 1}e^{q_1 1} $$
Which can be factored into:
$$ (e^{q_0 0} + e^{q_0 1})(e^{q_1 0} + e^{q_1 1}) $$
And this works in general, i.e.:
$$ \sum_{h=\{1,..,K\}^M} \prod_{j=1}^M f_j(h_j) = \prod_{j=1}^M \sum_{h_j=\{1,..,K\}} f_j(h_j) $$
So in the original equation we would get:
$$ F(v) = -b^Tv - log \prod_{j=1}^M \sum_{h_j=\{0,1\}} e^{(c_j + v^TW_j)h_j} $$
$$ F(v) = -b^Tv - \sum_{j=1}^M log \sum_{h_j=\{0,1\}} e^{(c_j + v^TW_j)h_j} $$
$$ F(v) = -b^Tv - \sum_{j=1}^M log (e^{(c_j + v^TW_j)0} + e^{(c_j + v^TW_j)1})$$
$$ F(v) = -b^Tv - \sum_{j=1}^M log (1 + e^{c_j + v^TW_j})$$


Easy and universal way to get filename shared with ACTION_SEND

Question: I'm receiving intents sent with default share mechanism (ACTION_SEND) from different applications.
If it is a file – I need to copy it.
I don't need a full path to file since I can open it directly with a stream.
InputStream input = getContentResolver().openInputStream(fileUri);

But I need to know a filename to save file properly.
Is there any easy and universal way to get a filename of the shared file not paying attention to the content type (it can be image from gallery, video, files from downloads)?

Or should I use something like this to get the full path from the uri and then get filename from it?
Get real path from URI, Android KitKat new storage access framework [duplicate]
Android Gallery on KitKat returns different Uri for Intent.ACTION_GET_CONTENT

Also I saw this article (A Uri Is Not (Necessarily) a File) and there is said:

You can perform the following operations on such Uri values:

Find out their DISPLAY_NAME and SIZE — the OpenableColumns — via a query() on the Uri (again, using a ContentResolver, or in theory a
CursorLoader)

Is it possible? How can I do that?
Answer: According to the MediaStore interface the DISPLAY_NAME column is indeed delivered.
Cursor cursor = getContentResolver().query(fileUri, projection, null, null, null);

projection contains DISPLAY_NAME
cursor.moveToFirst();
if (cursor.getCount() > 0) {
    // get your file name
}

I have not tested it but it should work ;-)


AR With Printed Buttons

Question: I made an AR Application that detects the printed marker & plays the video on it.
I'd like to have a button printed on paper, which triggers an event when its blocked by a finger.
IMAGE LINK: http://tinypic.com/view.php?pic=23le2h2&s=7
The application development is to have an AR Quiz that works with simple printed paper & Webcam only. What is the best solution to have the button event triggered by hiding the marker?
Operating System: Windows PC
Framework: FLARManager
Answer: You just need to listen when and what combination of markers is active and make if statments like:
<code>private function onEnterFrame (evt:Event) :void
{
  if (this.activeMarker_1 && this.activeMarker_2)
  {
     trace("no button is being pressed");
  }
  else if (this.activeMarker_1 && this.activeMarker_2 == null)
  {
      trace("answer: no");
  }
  else if (this.activeMarker_1 == null && this.activeMarker_2)
  {
      trace("answer: yes");
  }
  else if (this.activeMarker_1 == null && this.activeMarker_2 == null)
  {
      trace("both buttons are being pressed");
  }
}
</code>

AR With Printed Buttons


Normal quadric surfaces in $\mathbb{P}^3$

Question:
I'm trying to prove that the quadric surfaces $Q_1:xy-zw=0$ and $Q_2:z^2-xy=0$ are normal (exercise 3.17(b) from Hartshorne's Algebraic Geometry).

According to the exercise, $Y$ is normal when $\mathcal{O}_P$ is integrally closed for all $P\in Y$. I have a feeling that using the definition directly is not a good plan,now I'm stuck because I can't think of anything else.
Comment: If you are working over a field where the Jacobian criterion works, I believe it is the simplest way to show the normality. For a hypersurface, it is normal iff codim (to the hypersurface) of the Jacobian is at least 2.
Comment: I see. What you can do and now I think it is better for your example is checking the affine charts of $Q_1$ and $Q_2$. I believe, except for one chart for $Q_2$ everything is a polynomial ring. The chart on $D(z)$ for $Q_2$ is isomorphic to k[t, 1/t] which is a UFD so normal.
Comment: The example of the cone is done on p. $124$ ($\S5.1$) of Shafarevich's *Basic Algebraic Geometry Vol. 1* just using basic properties of integrality.  The answer [here](https://math.stackexchange.com/questions/2408031/why-is-mathbbcx-y-y2-x3-1-normal/2408078#2408078) gives more or less the same argument.  There is also a shorter answer using a bit more machinery [here](https://math.stackexchange.com/questions/1526820/example-of-a-normal-variety-or-scheme-which-is-not-locally-factorial).
Comment: @Youngsu, in section $3$ he hasn't mentioned jacobian criterion.
Comment: I think he may want you to do some unpleasant equation hacking at this stage in the text...
Comment: Here is an overkilled argument : they are toric varieties and the cones $\sigma_1, \sigma_2$ corresponding $to Q_1$ and $Q_2$ are strongly convex and rational, so $Q_1,Q_2$ are normal. In fact I'm even sure that it would be possible to translate it to a nice argument without refering to toric geometry, it would be a nice computation.
Comment: @youngsu can you please explain why the chart on D(w) for $ Q_2 $ is a polynomial ring?
Comment: @sss89 $Q_2$ does not have a $D(w)$ chart. I'd be nice if you can clarify this and let me know what you are getting for the chart you are asking.
Comment: @yongsu $ Q_2 $ is embedded in $ \mathbb{P}^3 $ where the coordinates are $ x,y,z,w $
Comment: @sss89: You are right. $D(w)$ is not a polynomial ring. I do not think my approach works for $Q_2$ as it has a singularity.
Answer: Using the hint Hartshorne provides for this exercise I was finally able to solve it. Hope it will be helpful for you too.
Let $P\in Q_{1}$. Since all the coordinates are symmetric, we can
assume, WLOG, that $w\neq0$. Then $\mathcal{O}_{Q_{1},P}\cong\mathcal{O}_{D\left(w\right),P}$
so it is sufficient to show that $Y=V\left(xy-z\right)\subseteq\mathbb{A}^{3}$
is normal. The morphism $\varphi:\mathbb{A}^{2}\rightarrow Y$ given
by $\left\langle x,y\right\rangle \mapsto\left\langle x,y,xy\right\rangle $
is an isomorphism (the inverse is given by $\left\langle x,y,z\right\rangle \mapsto\left\langle x,y\right\rangle $)
and thus $Y$ is normal since $A\left(\mathbb{A}^{2}\right)\cong k\left[x,y\right]$
is UFD.
Let $P\in Q_{2}$. If $x\neq0$ or $y\neq0$, $P$ has a neighborhood
isomorphic to $V\left(z^{2}-x\right)\subseteq\mathbb{A}^{3}$ which
is normal since it is isomorphic to $\mathbb{A}^{2}$. For $z\neq0$,
$P$ has a neighborhood isomorphic to $V\left(xy-1\right)\subseteq\mathbb{A}^{3}$
which is isomorphic to $\mathbb{A}^{2}\backslash V\left(x_{1}\right)$
which is an open subset of a normal variety and thus obviouslly normal.
Finally, suppose $w\neq0$, so $P$ has a neighborhood isomorphic
to $V\left(z^{2}-xy\right)\subseteq\mathbb{A}^{3}$ so we need to
show that $R=k\left[x,y,z\right]/\left(z^{2}-xy\right)$ is integrally
closed. Let $\alpha\in Quot\left(R\right)$ be integral over $R$.
$ Quot\left(R\right)/k\left(x,y\right)$ is finite field
extension of degree 2, so we can write $\alpha=f+g\cdot z$ for $f,g\in k\left(x,y\right)$.
The minimal polynomial of $\alpha$ over $k\left(x,y\right)$ is $\alpha^{2}-2f\cdot\alpha+\left(f^{2}-g^{2}xy\right)$
and since $k\left[x,y\right]$ is an UFD, by Gauss lemma, it is also
the minimal poynomial of $\alpha$ over $k\left[x,y\right]$ thus
$f\in k\left[x,y\right]$ and $f^{2}-g^{2}xy\in k\left[x,y\right]$
for which follows that $g^{2}xy\in k\left[x,y\right]$ and since $xy$
is square free, $g\in k\left[x,y\right]$ so $\alpha\in R$.
Comment: At the very end you conclude $f \in k[x, y]$ because $2f \in k[x, y]$, but what if the characteristic of $k$ is $2$?
Comment: In last part, how to apply Gauss lemma? When polynomial is already element of $k[x,y]$ , we can use Gauss lemma. For example, $f(x)=x^2 + \frac{1}{4}$ is irrreducible in $\mathbb{Q}[x]$ , but it is not in $\mathbb{Z}[x]$. ($\mathbb{Z}$ is UFD)
Comment: Although $k[x,y,z]/(z^{2}-xy)$ is integrally closed,why $Q_{2}$ is normal? We just know that for affine varieties, normal iff the coordinate ring is integrally closed. Here $Q_{2}$ is a projective variety,right?
Comment: I've covered $Q_{2}$ with affine varieties and showed that each of them is integrally closed. Since a point being normal is a local property, every point of $Q_{2}$ has a normal neighbourhood and thus normal.
Comment: you are right! Got it! Normality is a local property. I have trouble in proving this problem. I don't take an open normal affine cover before.Since $xy$ is square free, I know $k[x,y,z]/(z^{2}-xy)$ is integrally closed . But I can't get the desired conclusion that $Q_{2}$ is normal because for projective varieties, normal is not necessarily equivalent to the coordinate ring integrally closed .It seems that taking an open affine normal cover is necessary.Thanks
Comment: Jim, you're right, I did implicitly assumed the characteristic is other than 2. I'm yet to figure out what happens in characteristic 2.
Comment: @hew, this follows from the fact that $\alpha$ is integral over $k[x,y]$ (since its integral over $R$ which, in turn, is integral over $k[x,y]$). So exist some monic irreducible polynomial with coefficients in $k[x,y]$ that vanishes on $\alpha$ and Gauss lemma ensures it is equal to the minimal polynomial of $\alpha$ over $k(x,y)$.
Comment: @sss89 Do you means that "$\alpha$ is integral over $R$" imply "$\alpha$ is integral over $k[x,y]$" by regarding $^{k[x,y,z]} / _{(z^2 -xy)} \leq k[x,y]$ ? (mapping $x \mapsto x^2$ , $y \mapsto y^2$ , $z \mapsto xy$).
Comment: @hew I mean that $k[x,y]\subset R$ by $x\mapsto x$ and $y\mapsto y$.


How to negate this filter in Django?

Question: Here is my view function:
def job_find(request):
    queryset = Job.objects.filter(user=request.user).order_by('created_at')
    jobs = get_list_or_404(queryset)
    return render(request, 'jobs/all_jobs.html', {'jobs': jobs})

I want the queryset to contain all jobs which do not belong to the current user. To do this I must negate the filter, but how?
Answer: You can use exclude:
queryset = Job.objects.exclude(user=request.user).order_by('created_at')

How to negate this filter in Django?


Tem como simplificar essa quantidade de condições?

Question: Tenho o seguinte código:
        foreach (var lote in collection.ToList())
        {
            count++;

            ushort[] dadosBalanca = new ushort[9];

            if (lote.AlvoPasso > ushort.MaxValue)
            {
                var subtracao = (lote.AlvoPasso - 65536);
                dadosBalanca[3] = 1;

                if (lote.AlvoPasso > (ushort.MaxValue * 2))
                {
                    subtracao -= 65536;
                    dadosBalanca[3] = 2; //[OUT37]

                    if (lote.AlvoPasso > (ushort.MaxValue * 3))
                    {
                        subtracao -= 65536;
                        dadosBalanca[3] = 3; //[OUT37]

                        if (lote.AlvoPasso > (ushort.MaxValue * 4))
                        {
                            subtracao -= 65536;
                            dadosBalanca[3] = 4; //[OUT37]
                        }
                    }
                }

                dadosBalanca[4] = (ushort)subtracao; //[OUT38]
            }
            else
            {
                dadosBalanca[3] = 0; //[OUT37]
                dadosBalanca[4] = (ushort)lote.AlvoPasso; //[OUT38]
            }

            //...
        }

Este código já funciona, gostaria de sugestão de melhoria.
Comment: Não vejo necessidade de "enxugar" o código, o mesmo está com a sintaxe correta. Qual a necessidade que você está tendo?
Comment: Tem mais código dentro do foreach? Isso é relevante (não o código em si, mas a informação) porque o pode-se querer usar um `continue` para diminuir o nível de indentação.
Comment: Apesar de o código funcionar, pelos comentários nas respostas fica evidente que faltou definir as regras necessárias, então fechei. Pode ser editada para por os parâmetros que faltam e reaberta.
Answer: Não tem muito o que enfeitar. Você pode substituir aqueles if's encadeados por um for.
BTW, os três if's estarem encadeados não faz muito sentido porque eles escrevem no mesmo lugar, ou seja, um sobrescreve o outro. De qualquer forma, eu mantive o comportamento original no for.
O código pode ficar assim:
foreach (var lote in collection.ToList())
{
    count++;
    ushort[] dadosBalanca = new ushort[9];

    if (lote.AlvoPasso <= ushort.MaxValue) // Note que isso foi invertido
    {
        dadosBalanca[3] = 0; //[OUT37]
        dadosBalanca[4] = (ushort)lote.AlvoPasso; //[OUT38]
        continue;
    }

    var subtracao = (lote.AlvoPasso - 65536);
    dadosBalanca[3] = 1;

    for(ushort i = 2; i <= 3; i++)
    {
        if (lote.AlvoPasso > (ushort.MaxValue * i))
        {
            subtracao -= 65536;
            dadosBalanca[3] = i; //[OUT3X]
        }
    }

    dadosBalanca[4] = (ushort)subtracao; //[OUT38]
}

Comment: editei sua pergunta mas foi rejeitado, então quero sugerir para você mesmo editar, dentro do for, mudar o var para ushort ou fazer o cast antes de atribuir na posicao dadosBalanca[3] se não da erro, visto que var i=1 assume que i é inteiro e não ushort, e mudar o valor inicial do for para 2, pois a primeira subtração você já fez fora do for. Entendeu?
Answer: Sim, dá, bastante:
var deslocamento = lote.AlvoPasso / ushort.MaxValue;
dadosBalanca[3] = deslocamento;
dadosBalanca[4] = lote.AlvoPasso - ushort.MaxValue * deslocamento;

Coloquei no GitHub para referência futura.
Estou partindo do princípio que não tem como o deslocamento dar mais que 4, já que o código atual ignora isto. Se puder, vai dar erro no original e no meu, precisaria tratar, mas precisaria ver qual é o critério.
Comment: nesse caso o deslocamento pode ter mais de 4, só não coloquei mais, para não ficar extenso a pergunta, por isso quero melhorar, o critério é sempre multiplicar +1, nesse caso seguir a lógica do if, consegue entender?


create a falling object and click on it in Android

Question: I am new to developing Android apps. I want to make some rectangle objects randomly falling from top to bottom, and users are able to click on these objects. How do I create these rectangles and make them falling randomly and clickable. (Should I create the rectangles as buttons in .xml? How can I make them move if they are buttons. Or do I create the rectangles in a Java class? If so, how do I make them clickable).
What classes and libraries can I look into to do this small project?
Thanks!
Answer: By using animation class you can animate any object, whether its a button or anything else.
if i wanted to achieve such a thing, i will use Canvas.
There is also a library on Android Arsenal which do exactly what you want, i searched but i couldn't find it for you.


Filtrar através do href

Question: Bom, sou novo usando Javascript e estou tendo algumas dificuldades.
Tenho uma box que possui 6 links, isso envolvido em um dom-repeat, ou seja, são muitas 'boxes' com 6 links dentro.
Preciso checar se dentro de cada box existe algum link, se tiver um eu já posso deixar a box visível, porém se todos forem nulos ou vazios a box deve sumir.
Infelizmente não estou conseguindo pensar numa lógica boa o suficiente para conseguir o que preciso. Além disso estou com dificuldades em conseguir o valor do href.
Tentei criar um código, mas além de não estar funcionando, acho que estou pensando mal na forma de resolver o problema, me parece faltar algo para analisar todos os 6.
Função que criei para tentar resolver:
function teste(){
    var div = document.getElementsByClassName('box');

    var links = div.getElementsByTagName('a').href;

    if(links == '#'){
        div.style.display = 'none'
  }
}

Montei uma segunda função, mas também não funcionou
function teste2(){
  var box = document.getElementsByClassName('box');
  var link = box.getElementsByTagName('a').href;
  var contar = 0;

  for (x = 0; x < 6; x++){
    if(link == "#"){
        contar++
    }
  }

  if (contar == 6){
    box.style.display = 'none'
  }
}

HTML base

  A
  B
  C
  D
  E
  F

Comment: `getElementsByClassName` e `getElementsByTagName` retornam arrays (e não um único elemento), então vc deve percorrer estes arrays para acessar os elementos retornados
Answer: O principal problema no seu código é estar tentando acessar a propriedade href de um conjunto de valores. A função getElementsByTagName, como o próprio nome diz, traz uma lista de elementos pelo nome da tag, mas você tentou acessar a propriedade href da lista, não dos elementos. De qualquer forma, existe uma maneira mais simples:
Basta você utilizar o método querySelectorAll definindo o valor do href que você está buscando:

const boxes = document.querySelectorAll('.box');

for (let box of boxes) {
  const voidLinks = box.querySelectorAll('a[href="#"]');

  if (voidLinks.length > 0) {
    console.log('Foi encontrado pelo menos um link vazio');
  } else {
    console.log('Não há links vazios');
  }
}

  A
  B
  C
  D
  E
  F

  A
  B
  C
  D
  E
  F

Como você deseja ocultar aqueles que possuem todos os links vazios, basta verificar se existe pelo menos um link não vazio para deixar visível:

const boxes = document.querySelectorAll('.box');

for (let box of boxes) {
  const links = box.querySelectorAll('a:not([href="#"])');

  if (links.length == 0) {
    box.hidden = true;  // Só tem link vazio, oculta a div
  }
}

  A
  B
  C
  D
  E
  F

  G
  H
  I
  J
  K
  L

Comment: Entendi, muito obrigado pela ajuda. Funcionou da forma que eu queria aqui. Estarei mais atento para buscar informações específicas nas listas retornadas. Grato novamente
Answer: Usando .filter():

function teste(){
   var div = document.querySelectorAll('.box');
   [].filter.call(div, function(e){
      if(e.querySelectorAll("a:not([href='#'])").length == 0) e.hidden = true;
   });
}

  A
  B
  C
  D
  E
  F

   nada aqui

  A
  B

<button onclick="teste()">Checar</button>

Filtrar através do href


Axios not fetching data using Reactjs

Question: I am working with Reactjs/nextjs and i am trying to fetch data using "Axios", In "Api url" data is fetching/showing but in my webpage showing "There are no records yet",Where i am wrong ? Here is my current code
import React from 'react'
import { useEffect, useState } from "react";
import axios from 'axios';

function Displaydata() {
      const [posts,setPosts]=useState([]);

useEffect(()=>
{
    const getdata=async()=>
    {
        const { data: res } = await axios.get(
            "xxxxxxxxxxxxxxxxxxxx/api/Allvideo"
          );
          console.log(res);
          setPosts(res);
    };
})
return(

        {posts?.length ? posts.map((product: { id: any; link: any; }) =>

        {product.id}-{product.link}
)
            :
There are no records yet
}

    )
}

export default Displaydata

Comment: I don't see any `getData` invocation in the code.
Comment: @vighnesh153 i am new in reactjs , "By Default" i just want to display data
Answer: We need to pass second argument for useEffect as empty array or array of values. and then getdata function declared but not called. please find the below code.
useEffect(() => {
  const getdata = async() => {
    const { data: res } = await axios.get("xxxxxxxxxxxxxxxxxxxx/api/Allvideo");
      console.log(res);
      setPosts(res);
   };
   getdata();
 }, []);

hope this helps!!!

Axios not fetching data using Reactjs


Passando endereço para WriteProcessMemory

Question: Estou tentando passar um endereço de memória para WriteProcessMemory(), só que este endereço deve ser digitado pelo usuário, estou com dúvida de como posso fazer isso, eu tentei com strings, wstring, não tive sucesso.
int isSuccessful = WriteProcessMemory(hproc, /*VALOR DIGITADO PELO USUARIO(LPVOID)0x002bf55c*/, &NewValue, (DWORD)sizeof(NewValue), NULL);

Comment: Dê uma olhada no [tour]. Você pode aceitar uma resposta se ela resolveu seu problema. Você pode votar em todos os posts do site também. Alguma lhe ajudou mais? Precisa que algo seja melhorado?
Answer: Você tem certeza que deseja fazer isto? Parece que você está querendo fazer algo bem avançado e perigoso e está tendo uma dúvida muito básica. Esta combinação não costuma dar certo.
A aplicação tem permissão de escrita nesta área da memória? Por sorte o sistema operacional controla isto e ainda bem que não deixar a aplicação escrever em qualquer parte da memória. Você não pode escrever em outras aplicações e nem mesmo em certas partes da sua própria aplicação.
As variáveis usadas foram corretamente setadas? Vou considerar que sim, afinal você não colocou todo trecho do programa e deve considerar que há um problema apenas nesta linha.
Então basta ler um inteiro e usá-lo como ponteiro conforme você já estava tentando fazer. Provavelmente o problema é que estava lendo uma string.
int endereco;
scanf("%d", &endereco);
int isSuccessful = WriteProcessMemory(hproc, (LPVOID)endereco, &NewValue, (DWORD)sizeof(NewValue), NULL);

Coloquei no GitHub para referência futura.
Comment: mais e o hexa ?
Comment: 0xENDEREÇO, não passa como string?
Comment: eu já tentei fazer desse jeito também que você passou.
o endereço possui caracteres, fiquei na duvida agora.
ex: 0x002BF55C
Comment: ou, eu não preciso passa-lo como hexadecimal?
Comment: Então seu problema é outro, você precisa de um conversor de *string* em formato hexadecimal para um número inteiro para usar em algum lugar, não importa o lugar. O que você perguntou eu respondi. Se você ainda precisa saber como fazer o conversor veja se não tem respondido no *site*. Se não tiver faça uma pergunta pedindo isto.
Comment: quando eu uso o seguinte (LPVOID)0x002bf55c, funciona
porém ter que ficar compilando o código e trocando esse valor toda hora é bem chato, por isso estou tentando fazer de uma maneira em que eu possa fornecer este valor durante o programa


A closed discrete set

Question:
Let $V$ be a normed vector space.
Let $(b_n)\subseteq V, b_n \to b\in V.$  Show that $B := \{b,b_1,b_2\dots\}$ is closed.

I know that if $b_n\to b,$ then $b_n$ is Cauchy. That is, $\forall \epsilon > 0, \exists N\in\mathbb{N}, n,m\geq N\Rightarrow ||b_n-b_m|| < \epsilon.$ Also, if $(x_n)\subseteq B, x_n \to x$, then if $x\not\in B, ||x_n-x|| > 0\,\forall n.$ But how can I use the fact that $b_n$ is convergent to show that $B$ is closed? I think I can use the convergence of $(b_n)$ to show that $\exists \epsilon_0 > 0$ such that $||x_{n_k}-x|| \geq \epsilon_0\,\forall k$, where $(x_{n_k})$ is a subsequence of $(x_n).$ Also, it may be easier to show that $V\backslash B$ is open.
Answer: Suppose that $x\notin B$. Then in particular $x\ne b$, so let $\epsilon=\frac12\|b-x\|$. There is an $n_0\in\Bbb N$ such that $b_n\in B_\epsilon(b)$ for all $n\ge n_0$, and $B_\epsilon(b)\cap B_\epsilon(x)=\varnothing$, so $b_n\notin B_\epsilon(x)$ when $n\ge n_0$. You now have a nbhd of $x$ that excludes all but finitely many points of $b$. Let $\delta=\min\{\|x-b_k\|:k<n_0\}$; can you see how to use $\delta$ to get a nbhd of $x$ that is disjoint from $B$?
Answer: Let $x \in V\setminus B$ and $r=\frac{\|x-b\|}{2}>0.$ Then there exists $n_0 \in \mathbb{N}$ such  that $\|b_n-b\|<r$ for all $n \geq n_0.$ So
$$r=\|b-x\|-r<\|b-x\|-\|b_n-b\|\leq \|b_n-x\|$$ for all $n\geq n_0.$ Let $$\epsilon=\min\{r,\|b_i-x\|:1\leq i \leq n_0\}.$$ It follows that $$\|b_n-x\|\geq \epsilon$$ for all $n \in \mathbb{N}.$ Additionally $$\|b-x\|=2r>r\geq \epsilon.$$ So $$B_{\epsilon}(x)\subseteq V\setminus B.$$ We may hence conclude that $V\setminus B$ is open. In other words, $B$ is closed.
Answer: Let's prove something more general. If $(X,d)$ is a metric space and $x_n \to x$, then $\{x_n:n \geq 1\}\cup \{x\}$ is compact (hence closed).
Proof: Let $\{G_k: k \in K\}$ be an open cover of your set. Then $x \in G_k$ for some $k \in K$. Since $G_k$ is open, there is some $\epsilon > 0$ such that the ball $B_M(x, \epsilon) \subseteq G_k$. This is good news: because $x_n \to x$, there is $n_0 \geq 1$ such that $d(x_n, x) < \epsilon$ if $n \geq n_0$ and thus $x_n \in G_k$ if $n \geq n_0$. Now, choose indices $k_1, \dots, k_{n_0-1}$ such that $x_i \in G_{k_i}$ for $i=1, \dots, n_0-1$. Then
$$\{G_k, G_{k_1}, \dots, G_{k_{n_0}-1}\}$$
is a finite subcover, proving that your set is compact. $\quad \square$
Comment: If you have time, would you mind taking a look at [this question](https://math.stackexchange.com/questions/3701002/angle-between-two-affine-spaces)?
Answer: Let $c\in V$ \ $B.$ Take $U,$ a nbhd of $b$ and take $V,$ a nbhd of $c,$ with $U, V$ disjoint.
The set $S=\{n\in \Bbb N:b_n\not \in U\}$ is finite because $b_n\to b.$ So the set $D=\{b_n: n\in S\}=B\setminus U$ is a finite subset of $B.$
Now $c\not \in D$ and $D$ is finite so $c$ has a nbhd $V'$ which is disjoint from $D.$ So $V\cap V'$ is a nbhd of $c$ which is disjoint from $B.$ So $c \not\in \overline B.$
We could also say that  $c\not \in \overline {B\cap U}$ because $c\not \in \overline U,$ and that $c\not \in \overline D=\overline {B\setminus U}$, so $c\not\in \overline {B\cap U}\cup \overline {B\setminus U}=\overline {(B\cap U)\cup (B\setminus U)}=\overline B.$

A closed discrete set


How to distinguish a PDF file from other files?

Question: I have to deal with lot of files. How can I distinguish which one is a PDF file and which one is not ? I am running Python on Windows. Thanks for help please.
Comment: If you can't trust the file name, and want to check the contents, see http://stackoverflow.com/q/10937350/
Answer: if you don't trust the extension of the file name, you can read the first few bytes of the file and test if it starts with %PDF-
Like so:
with open(fn, 'rb') as fin:
    line=fin.read(20)
    if line.startswith('%PDF-'):
        # its a pdf file...
        # you can parse the version of PDF by the versioning x.x after %PDF-x.x
    else:
        # it is not a pdf file

Answer: If you want to rely on the file extension, you can use the following code:
#!python3

import os

def isPDFfile(fname):
    name, ext = os.path.splitext(fname)
    return ext.lower() == '.pdf'

if __name__ == '__main__':
    for fname in os.listdir('.'):
        if isPDFfile(fname):
            print(fname, 'is PDF file.')
        else:
            print(fname, 'is not PDF file.')

If you want to be sure that the name is not a directory, you can add the test:
def isPDFfile(fname):
    if not os.path.isfile(fname):
        return False
    name, ext = os.path.splitext(fname)
    return ext.lower() == '.pdf'

There is also os.walk() function that iterates through the files in a directory. If you want to find all PDF files inside a directory, you can write your own specialized walk that will return only PDF files:
def walkPDFfiles(directory):
    for dirpath, dirs, files in os.walk(directory):
        for fname in files:
            name, ext = os.path.splitext(fname)
            if ext.lower() == '.pdf':
                yield os.path.join(dirpath, fname)

And you can use it in the loop like that:
for fname in walkPDFfiles('.'):
    print(fname, 'is PDF file.')

Comment: @begueradj: When searching for the files with a different extension, the code must be modified. The extension(s) could be passed via an argument if wanted.
Comment: What if the question was about `.exe` files ?