Difference between free() function with or without malloc

Question: This is part of cs50 pset5 speller. Background is that I load a dictionary into a hash table with linked list and check word against the hash table to decide if that word is in the dictionary, after that I unload the hash table.
When I load the dictionary, I used malloc() and free() to insert a node into the linked list. The result of free() here is that it free the memory allocated to a pointer, but it will not remove the pointee (a node inserted into linked list in this case).
Here is my code:
bool load(const char *dictionary)
{
    FILE *inputfile = fopen(dictionary, "r");
    if (inputfile == NULL)
    {
        return false;
    }

    char tempWord[LENGTH+1];

    while (fscanf(inputfile, "%s", tempWord) != EOF)
    {
        //create a tempNode and make sure
        node *tempNode = malloc(sizeof(node));
        if (tempNode == NULL)
        {
            return false;
        }

        strcpy(tempNode->word, tempWord);
        tempNode->next = NULL;

        //get the index of this word
        int index = hash(tempWord);

        //move tempNode to the next node in the linked list
        if (table[index]->next != NULL)
        {
            tempNode->next = table[index];
        }

        table[index]->next = tempNode;

        free(tempNode);

        word_count ++;
    }
    fclose(inputfile);

    return true;
}

When I unload the dictionary, I used free() again, but this time without calling malloc() at all. So the elements on the linked list can be freed one after another. The result of free() here is that it 'removes' the node from the linked list.
Here is my code:
bool unload(void)
{
    for (int i = 0; i < N; i ++)
    {
        //freeing linked list, we need two tempNode in order to do this
        node *tempPtr = table[i];
        while (tempPtr != NULL)
        {
            node *deletePtr = tempPtr;
            tempPtr = tempPtr->next; //move the tempPtr to the next element, so we are note losing the linked list
            free(deletePtr); //once we moved the tempPtr to the next element, now we can delete where deletePtr is pointing at
        }
    }
    return true;
}

Although my code was compiled and can run without issue, I am very confused of why free() does different things here.
To summarize my questions:
(1)Am I correct to say that: in 'load', free(tempNode) does not 'erase' what tempNode is pointing to (which is a node in a linked list), but only free the memory allocated to tempNode; in 'unload', however, free(deletePtr) 'erase' both deletePtr and what deletePtr is pointing to (which is a node in a linked list)?
(2) If my observation in (1) is correct, why is free() doing different things here? Is that caused by the fact that load called malloc() and unload didn't?
(3) I understand I have to call free() if I called malloc(), but when malloc() isn't called, what does free() do?
=================================
Edit:
After more research, I realized that in load section, it is unnecessary to free() the memory assigned by malloc(). The reason is, in unload section, by free() each node, I will eventually be able to free the memory assigned before.
Comment: It's very straight forward. Every `malloc` has to have exactly one `free`. Not two, not zero, not anything else - exactly one. And the pointer passed to `free` must be the exact pointer returned by `malloc`. The `malloc` and the `free` don't need to be called in the same function or at the same time. But at some point in the program there should be one `free` for each `malloc`.
Comment: `free` does not "remove the node from the list".  Your program must remove the node from the list, and once you've done that you call `free` to tell the system that you are no longer using that memory.
Answer:
(1)Am I correct to say that: in 'load', free(tempNode) does not
'erase' what tempNode is pointing to (which is a node in a linked
list), but only free the memory allocated to tempNode;

The object to which tempNode points is not meaningfully distinguished from the memory occupied by the object to which tempNode points.  If that is a block of dynamically allocated memory then you must not attempt to access it after freeing it.  Any attempt to do so produces undefined behavior.
The question is thus meaningless.  There is no conforming way to tell whether the memory in question has been "erased", because you must not attempt to read it.  If you do attempt to read it then the program might behave as if the memory had been overwritten in some way, or it might not.  And it might do anything else within its power, too.  Crashing the program (eventually) is a popular alternative, but by no means a guaranteed one.

in 'unload',
however, free(deletePtr) 'erase' both deletePtr and what deletePtr is
pointing to (which is a node in a linked list)?

See above.

(2) If my observation in (1) is correct [...]

Observation (1) is not correct.

(3) I understand I have to call free() if I called malloc(), but when
malloc() isn't called, what does free() do?

The free() function has undefined behavior (see above) if it is passed a pointer value that is non-null and was not obtained from a memory allocation function, or one that has already been freed.


Connectedness of $\mathbb{R}^2\setminus \lbrace 0\rbrace$

Question: Is there a proof that $\mathbb{R}^2\setminus \lbrace 0\rbrace$ is connected without using the idea of path-connected sets ( i.e. using the definition of connected sets only ).
Comment: Otherwise you could take the mapping $f(x,y)=(e^x \sin y ,e^x \cos y)$ its range is $\frac{ \mathbb{R}^2 }{ \{ 0 \} }$ and it is continuous and we know that connected subsets through continuous mapping go to connected subsets and you are done..
Comment: In order to get the best possible answers, it is helpful if you say what your thoughts on the problem are so far; this will prevent people from telling you things you already know, and help them write their answers at an appropriate level. Also, people are much happier to help those who demonstrate that they've tried the problem themselves first. Many see giving commands as rude when asking for help; please consider rewriting your post.
Comment: @clark: +1. By far the best answer :)
Comment: @clark, it deserves to be an answer. I was writing an answer along that line and then I saw your comment...
Answer: $\Bbb R$ is connected, isn't it ? So $\Bbb R^2$ is as well, as a product of connected spaces.
Consider the following lemma (proof below) :

Let $A$ and $B$ two subsets of a topological space $X$. If $A$ and $B$ are connected and if $A\cap B$ is not empty, then $A\cup B$ is connected.

And now consider $\Bbb R^2\setminus \{0\}$ as the union of four open halfplanes $\{ x>0 \}\cup\{x<0\}\cup\{y<0\}\cup\{y>0\}$. Each one is connected, being homeomorphic to $\Bbb R^2$. Using the lemma, you see that $\Bbb R^2\setminus \{0\}$ is connected.
Proof of the lemma —
If $A\cup B \subset U\cup V$, with $U$ and $V$ open sets of $X$, with $U\cap V \cap (A\cup B) = \varnothing$. Then $A \subset U\cup V$ and since $A$ is connected, with have either $A\subset U$ or $A\subset V$. Similarly $B\subset U$ of $B\subset V$.
If $A\subset U$ and $B\subset V$ — or $A\subset V$ and $B\subset V$ —, then $A\cap B \subset U\cap V$, which is a contradiction.
So $A\cup B\subset U$ or $A\cup B\subset V$, what we wanted.
Comment: I started an answer along these lines, but your solution is far simpler and elegant. My solution was based on the same lemma, but using the observation that $\mathbb{R}^2 \setminus \{0\} = \cup_{p \in \mathbb{Z}^2 \setminus \{0 \}} B(p,1)$ (Euclidean norm).
Answer: HINT
Suppose that $A$ and $B$ are two disjoint open sets s.t. $A \cup B$ is $\mathbb{R}^2 \setminus \{0\}$, s.t. $A$ is nonempty. Then if $x \in A$, show that $B$ is empty, or alternatively that any $y$ is in $A$ as well. You might choose progresively larger open disks, or something similar.
Comment: The question is about $\mathbb R^2\setminus0$, not $\mathbb R\setminus0$.


Converter a saída em uma caixa de texto a uma tabela dinâmica

Question: Estou tentando fazer uma tabela dinâmica para a contagem de frequência de palavras extraídas de um arquivo externo. Me deparei com um modelo, agora eu estou tentando alterar a saída para exibir uma tabela em vez de mostrar os resultados em uma caixa de texto. Duas colunas devem aparecer desencadeada por onClick tanto botões que exibem a palavra e sua freqüência de ocorrências.
Abaixo está o que eu tenho trabalhado até agora:

Word Counter

Filename: <input id = "url" name="url" size=15 type="Text"/>

    Open document
Retrieve text

    <textarea id="ta_1" rows="20">

    </textarea>

        <button>Alphabetical Order</button>
        <button >Frequency Order</button>

    <textarea id="ta_2" rows="20">
    </textarea>

Comment: É mais ou menos [isso](http://jsfiddle.net/5TMX2/) que você quer? Se for, eu coloco na resposta com os códigos certinho. PS: No `input` os valores tem que serem dividos por um `;`
Comment: Só uma pergunta: o arquivo que vai ser carregado fica no próprio site, certo?
Comment: Você vai ter um vetor com os valores da tabela?
Comment: Tá mais, qual o seu problema? O que não funciona ou o que você não consegue fazer??
Answer: A function retrieve é a que está alterando a tela pelo visto.
function retrieve(node) {
            if (node.nodeType == Node.ELEMENT_NODE) {
                for (var m = node.firstChild; m != null; m = m.nextSibling)
                    retrieve(m);
            }
            else if (node.nodeType == Node.TEXT_NODE) {
                var p = document.getElementById("ta_1");
                p.appendChild(document.createTextNode(node.data));
            }
        }

Note que ele recupera o elemento "ta_1" e cria um texto dentro dele, que é esse tal node.data
Você vai precisar trabalhar essa parte aí, e inserir o seu resultado em uma tabela.
Você pode criar uma tabela no html, e então nessa function vc insere o conteudo dessa tabela.


Why drush "assume yes" -y option do not work for some commands

Question: Drush has global option -y (or --yes) which allow you not to type y on every promt during given command execution. (There is also -n or --no option to which following applies as well.)
This works perfectly when you run something like:
drush en i18n -y

The propblem arises, for example, when you trying to run rsync in that manner:
drush rsync @staging:sites/all/themes @production:sites/all/themes -y

Drush just don't get the -y option, and prompts you for a confirmation.
What is this and how to make use of -y option?
Comment: I would gladly hear downvoting reasoning, because I run into this [not so obvious] behaviour while scripting some automation, and it was, well, annoying enough.
Comment: `-n` is not the equivalent of `--no`, but rather `--no-interaction`: -n|--no-interaction see: https://github.com/drush-ops/drush/issues/3082
Answer: The solution is to pass all global options like -y or -n before drush command:
drush -y rsync @staging:sites/all/themes @production:sites/all/themes

This allows you to pass options to a shell command run with drush without getting in conflict with drush options:
drush [global options] command [command options]

This will pass [global options] to drush, and [command options] to a shell command.
Take a habit of passing -y and other global options right after you type drush.
Run drush topic docs-strict-options to get a help on that case.
Comment: This is a subtle difference, yet an important one when invoking commands. Thanks!


Send a token to another app and then validate

Question: There are two separate django projects, So I want both are generating tokens with the same user_id, secret key and same HS256 algorithm and then once Project B sends request along with token, the token should be decrypted and the required response should be send back from Project A. How do I go forward and implement it. Should i use JWT?
Answer: I have done something similar with an oauth2 provider and 2 django apps.
Take a look here:
https://github.com/DimitrisBovasianos/CustomOauth2Authorization
You have to create a custom authentication backend and a custom  middleware to handle the refresh token in case you want to use token based authentication.
Comment: I am using ldap for authentication in both the applications
Comment: My doubt is should i create a token when he/she logs in and once request comes in verify the token in the request and the one in current app?
Comment: If i were you i wouldn't have the same authentication in both apps.I would have it in one app ( that would serve let's say as a  backend ) and create the tokens and in the other one i would make a custom authentication that would sent the data to the first one for verification and the creation of the token.Even though i haven't used ldap before I think that would work in any type o 3rd party authentication backend.
Answer: You can write a custom authentication.
It can work like this:
Check header for a token and if there is not any then the user is not authenticated.
If there is a token, then send a request to project A with the token and ask if the token is valid and if it is, what is the user.
Then set get the data in project B and do what ever you want.
It's like how frontend frameworks like react and ... works.
You can use any external resources to check if a token is valid or ...
Check here for custom authentication


