Using display: table to center a modal on the page?

Question: I tried this which I found as a suggestion here on SO:

                xxx

This does not seem to center the modal at all. Can anyone tell me what I might be doing wrong?
Update:  Horizontal position is now fixed by using display: inline-block for the id modal
Comment: text-align:center only works for inline content. So div#modal has to be display:inline-block;
Comment: Thanks. This corrected the horizontal centering. But vertically it's still not in the middle. Any ideas?
Answer: Apply display: inline-block; to the div with id modal.

                xxx

And apply this CSS:
html, body {
    margin: 0;
    padding: 0;
    width: 100%;
    height: 100%;
}

See this working fiddle: http://jsfiddle.net/8uhbh6jz/
Answer: Add display:table-cell to modal div

            xxx


nginx: [emerg] "worker_processes" directive is not allowed here in /etc/nginx/conf.d/default.conf:1 in angular 15?

Question: Iam facing with this error,
nginx: [emerg] "worker_processes" directive is not allowed here in /etc/nginx/conf.d/default.conf:1
Docker File:
FROM artifactorycloud.ual.com/v-docker/node:16 AS builder
WORKDIR /app
COPY package*.json ./
RUN npm install
COPY . .
RUN npm run build --configuration=development
FROM artifactorycloud.ual.com/v-docker/nginx:alpine
COPY --from=builder /app/dist /usr/share/nginx/html
# Copy the nginx conf that we created to the container
COPY ./nginx.conf  /etc/nginx/nginx.conf
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]

This is my nginx.conf file:
Updated config file
server {
listen 80;
server_name  localhost;
        root   /usr/share/nginx/html;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

        gzip on;
        gzip_min_length 1000;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        location / {
            try_files $uri $uri/ /index.html;
        }

        location /ui/health {
            access_log off;
            add_header 'Content-Type' 'text/plain';
            return 200 "Healthy\n";
        }
    }

Original nginx.conf
worker_processes  1;

events {
    worker_connections  1024;
}

http {
    server {
        listen 80;
        server_name  localhost;

        root   /usr/share/nginx/html;
        index  index.html index.htm;
        include /etc/nginx/mime.types;

        gzip on;
        gzip_min_length 1000;
        gzip_proxied expired no-cache no-store private auth;
        gzip_types text/plain text/css application/json application/javascript application/x-javascript text/xml application/xml application/xml+rss text/javascript;

        location / {
            try_files $uri $uri/ /index.html;
        }

        location /ui/health {
            access_log off;
            add_header 'Content-Type' 'text/plain';
            return 200 "Healthy\n";
        }
    }
}

can anybody help me on that where i am wrong?
Answer: This is in fact not your main nginx.conf file, but a configuration file for your (or one of your) websites.
The main configuration file which accepts the worker_process directive is under /etc/nginx/nginx.conf.
Your http and events directives will also not work under /etc/nginx/conf.d/default.conf.
The default nginx.conf file already has these directives inside, and worker processes is set to auto:
worker_processes  auto;

Delete http, events and worker_processes from your website config file, and tweak those settings inside your main nginx.conf file.
Comment: i have updated my  nginx.conf file according to your suggestion can you please check its correct or not?
Comment: You should update your question in such a way that other people see the original configuration, so that they can see what is wrong.
You should delete the directives in your default.conf file, not in your main nginx.conf file ...
And you can test your nginx configuration with `nginx -t` without having to restart/reload.
Comment: I have only 1 nginx.conf file in my project as well as not able to test nginx configuration due to some security issue in VDI
Comment: There's the main configuration file at  /etc/nginx/nginx.conf, and there's the website configuration file at  /etc/nginx/conf.d/default.conf. You're mixing these 2.
Comment: I have followed below tutorial for implmenting-https://www.arunyadav.in/blogs/post/19/create-an-angular-app-and-deploy-using-in-nginx-and-docker
Comment: I have updated docker file also previously i have used same etc/nginx/conf.d/default.conf   in my docker file but in above post location is changed as well as can you tell me where file localted -default.conf file not located in my project folder
Comment: I dont know how your /etc/nginx/conf.d/default.conf  gets into docker container. If you didnn't add it, it's probably in the nginx image already.
First, revert your nginx.conf back to original, rebuild your image, and see if nginx works.
Comment: thanks for the update
Comment: My above error is fixed but in the logs I got new error-getrlimit(RLIMIT_NOFILE)" can you tell me how to fix this error
Comment: That's seems like another question altogether ... if the above answer helped you, upvote and accept it, and post a new question.


Is there a way to add content templates for blog