Can't clear textarea once Text has changed in Firefox and Chrome

Question: Simple use case:
Textarea and Button, when the button is clicked, the text in the Textarea changes.
Sample:
JS
$('button').click(function(){
    $('#t1').text('test');
});

HTML:
<textarea id="t1" cols="10" rows="5"></textarea><button>Clear</button>

Fiddler example
However when I change the button and then click the button the Text doesn't change in Chrome and Firefeox (in IE10 it works as). (Tested in the latest versions of Chrome and Firefox)
When I debugg it and, check the text of the textarea, it displayes the correct valeu.
Is this a browser bug, jQuery bug or am I missing something?
Comment: use .val('works') instead, see working fiddle: http://jsfiddle.net/uQ825/1/
Comment: thanks, but why does text work the first time and then it fails?
Answer: A textarea element has a value, so use val('') to set it, like this:
$('button').click(function(){
    $('#t1').val('test');
});

Example fiddle
Comment: I would imagine it's a peculiarity to do with the internal method browsers have of getting the text inside the textarea on page initialisation.
Comment: thanks, that solves it, but why does text work the first time and then it fails?
Comment: Setting the text sets the default value of the textarea.  Setting the default value of form controls will change the value only if the value has never been changed from the default value to start with.  That's why you're seeing it work before you edit the text but not after.


Reference the subgrid in quote entity after revised with the same data

Question: I Have a Subgrid in Quote entity, in which there are records of my custom entity, And also the custom entity display in left side of the form,Because the custom entity has N:1 relation with quote.
Every Quote can have many of my custom entitiey  records.
It is ok,But when I revise the Quote, I want the same data and records of previous subgrid display in the new quote subgrid, as well as other fields that copy and appear from the previous subgrid.
How can I do that?
Any Idea?
Answer: When you create a revised quote through the UI, a new quote is created behind the scenes. You can thus create a plugin that listens for the Create eventoperation for Quote. In this plugin you can retrieve the original quote and clone the relationships between your custom entity and quote.
In the plugin you can check the value of the revisionnumber attribute to see if the quote in question is a revised quote.
Subsequently you can look in the ParentContext for the QuoteId value from the ReviseQuoteRequest to get the guid of the quote that the clone was initiated from. See Catch the Revise Quote message inside a Plugin for an example of this.
You mention that the relationship from your custom entity to Quote is N:1. In this case you would need to either clone the custom records, or change the relationship to be N:N.


Minimize $\sum\limits_i || t_i - A_i \ x||^2$ wrt x

Question: I would like to find in closed form the solution to the following: Find x that minimizes
$$
f(x) = \sum\limits_i (t_i - x)^T A_i (t_i - x),\\
t_i, x \in \mathbb{R}^3,\\
A_i \in \mathbb{R}^{3\times3},\; A_i\,\text{positive semi-definite (covariance matrix)}
$$
Note, dimension of 3 for the vectors is arbitrary as I believe a solution will generalize to any dimensionality.
Since each $A_i$ is positive semidefinite, we can write it as $A_i=M_i^T M_i$ or $A_i = M_i M_i$ where $M$ is symmetric. Then we have the following:
$$
f(x) = \sum_i (M_it_i - M_ix)^{T} (M_it_i - M_ix)
$$
Letting $y_i = M_it_i$, we are minimizing over x:
$$f(x) = \sum_i (y_i - M_ix)^T (y_i - M_ix)$$
which is equivalent to minimizing:
$$f(x) = \sum_i || y_i - M_ix ||^2$$
This is as far as I have gotten. Perhaps the next step is to see if we can solve by taking derivative wrt x and setting to zero, but I'm not sure how to work out the derivative in vector/matrix equations. Maybe even if this step were to be done will it reveal a closed form solution?
Comment: If you go on the wiki page for matrix calculus, you can easily find out how to take the gradient of $A x$ and $x^T A x$ with respect to $x$. $f$ is convex, so take gradient, set it to 0 and you get the solution for optimizer.
Comment: You can find a matrix A such that the form you've written is equivalent to min. ||A x - b||^2.  Then the closed form solution simply amounts to multiplying the pseudoinverse of A with b.  A is a block matrix of Ms stacked on top of each other.  Do you see it?
Answer: The trick is to write explicitly $f(x)$ in terms of the components of $x$ and $y$. It is just a little tedious (but not hard), because of the matrix $M_i$. For example $(M_ix)_1=M_{i,11}x_1+M_{i,12}x_2+M_{i,13}x_3$. You will get $f(x)$ of the form $$f(x)=\sum_i\sum_{j=1}^3\sum_{k=1}^3C_{ijk}x_jx_k+\sum_i\sum_{j=1}^3D_{i,j} x_j+\sum_iE_i$$
Now take the derivatives with respect to the components of $x$, and equate them to $0$. You should get a system of three linear equations in $x_1$, $x_2$, and $x_3$.
Answer: Let's use a colon to denote the trace/Frobenius product, i.e.
$$\eqalign{
 &X:Y &= {\,\rm tr}(X^TY)        &\,\,\text{(matrix version)}\cr
 &x:y &= {\,\rm tr}(x^Ty) = x^Ty &\,\,\text{(vector version)} \cr
}$$
Then the function can be written as
$$\eqalign{
 f
 &= \sum_k A_k:(x-t_k)(x-t_k)^T \cr
 &= \sum_k A_k:xx^T - 2\sum_k A_kt_k:x + \sum_k A_k:t_kt_k^T \cr
 &= B:xx^T - 2b:x + \beta \cr
}$$
In the last line, all of the subscripted variables have been collected into three  matrix/vector/scalar  sums
$$\eqalign{
B = \sum_kA_k\,,\,\,\,\,\,\,\,b = \sum_kA_kt_k\,,\,\,\,\,\,\,\,\beta = \sum_k2A_k:t_kt_k^T \cr
}$$
Now let's find the differential and gradient of the function
$$\eqalign{
df &= B:d(xx^T) - 2b:dx + 0 \cr
 &= (B+B^T):dx\,x^T - 2b:dx \cr
 &= 2(Bx-b):dx \cr
\frac{\partial f}{\partial x} &= 2(Bx-b) \cr
}$$
Now set the gradient to zero and solve for the optimal $x$-vector
$$\eqalign{
Bx &= b \cr
 x &= B^{-1}b \cr
}$$


How to override twig templates

Question: I'm having a bit of a hard time with Drupal 8.
I've created a custom theme and am trying to override twig files. I've got debugging enabled so I know which files to copy to my template directory. However, when I copy a twig template it outputs nothing.
For example, I'm trying to wrap the site title in an H1 element. The core template file used in this case is /core/themes/stable/templates/block/block--system-branding-block.html.twig. If I add the H1 element in that file the header is inside a H1 element, but when I copy the twig file to my template directory the whole header is gone.
I can see in the source code that the file was found:

The documentation suggests that copying the relevant twig file is all that's needed but maybe I'm missing something? And if this should work, how can I debug this issue (the Apache error log doesn't report any errors).
Comment: Did you flush/clear the cache?
Answer: Yes, to override twig file you just need to have the twig file with filename suggestion you get with debugger.
In case you are not able to see it, make sure of following:-

Your custom theme is enabled.
Folder where you kept your twig file has right permission.
Clear your Drupal caches.
Comment: Thank you. I _think_ it may have been a permissions issue. Just tried copying / changing the twig file again with a fresh pair of eyes, and this time I also rebuild my install's directory and file permissions... and it now works as expected. (The twig file's permissions are 640, with me as the owner and www-data as the group owner).

How to override twig templates


ext2 or ext3 without journaling

Question: I've recently came across several servers with different "strategies" for their /boot partition (btw, always as /dev/sda1, 512M)
Some servers use ext2 for /boot, some use ext3 for /boot, and for the latter some have turned off journaling or turned off journaling and added the sync option.
I won't take relatime and similar in account since I don't believe those atime options are relevant here.

Are there any important and relevant differences between an ext2 partition and a ext3 partition with journaling turned off for a /boot partition? I believe that online file system growth and htrees have no use at all for a /boot partition and I don't see what else ext3 offers over ext2.
Would "sync" option be recommended if there is no journaling?
Does any of these setups stand out from the rest in terms of easy of administration in case of crash/panic/oops or performance wise?
Is there any general consensus on the partition/format type for such a small (512MB) /boot partition should be?
Answer: From a functional standpoint, ext3 is ext2 + journaling.
Using ext3 without journaling means to use an ext2 filesystem, but with a more recent code base (ext3's one).
However, there is not reason why you can't use ext4 as a boot partition, as Grub supports it since years.
The 512 MB limit for a boot partition is a vestige of some very old BIOS which can not boot from a partition larger the 512 MB. You can not use whichever size you want for your boot partition, but anything over 512-1024 MB is overkill.
Comment: Note: recent (2014+, I think) kernels use the same "ext4" code to access ext2/3/4 partitions, since the backward compatibility is excellent. Specifying ext2/ext3/ext4 only toggles default functionality bits (and what mount options you can/cannot request explicitly).
Comment: @Piskvor Thanks for the info. I haven't gone in the kernel source for a while, I guess I'm going to check the info you just gave me.
Comment: @BlakBat: Based off Linux Kernel News, I didn't bother to go all the way *ad fontes* (although links were provided :)).

ext2 or ext3 without journaling


How do I convert this parametric expression to an implicit one

Question: I have:
$$x=5+8 \cos \theta$$
$$y=4+8 \sin \theta$$
With $ -\frac {3\pi}4 \le \theta \le 0$
If I wanted to write that implicitly, how would I do it? I get that it's a circle, and I can easily write the circle implicitly, but I'm not sure how to convert the domain from $ -\frac {3\pi}4 \le \theta \le 0$ to a suitable domain in x and y.
I can think of a way to do it that would involve using the $Min$ function, but is that allowed in an implicit representation?
Answer: Use that $\exists \theta : (v,w) = (\cos\theta, \sin\theta) \iff v^2 + w^2 = 1$.
You immediately get that the parametric curve is a part of the curve defined by
the implicit equation
$$
\left(\frac{x-5}8\right)^2 + \left(\frac{y-4}8\right)^2 = 1$$
To get only the part that you want, you must also make sure that $-\frac{3\pi}4\le \theta\le  0$, which is equivalent to
$$
\cos \theta \ge -\frac 12, \sin\theta< 0
$$
and then you get the equation
\begin{cases}
\left(\frac{x-5}8\right)^2 + \left(\frac{y-4}8\right)^2 = 1\\
\frac{x-5}8 \ge -\frac 12\\
\frac{y-4}8 \le 0
\end{cases}
Comment: How did you get the cos >= -1/2, sin<0 part?
Comment: @CameronBall just take a look at the (x,y) plan to figure out.
Comment: Looking at this, I can't figure out where the -1/2 came from. http://upload.wikimedia.org/wikipedia/commons/thumb/7/71/Sine_cosine_one_period.svg/2000px-Sine_cosine_one_period.svg.png
Comment: nvm, got it looking at a unit circle.
Comment: Actually thinking about it more, I still don't understand. sin(theta) < 0 makes sense, but I feel like that -1/2 should be -sqrt(2)/2, what am I missing?
Comment: there is a mistake with this value indeed.
Answer: Just compute the range of $x,y$, or using the geometric meaning of polar coordinate, draw a picture to see how $x,y$ changes on the circle when $\theta$ changes.
The result is $x\in[5-4\sqrt{2},13],y\in[-4,4]$, where $x,y$ satisfies $(x-5)^2+(y-4)^4=8^2$.
Comment: This isn't enough, because it also describes a full circle also, while his parametric equations describe 3/4 of a circle. They both have the same ranges, but they are not the same


Why is Docker services keep running without my consent

Question: These docker services keep running without my consent, how to stop them:

/usr/bin/docker-containerd-current
/usr/bin/dockerd-current

I don't want to uninstall Docker, just want to stop services to reduce used RAM. I'm on CentOS.
Done all these, but those Docker services above launch themselves back:
sudo systemctl stop docker
sudo systemctl disable docker
sudo pkill -f docker

Run top or htop and they are still there.
Comment: How did you install docker? What does `sudo systemctl status docker` show before running stop?
Comment: Possibly some cron/timer is started them.  Perhaps something other service/script is starting them?  Maybe look at your system logs to look to see when it is getting started, and then look backwards and you can see what is starting it.
Answer: It's possible that a cron job or a script running from somewhere else that starts it. Look in the cron directories and files and in /var/log/messages and /var/log/cron to find what is starting it.
If you just want to stop the service from starting altogether:
systemctl mask docker

That will link the unit files to /dev/null which makes it impossible to start the service.


Android: How to get search suggestions

Question: How to get search suggestions when I type some text in my edittext. I am not talking about the interface, but how do i get the actual suggestions like when you type something in the google search bar.
Are there any APIs available?
Thx!
Rahul.
Comment: Sounds like this as you asked, with some answers.

http://stackoverflow.com/questions/6428502/google-search-autocomplete-api
Comment: I tried the guides from google docs. I can't get it to work. The cursor returns the valid search suggestions. But no search suggestions appears below the search box.
Answer: The Google Suggest API seems to be what you're looking for:
http://blogoscoped.com/archive/2006-08-17-n22.html
You can try it on that page, and it will show you the results of your query as XML, when you click submit.
Then, on Android you would use an XML parser, and there's a good example of that here:
http://www.ibm.com/developerworks/opensource/library/x-android/
Here's the official Android documentation on parsing XML: http://developer.android.com/training/basics/network-ops/xml.html
Comment: Thx! I got the idea. Thats what I was looking for.

Android: How to get search suggestions


deploy scrapy in a remote machine

Question: Hello I am using scrapy and I have managed to deploy it with scrapyd - this work perfectly in my localhost but when it comes to run it from another computer it doesn't work out.
this command works fine :
curl http://localhost:6800/schedule.json -d project=webplode -d spider=pingwebsite -d file=./testfiles/testfiles.xlsx
but when it come to run this one :
curl http://myip:6800/schedule.json -d project=webplode -d spider=pingwebsite -d file=./testfiles/testfiles.xlsx
I get the following error msg :
Failed to connect to myip port 6800: Connection refused
here is my scrapy.cfg
# Automatically created by: scrapy startproject
#
# For more information about the [deploy] section see:
# https://scrapyd.readthedocs.io/en/latest/deploy.html

[settings]
default = webplode.settings

[deploy:local]
url = http://myip:6800/
project = webplode

I don't find scrapyd.conf, I am running this on windows
Comment: ok - can you check whether scrapyd is running on the windows server? and make sure port 6800 is open.
Comment: Can you check if scrapyd is running correctly on the remote server? (f.e. `sudo service scrapyd status` on Ubuntu)
Comment: I am deploy it on windows
Answer: Finally I manage to solve my problem, I just have to change the settings of my scraper and add my ip address like below:
scrapy.cfg :
[settings]
default = webplode.settings

[scrapyd]
bind_address= myip

[deploy:local]
url = http://localhost:6800/
project = webplode

deploy scrapy in a remote machine


Dynamic tabs using angular 6

Question: I am using tabset for tabs.
For example: https://stackblitz.com/edit/ngx-bootstrap-tabs-manual?file=app%2Fapp.module.ts
I need to close and add the tabs dynamically using ngx-bootstrap,tabset.
Can anybody help me for the dynamic tabs.
Answer: Please replace below HTML code in app.component.html this file for dynamic tab
<alert type="success">
  Tabs! you can enable/disable tab switching with the button here.
</alert>

Disable tab switching: <input type="checkbox" [(ngModel)]="disableSwitching">

Tab switching is {{ disableSwitching ? 'disabled' : 'enabled ' }}.

<tabset #tabset>
  <tab *ngFor="let tab of tabsetData" [heading]="tab.tabtitle" [innerHTML]="tab.tabContent"></tab>
</tabset>

<button (click)='goto(0)'>Go to 1</button>
<button (click)='goto(1)'>Go to 2</button>
<button (click)='goto(2)'>Go to 3</button>

For app.component.ts file code
import { Component, ViewChild , ViewChildren , QueryList , AfterViewInit } from '@angular/core';
import { TabsetComponent, TabDirective } from 'ngx-bootstrap/tabs';
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent implements AfterViewInit  {
  disableSwitching: boolean;

  @ViewChild('tabset') tabset: TabsetComponent;
  tabsetData = [{
    tabtitle: "First Tab",
    tabContent: "
First Tab
"
  },{
    tabtitle: "Second Tab",
    tabContent: "
Second Tab
"
  },{
    tabtitle: "Third Tab",
    tabContent: "
Third Tab
"
  }];
  ngAfterViewInit(){
    console.log(this.tabset.tabs);
  }

  goto(id){
    this.tabset.tabs[id].active = true;
  }
}

Hope this helps! Thank you.

Dynamic tabs using angular 6


Integer Pointer Subtraction

Question: I've written a few lines of code predominantly from a book that gets you to declare an integer array, then subtract and pass two addresses from the array to another integer, in order to pass into a printf statement.  I'm not sure why, but my actual pointers: aPointer and bPointer seem to be 8 bytes, which poses a problem when I try and pass the subtracted addresses to an integer.
I then changed the latter to a long.  The errors are not present in Xcode now, but I cannot print the address of pointerSubtraction properly using the %p specifier which does indeed expect an int and not a long.
    int arrayOfInts[10];

            for (int i = 0; i < 10; i++) {
                arrayOfInts[i] = i;
                printf("%d", arrayOfInts[i]);
                // prints out 0123456789
            }

            printf("\n");

            int *aPointer = &arrayOfInts[1];  // get address of index 1
            int *bPointer = &arrayOfInts[7];  // get address of index 7
            long pointerSubtraction = bPointer - aPointer;  // subtract index 7 with 1

            printf("The size of aPointer is %zu bytes \n", sizeof(aPointer));
            printf("The size of aPointer is %zu bytes \n", sizeof(bPointer));
            printf("The address of aPointer is %p \n", aPointer);
            printf("The address of bPointer is %p \n", bPointer);
            printf("The address of final is %p \n", pointerSubtraction);
            printf("The value of pointerSubtraction is %ld \n \n", pointerSubtraction);

Comment: `pointerSubtraction` is not an address.  Think about it...what address would `&arrayOfInts[7] - &arrayOfInts[1]` possibly represent?
Comment: "the `%p` specifier which does indeed expect an `int` and not a `long`." -- ***WRONG!*** It expects a `void *`. Passing anything else to it results in undefined behavior.
Answer: You might like to use a variable typed ptrdiff_t to store the difference of two pointer values, two addresses.
To printf() out a ptrdiff_t use the length modifier "t". As ptrdiff_t is a signed integer use the conversion specifier "d".
#include <stddef.h>
#include <stdio.h>

int main(void)
{
  int a = 0;
  int b = 0, * pa = &a;

  ptrdiff_t ptr_diff = pa - &b;

  printf("pd = %td\n", ptr_diff);

  return 0;
}

Also the conversion specifier "p" is only defined for pointers to void. So the printf() calls shall look like:
      printf("The address of aPointer is %p \n", (void *) aPointer);
      printf("The address of bPointer is %p \n", (void *) bPointer);

Also^2 : The result of adding or substrating a value v from a pointer p is only a valid address if the result pv of the operation still refers to (an element/member of) the object the original pointer p pointed to.
Comment: Thanks for your answer, I'm even more confused about pointers as my book doesn't do much regarding printing pointers, this is something I'm trying to do extra to make more sense of them.  So what does `(void *)` actually mean?
Comment: @user1574598: `(void *) aPointer` tells the compiler to tread `aPointer` which is declared to be `int *` as if it where declared `void *` instead of `int *`. An `int *` typed variable is casted `void *`.
Comment: I see, well casting is something I'm not 100% with yet until I do some more reading.  Thanks for your reply.
Answer: In your code aPointer is the value pointed by *aPointer. Same thing for bPointer.
As the comment says pointerSubtraction is the value obtained by the subtraction, not the address.

Integer Pointer Subtraction


Como consigo copiar conteúdo de uma div para um hiddenfield?

Question: Tenho uma div que exibe o IP do usuário, na qual, esse endereço é pego por JavaScript. Porém, preciso utilizar o IP no Code-behind. A ideia seria copiar o conteúdo da div para um hiddenfield e trabalhar em cima dele. Estou tendo problema para fazer essa cópia. Segue abaixo o código:

  <asp:HiddenField ID="HiddenField1" runat="server" />

Answer: Seu código está sujo, com implementações que não se aplicam a pergunta. Mas vou tentar te ajudar.
Para obter o conteúdo do hiddenField basta:
var conteudo = document.getElementById("HiddenField1").value;

já para gravar conteúdo no hiddendField basta:
document.getElementById("HiddenField1").value = "192.168.0.1";

Answer: Me parece que você está tentando pegar um value de uma div:

          <-- a "div"
var valor = $('#list').val();  <-- pegando o "valor"

A div não possui "value". Se você quer pegar o texto da div, use .text():
$("#list").text().trim();

O .trim() remove possíveis espaços gerados pelo HTML.
Outra coisa é que você está jogando o conteúdo da div no campo ao fazer o submit. Seria melhor colocar um setTimeout para garantir que dê tempo do campo receber o valor antes do submit:
$('#btn').on('submit', function (e){
   e.preventDefault();
   var $this = $(this);
   var valor = $('#list').val();
   $('#HiddenField1').val(valor);
   setTimeout(function(){
      $this.submit();
   }, 50);
});

O e.preventDefault(); impede que o formulário seja submetido no evento, e o $this.submit(); no setTimeout irá fazer o envio após uma fração de segundo após o texto da div ter sido colocada no campo #HiddenField1.
Agora, o que se nota é que você está fazendo um submit de um botão #btn (pelo nome do id parace que seja um botão, e não o formulário). Se esse id se refere ao botão que submete o formulário, está errado. Esse id deveria ser o id do formulário, algo como:
<form id="form" ...>

   // elementos do formulário

   <button id="btn">Enviar</button>
</form>

E no código seria o id do form e não do botão:
$('#form').on('submit', function (e){
      ↑

Ou seja, esse id #btn não é nem necessário ter, se for esse o caso.
Answer: Para pegar o html de qualquer div com jquery utilize o seguinte argumento
var valorDiv = $('#list').html();
$('#id_input').val(valorDiv);

Comment: Olá amigo. Eu já havia tentado dessa maneira mas não funcionou, o campo hiddenfield vem vazio.
Comment: Da uma olhada nesse link https://docs.microsoft.com/pt-br/dotnet/api/system.web.ui.webcontrols.hiddenfield?view=netframework-4.8 ele tem uma função de change do valor do hiddenfield


Custom paragraph prefixed with number?

Question: I am looking at different CMS's and KMS's for suitable software user documentation systems. Im very impressed with Drupal.
I have a user case where I would like to be able to add a series of steps - so a user can read the steps and actions needed to take to complete a task.
I thought this could be achieved using paragraphs. However, I would like to have a sequential number at the beginning of each paragraph, eg:

Do step one
Add a widget
Enable the gadget

How would I do this in Drupal?
Thanks
Answer: Do you have control over the CSS? What about a CSS solution?
http://bl.ocks.org/trauber/5163440
<code>.paragraph-parent {
    counter-reset: paragraph;
    padding-left: 20px;
}
.paragraph-parent p {
    width: 75%;
}
.paragraph-parent p:before {
    position: absolute;
    margin-left: -20px;
    content: counter(paragraph);
    counter-increment: paragraph;
}
</code>

Custom paragraph prefixed with number?


@font-face alias issues on PC

Question: Just started using this technique and am having strange results on the PC side. Virtually every browser I preview this site in on a PC makes the font look totally horsey. Example:
On the Mac:
http://dropbox.smallparade.com/howto-mac.png
On a PC:
http://dropbox.smallparade.com/howto-pc.png
Anyone have experience with this issue? Is there a resolution? Does it have anything to do with how the fonts were created? Appreciate any help I can get. I used the font-face generator over at fontsquirrel.com.
Comment: Um.. what's the typeface at hand?
Comment: Could you define the browser(s) you used on the PC? I suggest you try it IE7/8, Safari and Firefox.
Answer: That's a Hinting problem.
When you generate your font-face kit (like in FontSquirrel), you need to specify Hinting on the Expert options.
Choose Expert, and under Rendering, select:
Apply Hinting - Improve Win rendering.
Comment: I'm trying FontSquirrel and they don't have the option you mentioned... they just have auto-hinting and font squirrel hinting... have they changed what it's called? which one should i use?
Comment: Choose the Expert option when uploading your font. Then, under Truetype Hinting, check TTFAutohint.
Answer: probably you can specify font-size in px for example
<code>font-size:11px/11px;
</code>
this might help you because i have faced same problem and i solved it like this only
Answer: I had this same issue, and just like Rinkalkumar I'd suggest specifying font-size.
But I've also found out that some fonts in some sizes simply render ugly.
So you may wanna try adjusting size few px +- just to check is this the issue.
Font face support isn't perfect yet, so if this proves to be an issue, you
may wanna try http://cufon.shoqolate.com/generate/   -  it involves javascript
but has proven to be great when you want fonts render consistently across browsers/platforms.
Answer: ttfautohint will rebuild the font's hinting for you.

@font-face alias issues on PC


Android Nexus 10 AOSP build AndroidViewClient

Question: I finally managed to successfully build a Nexus 10 image (full_manta-userdebug) with Google Mobile Services installed but unfortunately, I'm unable to use my MonkeyRunner script that uses AndroidViewClient.  It crashes out of the script with the following:
/system/bin/sh: uiautomator: not found

130628 14:12:41.242:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions] Script terminated due to an exception
130628 14:12:41.242:S [MainThread] [com.android.monkeyrunner.MonkeyRunnerOptions]Traceback (most recent call last):
  File "/home/allen/projects/cts-scripts/4.2/cts-setup.py", line 361, in <module>
    main()
  File "/home/allen/projects/cts-scripts/4.2/cts-setup.py", line 339, in main
    vc = ViewClient(device, serialno)
  File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 1188, in __init__
    self.dump()
  File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 1780, in dump
    self.setViewsFromUiAutomatorDump(received)
  File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 1530, in setViewsFromUiAutomatorDump
    self.__parseTreeFromUiAutomatorDump(received)
  File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 1688, in _ViewClient__parseTreeFromUiAutomatorDump
    self.root = parser.Parse(receivedXml)
  File "/home/allen/projects/AndroidViewClient/AndroidViewClient/src/com/dtmilano/android/viewclient.py", line 988, in Parse
    parserStatus = parser.Parse(uiautomatorxml, 1)
  File "/home/allen/android/android-sdks/tools/lib/jython-standalone-2.5.4-rc1.jar/Lib/xml/parsers/expat.py", line 212, in Parse
xml.parsers.expat.ExpatError: Content is not allowed in prolog.

Do I need to install the ViewServer for this to work or did I forget to include the uiautomator backend when I built the image?
Answer: Try uiautomator from command line to find out if it's there or not:
$ adb shell uiautomator

if your output is similar to
Usage: uiautomator <subcommand> [options]

Available subcommands:

help: displays help message
...

then you have uiautomator installed. Otherwise if the output is
/system/bin/sh: uiautomator: not found

then you forgot to include it in the image.
You don't need ViewServer if UiAutomator is used as AndroidViewClient back-end.
Comment: Ok, thanks.  I actually got the second response from the shell.  How do i include it in the image?  When I checked the frameworks/testing/ folder, there was a folder for uiautomator so it looks like it was there.  But what doesn't make sense is why it wasn't enabled.
Comment: It turns out that the build i got from my company's servers was no good.  I synced with the AOSP Jellybean build from the Google website and uiautomator was there.


PHP session variables issue with IE only

Question: I have got an issue which I am 99% sure is related to Internet Explorer (no way!): session variables are not being carried from one file to another (on the same domain). The pages are served by IIS 7.
To simplify the problem-solving process I have created two test files:
test_1.php:
<?php
session_start();
$_SESSION['test'] = '123';
?>
Go to result

test_2.php:
<?php
session_start();
echo $_SESSION['test'];
session_unset();
?>
Go to page 1

This works as expected in Chrome 33.0.1750.154 and Firefox 28.0, but in IE9 I get the following error:
Notice: Undefined index: test in D:\test_2.php on line 3

Am I missing something obvious?
Thanks
Comment: Is your copy of IE blocking cookies?
Comment: make sure `session_id()` returns the SAME value in both scripts. If you get different values, then your session cookies are set incorrectly and you're getting a different session in each script.
Comment: cfr John Conde, a different browser settings (for cookies, security,...) is the only plausible explanation for this. When facing a client problem (difference depending on browser), always look in the client part. What's the client part of sessions ? cookies (most of the time)
Comment: The IDs are different (in IE only!), so that's a start. We are on a network and all computers (that we've tested) seem to be affected, so it may well be a cookie setting that needs setting globally. Do you have any idea what this might be? Thanks
Answer: I finally realised this issue was due to there being an underscore in the IIS virtual directory/application, with help from this answer.


Best way to handle progress HUD in multiple parallel async request in swift

Question: I am making multiple parallel async request to REST api in swift , I am using MBProgressHUD to display the spinner currently I am using variables to control multiple request but want to know best design pattern to handle spinner in multiple async requests
Answer: Keep a count of the APIs. In their respective completion block, decrement this count by 1. In every completion block check for the count. Remove the spinner when the count reaches 0.
Edit 1: You can use dispatch_group_async and dispatch_group_notify. Create group of requests with dispatch_group_async and dispatch_group_notify will notify you once all the requests are complete. Use this to hide your spinner/activity indicator.
Edit 2: Thanks @brandonscript for pointing this out.
 Dispatch group can be used as:
let dispatchGroup = dispatch_group_create()
    let dispatchQueue = dispatch_queue_create("com.test.proj", DISPATCH_QUEUE_CONCURRENT)

    dispatch_group_async(dispatchGroup, dispatchQueue, {
         print("In thread 1")
    })

    dispatch_group_async(dispatchGroup, dispatchQueue, {
        print("In thread 2")
    })

    dispatch_group_notify(dispatchGroup, dispatchQueue, {
        print("Dispatch group execution complete")
    })

Console Output: In thread 1
In thread 2
Dispatch notify complete
Comment: `dispatch_group` is definitely a more appropriate solution than manually maintaining a counter, but you should also need to explain how to use them, otherwise your answer reads more like a comment than an answer.


Change bindingPath based on Selection in sap.m.Select

Question: I am new to SAPUI5 and currently, I am trying to understand the meaning and the usage of bindingContext and context.
Let's assume that I have the following files:
Years.json
{
  "FiscalYear": [
    {
      "Jahr": 2017,
      "JahrID": 2017,
      "AEIst": 400,
      "AEPlan": 200,
      "UEIst": 300,
      "UEPlan": 200,
      "EBITIst": 300,
      "EBITPlan": 400,
      "Umsatzkategorie": [
        {
          "Umsatzkategorie": "ABC",
          "AE": 2
        },
        {
          "Umsatzkategorie": "DEF",
          "AE": 3
        },
        {
          "Umsatzkategorie": "GHI",
          "AE": 6
        },
        {
          "Umsatzkategorie": "XYZ",
          "AE": 8
        }
      ],
      "FiscalYearPeriod": [
        {
          "Monat": "JAN.2017",
          "AEIst": 14,
          "UEIst": 11
        },
        {
          "Monat": "FEB.2017",
          "AEIst": 12,
          "UEIst": 32
        },
        {
          "Monat": "MAR.2017",
          "AEIst": 15,
          "UEIst": 10
        },
        {
          "Monat": "APR.2017",
          "AEIst": 18,
          "UEIst": 9
        },
        {
          "Monat": "MAI.2017",
          "AEIst": 19,
          "UEIst": 5
        },
        {
          "Monat": "JUN.2017",
          "AEIst": 20,
          "UEIst": 12
        },
        {
          "Monat": "JUL.2017",
          "AEIst": 13,
          "UEIst": 14
        },
        {
          "Monat": "AUG.2017",
          "AEIst": 10,
          "UEIst": 13
        },
        {
          "Monat": "SEP.2017",
          "AEIst": 7,
          "UEIst": 15
        },
        {
          "Monat": "OKT.2017",
          "AEIst": 9,
          "UEIst": 18
        },
        {
          "Monat": "NOV.2017",
          "AEIst": 8,
          "UEIst": 7
        },
        {
          "Monat": "DEZ.2017",
          "AEIst": 34,
          "UEIst": 20
        }
      ]
    },
    {
      "Jahr": 2018,
      "JahrID": 2018,
      "AEIst": 400,
      "AEPlan": 20022222222222,
      "UEIst": 300,
      "UEPlan": 200,
      "EBITIst": 300,
      "EBITPlan": 400,
      "Umsatzkategorie": [
        {
          "Umsatzkategorie": "ABC",
          "AE": 2
        },
        {
          "Umsatzkategorie": "DEF",
          "AE": 3
        },
        {
          "Umsatzkategorie": "GHI",
          "AE": 6
        },
        {
          "Umsatzkategorie": "XYZ",
          "AE": 8
        }
      ],
      "FiscalYearPeriod": [
        {
          "Monat": "JAN.2017",
          "AEIst": 14,
          "UEIst": 11
        },
        {
          "Monat": "FEB.2017",
          "AEIst": 12,
          "UEIst": 32
        },
        {
          "Monat": "MAR.2017",
          "AEIst": 15,
          "UEIst": 10
        },
        {
          "Monat": "APR.2017",
          "AEIst": 18,
          "UEIst": 9
        },
        {
          "Monat": "MAI.2017",
          "AEIst": 19,
          "UEIst": 5
        },
        {
          "Monat": "JUN.2017",
          "AEIst": 20,
          "UEIst": 12
        },
        {
          "Monat": "JUL.2017",
          "AEIst": 13,
          "UEIst": 14
        },
        {
          "Monat": "AUG.2017",
          "AEIst": 10,
          "UEIst": 13
        },
        {
          "Monat": "SEP.2017",
          "AEIst": 7,
          "UEIst": 15
        },
        {
          "Monat": "OKT.2017",
          "AEIst": 9,
          "UEIst": 18
        },
        {
          "Monat": "NOV.2017",
          "AEIst": 8,
          "UEIst": 7
        },
        {
          "Monat": "DEZ.2017",
          "AEIst": 34,
          "UEIst": 20
        }
      ]
    }
  ]
}

View (just the part I want to change):
<Select id="theList" forceSelection="false" change="onListSelect" selectedKey="{years>/FiscalYear/1/JahrID}" width="auto" items="{
                            path: 'years>/FiscalYear',
                            sorter: { path: 'Jahr' }
                        }" class="sapUiResponsiveMargin">
          <core:Item key="{years>Jahr}" text="{years>JahrID}" />
        </Select>