Question: I've been asked to add templates (where a blog post is pre-created with certain content) and the user simply selects it and make minor changes. Please note this is not a visual template, but a content one.
Thanks!
Comment: if you are asking about the content type then, make node tpl for that content type.
Answer: Go to Manage fields
Ex: <code>/admin/structure/types/manage/article/fields</code>
Then click on edit, for example, the body field. Look for Default Value and put whatever you want there.
Now when a user tries to add a new article, it will have the body pre-filled-out and they can change it if they wish.
Comment: Would it be possible to have more than one? For instance, a template for each occasion?
Comment: you would then need to create a content type for each occasion.
Answer: You can theme template by content type. You need to create a node--blog.tpl.php
and write your code in here. Check out this link for more info.
https://www.drupal.org/node/17565
Comment: Thanks mate, but that's not what I meant. What I want is, when the user adds a new blog post for instance, when the user hits create content, the blog will be pre-populated with some content and the user will only update this content. Does that make sense?
Comment: Ok. I suggest you may use the hook_form_alter then for your content type form and prepopulate the fields based on the logged in userid or from his profile fields. You may refer this answer [here](http://drupal.stackexchange.com/questions/10496/how-to-pre-populate-fields-on-a-node-creation-form-based-on-fields-from-profile2)
Comment: That'd roughly what I'm looking for but I'd prefer something that the user can edit the templates (no code knowledge required sort of thing)


How do I see the contents of Qt objects QByteArray during debugging?

Question: My program use some variables of type QByteArray to contain data (bytes). That bytes maybe are special characters like '\0', 1, ... So I cannot see all elements after special character when debugging. If I use std::vector, I can see all elements. I must use QByteArray but I cannot see all element of this variable when debugging. Help me, plz!
Thanks!
Example: QByteArray bytes(4, '\0');
Now, if debug, I just see "". But I want to see "'\0', '\0', '\0', '\0'" or something like like this.
I also have the same problem with QDateTime. But I resolved by this help: http://www.qtcentre.org/threads/32336-View-QDate-and-QDateTime-in-VisualStudio-debugger
This link may help but this not resolve my problem: http://qt-project.org/wiki/IDE-debug-helpers
Example:
QByteArray ba("Hello"); //debuging, see: ba = "Hello"
ba.append('\0');
ba.append("a message"); //we just see: ba = "Hello"

Comment: ba.replace( "\0", "\\0" ) if it's just about 0 bytes. ba.toHex() is generally useful for chars that cannot be printed.
Comment: @FrankOsterfeld: no, it maybe any character
Comment: @aviit What other characters are giving you difficulties?
Answer: I contribute here a piece of code I had to write since I could not find any method doing something close to that: display a QByteArray as a meaningful QString in a way python would do it: ascii is kept as this, special char are displayed as hexadecimal code.
If someone knows a better way ! (here it's QT 4.6)
QString toDebug(const QByteArray & line) {

    QString s;
    uchar c;

    for ( int i=0 ; i < line.size() ; i++ ){
        c = line[i];
        if ( c >= 0x20 and c <= 126 ) {
            s.append(c);
        } else {
            s.append(QString("<%1>").arg(c, 2, 16, QChar('0')));
        }
    }
    return s;
}

Such as:
QByteArray a;
a.append("et");
a.append('\0');
a.append("voilà");
qDebug() << toDebug(QByteArray(a));

returns:
"et<00>voil<e0>"

Answer: For debugging, you can convert QBytearray to QString and see the output.
For example:
QByteArray bArray;

QString str = "";

str.append(bArray);

QDebug() << str ; // this will display the content in your console/application output  window

hope this will resolve your issue.
Comment: The result is same, because QString cannot view all character that after first unprintable character.
My mean is to debug in IDE (Visual Studio 2010).
Comment: I think i got it, its a problem with '\0' this, instead you try using '\\0'. because single slash is used as command, thus '\0' means Null character in linux.
Please give it a try. I faced this problem many time.


Understanding how to use COM in Python

Question: I'm attempting to implement the equivalent of a VB program in python using COM. Here are the relevant lines from the VB program:
eConCall = New Microsoft.Dynamics.GP.eConnect.eConnectMethods
eConCall.eConnect_EntryPoint(sConnectionString, EnumTypes.ConnectionStringType.SqlClient, myXmlDocument, EnumTypes.SchemaValidationType.None)

In Python, I'm doing:
import win32com.client
eConCall = win32com.client.Dispatch("Microsoft.Dynamics.GP.eConnect.eConnectMethods")

but eConCall doesn't have a eConnect_EntryPoint method. In fact it doesn't seem to have any methods:
eConCall = win32com.client.gencache.EnsureDispatch("Microsoft.Dynamics.GP.eConnect.eConnectMethods")
dir(eConCall)

Prints:
['CLSID', '_ApplyTypes_', '__doc__', '__eq__', '__getattr__',
'__init__', '__module__', '__ne__', '__repr__', '__setattr__',
'_get_good_object_', '_get_good_single_object_', '_oleobj_',
'_prop_map_get_', '_prop_map_put_', 'coclass_clsid']

I'm pretty sure I'm misunderstanding how Dispatch should be used and how I should be getting access to eConnectMethods in Python. Can a kind soul help me out? How would I get a hold of an instance of eConnectMethods such that I can call eConnect_EntryPoint on it?
Comment: it might be helpful to attach the contents of python wrapper generated by makepy (located `gen_py`)
Answer: I think, you don't see any methods as you've got the so called late-binding, which means that whatever you try to invoke is checked at runtime via standard COM IDispatch interface and while you work with valid methods/properties - it just works. Or you get runtime error otherwise, quite like in VBScript.
Seems that your task is not that easy for late-binding trial&error, maybe you'd want to check an option of early-binding - check this link - http://oreilly.com/catalog/pythonwin32/chapter/ch12.html.
I would also suggest you to try some simpler COM examples, that will help you feel comfortable with the usage of IDispatch in Python, i.e. by checking more simple Excel or Word automation samples available online.
Update Ok, I missed that you already tried to create early-bound wrapper. Take a look at result of the makepy.py (somewhere in \Lib\site-packages\win32com\gen_py\.py) and compare it with IDL of the COM server. Maybe the method is still available through late-binding, though it didn't make it for some reason into the wrapper..
Answer: You should consider comtypes which allow low level access of COM

Understanding how to use COM in Python


Does convergence affect probability?

Question: A biased coin is tossed. The probability of heads turning up is 0.51.
Suppose you keep tossing the coin multiple times and keep a track record of the number of heads/tails. The moment you get more heads than tails, you stop tossing the coin.
Mathematically, can we safely say that for all series of coin tosses, the ultimate result is that more heads have turned up and hence the probability of more heads turning up ultimately is tosses is 1?
Comment: In this kind of rigged experiment, yes.
Answer: This question is related to the well-studied problem of random walks.
If we let $X_n$ be the difference between the number of heads seen in the first $n$ tosses and the number of tails seen in the first $n$ tosses,
positive if there are more heads than tails and negative if there are more tails than heads,
and set $X_0 = 0,$
then the sequence of variables $X_0, X_1, X_2, \ldots$
form a random walk over the integers with a $0.51$ chance of moving one place to the right on each move and a $0.49$ chance of moving to the left.
The question is (in effect) asking whether this random walk will eventually reach the value $K_k = 1$ (for some $k$) with probability $1.$
The answer is yes.
A less obvious fact is that the answer is still "yes" even if we replace the biased coin with a fair coin.
Comment: IIRC you are right about $0.49.$ Looking up "random walk" would be a way to start exploring.
Comment: thanks a lot.would the answer be still yes if the probability was 0.49. I think no.
What is the name of this topic(random walks ??).I would really love to deep dig into it.
Answer: Just to complement on the answers given, this actually follows from the Law of Big Numbers: for our example, we have a collection of Bernoulli trials $$X_1,\ldots ,X_m$$ with $X_i\in\{0,1\}$ (1 for heads and 0 for tails) and such that $\mu_i=E(X_i)=0.51$ for each $i$. If we define $$\hat X_m=\frac{1}{m}\,\sum_{i=1}^m\,X_i$$ then, following the (Weak) Law of Big Numbers, we will have that $$\lim_{m\to\infty}\,P(|\hat{X}_m-\mu|\le\epsilon)=1$$ for all $\epsilon>0$. The Strong Law of Big Numbers goes a bit further and claims that $$P(\lim_{m\to \infty}\hat{X}_m=\mu)=1$$
Thus, it's not only that we would always be able to toss the coin enough times so that the number of heads (1's) were bigger than the number of tails (0's) but that we can theoretically keep tossing the coin to get as close as desired to 0.51 as the ratio of heads over total tosses.

Does convergence affect probability?


LDA topic modelling improvement

Question: I am working on an LDA model to identify the topic of ~100,000 online courses based on their course descriptions and titles. In the further process, I would like to use these topics to cluster these courses. So far, the topics identified by our model have not been great and I am looking for ways to improve - and get to get some thoughts on my attempts for improvement. Here is a quick summary of our current - pretty standard - approach as well as some ideas that I have for improvement:
1.Merging title, subtitle, and course description
2.Removing descriptions on length < 100 words, and non-english descriptions
For training, I am using only longer descriptions in English. Of course this means that courses with non-English descriptions will be classified randomly.

Pick a random 30,000 descriptions

The number is somewhat arbitrary. I have noticed that the topics are more "clear" when using less descriptions for training. However, we don't want our topics to be biased based on the random descriptions that were chosen in this step.

Removing stopwords

Both self-defined and using library.

Removing punctuation
Lemmatizing words
Removing words that appear in over 50% of documents

To identify reoccurring topics I ran the model multiple times in a for loop and printed the resulting topics. Based on the topic-overlap of those iterations, I am considering to add Wikipedia articles related to the reoccurring topics and add them to the descriptions we use for training. This way I am hoping to "strengthen" those topics in the training data and make them more clear - in the hope of getting more interpretable topics. Currently, I am adding around 150 Wikipedia articles to a corpus of 30,000 course descriptions and the results seem to be promising.
My main question is: Is the approach of adding pre-selected wikipedia articles into our training data valid? What are the implications of this?
I am aware that by using this approach, I'm "pushing" the model in the direction of topics that we saw in initial runs - however, I believe that training on this data set will lead to a better/more interpretable classification of course descriptions.
What are your thoughts?
Answer: Using Wikipedia articles for your data augmentation sounds like quite reasonable for your task. I have worked on online course data (although not for LDA) and used similar approach. But using only 150 Wikipedia articles sounds like not enough to me. Wikipedia's API is well established and therefore obtaining a much larger Wikipedia corpus is possible with a little effort.
In our research, we represent courses using category labels from relevant Wikipedia articles, and "relevant" here is defined by top-100 in cosine similarity between a Wikipedia article and a course description. For our task of learning a concept graph, we found this approach to perform the best comparing to other representation schemes. If you are interested in details please look at here.
For topic modelling, you might actually benefit more from Wikipedia articles because their titles often serve as either pretty good topic labels, or as anchor words.

LDA topic modelling improvement


Why my while loop in c++ wont run correctly?

Question: I am just a newbie to programming and I was trying to write a while loop that runs as long as the input (num) is not a integer which doesn't ends with zero. What happen is when I enter a number that ends with zero, the program runs the loop correctly, but when i enter something nonsense such as rofl the program only print The input is not valid. and won't repeat the loop. I have tried to look for solutions but I am still stuck after a hour. Anyone can help me here? Thx so much!
void rev_sum() {
    int num;
    int a = 1;
    while (a < 2) {
        cout << "Please input a natural number without zero at the end:\n";
        cin >> num;
        if (!cin) {
            cout << "The input is not valid.\n";
            cin.clear();
            cin.ignore(INT_MAX);
        }
        if (num % 10 == 0) {
            cout << "The number cannot have zero at the end\n";
        } else {
            cout << "gj\n";
            break;
        }
    }
}

Comment: Please consider accepting an answer from below (if anything solved your issue from below) so that people facing the same issue can quickly find it.
Answer: Try replacing
cin.ignore(INT_MAX);

With
cin.ignore(numeric_limits<streamsize>::max(), '\n');

And change the
if (num % 10 == 0)

To
else if (num % 10 == 0)

Your final code should look like this:
void rev_sum() {
    int num;
    int a = 1;
    while (a < 2) {
        cout << "Please input a natural number without zero at the end:\n";
        cin >> num;
        if (!cin) {
            cout << "The input is not valid.\n";
            cin.clear();
            cin.ignore(numeric_limits<streamsize>::max(), '\n');
        }
        else if (num % 10 == 0) {
            cout << "The number cannot have zero at the end\n";
        } else {
            cout << "gj\n";
            break;
        }
    }
}

Comment: This worked perfectly!thank you<3 Also thank everyone who have helped~
Answer: if (num % 10 == 0) {

could be
else if (num % 10 == 0) {

otherwise the other else case might get executed
Answer: You set a = 1 at the start of the loop and then never change a which means the only way to leave your while loop is if you hit the break statement.  If your loop is not looping then it must be stuck somewhere. I'm unfamiliar with the statements if (!cin) and cin.ignore(...) so those are top suspects to check (or change). The statement cin >> num; completes no matter what they type so you can check to see what 'num' is equal to when you enter "rofl". Then after it fails, you still use num so you are processing this unintentional entry.  You can add continue; after cin.ignore(...) to jump back to the top of the while loop and ask the question again. You can also print something after the while loop in order to know when you get out.
With all that said, I would never trust the user to enter acceptable information and I would never trust cin to process it for me.  Personally, I would read cin as a string using cin.getline(buffer, buffer_size); And then I would complain to the user if they filled the buffer or gave me something that was not an integer (which you can check with a function like scanf()). Then you can spit back exactly what they gave you and you can be specific about your complaint.
Answer: cin.ignore(numeric_limits<streamsize>::max())

Answer: Would it not make more sense to only check that the number ends in 0 if the input was valid....
void rev_sum() {
    int num;
    int a = 1;
    while (a < 2) {
        cout << "Please input a natural number without zero at the end:\n";
        cin >> num;
        if (!cin) {
            cout << "The input is not valid.\n";
            cin.clear();
            cin.ignore(INT_MAX);
        } else {
            if (num % 10 == 0) {
                cout << "The number cannot have zero at the end\n";
            } else {
                cout << "gj\n";
                break;
            }
        }
    }
}


CentOS 7 Forward port to another IP:PORT

Question: I have CentOS 7 that uses IPTABLES for Forwarding port 30120 to windows server
For example :
Windows games server IP: 192.168.1.3
Linux Centos 7 server IP : 192.168.1.5
iptables -t nat -A PREROUTING -p tcp --dport 30120 -j DNAT --to-destination 192.168.1.3:30120

iptables -t nat -A POSTROUTING -p tcp -d 192.168.1.3 --dport 30120 -j SNAT --to-source 192.168.1.5

iptables -t nat -A PREROUTING -p udp --dport 30120 -j DNAT --to-destination 192.168.1.3:30120

iptables -t nat -A POSTROUTING -p udp -d 192.168.1.3 --dport 30120 -j SNAT --to-source 192.168.1.5

and I have rules to anti DDOS and secure SSH but it's not work with forward
still forwarding traffic from my Centos to 192.168.1.3:30120
My PC IP: 192.168.1.2
Have used for test in CentOS
iptables -A INPUT -s 192.168.1.2 -j DROP

This IP 192.168.1.2 can't access to CentOS 7 but can forwarding to windows server by port 30120
How it's blocked?
thank you.
Comment: In CentOS 7, you probably should be using `firewall-cmd` instead of `iptables`
Comment: In reference to @fpmurphy, at least you ought to make sure that you have firewalld disabled, stopped and masked and the iptables service started or else firewalld will overwrite your iptables rules.
Firewalld is the default frontend to iptables in centos7. It will not tolerate you adding iptables rules by yourself unless disabled.
Answer: The order of the rules matters, so if the port forwarding rules are before the DROP rule, those take precedence and only other traffic is dropped. If you want to drop all traffic, move the DROP line above the port forwarding lines.
Comment: They aren't even in the same chain.
Answer: The general syntax is:
firewall-cmd --add-forward-port=port=port-number:proto=tcp|udp:toport=port-number:toaddr=IP/mask

firewall-cmd --zone=public --add-masquerade --permanent

Case-specific example:
firewall-cmd --zone=public --add-forward-port=port=30120:proto=tcp:toport=30120:toaddr=192.168.1.100
  --permanent


Building an SSL server farm

Question: I'm interested in building the the architecture in the article referenced below.
I currently have a modestly-priced layer-4 load balancer and my application servers are the SSL endpoints.
I want to put an SSL server farm in between my load balancer and my app servers.
Then I will put another inexpensive load balancer between the SSL farm and my app servers, to do layer-7 routing.

My web application has a fairly high amount of consumer traffic, that 6 servers can handle at about 50% capacity. Additionally, I have infrastructure traffic that is several orders of magnitude heavier than my consumer traffic. This is data coming in from all over the world that must integrate with my web application in real time. In total I have 18 app servers to handle all the traffic, plus 6 database servers.  I will be adding 6 more app servers over the next 2 weeks and another 6 the 2 weeks after that. Conservatively, I estimate I will need to scale to 120 servers by the end of the year.
My motivation right now is to separate the consumer traffic from the infrastructure traffic. The consumer traffic is higher priority than the infrastructure traffic and I cannot allow a stampede on the infrastructure side to take down my consumer-facing servers. Having a website that is always up is the top priority. However if there is a failure in one of the consumer app servers, I want to route that traffic to the servers designated for infrastructure traffic.
The complication is that all the traffic is addressed using the same hostname and is nearly 100% https. The only way in my case to distinguish infrastructure from consumer traffic is by URL (poor architecture I inherited), so I need a layer 7 load balancer to be able to route. However for that to work I need either a fancy hardware-based SSL terminator or an SSL server farm as described above.  Because my user base is rapidly scaling, I worry that if I go down the hardware path it will become very expensive very fast, especially since I will need 4 of everything for high availability (2 identical setups in 2 facilities).  Meanwhile, the above diagram seems very flexible and more horizontally scalable.
Has anyone built this before? Are there pre-built configurations? What considerations should I make and what software should I use (I've heard of people using apache with mod-ssl, nginx, and stunnel)? Also, when does it make sense to buy an expensive load balancer vs building an SSL server farm?
http://1wt.eu/articles/2006_lb/index_05.html
Comment: Many people have built these before. But a better question is - why do you? You've mentioned cheap equipment, clusters and the wrong software all in the same question - so its hard to get a handle on what scale you are operating at. Why do you need an SSL unwrapping cluster? What is the purpose of your set-up? More details please ...
Comment: @sonassi added details, hope they help. I'm interested in getting your input!
Answer: For a 120 server cluster, consult a professional. I wouldn't have thought you will get an answer of significant enough detail for your application.
The most complex clustered configuration we have set up was only 20 servers, of which only 12% was HTTPS traffic (14Mbit pure SSL).
Our typical architecture is ...
If it helps, for web clusters, we typically use:
lvs (initial ssl load balancing)
    -> pound (ssl-unwrapping)
    -> varnish (caching)
    -> haproxy (load balancing)
    -> nginx (static content)
    -> php (dynamic content)
    -> mysql (db)

We had used stunnel in combination with HAProxy (in place of Pound), but it was causing some complications (with the inability to set headers) further down the chain.
Pound
We use this and it works extremely well, so much so that we were unable to push it to its limitations on the hardware we have and volume of traffic being pushed through Apache jMeter during testing.
There's also a note on the homepage of pound regarding performance improvements

If the PCRE, tcmalloc (from the Google perftools package) and/or Hoard are available Pound will link against them. This will provide a significant performance boost and is highly recommended.

But pound is regarded to be good for 'low' traffic applications, but doesn't seem to scale as well as its rivals, which others have documented in benchmarking tests
Software SSL terminators Benchmarks

http://vincent.bernat.im/en/blog/2011-ssl-benchmark-round2.html
http://vincent.bernat.im/en/blog/2011-ssl-benchmark.html
http://barry.wordpress.com/2008/04/28/load-balancer-update/

CPU usage is likely to be the key issue
CPU consumption is going to be your biggest issue, so being smart with the SSL key size is going to help, 1024bit (now deprecated by most SSL authorities) vs 2048bit vs 3072bit keys will increase overheads linearly.
Here's some good reading on general SSL performance, http://www.imperialviolet.org/2010/06/25/overclocking-ssl.html
What you will ultimately find here is that there is no 'right' answer and that only testing, testing again, then testing some more will show you what works best in your scenario.
Comment: This might also be of relevance: http://zombe.es/post/5183420528/accelerated-ssl
Answer: You can split the infrastructure from consumer traffic by using a Linux firewall. Using the netfilter/iptables string match functionality you can match the traffic based on the url. After the traffic is matched you can use this to perform QoS or forward the traffic differently.

Building an SSL server farm


Good C header style

Question: My C headers usually resemble the following style to avoid multiple inclusion:
#ifndef <FILENAME>_H
#define <FILENAME>_H

// define public data structures / prototypes, macros etc.

#endif  /* !<FILENAME>_H */

However, in his Notes on Programming in C, Rob Pike makes the following argument about header files:

There's a little dance involving #ifdef's that can prevent a file being read twice, but it's usually done wrong in practice - the #ifdef's are in the file itself, not the file that includes it.  The result is often thousands of needless lines of code passing through the lexical analyzer, which is (in good compilers) the most expensive phase.

On the one hand, Pike is the only programmer I actually admire. On the other hand, putting several #ifdefs in multiple source files instead of putting one #ifdef in a single header file feels needlessly awkward.
What is the best way to handle the problem of multiple inclusion?
Answer: In my opinion, use the method that requires less of your time (which likely means putting the #ifdefs in the header files).  I don't really mind if the compiler has to work harder if my resulting code is cleaner.  If, perhaps, you are working on a multi-million line code base that you constantly have to fully rebuild, maybe the extra savings is worth it.  But in most cases, I suspect that the extra cost is not usually noticeable.
Comment: I find this answer very useful. Funny thing is that I agree in a more ironic way: if the computer can do my job, why I'll do it? ;)
Answer: Keep doing what you do - It's clear, less bug-prone, and well known by compiler writers, so not as inefficient as it maybe was a decade or two ago.
You could use the non-standard #pragma once - If you search, there's probably at least a bookshelf's worth of include guards vs pragma once discussion, so I'm not going to recommend one over the other.
Comment: @R..: it claims to do so - http://gcc.gnu.org/onlinedocs/cppinternals/Guard-Macros.html. However, there are some restrictions that it uses to ensure the optimization is valid, and there could be false negatives where the restrictions are broken, but nevertheless the optimization would be valid in that case.
Comment: @R. It still doesn't? I'd have thought every major compiler would have this a decade ago. Then again, reading a file twice isn't really the resource hog it was in 89 when Pike wrote those notes.
Comment: Reading it twice is a resource hog. Just a single syscall takes more time, on modern machines, than parsing a small header file.
Comment: If gcc didn't suck, it would detect the standard idiom the first time the header was included, remember the filename, and ignore all future requests to include that filename. This is purely a case of compiler laziness.
Answer: Pike wrote some more about it in https://talks.golang.org/2012/splash.article:

In 1984, a compilation of ps.c, the source to the Unix ps command, was
  observed to #include <sys/stat.h> 37 times by the time all the
  preprocessing had been done. Even though the contents are discarded 36
  times while doing so, most C implementations would open the file, read
  it, and scan it all 37 times. Without great cleverness, in fact, that
  behavior is required by the potentially complex macro semantics of the
  C preprocessor.

Compilers have become quite clever since: https://gcc.gnu.org/onlinedocs/cppinternals/Guard-Macros.html, so this is less of an issue now.

The construction of a single C++ binary at Google can open and read
  hundreds of individual header files tens of thousands of times. In
  2007, build engineers at Google instrumented the compilation of a
  major Google binary. The file contained about two thousand files that,
  if simply concatenated together, totaled 4.2 megabytes. By the time
  the #includes had been expanded, over 8 gigabytes were being delivered
  to the input of the compiler, a blow-up of 2000 bytes for every C++
  source byte.
As another data point, in 2003 Google's build system was moved from a
  single Makefile to a per-directory design with better-managed, more
  explicit dependencies. A typical binary shrank about 40% in file size,
  just from having more accurate dependencies recorded. Even so, the
  properties of C++ (or C for that matter) make it impractical to verify
  those dependencies automatically, and today we still do not have an
  accurate understanding of the dependency requirements of large Google
  C++ binaries.

The point about binary sizes is still relevant. Compilers (linkers) are quite conservative regarding stripping unused symbols. How to remove unused C/C++ symbols with GCC and ld?

In Plan 9, header files were forbidden from containing further
  #include clauses; all #includes were required to be in the top-level C file. This required some discipline, of course—the programmer was
  required to list the necessary dependencies exactly once, in the
  correct order—but documentation helped and in practice it worked very
  well.

This is a possible solution. Another possiblity is to have a tool that manages the includes for you, for example MakeDeps.
There is also unity builds, sometimes called SCU, single compilation unit builds. There are tools to help manage that, like https://github.com/sakra/cotire
Using a build system that optimizes for the speed of incremental compilation can be advantageous too. I am talking about Google's Bazel and similar. It does not protect you from a change in a header file that is included in a large number of other files, though.
Finally, there is a proposal for C++ modules in the works, great stuff https://groups.google.com/a/isocpp.org/forum/#!forum/modules. See also What exactly are C++ modules?
Comment: As seen in the first paragraph in your second quote, in as late as 2007 the problem is still prominent. If only more recent benchmarks are available.
Comment: According to https://web.archive.org/web/20021218032155/http://gcc.gnu.org/onlinedocs/cppinternals/Guard-Macros.html, GCC could do the Multiple-Include Optimization already in late 2002. I wonder what compiler was Google using  using in 2007.
Answer: The way you're currently doing it is the common way. Pike's method cuts a bit on compilation time, but with modern compilers probably not very much (when Pike wrote his notes, compilers weren't optimizer-bound), it clutters modules and its bug-prone.
You could still cut on multi-inclusion by not including headers from headers, but instead documenting them with "include <foodefs.h> before including this header."
Answer: I recommend you put them in the source-file itself. No need to complain about some thousand needless parsed lines of code with actual PCs.
Additionally - it is far more work and source if you check every single header in every source-file that includes the header.
And you would have to handle your header-files different from default- and other third-party-headers.
Answer: He may have had an argument the time he was writing this. Nowadays decent compilers are clever enough to handle this well.
Comment: @R., Hm, reference, no I don't have. I read that not too long time ago here on SO though, that include guards are treated by gcc equivalent to `#pragma once`. And BTW the lexical parsing of `#ifdef` to first see what of a file has to be parsed for real should not be too difficult, no? In any case, I never found for me that *this* was a bottleneck when compiling large code. I often do precompilation with `-E` to see what the preprocessing phase produces and this is not measurable by human eye.
Answer: I agree with your approach - as others have commented, its clearer, self-documenting, and lower maintenance.
My theory on why Rob Pike might have suggested his approach: He's talking about C, not C++.
In C++, if you have a lot of classes and you are declaring each one in its own header file, then you'll have a lot of header files. C doesn't really provide this kind of fine-grained structure (I don't recall seeing many single-struct C header files), and .h/.c file-pairs tend to be larger and contain something like a module or a subsystem. So, fewer header files. In that scenario Rob Pike's approach might work. But I don't see it as suitable for non-trivial C++ programs.

Good C header style


How to publish multiple messages at once (batch processing) using Google Cloud PubSub's console

Question: I could successfully publish one message at a time on Google Cloud Pubsub using the console, and the result shows up in a table in BigQuery.
{"ID": 123, "Item1": "aaa", "Item2": "bbb"}

BigQuery Table:
| ID | Item1 | Item2 |
| 123 | aaa | bbb |
How can I publish multiple messages at once through the console? I tried the following code but it didn't work.
[{"ID": 123, "Item1": "aaa", "Item2": "bbb"}, {"ID": 123, "Item1": "aaa", "Item2": "bbb"}, {"ID": 123, "Item1": "aaa", "Item2": "bbb"}]

This is for a demo so I only want to use the console. Thank you!
Comment: I would like to point out that I changed the IDs in the messages, so they are not duplicates.      [{ "ID": 123, "Item1": "aaa", "Item2": "bbb"},  { "ID": 456, "Item1": "aaa", "Item2": "bbb"},  { "ID": 789, "Item1": "aaa", "Item2": "bbb"}]

Thank you!
Answer: Using the GCP console you can only publish one test message at a time.  If you want to publish a group of messages, you could write a custom application.  However, perhaps an easier story is to use the GCP SDK with the gcloud command.
See gcloud pubsub topics publish
You could script the execution of this command to run it once per message.
Remember that from the GCP Console, you can also have a Cloud Shell instance from which you can run the gcloud command.
Comment: Thank you very much!  We do have a custom app - this is for demo purpose. Seems like to can't publish multiple messages then.
Comment: Howdy my friend.  To the very best of my knowledge, the Cloud Console allows us to publish one message at a time.    The Cloud Console ability to publish messages is a simple test tool.  It isn't meant to be particularly rich in function.

If it were me and I needed to post multiple messages to Pub/Sub at one time and wanted to do that exclusively through a browser mechanism.  I might create a Cloud Function that takes a POST REST input containing a JSON array and publish each message in the array and then use a tool like Postman to submit the REST request.
Comment: Thank you for your suggestion, Kolban! Will try it out!
Answer: You could use a little script (of your preferred language), maybe reading from a json or csv and publishing using the batch setting. See the docs.
https://cloud.google.com/pubsub/docs/batch-messaging#python


Autenticação customizada com CPF e E-MAIL

Question: Estou pensando em uma forma de autenticar usuários usando o e-mail e o CPF do mesmo, até agora não achei uma forma de fazer, alguém tem uma sugestão?
public function auth(Request $request) {
    $credenciais = $request->only('cli_email', 'cli_cpf');
}

Answer: O Framework Laravel, possui uma forma de autenticação com a instância da classe User, sendo então possível conferir outros dados relevantes a seu proposito para ter acesso ao sistema, seguindo exemplo:
$user = User::where('cpf', $cpf)->where('email', $email)->first();
if ($user) // se verdade existe um usuário com essas informações
{
    Auth::login($user); //efetuando a operação de autenticação
}

mas, não seria uma falha de segurança?, porque, é fácil descobrir o CPF e o E-mail de algum usuário, a senha deveria também ser informada por ser um dado de cada usuário.
Comment: @ErlonCharles é a mesma lógica só agrupar o `where` e passar os dois parâmetros, porque ele só precisa da instância para logar. Ou seja [https://laravel.com/docs/5.6/queries#parameter-grouping](https://laravel.com/docs/5.6/queries#parameter-grouping)
Comment: Concordo com você quando diz que é uma falha de segurança, mas infelizmente o cliente precisa desse tipo de login, deixei o mesmo bem informado sobre a situação, muito obrigado pela resposta, já havia finalizado o job, mas mesmo assim ainda considero como resposta.
Comment: Sem problemas @geekcom, foi um alerta, e cliente é cliente nem sempre entende o nosso trabalho ... !!!
Comment: E se eu precisar usar `email` **ou** `cpf` junto com a senha?


"Moderation" versus "interaction"?

Question: I have come across these two terms which are used interchangeably in many contexts.
Basically, a moderator (M) is a factor that impacts on the relationship between X and Y. Moderation analysis is usually done using a regression model. For example, gender (M) can affect the relationship between "product research" (X) and "product purchase" (Y).
In interaction, X1 and X2 interact to influence Y. The same example here is that "product research" (X1) is affected by "gender" (X2) and together they affect "product purchase" (Y).
I can see that in moderation, M affects the X-Y relationship but in interaction, M (which is gender in this case) affects the other IV.
Question: If the aim of my project is to see how gender affects the relationship between X and Y, should I use moderation or interaction?
Note: My project is about the correlation between X and Y, not causal relationship between X and Y.
Comment: Terminology like "gender affects the relationship" may be confusing you.  With very few exceptions, people do not change their gender (and when they do, I doubt it affects their research-purchasing patterns).  What you seem to want to know is "how does the relationship between X and Y differ by gender?"  The *very first* thing to do is to make scatterplots of Y against X broken down by gender and compare them.  What you do next depends on the aims of your research.  For many applications, you might just stop at characterizing the two scatterplots.
Comment: The record does not show any significant change was made to the question.
Comment: Thanks whuber. I have asked a slightly different question just to clear my confusion.
Answer: You should consider the two terms to be synonymous.  Although they are used in slightly different ways, and come from different traditions within statistics ('interaction' is associated more with ANOVA, and 'moderator variable' is more associated with regression), there is no real difference in the underlying meaning.  In fact, statistics is littered with synonymous terms that come from different traditions that mean the same thing.  Should we call our X variables 'predictor variables', 'explanatory variables', 'factors', 'covariates', etc.?  Does it matter?  (No, not really.)
The way to think about what an interaction is, is that if you were to explain your findings to someone you would use the word 'depends'.  I will make up a story using your variables (I have no way of knowing if this is accurate or even plausible):  Lets say someone asks you, "if people research a product, do they purchase it?"  You might respond, "Well, it depends.  For men, if they research a product, they typically end up buying one, but women enjoy looking at and thinking about products for its own sake; often, a woman will research a product, but have no intention of buying it.  So, the relationship between researching a product and buying that product depends on sex."  In this story, there is an interaction between product research and sex, or sex moderates the relationship between research and purchasing.  (Again, I don't know if this story is remotely correct, and I hope no one is offended by it.  I only use men and women because that's in the question.  I don't mean to push any stereotypes.)
Comment: @yue86231, when you have an interaction term in the model, the main effects (ie, research & gender here), are the slopes when the other variable is 0. It might help you to read my answer here: [What does "all else equal" mean in multiple regression?](http://stats.stackexchange.com/a/84316/7290)
Comment: Thanks gung. And the story makes a lot of sense too. Of course, there is no stereotyping; it is just an example.
Comment: Thanks @gung for the wonderful explanation, I still have one question to this interaction effect of moderator: it that possible that the slopes of "research" and "gender" are not significant and the interaction is significant? I assume this possibility exists, but I cannot image one situation of that. Could you give me a tip?
Answer: I think you have things mostly correct except for the part about "in interaction, M (which is gender in this case) affects other the IV."  In an interaction (a true synonym for a moderator effect--not something different), there is no need for one predictor to influence the other or even be correlated with the other.  All that is implied by "interaction" (or "moderator") is that the way one predictor relates to the outcome depends on the level of the other predictor.
Answer: Moderation Vs Interaction
Both moderation and interaction effects are very much similar to each other. Mathematically, they both can be modelled by using product term in the regression equation. Often researcher use the two terms as synonyms but there is a thin line between interaction and moderation. The difference between the two is broadly similar to the difference between correlation coefficient and regression coefficient.
When we say X and Z interact in their effects on an outcome variable Y, and there is no real distinction between the role of X and the role of Z.  They are both considered predictor variables. Then we identify this effect as interaction effect.
While, in case we have clear distinction between the predictor and moderator variables (on the basis of theory) and we are interested to see the impact of predictor on response (affected by moderator), then this effect is known as moderation effect. One should carefully choose the term which is more suitable to answer one's research question.
For detailed comparison of these terms, refer
http://learnerworld.tumblr.com/post/147085936920/interaction-moderationenjoystatisticswithme
and
http://learnerworld.tumblr.com/post/147089718705/mediationmoderationinteractionenjoystatisticswithme
Answer: I think the most general model one can write regarding moderation of a variable z "in a relationship between y and x" is:
y = f(x) + g(z) + h(x)z
The marginal effect of x is f'(x)+h'(x)z, so the moderation effect is h'(x).
Mike

"Moderation" versus "interaction"?


Adding an array of objects to session storage

Question: I've been trying to save an array with the contents of the cart on a website. Both the object and the array are filled as expected, however when checking the sessionStorage, there's an array with an empty object, I've been at this for a while, taking on and off breaks but am currently losing my sanity.
Could anyone point me in the right direction?
var cartContents = [];
var obj = new Object();

setTimeout(function(){

    var prodId = JSON.stringify(meta.product.id); //meta.product.id
    var prodName = $('h1.product-single__title')[0].innerText; //$('h1.product-single__title')[0].innerText
    var quantity = "1";
    var unitPrice = $('span.price-item')[0].innerText.substring(1); //$('span.price-item')[0].innerText.substring(1)
    var currency = $('span.price-item')[0].innerText.charAt(0); //$('span.price-item')[0].innerText.charAt(0)

    Object.defineProperty(obj, 'id', {
        value: prodId,
        writable: false
    });
    Object.defineProperty(obj, 'name', {
        value: prodName,
        writable: false
    });
    Object.defineProperty(obj, 'quantity', {
        value: quantity,
        writable: false
      });
      Object.defineProperty(obj, 'unitPrice', {
        value: unitPrice,
        writable: false
      });
      Object.defineProperty(obj, 'currency', {
        value: currency,
        writable: false
      });
      cartContents.push(obj);
      console.log(cartContents)
      sessionStorage.setItem("cartContents", (JSON.stringify(cartContents)));
    }, 3000);

Answer: since you are going to stringify it anyway, you don't need the Object class modification. Use this simple approach

var cartContents = [];
var obj = new Object();

setTimeout(function(){

    var prodId = JSON.stringify(meta.product.id); //meta.product.id
    var prodName = $('h1.product-single__title')[0].innerText; //$('h1.product-single__title')[0].innerText
    var quantity = "1";
    var unitPrice = $('span.price-item')[0].innerText.substring(1); //$('span.price-item')[0].innerText.substring(1)
    var currency = $('span.price-item')[0].innerText.charAt(0); //$('span.price-item')[0].innerText.charAt(0)

      obj.id = prodId;
      obj.name = prodName;
      obj.unitPrice = unitPrice;
      obj.currency = currency
      cartContents.push(obj);
      console.log(cartContents)
      sessionStorage.setItem("cartContents", (JSON.stringify(cartContents)));
    }, 3000);


How to send data to the server with an image?

Question: I am creating a form that captures user data and profile picture, I program this in jquery ui (modal form) and sending jquery ajax post, on the server side (PHP5.2) need to get the value of the variable $ _File and the other values of the username, email, password, well my problem is in the delivery of data and image.
I hope you have understood me and I can help
Code HTML

                    All form fields are required.

                <form id="formulario">
                    <fieldset>

                            Name
                        <input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" />

                            Email
                        <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />

                            Password
                        <input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />

                    </fieldset>

Photo: <input type="file" name="photo" class="ui-autocomplete-input ui-widget-content ui-corner-all">

                </form>

CODE JS
$("#dialog-form").dialog({
    autoOpen: false,
    height: 620,
    width: 480,
    modal: true,
    buttons: {
        "Create an account": function() {
            //allFields.removeClass("ui-state-error");
            var info = $("#formulario").serialize();//
            //Here!!
            // How data gathering more data in the image?
            console.log(info);
            $.post("AddUser.php", info, function(data) {
                console.log(data);
                $('#grid-data').load("GridData.php", function() {
                    //console.log('load data OK');
                });
            });
            $(this).dialog("close");
        },
        Cancel: function() {
            $(this).dialog("close");
        }
    },
    close: function() {
        //allFields.val("").removeClass("ui-state-error");
    }
});

regards
thanks
MauricioHz
Santiago, Chile
Comment: Ajax cannot do file uploads. The standard workaround is to clone your form into a hidden iframe and do a conventional POSt-based upload there: http://www.php.net/manual/en/features.file-upload.post-method.php
Comment: You can't upload files via AJAX.  You need to use an iFrame, Flash, or the xmlhttprequest2
Comment: Post your `AddUser.php` code so we can see what the PHP that is processing the AJAX request does.  Also, you can just upload the image to the server and then send the link in the AJAX request.  Otherwise you would be storing the image in the database as binary rather than filesystem.
Comment: https://developer.mozilla.org/en-US/docs/Web/API/FormData
Answer: Try
var info = new FormData($("#formulario")[0]);
$.ajax({
  url: "AddUser.php",
  data: info,
  processData: false,
  contentType: false,
  type: "POST",
  success: function(data) {
      console.log(data);
      $('#grid-data').load("GridData.php", function() {
      //console.log('load data OK');
      });
  }
});

Answer: It's sad to tell you that Ajax can't upload the file for javascript can't handle local file.
usually, there are 3 ways.
1.base64encode the image content, then you get the base64encoded string. post the string to the server . the server get the image content by decode the string

use flash upload the file . js and flash interact to implement file upload.
use iframe. javascript handle the html dom dynamic, trigger the submit event, then you can get the otected-stream.
Answer: I could get a good result with jquery form pluggins,
http://hayageek.com/ajax-file-upload-jquery/


Como resgatar id de um controller para outro controller no angularjs?

Question: Tenho um app móvel, tenho um zona onde listo todas as noticias que ah, e tenho opção para fazer gosto da noticia o que me está acontecer e que não estou a conseguir pegar o id da noticia para enviar para o mysql gostaria de saber como posso pegar o id do controller que listo as noticias e usar o id da noticia para usar no controller que faz o gosto da noticia.
Controller Lista Noticias
.controller('ListaNoticiasHome', function($scope, $http, $stateParams, sessionService, $partilharRecursos) {
     $http.get("https://www.sabeonde.pt/api/api_noticias_home.php").success(function (data) {
        $scope.noticias_home = data;

        $partilharRecursos.set('idNoticia', data.id);
    });
})

Controller Like
.controller('LikeNoticiasHome', function($scope, $http, $stateParams, sessionService, $partilharRecursos) {
    var hasLiked = false;
    $scope.like= function (){

        if (!hasLiked) {
            hasLiked = true;
            $scope.liked = 'Não Gosto';
            $scope.likeCount += 1;

            $http.get("https://www.sabeonde.pt/api/api_like_noticias.php?post_id="+$partilharRecursos.get("idNoticia")+ "&user_id=" + sessionService.get('user_id')).success(function (data) {
                $scope.like_noticias_home = data;
            });

        } else {
            hasLiked = false;
            $scope.liked = 'Gosto';
            $scope.likeCount -= 1;

            $http.get("https://www.sabeonde.pt/api/api_unlike_noticias.php?post_id="+$partilharRecursos.get("idNoticia")+ "&user_id=" + sessionService.get('user_id')).success(function (data) {
                $scope.like_noticias_home = data;
            });
        }
    }
})

HTML

{{noticias.titulo}}

 {{liked}}

{{noticias.likes}}

 Partilhar

 Ver +

Answer: Seria isso?
EDIT 1

var app = angular.module("App", []);

app.controller("AppController1", function($scope) {
  $scope.varController1 = "JEC nao vai cair!!!";
  $scope.consultarOutroController = function() {
    var scopeOutroController = angular.element('[ng-controller=AppController2]').scope();
    alert(scopeOutroController.varController2);
  };
});

app.controller("AppController2", function($scope) {
  $scope.varController2 = "JEC nasceu campeão!!!";
  $scope.consultarOutroController = function() {
    var scopeOutroController = angular.element('[ng-controller=AppController1]').scope();
    alert(scopeOutroController.varController1);
  };
});

    <input type="button" value="Consultar outro Controlador 1" ng-click="consultarOutroController();" />

    <input type="button" value="Consultar outro Controlador 2" ng-click="consultarOutroController();" />

EDIT 2
Outra forma de compartilhar dados entre controllers é utilizando o $rootScope. Esse cara trabalha de forma parecida com uma variável global no js.
app.controller("AppController1", function($scope, $rootScope) {
    $rootScope.varController1 = "JEC nasceu campeão!!!";
});

app.controller("AppController2", function($scope, $rootScope) {
    alert($rootScope.varController1);
});

EDIT 3
Controller Lista Noticias
.controller('ListaNoticiasHome', function($scope, $rootScope, $http, $stateParams, $partilharRecursos, sessionService) {
    $http.get("https://www.sabeonde.pt/api/api_noticias_home.php").success(function (data) {
        $scope.noticias_home = data;
    });
    $partilharRecursos.set('idNoticia', '<passe aqui o id>');
});

Controller Like
.controller('LikeNoticiasHome', function($scope, $http, $rootScope, $stateParams, $partilharRecursos, sessionService) {
    var hasLiked = false;
    $scope.like= function (){

        if (!hasLiked) {
            hasLiked = true;
            $scope.liked = 'Não Gosto';
            $scope.likeCount += 1;

            $http.get("https://www.sabeonde.pt/api/api_like_noticias.php?post_id="+ $partilharRecursos.get("idNoticia") + "&user_id=" + sessionService.get('user_id')).success(function (data) {
                $scope.like_noticias_home = data;
            });

        } else {
            hasLiked = false;
            $scope.liked = 'Gosto';
            $scope.likeCount -= 1;

            $http.get("https://www.sabeonde.pt/api/api_unlike_noticias.php?post_id="+ $partilharRecursos.get("idNoticia") + "&user_id=" + sessionService.get('user_id')).success(function (data) {
                $scope.like_noticias_home = data;
            });
        }
    }
});

Serviço que partilha recursos
.service('$partilharRecursos', function () {
    var property = {};

    return {
        get: function (key) {
            console.log("Key: " + key);
            console.log(property);
            return property[key];
        },
        set: function(key, value) {
            console.log("Key: " + key);
            console.log("Value: " + value);
            property[key] = value;
            console.log(property);
        }
    };
});

Comment: Vamos [continuar esta discussão no chat](http://chat.stackexchange.com/rooms/30170/discussion-between-cesar-sousa-and-emir-marques).


How can we find whether this problem has unique, none, infinitely many solutions?

Question: Everytime I encounter this kind of question, I got stuck. Please help me if anyone knows how to solve and teach me how to solve.

This is what I did basically,
$$f(x,y)=(1-y^2)^{1/2}$$
$$f(y)=-y/(1-y^2)^{-1/2}$$  where $y \ne {-1,1}$
Then I got stuck.
Comment: For your information, "namely" is not a quantity. It's synonymous with "by which I mean".
Comment: Thanks, one more thing I learnt today, appreciated
Comment: What have you tried? What do you know about the theory of differential equations (e.g. theorem of Picard-Lindelöf)?
Answer: $$
\int \frac{1}{\sqrt{1-y^2}}dy = \int dx \Rightarrow \arcsin (y) = x + C
$$
$$
y = \sin(x+C) \Rightarrow \begin{cases}|b|> 1 \rightarrow \mbox{No Solution} \\ |b| \leq 1 \rightarrow \mbox{Unique Solution}\end{cases}
$$
Comment: Thank you everyone :)
Comment: Appreciated....
Answer: The given ODE is $x$-free. This implies that the set of solution curves is invariant under horizontal translation, hence the number of solutions of an IVP stipulating $y(a)=b$ does not depend on $a$.
It is obvious that there are no solutions if $|b|>1$. Therefore it remains to look at the interval $-1\leq b\leq 1$.
Consider the right side
$f(x,y):=\sqrt{1-y^2}$ of the given ODE. When $|b|<1$ then
$${\partial f\over\partial y}={-y\over\sqrt{1-y^2}}$$
is bounded in a neighborhood of $(a,b)$. In this case the general existence and uniqueness (GEU)  theorem says that there is an interval $\ ]a-h, a+h[\ $ such that there is exactly one solution
$$\phi:\quad]a-h,a+h[\ \to{\mathbb R}$$
satisfying $\phi(a)=b$.
The case $b=1$ is special ($b=-1$ is exactly analogue). Here the basic "technical assumption" of the GEU theorem is violated, and trouble is in the offing. Note that the "ordinary solutions" of the given ODE are sine arcs of the form
$$y=\sin(x-c)\qquad\left(c-{\pi\over2}<x<c+{\pi\over2}\right)\ .$$
Here the solution $y=\sin\bigl(x+{\pi\over2}\bigr)$ living on the interval $\ ]-\pi,0[\ $ can be smoothly extended to the point $(0,1)$. Furthermore there is the "special solution" $y_1(x):\equiv1$ going through this point. Out of this material we can fabricate essentially two different solutions through the initial point $(0,1)$, namely $x\mapsto y_1(x)$ and
$$x\mapsto y_2(x)=\left\{\eqalign{&-1\qquad\qquad\qquad(x<-\pi)\cr
&\sin\bigl(x+{\pi\over2}\bigr)\qquad(-\pi\leq x\leq 0) \cr &1\qquad \qquad\qquad(x>0)\ .\cr}\right.$$
Any solution through $(0,1)$ coincides in a neighborhood of $x=0$ with one of $y_1$ or $y_2$.


Factoring $ x^2 + x +1 > 0$ from Spivak Calculus exercise

Question: Hi!! I found me in trouble when I saw the solution of a simple inequality, that can be found at the end of the first chapter, that is the exercise 4 - (viii): $x^2+x+1 > 0$.
Very easy to solve I know, but I also saw the related solution on the Spivak Calculus Answer Book and I did not understand how succeed to factoring the polynomial ( already factored into the solution ), I show what I mean:
$$x^2 + x + 1 > 0  = \left( x + \frac{ 1}{2}  \right)^2 + \frac{3}{4}$$
On the RHS there is the factored expression and now my question is: how can I get this form for every second degree polynomial? Is there a specific formula to get this form?
I hope someone could help me
Comment: Look up: completing the square.
Comment: Among the various methods for motivating how one might discover how  to complete the square, here's one you might not come across. Note that $x^2+x+1=x(x+1)+1,$ where the two variable factors are "not balanced" (the zeros of $x$ and $x+1$ are $0$ and $-1,$ which are not symmetric with respect to the origin). To balance the variables, change variables by letting $x=u-\frac{1}{2}$ and $x+1=u+\frac{1}{2},$ so that $x(x+1)+1$ becomes $(u-\frac{1}{2})(u+\frac{1}{2}) + 1 = u^2-\frac{1}{4}+1=u^2+\frac{3}{4}.$ Now convert back to $x$'s using $u=x+\frac{1}{2}.$
Comment: By the way, the expression you got is not "factored". Factoring an expression generally means to reduce it to a product of polynomial factors each of lesser degree than the original expression. The expression $x^2 + x + 1$ cannot be factored in the reals, however, it is possible to find a factorisation in the complex numbers, i.e. $x^2 + x + 1 = (x - \omega)(x - \overline{\omega})$, where $\omega$ and its conjugate are complex cube roots of $1$. Completing the square is not the same as factorisation, however, it can help you simplify expressions and solve equations/inequalities.
Comment: Thank you all for the answers and the comments! Now everything's clear!
Answer: As suggested, this was achieved through completing the square:
$$ x^2 +x+1 = x^2 + x +\left(\frac{1}{2}\right)^2 + 1 -\frac{1}{4}$$
$$ = \left(x+\frac{1}{2}\right)^2  + \frac{3}{4}$$
You need to go and read up completing the square to understand how I got the above.
Answer: Completing the square is the process you're looking for. Basically, for a quadratic $ax^2 + bx + c = a(x^2 + \frac{b}{a}x + \frac{c}{a})$. The term inside the bracket can be written as $$\left(x + \frac{b}{2a}\right)^2 - \left(\frac{b}{2a}\right)^2 + \frac{c}{a}$$ so that for any general quadratic expression we have $$ax^2 + bx + c\equiv a\left(\left(x + \frac{b}{2a}\right)^2 - \left(\frac{b}{2a}\right)^2 + \frac{c}{a}\right ).$$
In fact, writing it in this form is a useful tool because $x = -\frac{b}{2a}$ is the minimum/maximum point of the quadratic.
Answer: $$ax^2+bx+c=a\left(x^2+\frac{b}{a}x+\frac{c}{a}\right)=a\left(\left(x+\frac{b}{2a}\right)^2+\frac{c}{a}-\frac{b^2}{4a^2}\right)\\=a\left(x+\frac{b}{2a}\right)^2+\frac{b^2-4ac}{a}$$
Comment: (I think maybe you need to adjust the last term in your answer.)
Answer: For $a\not =0$, we have$$\begin{align}ax^2+bx+c&=a\left(x^2+\frac{b}{a}x\right)+c\\&=a\left(\color{red}{x^2+\frac{b}{a}x+\left(\frac{b}{2a}\right)^2}-\left(\frac{b}{2a}\right)^2\right)+c\\&=a\left(\color{red}{\left(x+\frac{b}{2a}\right)^2
}-\left(\frac{b}{2a}\right)^2\right)+c\\&=a\left(x+\frac{b}{2a}\right)^2-a\cdot\frac{b^2}{4a^2}+c\\&=a\left(x+\frac{b}{2a}\right)^2-\frac{b^2}{4a}+c\end{align}$$
Answer: We see that $x^2+x+1=(x^2+x+{1\over 4})+{3\over 4}=(x+{1\over 2})^2+{3\over4}$. Since $(x+{1\over 2})^2\ge 0$ for all $x\in \mathbb{R}$, then it follows that $(x+{1\over 2})^2+{3\over4}>0$ and so $x^2+x+1>0$.
Answer: Simply you have to add and subtract the square of half of $x$'s coefficient then the algebraic statement will be written as sum or difference of to square.


É possível fazer uma conexão à um banco de dados MySql sem o MySql.Data.dll?

Question: Sempre que vou usar um banco de dados MySql em uma aplicação de console ou windows forms, é preciso ter o dll MySql.Data.dll dentro da pasta da aplicação.
Com isso, gostaria de saber, se tem alguma maneira de utilizar o MySql sem um dll. Pensei em tentar utilizar o System.Data.SqlClient, mas não sei se é possível.
Comment: Sempre tem, não sei dizer o tamanho do malabarismo para conseguir.
Comment: @bigown Sabe pelo menos por onde devo começar?
Comment: O problema é justamente esse, tem muitas formas espalhadas.
Answer: O System.Data.SqlClient(referencia aqui) é exclusividade do SQL Server(como nessa resposta do LINQ). Sem uma DLL de terceiros é quase impossivél conectar.
De acordo com as minhas pesquisas existe outros modos de conectar o MYSQL ao c# e não é exclusividade do MySql.Data.dll. Nesse site encontrei algumas opções de conectores para .NET:

MySQLDriverCS
SevenObjects MySqlClient
dotConnect for MySQL (former MyDirect.NET and Core Labs MySQLDirect.NET)
eInfoDesigns.dbProvider

Acredito que a MySQLDriverCS é a mais utilizada, o resto já não deve ser utilizada no mercado(difícil até de achar referencias). Segue exemplo utilizando o MySQLDriverCS encontrado nesse link.
    using MySQLDriverCS;
    using System.Data;
    MySQLConnection myConn;
    MySQLDataReader MyReader = null;
    try
    {
      myConn = new MySQLConnection(new MySQLConnectionString("123.456.789.100",
                                                    "mydatabase",
                                                    "user",
                                                    "pass").AsString);
      myConn.Open();
      string sql = "SELECT * FROM Table";
      MySQLCommand cmd = new MySQLCommand(sql, myConn);
      MyReader = cmd.ExecuteReaderEx();
      while (MyReader.Read())
      {
        Console.WriteLine( MyReader["Product_Name"].ToString() );
      }
      MyReader.Close();
    }
    catch(Exception ee)
    {
      Console.WriteLine( ee.ToString() );
    }
    finally
    {
       if (MyReader != null && !MyReader.IsClosed)
       {
          MyReader.Close();
       }
       if (myConn != null && myConn.State == ConnectionState.Open)
       {
          myConn.Close();
       }
    }

Pelo que eu percebi é MUITO parecido com o MySql.Data.dll.
Comment: Pelo que eu vi todos necessitam de alguma dll ou instalação, nenhum deixa o source code ou algo do tipo.
Comment: @Francisco kkk é que antes de você editar, você disse "com **ESTE** dll"
Comment: @Francisco sem a DLL não é possível.


zero of a function

Question: I would like to find zeros of this function $f(x) = 6x^4 + x^2 - 1$
I've tried Descartes's rules but I couldn't find the zero from any of my possibilities
Answer: Hint:
Start with finding the zeros of $$g(y)=6y^2+y-1$$
Then consider the relationship between $f(x)$ and $g(y)$
Answer: Hint:
What if we set $u=x^2$? Then our equation becomes $$f(u)=6u^2+u-1$$ Can you solve that?
Answer: Hint:
This is a biquadratic equation. Set $u=x^2$ and find the non-negative root  of the quadratic equation
$$6u^2+u-1=0.$$
Note that, as the leading coefficient and the constant term do not have the same sign, the quadratic equation will have one positive and one negative  root. So the given biquadratic equation has two opposite real roots and two opposite imaginary roots.
Answer: Start with factoring and then solve each factor
$$f(x) = 6x^4 + x^2 - 1=(3x^2-1)(2x^2+1)=0 \implies $$
$$ x=\pm \frac {\sqrt 3}{3}, x=\pm i \frac {\sqrt 2}{2}$$
Answer: Substituate $y=x^2$, then
$$6x^4+x^2-1=6y^2+y-1$$
to find the roots of the original function, start to solve the below one
$$6y^2+y-1=0$$
$$y_{1,2}=\frac{-1 \pm \sqrt{1^2-4\cdot 6\cdot(-1)}}{2\cdot 6}=\frac{-1 \pm \sqrt{25}}{12}=\frac{-1 \pm 5}{12}$$
$$y_1=\frac{-1 + 5}{12}=\frac{4}{12}=\frac{1}{3}$$
$$y_2=\frac{-1 - 5}{12}=-\frac{6}{12}=-\frac{1}{2}$$
Now you can express $y$ by $x$
$$y_1=x^2=\frac{1}{3} \implies x_1=\frac{\sqrt{3}}{3}, \ \ \ x_2=-\frac{\sqrt{3}}{3}$$
$$y_2=x^2=-\frac{1}{2} \implies x_3=\frac{\sqrt{2}}{2}i, \ \ \ x_4=-\frac{\sqrt{2}}{2}i.$$
Obviously thre are four solutions including only two real solutions.

zero of a function


Zoom H6 - Record electric guitar with pedals

Question: I was wondering how the Zoom H6 recorder performed when recording "heavy" electric guitar. I would like to plug my electric guitar plus some pedals (Whammy, Delay, Reverb & Big Muff) and mix it on my computer.
It seems possible to plug the guitar directly into the Zoom.
Do you have any experience using the Zoom as a Audio Interface?
Answer: The H6 offers Mic and Line inputs.  If your effects chain ends up at Line level you can connect it directly.  If it ends up at "guitar" level, you'll need to run it through something that makes it look like a Line or Mic source first.
"All four main H6 inputs (inputs 1-4) are combo connectors that can accept either XLR or ¼" balanced or unbalanced phone cables. They can handle both mic- and line-level signals, which means that you can connect either external microphones or line-level devices like mixers, portable music players, electronic keyboards, or electric guitars or basses with active electronics (passive electric guitars or basses can also be connected with the use of a mixer or effects device)."
Comment: Voltages  can vary considerably.  100mv is often quoted, but some guitars can produce as much as 1v.  It needs to be treated as a voltage source into a high-impedence input.  If this is all jargon to you, don't worry.  The main point is that a guitar pickup won't sound good into a socket labelled "mic" or "Line In", even if the plug DOES fit.
Comment: The interface is not optimum.   But sound will get through, and electric guitar is all about manipulation and effects, not about pure amplification.  If it's all you've got try.  If you like the sound you get, then it's good.
Comment: Thank you for your answer. What do you mean exactly by guitar level ? Do you have any idea how good the sound is ? thanks
Comment: Ok thank you. So in conclusion I should not use the Zoom H6 as Audio interface for my electric guitar ? Thanks.
Answer: I've been exploring this option as well and the easy solution is buying an active DI Box. Try to find one with a 1 Megaohm Input.


Como fazer que o retorno de uma query (PDO) já me traga um array pronto?

Question: Eu que eu tenho :
Periodo     |   Cliente
_________________________
jan2014     |   Cliente A
jan2014     |   Cliente B

Eu que eu quero :
array(
    'jan2014' => array(
        0 => 'Cliente A',
        1 => 'Cliente B',
    )
)

Answer: Para conveter um array que do PDO na estrutura na pedida de forma manual crie um novo array($saida) e adicione os elementos conforme a chave(periodo)
//array na estrutura do PDO
$entrada = array(
                0 => array('periodo' => 'jan2014', 'cliente' => 'cliente A'),
                1 => array('periodo' => 'jan2014', 'cliente' => 'cliente B'),
                2 => array('periodo' => 'fev2014', 'cliente' => 'cliente C'),
                3 => array('periodo' => 'jan2014', 'cliente' => 'cliente D'),
                4 => array('periodo' => 'mar2014', 'cliente' => 'cliente E'),
                5 => array('periodo' => 'mai2014', 'cliente' => 'cliente F'),
                6 => array('periodo' => 'jan2014', 'cliente' => 'cliente G'),
                7 => array('periodo' => 'mai2014', 'cliente' => 'cliente H'),
                8 => array('periodo' => 'jun2014', 'cliente' => 'cliente I'),
                9 => array('periodo' => 'mar2014', 'cliente' => 'cliente J'),

        );

$saida = array();

foreach($entrada as $item){
   $saida[$item['periodo']][] = $item['cliente'];
}

o resultado do array novo será:
Array
(
    [jan2014] => Array
        (
            [0] => cliente A
            [1] => cliente B
            [2] => cliente D
            [3] => cliente G
        )

    [fev2014] => Array
        (
            [0] => cliente C
        )

    [mar2014] => Array
        (
            [0] => cliente E
            [1] => cliente J
        )

    [mai2014] => Array
        (
            [0] => cliente F
            [1] => cliente H
        )

    [jun2014] => Array
        (
            [0] => cliente I
        )

)

depois para obter os valores do novo array basta usar dois foreachs:
foreach($saida as $key => $item){
    foreach ($item as $subitem){
        echo 'periodo: '. $key  .' - '. $subitem .'
';
    }
}

Answer: Você precisa utilizar o PDOStatement::fetchAll
Exemplo:
<?php
    $sth = $dbh->prepare("SELECT name, colour FROM fruit");
    $sth->execute();

    /* Fetch all of the remaining rows in the result set */
    print("Fetch all of the remaining rows in the result set:\n");
    $result = $sth->fetchAll();
    print_r($result);
?>

Resultado:
Array
(
    [0] => Array
        (
            [NAME] => pear
            [0] => pear
            [COLOUR] => green
            [1] => green
        )

    [1] => Array
        (
            [NAME] => watermelon
            [0] => watermelon
            [COLOUR] => pink
            [1] => pink
        )

)

Comment: Não funcionou, ele continual trazendo todas as linha.
Comment: Acho que esse não é o ponto da pergunta, ele quer trazer arrays multi-dimensionais e não o nome da coluna.
Comment: Ah sim, desculpe. Acredito que será necessário a criação de um `while` ou `foreach` para organizar da maneira que deseja.


After moving Drupal 7 site, adding /user or /?q=user to base URL simply reloads maintenance page

Question: I've just moved a Drupal 7 site from Bluehost to Inmotion (by reinstalling the latest core and adding the 'sites' directory from the old server account, then uploading the database). Since the move I can't log in from the browser.
The DNS has transitioned. At the new location Drupal is installed in a subdirectory -- public_html/sub. I've altered the .htaccess file at the level above (public_html/.htaccess) as per these directions https://support.lunarpages.com/knowledge_bases/article/549 so that the site will open there with the base url in the browser.
That does happen, with the base URL currently showing the under maintenance message, just as the site was left. But when I attempt to go to /user or even /?q=user to log in and resolve any last errors from the move, then bring the site back online, I am not given a login form. It simply continues to show the under maintenance message.
I'm guessing this problem is somehow related to .htaccess and/or settings.php, but I can't seem to find the right combo of changes that will allow me to log in. Any suggestions? (I did clear the cache and sessions tables in the DB when this error first occurred, but no help.)
Comment: Are you using stock htaccess or customized?
Comment: At the public_html level (just above the site's subdirectory) I am using the changes from the lunarpages link above to point requests to my Drupal subdirectory. Within the Drupal site subdirectory itself my .htaccess is stock from Drupal.
Answer: Update your settings.php to this:
<code>$conf['site_offline'] = 0;</code>
From https://www.drupal.org/node/276457#comment-901392
Comment: The hosting company's tech support did this, and yes, it does bring the site back online. But /user and other links (including standard menu links) do not work; they simply load the home page. Thus,I still cannot log in. The site is online and broken rather than offline and broken -- but still broken.
Comment: Thanks for trying to help. I gave up and moved all the files up to the public_html directory. The site now works.


Conditional probability formulas

Question: For a compound event $E_1E_2$,
Pr($E_1E_2$) = Pr($E_1$)Pr($E_2$|$E_1$)
such that if $E_1$ and $E_2$ are independent events, we can say that:
Pr($E_1E_2$) = Pr($E_1$)Pr($E_2$)
Is there an analogous formula that can be derived for the conditional probability:
Pr($E_1E_2$|$E_3$)?
I would like to be able to reduce Pr($E_1E_2$|$E_3$) to terms that do not involve all three of the events $E_1$, $E_2$, $E_3$, given the assumption that only $E_1$ and $E_3$ are independent.
If this cannot be done, then what assumptions would be necessary in order to be able to do it?
Answer: Here is one way to write it given the assumption:
$$
P(E_1\cap E_2\mid E_3)=P(E_2\mid E_1\cap E_3)P(E_1\mid E_3)=P(E_2\mid E_1\cap E_3)P(E_1).
$$
Comment: Is there no way to re-write it as a product of terms, each of which only involves one or two out of the three events?
Comment: I don't think there is, but I am not sure. You should probably edit your question and state you're looking for such an expression.
Comment: OK I edited my question. I guess this boils down to something like: if A and B are independent, can I write P(A|BC)=P(A|C)? If not, what are the minimal assumptions that are necessary in order for that to be true?
Answer: Hint: If you write out $$Pr(E2|E1)=\frac{Pr(E_2\cap E_1)}{Pr(E_1)}$$ then you can investigate more complicated formulas involving more events. Don't remember a formula but understand them.
Comment: The problem is that I can't figure out how using that formula would enable me to show, for example, that P(A|BC)=P(A|C), given A and B being independent.

Conditional probability formulas


Como fazer o FAB sobrepor os itens em uma ListView

Question: Tenho uma activity onde inflo os itens personalizados em uma ListView. No setContentView() dessa activity eu boto um arquivo que tem apenas uma ListView declarada.
 <ListView xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:tools="http://schemas.android.com/tools"
     android:id="@+id/list_exercicios"
     android:orientation="vertical"
     android:clickable="true"
     android:layout_width="match_parent"
     android:layout_height="match_parent"/>

Em outro arquivo XML eu crio o layout dos itens que vão na ListView.

<LinearLayout
    android:id="@+id/exercicios_container"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/exercicios_background"
    android:orientation="vertical">

    <TextView
        android:id="@+id/pergunta"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/title_exercicios_background"
        android:gravity="center"
        android:text="Aqui vai a pergunta"
        android:textColor="@color/letras_exercicios"
        android:textSize="25sp" />

    <RadioGroup
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <RadioButton
            android:id="@+id/radio_button_a"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="Aqui vai a perunta"
            android:textColor="#FFFFFF"
            style="@android:style/Widget.CompoundButton.CheckBox"/>
        <RadioButton
            android:id="@+id/radio_button_b"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="Aqui vai a perunta"
            android:textColor="#FFFFFF"
            style="@android:style/Widget.CompoundButton.CheckBox"/>
        <RadioButton
            android:id="@+id/radio_button_c"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="Aqui vai a perunta"
            android:textColor="#FFFFFF"
            style="@android:style/Widget.CompoundButton.CheckBox"/>
        <RadioButton
            android:id="@+id/radio_button_d"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="Aqui vai a perunta"
            android:textColor="#FFFFFF"
            style="@android:style/Widget.CompoundButton.CheckBox"/>
        <RadioButton
            android:id="@+id/radio_button_e"
            android:layout_width="match_parent"
            android:layout_height="50dp"
            android:text="Aqui vai a perunta"
            android:textColor="#FFFFFF"
            style="@android:style/Widget.CompoundButton.CheckBox"/>

    </RadioGroup>

    <TextView
        android:id="@+id/finished_question"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/terminei_background"
        android:text="@string/txt_responder"
        android:textSize="25sp"
        android:textColor="#FFFFFF"
        android:gravity="center"
        android:onClick="terminou"/>

</LinearLayout>

O problema é que se eu botar o FAB nesse arquivo ele aparece em todos os itens e não funciona,  e se eu botar no arquivo da ListView dá erro.
Answer: Deve usar ConstraintLayout ou FrameLayout
Algo como:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <ListView
             android:id="@+id/list_exercicios"
             android:orientation="vertical"
             android:clickable="true"
             android:layout_width="match_parent"
             android:layout_height="match_parent"/>

       <android.support.design.widget.FloatingActionButton
            android:id="@+id/fab"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="end|bottom"
            android:layout_margin="16dp"
            android:src="@drawable/ic_done" />

    </FrameLayout>

</LinearLayout>

Answer: Tente da seguinte forma:
XML

<ListView
    android:id="@+id/list_exercicios"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentLeft="true"
    android:layout_alignParentStart="true"
    android:layout_alignParentBottom="true" />

<android.support.design.widget.FloatingActionButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="8dp"
    android:clickable="true"
    android:id="@+id/fab"
    android:src="@mipmap/ic_icon"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    />

Activity
public class SuaActivity extends AppCompatActivity {

   private FloatingActionButton fab;
    private ListView listaExercicio;

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.seu_xml);
         // Referencia da Lista
        listaExercicio = ListView.class.cast(findViewById(R.id.list_exercicios));
         // Referencia do Floating Action Button
        fab = FloatingActionButton.class.cast(findViewById(R.id.fab));
    }

}


Media Browser in WYSIWYG editor doesn't allow uploads for non-admins

Question: As admin everything works as expected. I can upload images. As a non-admin user I can use the "Web" and "Library" functions but not the file upload function.

I have it enabled:

And the user has the correct permissions applied:
Answer: There are two things need to be configured for WYSIWYG editor.
First settings can be found on admin/config/media/browser. Either you check all available plugins like you have done in screenshot or leave all unchecked for allowing all. That's already done by you.
Next is to check permissions, where you have to give Add and upload new files, view own files etc permissions (like my screenshot below)

Another permission to check is Use media browser, which you must have done & so that it's appearing. Once these are in place, it should work for the role you are checking.


Find linear transformation isomorphism

Question: I need to figure out if $\ T: \mathbb R_3[x] \rightarrow \mathbb R^{3}$ in which
$$\ T(x^2+2x) = (1,2,1) , \ T(x+1)=(0,1,1) , \ T(x^2-2)=(1,0,-1)$$ is an isomorphism.
I understand that in order for $T$ to be isomorphism $Ker(T) = \{0\} $
The set $\{x^2+2x;x+1;x^2-2\}$ is linearly dependent and I can't just determine $T$ of a basis of vectors of $\ \mathbb R_3[x] $. I'm not sure how to determine if $T(v) = 0 $ only if $v=0 $
Comment: Try finding $T(x^2)$, $T(x)$, $T(1)$ using linearity
Comment: Remember that you can choose images of elements of a basis freely. So can you A) extended $\{x+1,x^2-2\}$ to a basis of $\Bbb{R}_3[x]$, and B) choose an image for the third basis vector in such a way that $T$ becomes an isomorphism?
Comment: Unless I'm missing something, I can't find T(1). $\ T(1) = \alpha_1 T(v1) + \alpha_2 T(v2) + \alpha_3 T(v3) $ and then $\ (1,0,0) = \alpha_1 (0,2,1) + \alpha_2 (1,1,0) + \alpha_3 (-2,0,1) $ which can't be solved.
Comment: But how do I figure the image of the third basis that I chose?
Comment: @YardenGur It suffices to complete the given basis, for example by $x^2+2x, x+1$ adding a third linearly independent vector that is $x^2$ or $x^2+1$ for example.
Answer: Yes as you noted we don't have sufficient information to define $T$ indeed the vectors $x^2+2x,x+1, x^2-2$ are linearly dependent since
$$(x^2-2)+2(x+1)=x^2+2x$$
Of course we can find infinitely many isomorphism, extending the given basis, such that the condition given are fulfilled but $T$ can't be determined uniquely form the given information.
For example we can set
$$\ T(x^2+2x) = (1,2,1) , \ T(x+1)=(0,1,1) , \ T(x^2)=(0,0,1)$$
and in this case $T$ is an isomorphism which satisfies the given conditions.
Comment: @YardenGur This way corresponds to the suggestion given also by Jyrki Lahtonen in the comment.
Comment: @YardenGur Yes exactly we can't determine $T$ from the given information but we can complete the bases and define $T$ arbitrarly.
Comment: Thanks! but could you explain to me how did you figure that $\ T(x^2) = (0,0,1) $ ?
Comment: @YardenGur We can choose arbitrarly a third linerly independent vectors as argument for $T$ (that is $x^2$) and send it to a third linearly independent vector $T(x^2)=(0,0,1)$.
Comment: Ok so If I understand you correctly, we dont' know what T actually do and we also can't figure it out. So you just choose any vector that will complete the other two to a basis for R3 and then just choose any value we want for the image of this vector as long as all three image vectors are also linearly independent so the transformation will be isomorphism ?
Answer: Calling
$$
A = \left(\begin{array}{ccc}
1 & 2 & 0\\
0 & 1 & 1\\
1 & 0 & -2
\end{array}\right), X_2 = (x^2, x, 1)^{\top}, B = \left(\begin{array}{ccc}
1 & 2 & 1\\
0 & 1 & 1\\
1 & 0 & -1
\end{array}\right)
$$
we have
$$
T\left(A X\right) = B X
$$
but $A$ has not maximum rank because $\det(A) = 0$ as the second row times $-2$ added to the first row gives the third row.
hence $T$ is not an isomorphism, because $T:\mathbb{R^2}\to \mathbb{R}^3$ because $B$ has maximum rank, and then $T$ is not bijective.
Comment: $T$ is not properly defined from the given information
Comment: If $T$ is linear which I assumed, it is conveniently defined.
Comment: Note that $\det(A)=0$.
Comment: Yes. You are right! I inverted $B$ instead $A$. I will change my answer accordingly. Thanks.

Find linear transformation isomorphism


How to smooth scroll to page anchor in angular 4 without plugins properly?

Question: What I want to achieve is a click to  and do a smooth scroll to bottom / specified div area which i define with hashtag just like  i think it should be like this.
here is the live example in the w3school example which is written for JQuery: https://www.w3schools.com/jquery/tryit.asp?filename=tryjquery_eff_animate_smoothscroll
What I do is peek from this answer: Angular2 Routing with Hashtag to page anchor
but i don't really understand the answer, the answer is looked like this :
this part is HTML part :
Jump to 'Test' anchor

and below this, the router.navigate is where should I put the code? component.ts right? but how do i access this function? should i implement (click)?
this._router.navigate( ['/somepath', id ], {fragment: 'test'});

and below this, i get it, which it should write in my component.ts :
** Add Below code to your component to scroll**

  import {ActivatedRoute} from '@angular/router'; // <-- do not forget to import

  private fragment: string;

  constructor(private route: ActivatedRoute { }

  ngOnInit() {
    this.route.fragment.subscribe(fragment => { this.fragment = fragment; });
  }

  ngAfterViewInit(): void {
    try {
      document.querySelector('#' + this.fragment).scrollIntoView();
    } catch (e) { }
  }

what is the "somepath" mean? I should add a route in my routes.ts right? usually, i add a new path in here for example like this :
export const routes: Routes = [
  { path: '', redirectTo: '/home', pathMatch: 'full' },
  { path: 'product', redirectTo: '/product' },
  ...homeRoutes,
  ...productRoutes
];

can anyone provide me with full example code in HTML, routes, and component?
Comment: from what i read and what i search, it will be a hell of a code for just a SMOOTH SCROLL its not simply like JQuery i think, so i decided to use this plugins which is work perfectly : https://www.npmjs.com/package/@nicky-lenaers/ngx-scroll-to feel free to use it
Answer: I was looking for a similar solution and tried to use the ngx-scroll-to package and found that its not working in latest version of angular (angular 6+) so decided to look into other option and found a solution which uses the browser's native scrollIntoView and this seems to be the best solution so far
HTML code :
<button (click)="scrollToElement(target)"></button>

Your target

Ts code :
scrollToElement($element): void {
    console.log($element);
    $element.scrollIntoView({behavior: "smooth", block: "start", inline: "nearest"});
  }

Comment: Super! Right now the best solution. You would also need a Polyfill in order support more browsers: https://github.com/iamdustan/smoothscroll
Comment: Note that unfortunately this doesn't work on iOS Safari - seems that `scrollIntoViewOptions` isn't supported at all.
Comment: *IMPORTANT* now Nicky Lenaers ngx-scroll-to supports Angular 8!
Comment: It seems to me that this, with the polyfill, is the correct answer.
Comment: A simple and "native" solution that doesn't require an external library seems to be the best one
Comment: how can we combine `scrollIntoView` function with a fixed header?
Comment: It's not obvious from your example what are you passing in `target` variable to `scrollToElement()` function. Can you please explain?
Comment: It should be noted that this solution (and all the other solutions except for the CSS one which is not widely supported), will not update the router and browser URL history. This means there's no back/forward navigation, and scroll to fragment using URL functionality.
Answer: CSS only solution
html {
  scroll-behavior: smooth;
}

It works even after navigation or page reload.
Please note that it does not work in IE, Edge or Safari.
Comment: This can break a lot of stuff. We had to disable it because of a 3rd party modal no longer working property (due to auto-focus). Be very very careful
Answer: You can simply do this in your component.
const element = document.querySelector("#destination")
if (element) element.scrollIntoView({ behavior: 'smooth', block: 'start' })

Ref: https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Comment: Didn't work for me but when I switched the first line in the above code example to: const element = document.getElementById("#destination"); then it worked.
Answer: In new Angular versions the solution is:
component.html

scroll

   .
   .
   .
<form id="myForm">
   .
   .
   .
</form>

component.ts
constructor(private viewportScroller: ViewportScroller) {}

scrollTo() {
    this.viewportScroller.scrollToAnchor('myForm');
}

your-general-styles.css
html {
  scroll-behavior: smooth;
}

Comment: This should be the accepted answer...Elegant solution in my opinion..Thanks
Comment: Does nothing for me. Don't know why. Trying to scroll to the top of div. Angular 13.
Answer:  // you can use ViewportScroller calss
 constructor(
        private viewPortscroller: ViewportScroller
        ) {}

scrollingTop() {
    this.viewPortscroller.scrollToPosition([0 , 0]);
  }

// and for smoothly scroll you can do that

html, body {
     height: 100%;
     scroll-behavior: smooth;
 }

Answer: you have to add the flowing:
1- in app-routing.module.ts :
@NgModule({
  imports: [RouterModule.forRoot(routes,
      {
        useHash: true,
        scrollPositionRestoration: 'top',
        anchorScrolling: 'enabled',
        scrollOffset: [0, 64],
        relativeLinkResolution: 'legacy'
      }
    )],
  exports: [RouterModule]
})
export class AppRoutingModule { }

2- in style.scss :
body, html {
  overflow-x: hidden;
  scroll-behavior: smooth !important;
}

3- in the .html file :

    Home

    About

OR like this:

           testimonials

Comment: Just to add on to this for those wondering, you also need to give your element an `id` of whatever the `fragment` name is.  In this example, `about` is the fragment, so the about section (anchor) needs to have `id="about"`
Answer: I just used ngx-page-scroll. It can be as simple as:
Categorias

....

Visit the package page for more information: https://www.npmjs.com/package/ngx-page-scroll
It also provides mechanisms to configure scrolling process, or event implement custom behavior through a service that controls the scrolling from the component's controller.
Answer: You can do it with the help of ViewportScroller which defines a scroll position manager.
First of all, you have to inject it in the constructor like the following:
import { ViewportScroller } from '@angular/common';
...
constructor(
   ...
   private readonly _viewportScroller: ViewportScroller){}
...

Then
this._viewportScroller.scrollToPosition([0, 0])

NOTE
Add this style to your  CSS  or  SCSS  file to add a smooth scroll effect in your app.
html {
  scroll-behavior: smooth;
}

Methods
ScrollToPosition

/**
 * Scrolls to a specified position.
 * @param position A position in screen coordinates (a tuple with x and y values).
 */
abstract scrollToPosition(position: [number, number]): void;

ScrollToAnchor

/**
 * Scrolls to an anchor element.
 * @param anchor The ID of the anchor element.
 */
abstract scrollToAnchor(anchor: string): void;

setOffset
getScrollPosition
setHistoryScrollRestoration
For More Information
Answer: Try removing the square brackets:
class="startScroll" scrollTo="'#firstDiv'" scrollBoxID="'#scrollBox'"

Comment: I have tried with removed and getting this error: `ERROR TypeError: Cannot read property 'top' of undefined`
Answer: I got it work by doing this, consider that top-page is the id that you want to scroll to.
document.getElementById("top-page").scrollTo({ behavior: "smooth", top: 0 });

Answer: you could use css with this :

html {
  scroll-behavior: smooth;
}
Answer: document.getElementById("top-page").scrollIntoView({ behavior: "smooth" });
Answer: Add the below lines in style.css to get nicescroll in your angular application page.
::-webkit-scrollbar {
    width: 5px;
}

::-webkit-scrollbar-thumb {
    border-radius: 10px;
    -webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.5);
    background: #c3c3c3 !important;
}

Answer: You can use the native feature for anchor-based scrolling in angular.
Please refer to this link for more info.
Answer: constructor(private el: ElementRef)

ngAfterViewInit() {
  setTimeout(() => {
    this.el.nativeElement.scrollIntoView({
      behavior: 'smooth',
      block: 'center',
    });
  }, 0);
}


rails rspec, erro no post :create, params require

Question: Estou iniciando nos testes com rspec no RubyOnRails e estou tento um problema ao testar o create do meu controller:
it "creates lançamento" do
  post :create, params: attributes_for(:lancamento), format: :js, xhr: true
  expect(Lancamento.count).to eq(1)
end

Já criei a factory com o FactoryGirl.
O erro é o seguinte:
1) LancamentosController testa cadastro lançamento creates lançamento
 Failure/Error: params.require(:lancamento).permit(Lancamento.fields)

 ActionController::ParameterMissing:
   param is missing or the value is empty: lancamento

Qualquer ajuda é bem vinda, obrigado!
Answer: Faz
post :create, params: { lancamento: attributes_for(:lancamento) }, format: :js, xhr: true
e deve resolver teu problema.
E como sugestão, não programa em portugues. Motivos: http://www.akitaonrails.com/2008/07/31/tradu-o-por-que-voc-n-o-deve-codificar-em-portugu-s
Comment: Resolveu! obrigado, só que agora ele para no expect retornando 0.
Comment: Faz um debug no teu controller, pois ele pode ta caindo no else do save por alguma validação.
Comment: Exatamente, validação, vou arrumar a factory do lançamento. Obrigado!