//... some more stuff

<GenericTile class="sapUiTinyMarginBegin sapUiTinyMarginTop tileLayout" frameType="TwoByOne" id="idtile" header="Auftragseingang Gesamt" subheader="Aktuell in EUR" press="press">
    <TileContent footer="YTD">
        <content>
            <NumericContent scale="M" indicator="Down" value="{years>/FiscalYear/1/AEPlan}" valueColor="Error" />
        </content>
    </TileContent>
</GenericTile>

Controller:
onListSelect: function(oEvent) {
    var selectedItem = oEvent.getSource().getSelectedItem();
    var context = selectedItem.getBindingContext("years"); //trying to get the binding path
    console.log(context);
    var oTile = this.getView().byId("idtile");
    //pseudocode:
    //get relevant tile (oTile in this case) and change the binding path of the numeric content value to something else

    oTile.setBindingContext(new sap.ui.model.Context("years", "/years>/FiscalYear/1/AEPlan"));

},

What I want to achieve is the following case:
Based on the selected value of sap.m.Select I want to adjust the binding path for the mentioned tile.
For example: If its binded to the node 2017 and the users selects 2018 in the select control, the value of the numeric content of the tile should be adjusted to the relevant one from the node 2018.
https://flpportal-p1942326342trial.dispatcher.hanatrial.ondemand.com/sites/digidash#dashboard3602-Display
This is an example of what I want to achieve.
Actually I am struggling with the understanding of the bindingContext and bindingPath.
I would really appreciate it, if someone could provide me an example for the mentioned case. Hopefully this will provide a better understanding of that case.
Answer: You need to do ElementBinding, here the documentation

Tutorial theory
Tutorial demo

I made a snippet selecting a year from a table row here: bind values of specific array of a json model to a control in sapui5
you just need to do the same using the Select 'change' event
EDIT
Didn't try it, but I would change this:
onListSelect: function(oEvent) {
    var selectedItem = oEvent.getParameter('selectedItem');
    var sPath = selectedItem.getBindingContext("years").getPath(); //This path will include the index of your selected year (e.g. /FiscalYear/1/)
    this.getView().byId("idtile").bindElement("years>" + sPath);
}

On the other hand, if you want to do the element binding at the very begining without doing a selection yet and binding the hardcoded path '/FiscalYear/1/'. Just choose an event in the lifecicle and do elemenet binding with the hardcoded path. For example using onInit
onInit: function() {
    this.getView().byId("idtile").bindElement("years>/FiscalYear/1/");
}

And make the binding relative in the XML, so it completes the path binded by element binding:
<NumericContent scale="M" indicator="Down" value="{years>AEPlan}" valueColor="Error" />

Comment: I already tried to configure it with your snippet before I asked the question, the thing is that i am binding here to a path with an already specified index. Based on your snippet and the linked tutorial, I guess I know how it works for an ongoing aggregation binding, but I am confused about how to solve it with changing the index in the path.
And one more thing: what is getParameter function and especially the value "listItem" about?
Comment: Sorry, I just realized that you are the same user... The getParameter is a function available in the event object. you can see the parameters of each event in the documentation. for example [this is the docu](https://sapui5.hana.ondemand.com/#/api/sap.m.Select/events/change) for sap.m.Select 'change' event. As you can see you can retrieve 'selectedItem' from the event parameters. In the sap.m.List of the other example, the parameter was called 'listItem'
Comment: thanks for that clearance. Sometimes its really hard to understand the docu, maybe just from my perspective. I tried to adjust the settings you have mentioned (or better to say from the example) but the values on the tiles are not changing. could that be possible because of the static binding path? if yes, is there any way to solve that?
Comment: I've just edit my answer. Are you passing the model name when using "bindElement()" ?? Check it, because I think the 'getPath()' returns the path without the model name. I can't test it right now
Comment: iam directly trying this to tomorrow, i guess iam getting a better understanding of that whole thing right now. I owe you at least a beer Rafael! have a good night!
Comment: no problem!! I enjoy it and learn a lot while solving issues :)
Comment: thanks again, i made work. option 2 was the way to go for me. iam defining the binding path now in the controller for each of the controls and then I am able to switch the values by selecting a different item in the select-control. I owe you a beer! ;)


conditial else statements not running in three.js and raycaster

Question: I started to follow several YouTube tutorials for playing with three.js for beginners. I saw one of the examples create three spheres floating in space and to make them clickable.
So I followed the tutorial on how to setup a three.js scene and created 6 3d objects that are cylinders. What I wanted is that...
if you click on an object, the camera points and looks at the object and the camera also transitions physically in front of that object, so i can display text or something there. Once there I'll restrict controls until the user clicks on the object where a tween will take them back to the original position and orientation.
I tried to have the logic be that if you click on object 1 && you haven't clicked on it before then go towards and look at it, else if you click on object 1 && if it HAD been clicked, then the camera will tween in reverse and orient back towards the origin... if else you click on object 2 && you haven't clicked on it before then go towards and look at it, else if you click on object 2 && if it HAD been clicked....... and so on and so on until both scenarios for each object is accounted for. I saw the tutorial do this on one object by creating a boolean variable to set the status to either have been or have not been clicked. I tried to incorporate that into my code but I think the problem is that the Javascript system is not marking or retaining the information that changes the variable to one or the other....it could be a syntax error, it could be that the approach i am taking isn't even possible (unknown unknowns), or a simple typo.
Once I made them 5 separate If statements then I was able to see each of the tweens go toward the object as I wanted but none of the tweens respond to the part that checks if they have already been clicked and to tween the camera back to the center.
here is my code with one of the 5 objects for reference....
<code>//ONE OF THE OBJECTS FOR REFERENCE
const minigeometry1 = new THREE.CylinderGeometry(5, 5, 0.5, 50);
const minimaterial1 = new THREE.MeshStandardMaterial({ color: 0xffff00 });
const minicylinder1 = new THREE.Mesh(minigeometry1, minimaterial1);
minicylinder1.name = 'minicylinder1';
minicylinder1.position.z = 7.5;
minicylinder1.position.x = -28
minicylinder1.rotation.z = Math.PI / 2;
scene.add(minicylinder1);

//CLICK EVENT ANIMATIONS
//CAMERA MOVEMENT TWEEN FUNCTION//
function tweenCamera(finalPosition, tweenSpeed) {
    let initialPosition = new THREE.Vector3(camera.position.x, camera.position.y, camera.position.z);
    new TWEEN.Tween(initialPosition)
        .to(finalPosition, tweenSpeed)
        .onUpdate(() => {
            camera.position.set(initialPosition.x, initialPosition.y, initialPosition.z);
        })
        .easing(TWEEN.Easing.Cubic.Out)
        .start();
}

//WHERE THE CAMERA IS CURRENTLY LOOKING, I THINK
let currentTarget = new THREE.Vector3();
currentTarget.set(controls.target.x, controls.target.y, controls.target.z);

let originTarget =  new THREE.Vector3();
originTarget.set(0,0,0);

//TELLS CAMERA TO ORIENT TOWARD SPECIFIED OBJECT (target controls = camera orientation?)
let minicylinder1Target = new THREE.Vector3();
minicylinder1Target.set(minicylinder1.position.x, minicylinder1.position.y, minicylinder1.position.z);

let minicylinder2Target = new THREE.Vector3();
minicylinder2Target.set(minicylinder2.position.x, minicylinder2.position.y, minicylinder2.position.z);

let minicylinder3Target = new THREE.Vector3();
minicylinder3Target.set(minicylinder3.position.x, minicylinder3.position.y, minicylinder3.position.z);

let minicylinder4Target = new THREE.Vector3();
minicylinder4Target.set(minicylinder4.position.x, minicylinder4.position.y, minicylinder4.position.z);

let minicylinder5Target = new THREE.Vector3();
minicylinder5Target.set(minicylinder4.position.x, minicylinder5.position.y, minicylinder5.position.z);

//RAYCASTER SETUP AND CLICK EVENT FUNCTION
const raycaster = new THREE.Raycaster();
const mouse = new THREE.Vector2();

function onClick(event) {
    //Normalized mouse coordinates (-1, +1)
    mouse.x = (event.offsetX / window.innerWidth) * 2 - 1;
    mouse.y = -(event.clientY / window.innerHeight) * 2 + 1;

    raycaster.setFromCamera(mouse, camera);

    const intersects = raycaster.intersectObjects(scene.children, true);

    //THIS DETERMINES WHETHER WE HAVE CLICKED ON AN OBJECT OR NOT
    let coin1Clicked = false;
    let coin2Clicked = false;
    let coin3Clicked = false;
    let coin4Clicked = false;
    let coin5Clicked = false;

    //IF WE CLICK ON COIN1 FROM THE MAIN POSITION, WE WILL ZOOM INTO IT
    if ((getIndexInIntersectsArray(minicylinder1, intersects) > -1) && !coin1Clicked) {
        //TWEEN TO ORIENT CAMERA TOWARDS COIN1
        new TWEEN.Tween(currentTarget)
            .to(minicylinder1Target, 2500)
            .onUpdate(function() {
                controls.target = currentTarget;
            })
            .easing(TWEEN.Easing.Quartic.InOut)
            .start()
        coin1Clicked = true;
        //RESTRICT CAMERA ROTATION AND ZOOM OUT
        tweenCamera(new THREE.Vector3(minicylinder1.position.x, minicylinder1.position.y, 25), 2500)
        return coin1Clicked;
    } else if ((getIndexInIntersectsArray(minicylinder1, intersects) > -1) && coin1Clicked) {
        //TWEEN TO ORIENT CAMERA TOWARDS COIN1
        new TWEEN.Tween(currentTarget)
            .to(originTarget, 2500)
          .onUpdate(function() {
                controls.target = currentTarget;
            })
            .easing(TWEEN.Easing.Quartic.InOut)
            .start()
        coin1Clicked = false;
        tweenCamera(new THREE.Vector3(origPos.position.x, origPos.position.y, origPos.position.z), 2500);
        return coin1Clicked;
    }

    if ((getIndexInIntersectsArray(minicylinder2, intersects) > -1) && !coin2Clicked) {
        //TWEEN TO ORIENT CAMERA TOWARDS COIN1
        new TWEEN.Tween(currentTarget)
            .to(minicylinder2Target, 2500)
            .onUpdate(function() {
                controls.target = currentTarget;
            })
            .easing(TWEEN.Easing.Quartic.InOut)
            .start()
        coin2Clicked = true;
        //RESTRICT CAMERA ROTATION AND ZOOM OUT
        tweenCamera(new THREE.Vector3(minicylinder2.position.x, minicylinder2.position.y, 25), 2500)
        return coin2Clicked;
    }
    if ((getIndexInIntersectsArray(minicylinder3, intersects) > -1) && !coin3Clicked) {
        //TWEEN TO ORIENT CAMERA TOWARDS COIN1
        new TWEEN.Tween(currentTarget)
            .to(minicylinder3Target, 2500)
            .onUpdate(function() {
                controls.target = currentTarget;
            })
            .easing(TWEEN.Easing.Quartic.InOut)
            .start()
        coin3Clicked = true;
        //RESTRICT CAMERA ROTATION AND ZOOM OUT
        tweenCamera(new THREE.Vector3(minicylinder3.position.x, minicylinder3.position.y, 25), 2500)
        return coin3Clicked;
    }
    if ((getIndexInIntersectsArray(minicylinder4, intersects) > -1) && !coin4Clicked) {
        //TWEEN TO ORIENT CAMERA TOWARDS COIN1
        new TWEEN.Tween(currentTarget)
            .to(minicylinder4Target, 2500)
            .onUpdate(function() {
                controls.target = currentTarget;
            })
            .easing(TWEEN.Easing.Quartic.InOut)
            .start()
        coin4Clicked = true;
        //RESTRICT CAMERA ROTATION AND ZOOM OUT
        tweenCamera(new THREE.Vector3(minicylinder4.position.x, minicylinder4.position.y, 25), 2500)
        return coin4Clicked;
    }
    if ((getIndexInIntersectsArray(minicylinder5, intersects) > -1) && !coin5Clicked) {
        //TWEEN TO ORIENT CAMERA TOWARDS COIN1
        new TWEEN.Tween(currentTarget)
            .to(minicylinder5Target, 2500)
            .onUpdate(function() {
                controls.target = currentTarget;
            })
            .easing(TWEEN.Easing.Quartic.InOut)
            .start()
        coin5Clicked = true;
        //RESTRICT CAMERA ROTATION AND ZOOM OUT
        tweenCamera(new THREE.Vector3(minicylinder5.position.x, minicylinder5.position.y, 25), 2500)
        return coin5Clicked;
    }

}
function getIndexInIntersectsArray(elem, array) {
    var ind = -1;
    for (var i = 0; i < array.length; i++) {
        if (array[i].object.name == elem.name) {
            ind = i;
        }
    }
    return ind;
}

window.addEventListener("click", (event) => {
    onClick(event);
})

var animate = function() {
    requestAnimationFrame(animate);
    cylinder.rotation.y += 0.025;
    minicylinder1.rotation.y += 0.025;
    minicylinder2.rotation.y += 0.025;
    minicylinder3.rotation.y += 0.025;
    minicylinder4.rotation.y += 0.025;
    minicylinder5.rotation.y += 0.025;
    controls.update();
    render();
    TWEEN.update();

};

function render() {
    renderer.render(scene, camera);
}

animate();
</code>
Could anyone share any insight please? Pretty please?
Thanks in advance!
P.S. if you feel my code is inefficient...I'm sure it is, I think i can use switch statements but i don't know how to do that yet as this is the FIRST project I've ever done so I have nothing to compare it with.
Answer: Note to self: after testing where the break in the flow of....processing/displaying? (I can't think of an appropriate word), by printing messages to the console to see what was/wasn't happening like I wanted, I realized that I had to put the
let coin1Clicked = false;
.
.
.
let coin5Clicked = false;
code OUTSIDE my onClick function. I don't know why though since I thought I was making them local variables (vs global variables) which shouldn't have been an issue, at least I thought. Once I made them global variables, the if...else statements are working! On to GSAP!


Rails: For each 3 records do

Question: I'm currently learning rails. I'm trying to figure out the following:
<% @obj.{For each 3 records} do |records| %>

<%end %>

How would I implement this "for each 3 records"?
What am I trying to do? I would like to display data in 3 columns. Therefore I'm using a table. Each record is a table data (). After each 3 record I would need to print a

.
Many thanks for your help
Answer: You can use each_slice and pass 3 as argument:
<% @obj.each_slice(3) do |records| %>
  <%= records %>
<% end %>

You can add what you need to be printed at the end of each group, something like:
[1,2,3,4,5,6,7,8,9].each_slice(3) do |element|
  puts "#{element} group end"
end
# "[1, 2, 3] group end"
# "[4, 5, 6] group end"
# "[7, 8, 9] group end"

Answer: Do you want to repeat three times? like, maybe:
<% 3.times do %>
  ....
  #using @obj.record
  ...
<%end %>

Answer: You can use in_groups_of for array like:
[1 2 3 4 5 6 7 8 9 10].in_groups_of(3, false) do |group|
  puts group
end

# [1, 2, 3]
# [4, 5, 6]
# [7, 8, 9]
# [10]

Answer: I think you're looking for find_in_batches or possibly in_batches.
In your controller, you might do something like:
@foos = Foo.where(some: :condition)

Then in your view:
<% @foos.in_batches(of: 3) do |foos_relation| %>
  ... do something with your relation of three foos
<% end %>

Rails: For each 3 records do


not able to run java native access for libhydro.dll

Question: I am trying to load libhydro.dll using java native access.I kept the LibHydro.dll which is a 32 bit in C:\Windows\SysWOW64 My system is a 64 **bit windows 10 machine.I tried to register the dll but i am getting error as
Make sure the library is stored at the specified path or debug it to check for problems with the binary or dependent dll files.The specified module could not be run.
When i try to run my program it is throwing error as
C:\JNI_project>javac New.java

C:\JNI_project>java New
Exception in thread "main" java.lang.UnsatisfiedLinkError: Unable to load library 'LibHydro': The specified module could not be found.

        at com.sun.jna.NativeLibrary.loadLibrary(NativeLibrary.java:163)
        at com.sun.jna.NativeLibrary.getInstance(NativeLibrary.java:236)
        at com.sun.jna.Library$Handler.<init>(Library.java:140)
        at com.sun.jna.Native.loadLibrary(Native.java:379)
        at com.sun.jna.Native.loadLibrary(Native.java:364)
        at New.main(New.java:10)

My program is
 import com.sun.jna.Library;
import com.sun.jna.Native;

/** Simple example of Windows native library declaration and usage. */
public class New{
   public interface LibHydro extends Library {

   }
   public static void main(String[] args) {
    LibHydro lib = (LibHydro) Native.loadLibrary("LibHydro",
           LibHydro.class);

   }
}

please guide me.
Comment: See if this helps, http://stackoverflow.com/questions/14286647/trying-to-use-dll-from-java-jna-unable-to-load-library-exception
Answer: You must use a 32-bit JRE if your library is 32-bit. This is a restriction imposed by the WoW64 system (the link says, in part, 32-bit applications ... that plug into the process space of components that are implemented purely as 64-bit processes (e.g. Windows Explorer) cannot be executed on a 64-bit platform). The 64-bit JRE is purely a 64-bit process.
Addintionally, your library should be on the PATH for Windows (on Unix like systems you can use LD_LIBRARY_PATH), or you can use a script and something like -Djava.library.path=/somewhere on both.
Comment: In libhydro site it is written as ::- NOTE: This DLL must be located in c:\temp\MBlibHydro in order for MBlibHydro.dll to locate it.  The location can be changed by altering the function path names in mLibHydro.bas in the source code of MBlibHydro.DLL. does it mean i have to get MBlibhydro.dll and store it in some folder in my system for the working of LibHydro.dll
Comment: In libhydro site it is written as ::- NOTE: This DLL must be located in c:\temp\MBlibHydro in order for MBlibHydro.dll to locate it. The location can be changed by altering the function path names in mLibHydro.bas in the source code of MBlibHydro.DLL. does it mean i have to get MBlibhydro.dll and store it in some folder in my system for the working of LibHydro.dll
Comment: Is `MBlibHydro.DLL` an additional DLL that needs loading?
Answer: You need to tell JNA where to load the library.  JNA can usually find it if it's on PATH, but for libraries intended to be loaded by JNA directly you should set the system property jna.library.path to include all paths to your DLLs.


Give an example of a cover for $\Bbb R$ (with the standard topology) that's infinite, but locally finite.

Question:
A collection $\{A_j\}_{j \in J}$ of subsets of a topological space $X$ is locally finite if for every $x \in X$, there exists a neighborhood $U_x$ for which $U_x \cap A_j \ne \emptyset$ for finitely many $j$. Give an example of an cover for $\Bbb R$ (with the standard topology) that's infinite, but locally finite.

I'm not sure if I understand what they're asking here. It seems that they want me to construct some cover $\{A_j\}$ for which $\Bbb R \subset \bigcup_{j} A_j$ and now for every $x \in \Bbb R$ I should be able to find a neighborhood $U_x$ for which $U_x$ meets $A_j$ for $j \in \{1, \dots n\}$? How should I approach this?
Answer: It's kind of the opposite. They want a cover that every point has a neighborhood that only intersects with finitely many elements of your cover.   For $\mathbb{R}$,  this is pretty trivial,  just take any cover of overlapping intervals that only overlap with one other interval on either side.   For instance,  take intervals of width 1, moving back and forth every .5,   so intervals of the form $(.5n,.5n+1), n\in \mathbb{Z}$.   You can see that any point in the reals has an open neighborhood that only intersects at most 2 of these.
Answer: Take, for instance $\{(n-1,n+1)\mid n\in\Bbb Z\}$. Can you show that it is locally finite?
Comment: Okay, width 2 marching by 1s is simpler than width 1 marching by 1/2s :)
Comment: @Alan It's simpler to write, but it's the same idea.
Comment: Picking $x \in \Bbb R$ I have that any nbhd $U_x$ meets some of the elements of the cover you described. Intuitively it seems that there is only couple of intervals that meet $U_x$, but I am not sure how to argue this mathematically.
Comment: @JimingLe Specify the radius of a ball around $x$ that's small enough to get you the result you want.  For any $x$ you only need to find one suitable neighborhood so just construct a neighborhood $U_x$ that works.
Comment: Wouldn't $(x-\frac12, x+ \frac12)$ work just fine? It seems to me that pretty much any $(x-\varepsilon, x+\varepsilon)$ would work?
Comment: Yes, any open interval centered at $x$ will work.

Give an example of a cover for $\Bbb R$ (with the standard topology) that’s infinite, but locally finite.


Deleting All Partitions From the Command Line

Question: How do you delete all partitions on a device from the command line on Linux (specifically Ubuntu)? I tried looking at fdisk, but it presents an interactive prompt. I'm looking for a single command, which I can give a device path (e.g. /dev/sda) and it'll delete the ext4, linux-swap, and whatever other partitions it finds. Essentially, this would be the same thing as if I were to open GParted, and manually select and delete all partitions. This seems fairly simple, but unfortunately, I haven't been able to find anything through Google.
Answer: The wipefs program lets you easily delete the partition-table signature:
wipefs -a /dev/sda

From man wipefs

wipefs can erase filesystem, raid or partition-table signatures (magic
  strings) from the specified device to make the signatures invisible
  for libblkid.
wipefs does not erase the filesystem itself nor any other data from
  the device.  When used  without  any  options,  wipefs  lists  all
  visible filesystems and the offsets of their basic signatures.
wipefs  calls  the BLKRRPART ioctl when it has erased a
  partition-table signature to inform the kernel about the change.
Answer: Would this suffice?
dd if=/dev/zero of=/dev/sda bs=512 count=1 conv=notrunc

Comment: This will not delete the partitions. By deleting the partitions he meant to preserve the MBR and just empty the partition table.
Comment: No, this appears to do exactly what I need. I don't really care if the data is still there. GParted shows that the partitions are gone after running this, and that's what I wanted.
Comment: Don't forget to unmount the driver, otherwise it won't work.
Comment: Is the `conv=notrunc` option really needed? See [here](https://stackoverflow.com/a/20531600/1582182).
Comment: To be fair, he said delete the partitions, not the partition table or data, so it wasn't really clear. But I think we knew he just wanted the parts not to register, which makes this the correct answer.  To delete the data would be uneccesary.  IF you want to zero it, thats a different story, that's deleting the data too.
Comment: @jrh : No.  This only zeroes (`count=1`) 1 block of (`bs=512`) 512 bytes (starting at the first block of the device).  (It also won't truncate the output file, but the output target is a block device, so this seems [to do nothing](https://stackoverflow.com/a/20531600/478891)).
Comment: Mircea Vutcovici wasn't talking about your data, but about the bootstrap code in your MBR.  That's now gone, because you've erased it along with the 4 primary entries from the MBR-style partition table.
Comment: This also works great if you've used ZFS on a drive and are repurposing it for something else.  Neither a standard Windows or Linux partitioning and format will get rid of the ZFS labels on it which can cause you major problems.
Comment: Does this try and fill the entirety of the /dev/sda disk with zeros? That sounds pretty time consuming if /dev/sda is large, I'm just looking to put a new filesystem on it, there's nothing secure on it that I want to erase.
Comment: This works for MBR, but not modern GPT.  GPT is bigger and also has a backup table at the end of the disk.
Answer: Quick and Dirty: use gparted to delete the partitions, or if you're in a hurry:
dd if=/dev/zero of=/dev/[disk device] bs=512 count=1

This will zap the MBR of the drive (Data is still intact).
Alternatively:
dd if=/dev/zero of=/dev/[disk device]

to wipe the whole drive (write a single pass of zeros over everything. Not "secure" but usually good enough), or use a "disk shredder" tool for a secure wipe.
Comment: why is the second "not secure"?
Comment: Not secure because it's possible that the disk's contents could be partially recovered by someone with physical access to it. A secure wipe writes multiple passes of random data over the whole disk.
Answer: Use improved non-interactive version of fdisk, which is sfdisk
To erase partition table use this command:
sfdisk --delete /dev/sda

Note: no confirmation will be thrown, the partitions will be deleted instantly and forever!
Comment: fair point, added
Comment: I think it's worth making it clear that after running this command there won't be any confirmation prompts whatsoever, the partition will be deleted instantly.
Answer: See man sfdisk, which is a non-interactive variant of fdisk. Other than that, you can delete the whole partition table with dd, as pk wrote.
Answer: You should be able to use parted for this aswell, although that may involve some scripting to loop through the partitions.
Comment: It may be worth to mention that e.g. `parted /dev/mmcblk0 --script mklabel gpt` deletes all existing partitions. For me it was `parted /dev/mmcblk0 --script mklabel msdos`
Answer: If we're talking about MBR-style partitions...
dd if=/dev/zero of=/dev/[disk device] bs=1 count=64 seek=446 conv=notrunc

Explanation:

dd

This standard command copies bytes from a source and writes them to a destination. It's the simplest flexible tool for this job.

if=/dev/zero

Here, we specify that we're reading from /dev/zero, which is a special device which emits NUL bytes--zeros.

of=/dev/[disk device]

Here, we specify which device we're writing to.

bs=1

dd thinks in terms of blocks. The default block size may be 512 bytes, 1024 bytes or 4096 bytes, depending on your system. However, we need to address things more precisely than that, so we tell dd to use a block size of 1 byte.

count=64

Here, we tell dd to write 64 blocks (or bytes, because of our bs=1 parameter), since the primary partition table consists of 4 16-byte partition entries, for a total of 64 bytes.

seek=446

The primary partition table within the MBR (so, not talking about GPT here) is located 446 bytes in, so we instruct dd to seek 446 bytes in before writing.
Extended partitions are generally created by using a primary partition slot to point at the extended partition table, so if we erase the 4 primary partitions, we effectively wipe the extended partition table as well; the OS won't be able to find it, so it won't be able to read and interpret it. (If you want to wipe the extended partition table, you'll need to know more about the operating system; different operating systems do extended partitions in different ways.)
Answer: I wanted to do the same thing (except in Slackware 14.2) but found I could not effect most of the solutions proposed here, with the most elaborate and well-documented solution creating new problems for making replacement partitions.  That deleted the partition but some partitioning software apparently found the partition backups automatically.
I found f3probe (http://oss.digirati.com.br/f3) solved the problem of deleting all the partitions, quickly and easily, working with large capacity drives, and created exactly 1 partition spanning the whole drive, which was easy to delete.
It was also easy, from there to create new partitions, in a straight-forward way.
i.e.
f3probe --destructive --time-ops /dev/sdb
# Now we know only 1 partition exists on /dev/sdb
#    which is /dev/sdb1
#
# Unmount that partition
umount /dev/sdb1

#
# Delete that single partition
parted /dev/sdb rm 1

#
# Now you can create new partitions
# i.e. parted /dev/sdb mkpart primary fat32 1049K 15.8G
#
# Update /etc/fstab before rebooting....

Answer: Using gparted from petalinux on EMMC for me it was
parted /dev/mmcblk0 --script mklabel msdos

Here the corresponding help output
# parted /dev/mmcblk0 --script help mklabel
  mklabel,mktable LABEL-TYPE               create a new disklabel[ 6897.473870]  mmcblk0:
 (partition table)

        LABEL-TYPE is one of: aix, amiga, bsd, dvh, gpt, mac, msdos, pc98, sun, loop

BTW: concerning wipefs -a /dev/sda (and maybe some other solutions here)
Using this made commands like parted /dev/mmcblk0 --script mkpart primary fat32    1MiB 2049MiB for me to fail with Error: /dev/mmcblk0: unrecognised disk label. The mklabel command of gparted is 'repairing' this condition resp. seems to be a good preparation for follwing steps.
See also
https://unix.stackexchange.com/questions/200582/scripteable-gpt-partitions-using-parted


Não consigo utilizar char '&' Qt Creator

Question: Estou tentando retornar uma QString, que sera usada como uma URL e preciso usar '&' como um separador na URL. Porém, quando o caracter é colocado na QString, ele faz uma quebra na URL e o que deveria aparecer após o '&' não aparece.
retorno = "start http://localhost:5000/robo/?Nome="+nome+"&Capital="+capital;

No caso, 'nome' e 'capital' são QStrings declaradas anteriormente. Já tentei declarar um QChar com o código ASCII do '&' e tenho o mesmo erro.
Comment: Não consigo ver problema, pode ser em algo onde está usando a variável. Um [mcve] seria útil.
Comment: independente do problema do &, provavelmente seria melhos no seu caso usar os recursos da própria Qt (ou mesmo nativos do OS) para iniciar um processo, em vez do "start".
Comment: O retorno é enviado ao sistema da seguinte maneira
system(retorno.toStdString().c_str());
Comment: será que não é problema de interação com o console? Provavelmente eu nem faria isso
Answer: Isso ocorre porque o & (E comercial - ampersand) é usado pelo sistema para separar dois comandos em uma mesma linha, é um caractere "especial", assim como pipe (|) e os paranteses (( e )), e todos podem ser escapdos com ^
No entanto se esta usando Qt, ele já tem funções prontas para isto, que evita você ter que ter este trabalho de ficar escapando os caracteres, por exemplo:
Usando QProcess
Usando QProcess com QStringList você pode passar os argumentos e o próprio "Qt" vai escapar eles pra ti:
retorno = "http://localhost:5000/robo/?Nome="+nome+"&Capital="+capital;

QProcess process;
process.start("start", QStringList() << retorno);

O que provavelmente já deve resolver, no entanto é interessante notar que o próprio Qt tem uma classe chamada QDesktopServices
Usando QDesktopServices
Que já tem o objetivo de interagir com funções do sistema operacional, ou seja se você portar o seu programa para Linux ou OSX não vai precisar mudar nada nesta parte (vai depender do que mais você fez), exemplo com openUrl (QUrl é necessário):
retorno = "http://localhost:5000/robo/?Nome="+nome+"&Capital="+capital;

QDesktopServices::openUrl(QUrl(retorno));

Pronto, assim ele vai buscar o programa do sistema que esta associado ao protocolo da URL, no caso HTTP provavelmente irá abrir o navegador padrão e também não vai precisar de "escapes" (como o ^).
Answer: O problema estava no caracter '&' que era passado para o console. Coloquei '^' antes de cada '&' da QString e o console entendeu como um caracter ao invés de um comando.
Comment: O caractere `&` tem um significado especial no Qt. Ele é usado para indicar teclas de atalho e controlar os focos dos botoes,


Comparing Regression Coefficients from a "log-log" to an Alternative De-meaning Procedure

Question: Consider two regression models:
$log(y_i) = \log(x_i)\alpha + \epsilon_i \,\,\,\,\,$      (Model 1),
$log(y_i) = (\frac{x_i}{\overline{x}})\beta + \varepsilon_i \,\,\,\,\,\,\,\,$      (Model 2),
where $\overline{x}$ is the sample average of $x_i$.
Both of these models transform the variable $x_i$, the first with a log, the second by dividing by the sample average.
In short, why aren't $\alpha$ and $\beta$ equal?
I am confused because, it is my understanding that:
$\alpha = \frac{\partial \log(y)}{\partial \log(x)} = \frac{\partial \log(y)}{\partial y}\frac{\partial y}{\partial x} \frac{\partial x}{\partial \log(x)} = \frac{\partial y}{\partial x}\frac{x}{y}$
and
$\beta = \frac{\partial \log(y)}{\partial (\frac{x_i}{\overline{x}})} = \frac{\partial \log(y)}{\partial y}\frac{\partial y}{\partial x} \frac{\partial x}{\partial (\frac{x_i}{\overline{x}})} = \frac{\partial y}{\partial x}\frac{x}{y}$
However, in simulations, these two regression coefficients do not exactly equal each other. Is there an approximation going on somewhere in my definitions that I am ignoring? Is there some kind of small-sample bias that is relevant in practice that is missed here?
Comment: You probably need to provide either code from which the simulation can be read or a detailed description of the simulation. Personally I get very similar estimates. If you make a first order Taylor approximation of the log function around $\bar x$ then you get $\log(x) \approx \log(\bar x) + (x-\bar x)/\bar x$ this identity can be used to go from model 1 to model 2. $\log(y) = \lambda + \log(x)\alpha + u$ becomes $\log(y) = \lambda + [\log(\bar x) + (x-\bar x)/\bar x]\alpha + u$ which becomes $\log(y) = (\lambda + \log(\bar x)\alpha - \alpha) + (x/\bar x)\alpha + u$.
Comment: IF you include a constant the OLS estimates of the coefficients of $(x/\bar x)$ and $\log(x)$ should not change that much.
Comment: This is very helpful. And I get very similar estimates as well but they are not exact. Is there a way to "undo" the Taylor approximation in order to write $\alpha$ as a function of $\beta$?
Comment: I do not think so.
Answer: You made a small mistake when taking the derivative of Model 2.
$$log(y) = \Bigl(\frac{x_i}{\bar{x}}\Bigr)\beta + e_i$$
If you are differentiating with respect to $x_i$ then $\bar{x}$ and $\beta$ are treated as constants exactly the same way if you were differentiating $x*5*2$, the derivative of which would be just 10. Therefore:
$$\frac{1}{y}\frac{dy}{dx_i}= \frac{\beta}{\bar{x}}$$
$$\beta =\frac{dy}{dx_i}\frac{\bar{x}}{y} $$
And hence the two are not equal.
On an intuitive level you can think, that since the original two models apply different transformations to the $x$ variable it is logical that the OLS parameters $\alpha$ in Model 1 and $\beta$ in Model 2 will give different results.
On another important note, if you are trying to estimate the regression coefficient, you are differentiating the wrong functions with respect to the wrong variables. The OLS regression estimates regression coefficients by minimizing the sum of squared residual, and hence the funciton that you need to take the derivative of is:
$$\sum_{i=1}^{n}{\hat{u}_i}^2 = \sum_{i=1}^{n}{(y_i - \hat{y}_i)^2} =\sum_{i=1}^{n}{(y_i-\hat{\beta}x_i)^2} $$
You can see the full derivation of the estimation here:
https://are.berkeley.edu/courses/EEP118/current/derive_ols.pdf
For a multivariate case where you have many different variables such that $y = \beta_1 x_1 + \beta_2 x_2 + \beta_3 x_3 ... +e$ see this:
https://pdfs.semanticscholar.org/7aa9/77cea941df656739bf428a73cb62da6c0e74.pdf


How does Amazon choose first party skills for Alexa

Question: Amazon refers to skills created by developers as "Third Party Skills". From what I understand there are also "First Party Skills' that don't require a specific invocation name but are built in. Spotify is an example, you can ask your Alexa to play music and it can use Spotify. I have been unable to find any documentation on first part skills or lists of first party skills does anyone have a list or any experience with how to partner or create first party skills?
Comment: How is this a specific programming related question? It's at best a request for off-site resources, which is off-topic here.
Answer: Basically when you refer to first party skills you are discussing built-in functionality, common things like localized time, weather, ect., as well as partnered up skills. Here is an article from 12/17 https://arstechnica.com/gadgets/2017/12/guidemaster-everything-amazons-alexa-can-do-plus-the-best-skills-to-enable/ certainly not complete, however it is a list.
As far as how you would develop first party skills, either get a position on the Alexa development team or work for a global large company that can provide Alexa an additional native skill that it doesn't currently possess. My guess would be the more sure way is working for Amazon.
Now what you didn't ask about is the ability to develop a third party skill and in the absence of a built-in way to respond to a users request, Amazon has created CanFulfillIntents which will provide your provided responses without the user having to envoke your skill. documentation here: https://developer.amazon.com/docs/custom-skills/request-types-reference.html


DDEV php/twig error "Unknown "link_attributes" filter."

Question: So I'm trying to setup a local environment with ddev for the first time. I got it running, cloned my live files with git and imported my DB.
Site ain't working and got this in the log : "PHP message: Uncaught PHP Exception Twig\Error\SyntaxError: "Unknown "link_attributes" filter." at /var/www/html/web/themes/customs/myTheme/templates/menu--main.html.twig
Any pointer how to fix that ? I did :

ddev exec drush en link_attributes
-> [notice] Already enabled: link_attributes

This site with the same file/db is working on 2 VPS. What's going on ?
Comment: You probably want to install `twig_link_attributes`, see https://www.drupal.org/project/twig_link_attributes
Comment: Yeah I just realized that it's not from the module link_attributes but twig_link_attributes... When I scrolled the module list, I saw link_attributes and checked it was enabled and downloaded. Damn filter named the same as another module D:

Thx mate !

** It din't download cause it's a git submodule... Gonna fix that.
Answer: It was an module identification problem. I thought it was the link_attributes modules but the error is from twig_link_attributes. That one didn't download cause it's a git submodule or something... Anyway that folder is empty.


knockoutjs click binding not working in nested foreach

Question: So i have a really weird problem with a knockoutjs click binding not getting attached to anchor tags. Other data-bind="" works but not the click binding.
Below you can see the HTML and part of the viewmodel js file
var tag = function (data) {
    this.count = data.Count;
    this.id = data.Id;
    this.title = data.Title;
    this.tagGroup = data.TagGroup;
};
 var tagContainer = function (data) {
    this.tagList = $.map(data.Tags, function (item) { return new tag(item); });
    this.letter = ko.observable(data.Letter);
};

var searchViewModel = function(){
   var self = this;

   self.tagContainerList = ko.observableArray([]);

   self.addFilter = function (tag) {
    //move tag to active filters and do some more cool stuff here
    };

};

      ×

Basically it is a modal popup and its loaded when user clicks a link on the page.
I send a request to server and it returns me a list of Tag Containers each have the starting Letter and a list of tags to be rendered below the letter like this:
A
 a word 1
 a word 2
B
 b word 1
 b word 2
C
 c word 1
 c word 2
and so on...
The letters are rendered correctly A,B,C and each gets the correct tag list rendered below them with text:title displaying correctly.
Everything works except the addFilter(); function that i want to bind to each link in the taglist. The browser just jumps up and adds a hash character to the url. Firebug is not showing any errors on bindings either.
The reason the div container has a with:searchViewModel is because there is a master viewmodel for the whole page. But this should not matter since it is working on every other page of the project.
The only thing i can think of is that the click binding $root.addFilter is wrong but i tried just addFilter where firebug gives the error "addFilter is not defined;"
And i tried both $parent and $root.
Does anyone have any suggestions?
Comment: Would you explain how you solved it, I would highly appreciate it.
Answer: One thought I've had. Your addFilter function expects a parameter (tag) but you are not passing it anything in the binding:

Could this be the problem?
Maybe something along the lines of:

would help?
Comment: It does unfortunately not work getting $parent.addFilter is not a function  tried with $root aswell. But it did give me an idea, i will try some things with that approach.
Comment: Still no luck, i am using the click:addFilter in other parts of the page where you can add search filters and the $data is usually not required if you are for example calling a function when iterating through an observable array
Comment: Sorry to hear that. You say that "Firebug is not showing any errors on bindings either." This would imply your addFilter function is getting called otherwise an error would be raised. Have you tried putting a breakpoint on the addFilter function (I find Chrome very good for debugging knockout) and see if there problem lies inside the function? I suggest you inspect what is being passed in the tag parameter and see if that is the problem.
Comment: No binding errors in firebug, thats what usually helps me find the errors but this time its just quiet :(  The click binding is never attached to the anchor tag since not even the preventDefault behaviour is run, meaning the browser tries to navigate to #
Comment: I'm stuck then, Kimpo. Either time to add a jsFiddle to your question or maybe another SO user will step up. Sorry!
Comment: Thanks for the tip, i will try to reproduce it in jsfiddle
Comment: ok, got it working now. it was actually the outer viewmodel messing up things. so i could not refer to the child viewmodel from the nested foreach.... ehhh .ye that made sense :) well it is working anyways
Comment: i will still give you credit Mark even though it wasnt direct answer. The discussion got my brain working again which led me to find the problem :D cheers!
Comment: That's very kind, Kimpo. Thanks. And more importantly, glad you got it working.
Answer: I ran into something similar and at first I ran data-bind="click:function() { console.log($parents) }". Note that its $parents not $parent. I looked to find the context, and the one I needed looked something like data-bind="click:$parents[1].onCardClick"
Comment: Xerri offered a very viable solution, I was stuck in exactly the same situation and it solved my problem. only change i made was to put parentheses data-bind="click:$parents[1].onCardClick() and it worked as charm.
Comment: This was my issue also, a click binding inside a nested foreach loop wouldn't work with $parent.onCardClick and also wouldn't work with $root.onCardClick (it said root undefined). This is a great solution.
Answer: I found in ko context and try to use sample like below.
$parentContext.$parent.onButtonClick


How to access MongoDB atlas through https API?

Question: Since I've been migrated to Mongodb Atlas I got an cors error.
The only URL I found on my mongodb dashboard was mongodb+srv://<username>:<password>@cluster0.cnh0m.mongodb.net/myFirstDatabase
Here is my code :

getClap = async () => {
    try {
        const res = await axios.get(`mongodb+srv://...`)
        console.log(res.data);
    } catch (err) console.error(err);
};

Is there any way to connect mongodb directly with axios like before with mlab ? Using an HTTPS address ?
Answer: I found the answer reading the mlab documentation.

Q. Does Atlas have a Data API?
If you are using the mLab Data API note that MongoDB Atlas does not
have a data API. However, we have open-sourced the mLab Data API and
made it easy for you to self-host the mLab Data API on Heroku.
Once you have re-configured your application to use your self-hosted
mLab Data API, you'll be able to migrate your mLab-hosted deployments
to MongoDB Atlas.

source link


Load Balanceing IIS Server Is Always Sticky for 60 seconds

Question: I have a load balancer setup with two server farms behind it, one has 3 Apache servers on Linux and the other has 2 IIS servers. I configured 2 virtual services on the load balancer identically, one pointing to each farm and set to do round robin balancing with no persistence. The Apache servers work just as expected, but the IIS servers stick the session for 60 seconds before sending the next request to the next server.
To demonstrate this I simply created an HTML page that shows the server name. When I go to the virtual address presented by the load balancer, I see server 1, 2, 3, 1, 2, 3, etc when I press refresh on the Apache servers. However when I go to the virtual address pointing to the IIS servers when I press refresh I am still on the same server. If I wait 60 seconds then refresh I am directed to the other IIS server.
The current load balancer that I am using is from Kemp Technologies. However, before I setup the Kemp I saw the exact same behavior when using HAproxy. Therefore this seems to be a Windows issue on the back end server somehow, instead of the load balancer. However I don't really understand how this is possible since it should be the load balancer determining which backend server will service the request.
Has anyone else seen this type of behavior? Is there something that I can modify to allow my Windows servers to be balanced in a true round robin fashion?
EDIT --
The test pages on the IIS systems run a server side ASP script to insert the current date/time with a simple ASP script <%=now()%>. This allows me to see that the pages are not being cached and are being dynamically regenerated on each request. These pages also contain the IIS host name so I can tell which IIS server actually generated the rendered page.
Comment: You're not using NLB or ARR with IIX 7.x are you? By default and on its own, IIS pretty much can't do what you're seeing. It almost definitely has to be coming from your LB config, default behavior, or something else in the environment.
Comment: I am not using NLB. These test servers are stand alone.
Comment: Have you tried posting this question to Kemp's forums, or asking their support? This might be a quirk of their configs, that most folks on SF wouldn't know about. I haven't been much of a networks guy, I just know my apps have always been behind F5 or Cisco or sometimes Citrix.
Answer: Yeah, your intuition is right -- it's really not possible for IIS to be causing this issue, as those devices have no control over where the requests get routed.
Are you certain that your browser isn't simply caching the page, with the next request going to the other server properly and getting a 304 (not modified) response?
In other words - are you using a method other than what your browser displays to verify where the requests are going?
Comment: I should have specified this in the original post - sorry. The short answer is yes I am sure that the request is being fulfilled. I have simple classic ASP page with a <%=now()%> parameter that will display the time that the page was rendered on the server. On each refresh I can see the time updated so I know that nothing is being cached.
Comment: In testing other load balancers this problem has not been observed.
Answer: Comparative network tracing is your best bet to prove/disprove this, and to generate theories about why.
Simplest thought: IIS might have keep-alives enabled and Apache not (or simply closing the connection each time, whatever the mechanism)...