Method Parameters and JSTL

Question: What is the "items" attribute syntax for a method with a parameter that returns a list using JSTL? For instance if I have a method
List<String> fName = null;
public List<String> FirstName(String firstName)
{
    return firstName
}

and a JSP
<c:foreach var="something" items="fname">
    ${something}
</c:foreach>

How do I supply the method with the Parameter?
Thank you.
Comment: You can not call method in a c:forEach tag. It is used basically to iterate over a collection. I think JSTL does not support calling java methods directly from the JSP. There is no such tags in JSTL to do this. If you need to call java method from the JSP, you should look into Ajax or may be DWR.
Comment: @Ashish Thanks. I've changed by code snippet to be a little more readable. I'm passing the list into a c:foreach and it would work fine if I didn't need a parameter on the method. Are you familiar with making this work if the method had a parameter?
Answer: This doesn't make much sense. There is something wrong in the flow. You should prepare exactly the list the JSP needs in the servlet.
List<String> firstNames = something.list(firstName);
request.setAttribute("firstNames", firstNames);
request.getRequestDispatcher("result.jsp").forward(request, response);

and then
<c:forEach items="${firstNames}" var="firstName">
    ${firstName}

</c:forEach>

The list can of course be a bean property, but to the point, you just need to make sure that exactly the list you want to display is already been prepared in the servlet so that JSP EL just have to get it as a bean property.

Unrelated to the concrete problem, in JSP/EL 2.2 (along Servlet 3.0) it's possible to pass arguments to bean methods, but this is definitely not the right solution in your particular case.
Comment: Thanks for you help. My issue was that I was trying to send the list to the JSP prior to preparing it. I figure it out later that day, but your post help me realize that I was correct in what I "figured out". Thanks.
Answer: How do you pass the variable to your jstl?
If your process this in a single page. This is an example
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %>
<%@ page isELIgnored="false" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.util.List;" %>
<%
    List<String> xList = new ArrayList<String>();

    xList.add("a");
    xList.add("b");
    xList.add("c");

    pageContext.setAttribute("sList", xList);
%>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>

    <c:forEach var="lst" items="${sList}">
        ${lst}
    </c:forEach>

Note: you should know the good programming practice. What I post is just a sample where the foreach print the value. The variable maybe come from a sevlet.
EDITED:
Passing variable value from servlet to jsp. Inside your servlet it could be in do post or do get or other function which have the HttpServletRequest/HttpServletResponse
request.setAttribute("sList", xList);
request.getRequestDispatcher("your.jsp").forward(request, response);

Comment: I have basic knowledge of programming, and it's a method in a servlet that I'm having an issue with. The method takes a parameter and returns a list so I'm not certain if the syntax in the c:foreach is supposed to be different than what you typed in your answer. thanks.
Comment: Yes it is the same way. The problem maybe is how you pass the variable value to your jsp page. See the edited post. If the process of calling your jsp page is different with my example, please let me know.
Comment: Thank you for you help. I needed to prepare the servlet before sending it to the JSP and then I could use the request.set/getattribute.

Method Parameters and JSTL


Confusion about $\mathbb{Z}[x]$ being not a PID and generators of ideals of form $\left(f_1(x), \ldots, f_n(x)\right)$

Question: Not principal ideal. It's a well known fact, that $\mathbb{Z}[x]$ is not a PID, for example consider the following ideal
\begin{align}
I = \left(x, x + 2\right) = \{a(x)(x+2) + b(x)x| a(x), b(x) \in \mathbb{Z}[x]\}
\end{align}
It's not difficult to prove that this ideal isn't principal.
Principal ideal. Also, let's look at the following ideal:
\begin{align}
J = \left(x^2 - 4, x^2 - x - 2\right) = \{a(x)(x^2 - 4) + b(x)(x^2 - x - 2)| a(x), b(x) \in \mathbb{Z}[x]\}
\end{align}
I have also proven that this ideal is principal, it is generated by greatest common divisor of polynomials $x^2 - 4$ and $x^2 - x - 2$, namely $J = \left(x-2\right)$
Main confusing ideal. Now let's consider the following ideal
\begin{align}
V = \left( f_1(x), \ldots f_n(x) \right ), ~~~~~~~ \text{where}~~f_1(x), \ldots f_n(x) \in \mathbb{Z}[x]
\end{align}
I claim, that this ideal is principal and it's generated by the greatest common divisor of all $f_j(x)$. My proof is the following. Consider the greatest common divisor by $g(x)$. Obviously, that $V \subset \left( g(x) \right)$. Let's proof other inclusion. Consider arbitrary element $ \hat{h}(x) = h(x) g(x) \in \left( g(x) \right)$ Since $g(x)$ is greatest common divisor, $g(x)$ can be written as a linear combination of $f_j(x)$:
\begin{align}
g(x) = \sum_{j=1}^{j=n} \alpha_j(x) f_j(x)
\end{align}
Значит:
\begin{align}
\hat{h}(x) = h (x) g(x) = h(x) \sum_{j=1}^{j=n} \alpha_j(x) f_j(x) = \sum_{j=1}^{j=n} \hat{\alpha_j}(x) f_j(x) ~~~~~~~\text{where}~~~~ \hat{\alpha_j}(x) = h(x) \alpha_j(x)
\end{align}
So $V$ is principal. Using this proof, if we take $n = 2$ and $f_1(x) = x$ and $f_2(x) = x + 2$ we conclude that $\left(x, x+2\right) = \left( \gcd(x, x+2) \right) = \left(1\right) = \mathbb{Z}[x]$, what is obviusly falce, since $\left(x, x+2\right)$ is firstly proper, and secondly it's not principal. What am i doing wrong? Note that my question isn't answered in linked question, because it's rather obvious fact which i prove by myself that $\left( x, x + 2 \right)$ is not a principal ideal, i am interested in where is the mistake in computations that $\left( f_1, f_2, \ldots, f_n \right)$ is principal, since this computations MUST be wrong, but i don't know where.
Comment: You already mentioned a counterexample in your first paragraph. See the linked dupe for proofs.
Comment: @BillDubuque have you read my question? I have asked where is contradiction, and in answer is explanation, that $\gcd$ doesn't work the same way in ring of integer polynomials, as in ring of integers, it's not a duplication if question you mentioned, because i ALREADY proven by myself what is written in question you linked, soit's NOT a duplication of linked question
Comment: if $\,g\mid f_i\,$ then $I := (f_1,\ldots\,f_n) = (g)\iff g = \sum a_i f_i$. In particular $\,g = \gcd f_i$ generates $I$ iff it can be written as a linear combination of the generators, i.e. a Bezout identity exists. Your error is assuming that this is always true. There are simple counterexamples, e.g. first linked dupe (same as answer).
Answer: I do not believe you can write the greatest common divisor $g(x)$ as a linear combination of the $f_j(x)$. To see this, just use the example you gave. Suppose $f_1(x) = x$, $f_2(x) = x+2$ and $g(x) = 1$. Suppose also that we can write:
\begin{equation}
 g(x) = \alpha_1(x)\cdot f_1(x) + \alpha_2(x)\cdot f_2(x)
\end{equation}
With $\alpha_1,\alpha_2\in\mathbb{Z}[x]$. This gives us:
\begin{equation}
 1 = (\alpha_1(x)+\alpha_2(x))x + 2\alpha_2(x)
\end{equation}
Just by matching term by term in the polynomial, we see that $\alpha_1(x) = -\alpha_2(x)$ and $\alpha_2(x) = 1/2$. But $\alpha_2\notin\mathbb{Z}[x]$. So this cannot happen and we cannot write $g(x)$ as a linear combination of the $f_j(x)$.
Comment: @NeoFanatic Essentially, yes, the Euclidean algorithm fails in $\Bbb Z[x]$ (it works in rings like $\Bbb Z$ and in $\Bbb Q[x]$), and that's basically what allows ideals to be non-principal. Be a bit careful with this remark, as there are principal ideal domains where the Euclidean algorithm doesn't work (such as $\Bbb R[x, y]/(x^2 + y^2 + 1)$). But if you have an integral domain with Euclidean algorithm, then you necessarily have a principal ideal domain.
Comment: For integres $a, b \in \mathbb{Z}$ it's always true, that i can write $ax + by = \gcd(a, b)$ and the proof uses Euclidean algorithm, namely you construct the linear combination "from the end". I understand you counterexample, so $\gcd$ in integers doesn't work the same as $\gcd$ in polynomial ring....
Comment: Please strive not to post more (dupe) answers to dupes of FAQs, cf. recent site policy announcement [here](https://math.meta.stackexchange.com/q/33508/242).


How To Change Dell Bios Settings Remotely?

Question: I recently noticed at a clients that their Dell laptops appear to have SMART disabled in bios by default. I noticed this while swapping out a disk on a desktop which had failed without any warning.. wonder why we didn't get anything. :-)
Anyone know how to script bios changes on Dell machines? Is it even possible?
This particular client has loads of laptops and maybe 50-75% of the company will be out of the office on any given day - making updating this difficult and expensive - unless I can script it.
The dell site mentions an openmanage package which they offer/sell, but that looks like overkill for such a simple need.
Answer: What Dell has for this is the Dell Client Configuration Utility, which gives you the option to configure bios changes (either for a single model or multiple models, and whatever doesn't apply to that bios is skipped), and then package it in an msi for silent/unattended deployment to the workstation, a reboot is still required though.
http://en.community.dell.com/techcenter/os-applications/w/wiki/2545.aspx
Comment: That sounds perfect. haven't tried it out yet but I'll mark that as the answer. Msi rollout + reboot isn't a problem.
Comment: @lan, it is quite nice, however I haven't gotten it to work with SCCM operating system deployment, so I can configure the BIOS as the machine is being imaged.


Expected value, correlation, and independence

Question: I need help with a problem.
Supposed x, y, and z are events in F (algebra of sets) in a probability space (universal set, F (algebra of sets), P). Define two random variables:
a(omega) =
<code>   {1 if omega is an element of set X
   {0 if omega is not an element of set X
</code>
b(omega) =
<code>   {2 if omega is an element of Y
   {1 if omega is an element of Z
   {0 if omega is not an element of Y or Z
</code>
a) Find E[A], E[B], and E[AB]
b) Are A and B uncorrelated? Under What conditions on (X,Y,Z) is sufficient for zero correlation between A and B?
c) Are A and B independent? What conditions on (X,Y,Z) is sufficient for zero independence of A and B?
Attempts: a) Find E[A], E[B], and E[AB]
E[A] = sum(xi*p(i)) = 1*p(X)+0*(1-p(X) = p(x)
E[B] = sum(xi*p(i)) = 2*p(Y)+1*P(Z)+0*P(YUZ) = 2p(Y)+p(Z)
E[AB] = E[X]*E[Y] if independent and
E[AB] = E(A)E(B) + Cov(A,B) if not independent
How can I find the Cov(A,B) of this problem?
b) Are X and Y uncorrelated? What conditions?
X and Y are uncorrelated when cov(A,B) = 0 which is when E[AB] - E[A]-E[B] = 0.
c) Are X and Y independent? What conditions?
X and Y are independent when P(X intersect YUZ) = P(A)*P(YUZ)
Comment: There is no such thing as _zero independence_. Random variables are independent or not independent; there are no fine distinctions. This is different from correlation where random variables can be uncorrelated or correlated, but for correlated random variables, we can talk of the _degree_ of correlation (highly correlated, weakly correlated, perfectly correlated etc) and well as positively or negatively correlated. Independence is absolute and random variables cannot be "somewhat" independent or highly independent.
Comment: Welcome to our site! You can make your question more readable by using $\TeX$ markup: it's enclosed between dollar signs $\$$. You can also use the markup tools above the textbox when you're writing or editing the question; this will help clarify what you are asking, which currently looks like just a jumble of stuff. In the meantime, why don't you consult your definitions, because they will indicate how to compute the covariance.
Answer: (a) With that definition of random variable $A$, it is sometimes called an 'indicator function'. Clearly: $\mathrm{E}[A]=\mathrm{Prob}[X]$, i.e. the expected value of $A$ is the probability that the event $X$ occurs.
As for the random variable $B$, that is ill-defined: What is its value if $\omega \in Y\cup Z$ ??
Comment: +1 -- but on the strength of your last comment, I had to vote to close the question!


Find $E[N^2 | N > 2]$ for a frequency distribution

Question: N has probability mass function: $p_o = p_1 =0$ and $p_k = \frac{1}{(e^1-2)k!}$ for $k=2,3,4,...$ I Solved for the pgf of N and got $G(t) = \frac{e^t}{e^1-2}$
How do I calculate $E[N^2 | N>2]$?
Comment: $\sum\limits_{k=2}^\infty 1/(e^1k!) = 1-2e^{-1} \approx  0.26424$ so that would not be a probability mass function
Comment: What I did was $\sum_{k=1}^{\infty} \frac{c}{k!} = 1$ which using exp series gave $ce^1=1$ Did I do anything wrong here?
Comment: You need to decide whether your sum starts with $0$ or $1$ or $2$ or $3$.  Though it does not really matter if you are conditioning on $N \gt 2$
Comment: Did I get the pmf wrong? The c value I got was 1/e
Answer: \begin{align}
\mathbb{E}[N^2 | N > 2] &= \sum_{n=0}^\infty n^2 Pr(N=n|N>2) \\
&= \frac1{1-P(N\le 2)}\sum_{n=3}^\infty n^2\cdot \frac{1}{(e-2)n!} \\
&=\frac1{1-\frac1{2(e-2)}}\sum_{n=3}^\infty n\cdot \frac{1}{(e-2)(n-1)!} \\
&= \frac1{1-\frac1{2(e-2)}}\sum_{n=3}^\infty (n-1+1)\cdot \frac{1}{(e-2)(n-1)!} \\
&=\frac{2}{2(e-2)-1} \left(\sum_{n=3}^\infty \frac{1}{(n-2)!}  + \sum_{n=3}^\infty \frac{1}{(n-1)!} \right)
\end{align}
I am leaving the last step for you to simplify.


Email sent! But not received on inbox. PHP -> localhost -> XAMPP -> Web Server

Question: Here are my configuration files.
sendmail.ini
<code>[sendmail]

; you must change mail.mydomain.com to your smtp server,
; or to IIS's "pickup" directory.  (generally C:\Inetpub\mailroot\Pickup)
; emails delivered via IIS's pickup directory cause sendmail to
; run quicker, but you won't get error messages back to the calling
; application.

smtp_server=(Correct SMTP Server)

; smtp port (normally 25)

smtp_port=25
</code>
php.ini
<code>[mail function]
; For Win32 only.
; http://php.net/smtp
SMTP = (Correct SMTP Server)
; http://php.net/smtp-port
smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
sendmail_from = (user@(server.com)) <- correct name
</code>
PHP code
<code><?php
$from_name = "testing";
$from_email = "email@example.com";
$headers = "From: $from_name <$from_email>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$body = "Hi,\nThis is a test mail from $from_name <$from_email>.";
$subject = "Test mail from test";
$to = "email@example.com";

if (mail($to, $subject, $body, $headers)) {
  echo "success!";
} else {
  echo "fail…";
}
?>
</code>
When i ran the code, it indeed say email sent but when I checked the email, there is nothing to receive... please help! thank you i will provide as many relevant information as possible to solve this issue.
Comment: Are you sending it to a large domain (e.g. gmail, aol, yahoo)?  If so sending mail without taking certain steps (proper DNS, non-generic hostname for your IP) will increase your spam score.  Also, are you authenticating with the SMTP server if it requires it?
Comment: Do you have an MX record set up?
Comment: @drew I am sending it to the company's microsoft outlook email. I did not authenticate with the SMTP server because it does not require any authentication user and password.
Comment: @blake Pardon my lack of knowledge sir, but what is MX record set up?
Answer: If you're testing this from home or a small office then your ISP is likely to be blocking out-bound traffic on port 25. You're PHP will not fail but your message will be blocked. You'll need to connect to an external SMTP server on another port such as 465 or 587. Consult your ISP's website for the details on what they allow.
Comment: Resist, i tried both 465 and 587 port number. It does not work, and no i am not testing from home or a small office. I am currently working in a MNC.. Is there any other way I can approach this? Thank you
Comment: Okay latest update: I used my own personal hotmail address to send to the company's email and it worked. Vice versa, i used my company's email to send "test" to my personal hotmail address. This shows that the company does not block out-bound traffic, what could be the problem now? Anyone? Thank you!
Answer: If you look closely you will see you're missing a concatenation on your second $header variable, therefor, you're not sending the "From:" header which is likely causing the mail to be rejected.


Type 'string' is not assignable to type 'keyof FitEnum | undefined'

Question: I'm trying to write a service for working with images. I use typescript and sharp. I get this error when I pass a string to fit.

Overload 2 of 2, '(options: ResizeOptions): Sharp', gave the following
error.     Type 'string | undefined' is not assignable to type 'keyof
FitEnum | undefined'.       Type 'string' is not assignable to type
'keyof FitEnum | undefined'

Tell me how it can be fixed.
import sharp          from 'sharp';
import FileUpload     from '../FileServices/file_upload';
import {IImageUpload} from './types';

class ImageUpload extends FileUpload implements IImageUpload{

  constructor(
    readonly file: Express.Multer.File,
    readonly width?:number,
    readonly height?:number,
    readonly fit?:string,
    readonly watermark?:boolean,
  ) {
    super(file);
  }

  public async resize_image(){
    let file_info = await sharp(this.bufferFile).resize({
        width: this.width,
        height: this.height,
        fit: this.fit
      }
    ).toBuffer({ resolveWithObject: true })
    this.bufferFile = file_info.data;
  }
}

use class ImageUpload
  if(req.file){
    let resizeImg = new ImageUpload(uploadFile,Number(req.body.width),Number(req.body.height),req.body.fit)
    await resizeImg.resize_image();
    let data_file = resizeImg.save_file();
    console.log(data_file);
  }

Comment: Can you show the code how you're using this `ImageUpload` class?
Comment: @CuongVu yes. changed the question
Answer: You declared readonly fit?: string and pass it to sharp's resize config which expects keyof FitEnum type not string. You can solve it by:
import sharp, {FitEnum} from 'sharp';

...

  constructor(
    ...
    readonly fit?: keyof FitEnum,
    ...
  )

Answer: As in the type definition, The fit options need to be one of "contain", "cover", "fill", "inside", "outside"
   interface FitEnum {
        contain: 'contain';
        cover: 'cover';
        fill: 'fill';
        inside: 'inside';
        outside: 'outside';
    }

   interface ResizeOptions {
        fit?: keyof FitEnum | undefined;
    }

So, you need to do the following
import { FitEnum } from 'sharp'

and then
  constructor(
    // other props
    readonly fit?:keyof FitEnum,
  ) {
    super(file);
  }

Comment: the answer above was earlier.  Thank you also for taking the time and helping me)


How to break inner loop and next for outer loop in ruby?

Question: I dont want to use if statement.
count = 0
10.times do |i|
  all = (i..20).collect{ |ii| ii < rand(30) || break }
  count+=1 if all # i dont want to use `if` statement
end

p count

How can I do that?
Answer: I got something in the similar matter:
count = 0
10.times do |i|
   (i..20).collect{ |ii| ii < rand(30) || break } || next
   count += 1
end

So it is just boolean algebra. if condition is taken place, when all, i.e. result of collect method, isn't nil, so we need to next keyword worked, when result of collect is nil. Therefore we just set or operator between collect and next, in order to next is occuring when result of collect is nil.
Answer: count = (0..9).count { |i| (i..20).all?{ |j| j < rand(30) } }

Comment: nice, but i asked another question.

anyway thanks +1
Comment: Fair enough - just in case it was useful..


Different color in different ViewControllers in NavigationBar

Question: I have been facing problems with my navigation bar color. I used the below code
[[UINavigationBar appearance] setBarTintColor:[UIColor colorWithRed:0.086 green:0.525 blue:0.427 alpha:1]];
[[UINavigationBar appearance] setTintColor:[UIColor blackColor]];

in my AppDelegate to give a uniform color throughout. But it seems, there is some issue in its working as I'm getting a different shade in some ViewControllers.
Please check on the images below.
This should be the original color :

But in another ViewController I'm getting this :

What might be the issue?
Answer: Because you are setting some as Opaque and some as not, also some might be translucent.
Recheck them and you should get the same shade ;)


Configuring per-directory permalink settings in jekyll

Question: Is it possible to have different permalink settings for different directories?
For example, if I have a Jekyll setup where blog entries are written into /blog/_posts/ and news items in /news/_posts, then by default each entry will have permalinks in the format /blog/2011/06/24/slug.html and /news/2011/06/24/slug.html.
The permalinks for blog entries are fine as they are, but I need to change the permalinks format for news to something different, say /news/2011/slug.
I've tried changing the permalink settings in the YAML front matter for the layout used by news item, however, this does not work since permalink settings in YAML front matter are not interpolated (as confirmed in the answer to this question).
Is there a mechanism to configure path specific settings in _config.yaml? Or is there a better what to achieve this results?
Comment: Have you tried `defaults: - scope` in `_config.yml`?
Answer: Not sure if this will be any help now but I ran into the same problem trying to make a blog/portfolio and wanting to have /articles/2013/.. and /work/2013/..
What I did is just change the permalink to:
permalink: /:categories/:year/:title

and added 'articles' as a category for my blog posts and 'work' as a category for my work and it worked fine.
Comment: This doesn't work if a post has several categories. They will be listed in URL. That would look disgusting. Is the way to use only 1st category?
Answer: Just got inspired by jose's comment. Why not do this:
permalink: /:categories/:title

and then in the front matter for your blog just do
categories: blog 2013 05 01

for news only do
categories: news 2013

Answer: The only way you can achieve that is by having two different jekyll instances.
You could have (for example) a full site with the pages and blogs, and a "microsite" inside the news folder, with it's own ´_config.yaml´ . The "top" would have to ignore the news directory completely, and the news directory would have to be configured to generate its output inside "../_site/news".
The biggest hurdle would be that you would not be able to run Jekyll as a server; you would have to use a script (i.e. a Rakefile) to generate the static pages for both jekylls, and serve them with a different server (i.e. unicorn).
Like I said, it'd be a bit of a hurdle, but doable in 1h or less.
Comment: That's exactly what I was hoping to avoid. Looks like there isn't a way around it, huh. +1 for now. Will accept if nothing new comes along. Many thanks.


SQLAlchemy 0.7.8 raw string queries issue with params

Question: I'm using SQLAlchemy with Pyramid application and I need to use 'format' paramstyle. For example:
DBSession.execute('SELECT id FROM users WHERE email = %s;', email)

This in theory should work, but I get sqla error:
('SQL Error!', AttributeError("'list' object has no attribute 'keys'",))

even while email is string and not list. I tried using tuple but I get the same error (but instead of "list" it says "tuple").
I use pg8000 as DB driver.
How else should I supply params to the query?
Comment: When you get a python error, please include the full traceback.
Answer: By using the execute method of the session, the parameters handling is done by SQLAlchemy, thus you need something like:
DBSession.execute('SELECT id FROM users WHERE email = :email;', {'email': email})

However, if you use the execute method of the engine instead, then the parameters handling is done by the underlying DB-API, which is pg8000 in this case, e.g.
DBSession.bind.execute('SELECT id FROM users WHERE email = %s;', email)

Anyway, I always stick with the former, to have a consistent way to handle parameters across different drivers / databases.
Answer: Reading through http://pybrary.net/pg8000/dbapi.html#pg8000.dbapi.CursorWrapper.execute it looks like pg8000.dbapi.paramstyle is set to named thus it is expecting a mapping which would look like:
DBSession.execute('SELECT id FROM users WHERE email = %(email)s', {'email': email})

It appears you want to set paramstyle to pyformat which looks like the most flexible option - allowing a sequence or mapping (or maybe just to format if not required).
Comment: Yeah, but default sqlalchemy `paramstyle` is set to `format` (I also tryied to set it with
    `engine.dialect.paramstyle = 'format'`
and I'm not sure if there is any other way to change `paramstyle` when using sqlalchemy.

I would really like to user any other `paramstyle` but we need to use same text queries in couple separate applications, and rest of them use `format`.
Comment: @MarekSzwalkiewicz What is `pg8000.dbapi.paramstyle` currently set to? (Apparently the default should be `format`)
Comment: I'm not sure if I have access to `pg8000` objects trough sqlalchemy, I'm setting everything up with `engine_from_config` - so I'm afraid that I can't check it with pshell, but by default it is set to `format` and should not be overwritten by sqlalchemy.


Running postfix queues from a ramdisk - why not?

Question: I'm in the process of configuring postfix on my server and I was wondering why people do not run the postfix queues from a ram disk?
The default home directory containing all the queues is (for the Ubuntu distribution) /var/spool/postfix.  This of course is a folder which exists on hard disk under normal circumstances.
The basic answer which I've found from Google is that it protects against mail getting lost if the server crashes.
The question this still leaves me with is this:
If the server did crash and the postfix queues were being stored on disk, would they not most likely be lost due to the kernel's internal hard disk caching.  From what I understand, these files are pretty short lived.  I'm struggling to see the difference between this and running more explicitly in RAM and saving to HD as postfix is shut down cleanly.
Have I missed something obvious here?
Answer: As part of postfix returning a 250 "accepted" code to the sending server, it is communicating to that server that it has truly accepted the message, and that the sending server can forget about it. This means that postfix will have already written the file to disk.
I would highly recommend not using a ramdisk for your queues - if need be, throw in a pair of SSDs in a RAID1 array. They should provide plenty of IOPs for you.
Comment: Perhaps I've missed something. Any comments on how it achieves this when the kernel caching disk writes to a hard drive?  I'm just struggling to see the difference, that's all.
Comment: Look into what [fsync()](http://linux.die.net/man/2/fsync) does.
Comment: No problem. `fsync()` is used by **many** applications, for ensuring that data gets written to non-volatile storage. As you could imagine, it's used extensively by database servers, to ensure data integrity on disk.
Comment: What @ErikA says. Given the case that your server crashes hard after the spool file is written to the filesytem, but before the fsync call is issued, the MTA will *not* send the 250. The sender will then most likely timeout and re-queue the message for another attempt according to its own schedule.


React.js vs Javascript variable declaration

Question: I have here a code using React.js, this code returns undefined in the console..
<code>getTicket = async() =>{
    var ticketData;
    this.state.client.get('ticket').then(
        await function(data){
            ticketData = data['ticket'].toString();
            console.log(data['ticket'])

        }
    )
    await this.setState({ ticketInformation: ticketData })
}
</code>
while this one is javascript, this code returns the value of ticketData..
<code>  var ticketData;
  client.get('ticket').then(
    function(data) {
      ticketData = data['ticket'];
      console.log("TICKET:: " + JSON.stringify(ticketData.id));
    }
  );
</code>
my question is, what is the difference between the 2? on the first code as you can see, I am using a async/await which should not return undefined as far as I know.. Somehow the 2nd code has no async/await but fully giving a value to the global variable.
Comment: You need to check React first. you are using functional component + this.state while this keyword is not available. Also, you didn't declare any state as well.
Comment: @Kid I already have my state declaration on top of my code.. what do you mean while this keyword is not available?
Answer: I guess that's because when you first call getTicket function, this.state.client is undefined. You should give it a value as default first but in my knowledge, it's not good to give function to a "state". You should make the convert value function as a call back outside, not in "state" cuz React re-make the function again whenever the state value change and it wastes memory.
Answer: Try it as following, I hope you gain a goal.
<code>   await this.state.client.get('ticket').then(
        function(data){
            ticketData = data['ticket'].toString();
            console.log(data['ticket'])

        }
    )
</code>


Why can't Go cast back an interface that implements a generic?

Question: I'm trying to explore the type system of Go, having fun programming a small side project, but I end up on a weird case.
When an interface that can take a type, in which use it for a function, a struct that implement that interface which is contained into a map of the interface, when retrieved I can't cast it back to the implementation. Why? How? What's wrong?
package main

import (
    "context"
    "fmt"
)

type State struct {
    Data string
}

type InterfaceFuncs[T any] interface {
    Init(ctx context.Context,
        stateGetter func() T,
        stateMutator func(mutateFunc func(T) T)) error
}

type ConfigWrap[T any] struct {
    InterFuncs InterfaceFuncs[T]
}

type Controller[T any] struct {
    mapinterfaces map[string]ConfigWrap[T]
}

func New[T any](initialState T) *Controller[T] {
    return &Controller[T]{
        mapinterfaces: make(map[string]ConfigWrap[T]),
    }
}

func (c *Controller[T]) RegisterFuncs(pid string, config ConfigWrap[T]) error {
    c.mapinterfaces[pid] = config
    return nil
}

func (c *Controller[T]) InterFuncs(pid string) (*InterfaceFuncs[T], error) {

    var pp ConfigWrap[T]
    var exists bool

    if pp, exists = c.mapinterfaces[pid]; exists {
        return &pp.InterFuncs, nil
    }

    return nil, fmt.Errorf("InterFuncs not found")
}

func main() {

    ctrl := New[State](State{})

    ctrl.RegisterFuncs("something", ConfigWrap[State]{
        InterFuncs: &ImpltProcFuncs{
            Data: "get me back!!!!",
        },
    })

    // why can't we cast it back to ImpltProcFuncs
    getback, _ := ctrl.InterFuncs("something")

    // I tried to put it as interface but doesn't works either
    //// doesn't work
    switch value := any(getback).(type) {
    case ImpltProcFuncs:
        fmt.Println("working", value)
    default:
        fmt.Println("nothing")
    }

    //// doesn't work
    // tryme := any(getback).(ImpltProcFuncs) // panic: interface conversion: interface {} is *main.InterfaceFuncs[main.State], not main.ImpltProcFuncs
    // fmt.Println("please", tryme.Data)

    //// doesn't work
    // tryme := getback.(ImpltProcFuncs)

    //// doesn't work
    // switch value := getback.(type) {
    // case ImpltProcFuncs:
    //     fmt.Println("working", value)
    // }
}

type ImpltProcFuncs struct {
    Data string
}

func (p *ImpltProcFuncs) Init(
    ctx context.Context,
    stateGetter func() State,
    stateMutator func(mutateFunc func(State) State)) error {
    return nil
}

How can I have my ImpltProcFuncs back as a variable to get Data?
What am I missing?
I thought that Go were able to cast anything back from interface.
Comment: "i can't cast it back to the implementation" of course not as there _are_ _no_ casts in Go. Only type conversions and type assertions. And pointer-to-interface is basically never a good idea and it's a fundamental bad idea if you are not acustomed to the type system of Go.
Answer: All right, after digging around, you can thank ChatGPT with Bing...
    if impl, ok := (*getback).(*ImpltProcFuncs); ok {
        fmt.Println("working", impl.Data)
    } else {
        fmt.Println("not working")
    }

When executed, it outputs "working get me back!!!!"
Comment: Alternative `func (c *Controller[T]) InterFuncs(pid string) (InterfaceFuncs[T], error)` (a pointer to an interface is [rarely useful](https://go.dev/doc/faq#pointer_to_interface))


AWS- Build a Modern Web Application(Mythical Mysfits)-Error with Docker Image

Question: I am new in the area of network and server management with zero experience. I am trying to learn from the tutorial "MythicalMysfits" from AWS. The other post helped and I updated pip to pip3, but now I am stuck due to a different error on Module 2B- Step1 - A, https://aws.amazon.com/getting-started/hands-on/build-modern-app-fargate-lambda-dynamodb-python/module-two/ . After running the docker command,
docker build . -t REPLACE_ME_AWS_ACCOUNT_ID.dkr.ecr.REPLACE_ME_REGION.amazonaws.com/mythicalmysfits/service:latest

I am still getting error of insufficient space, I tried clearing cache with cmd- sudo yum clean cache, but still error persists-
Need to get 337 MB of archives.
After this operation, 1111 MB of additional disk space will be used.
E: You don't have enough free space in /var/cache/apt/archives/.
The command '/bin/sh -c apt-get install -y python3-pip python-dev build-essential.' returned a non-zero code: 100

How can I fix this error?
Answer: Actually after some research and hit and trial I was able to successfully solve the problem of space , by running below command-
docker rmi $(docker images -q)
docker rm -v $(docker ps -qa)

or
docker container prune


Proof of Besov space embeddings: $B_{p, \infty}^{s+\varepsilon}$ is continuously embedded in $B_{p, 1}^s$

Question: Let's consider the Besov spaces $B_{p,q}^s$, $p,q \in [1,\infty]$, $s\in \mathbb{R}$ and $\varepsilon >0$. I keep coming across that $B_{p, \infty}^{s+\varepsilon}$ is continuously embedded in $B_{p, 1}^s$, i.e. there exists an constant $C$ with $\|\cdot\|_{B_{p,1}^s} \leq C\|\cdot\|_{B_{p, \infty}^{s+\varepsilon}}$, but unfortunately I have no idea how to prove it. Could anybody give me a hint (or proof)?
Answer: After some thought, I came to the following proof. I hope firstly that it is correct and secondly that it may be able to help others.
$$ \begin{align*}
\|f\|_{B_{p,1}^s} &= \sum_{j \geq -1} 2^{js} \|\Delta_j f\|_{L^p} \\ &= \sum_{j \geq -1} 2^{-j(s+\varepsilon- s)} 2^{j(s+\varepsilon)} \|\Delta_j f\|_{L^p} \\ &= \sum_{j\geq -1} 2^{-j\varepsilon} 2^{j(s+\varepsilon)} \|\Delta_j f\|_{L^p} \\ &\leq \sum_{j\geq -1} 2^{-j\varepsilon} \sup_j 2^{j(s+\varepsilon)} \|\Delta_j f\|_{L^p} \\ &= \sum_{j\geq -1} 2^{-j\varepsilon} \|f\|_{B_{p, \infty}^{s+\varepsilon}} \\ &= C_{\varepsilon} \|f\|_{B_{p, \infty}^{s+\varepsilon}}
\end{align*}.$$
Comment: It is right, gj
Comment: Exactly. Because you are summing over dyadic pieces, you see that if N are dyadic integers then $\sum N^{-\varepsilon}< \infty$, so the morality is that if you can afford loosing an $\varepsilon$ of regularity, then you can change your third index


Pode ocorrer do Entity Framework não mapear uma tabela no MVC?

Question: Adicionei uma tabela nova no Model.edmx, mais não foi criado no Model.Context.cs o
public DbSet<informacoes> informacoes { get; set; }

é também não foi criado no Model.tt a classe desta tabela.
como resolver isso?
Answer: Clica com o botão direito sobre o Model.tt e ache a opção Run custom tool:


Fourier-Legendre Series and Closure

Question: My professor taught us this last week

Legendre Polynomials form a maximal orthogonal set in this larger
  space (previously we were looking at polynomials)

  This means that there is no nonzero square-integrable
  function which is orthogonal to all Legendre
  polynomials. This allows us to expand any square-integrable function
  f(x) on [−1, 1] in a series of Legendre polynomials $$\sum_{n\geq0} c_nP_n(x)$$
  where $$c_n = \frac{<f,P_n>}{<P_n,P_n>}$$
  This is called the Fourier-Legendre series

My doubt in this is how can we write this? Legendre polynomials don't form a basis in the space of square integrable functions.

Further, the more pressing issue is that we are doing an infinite summation,  and vector spaces are closed only under finite additions. What is the guarantee that this sum would still belong to the vector space of square integrable functions?
Answer: $L^2[-1,1]$ is a Hilbert space, and the normalized Legendre polynomials $\{ p_n \}_{n=0}^{\infty}$ form a complete orthonormal subset of $L^2$. (Normalized means $\langle p_n,p_n\rangle=1$ for all $n$.) Completeness means that, for any $f\in L^2$, if $\langle f,p_n\rangle=0$ for all $n=0,1,2,3,\cdots$, then $f=0$ a.e.. Completeness is equivalent to $\lim_{N\rightarrow\infty}\sum_{n=0}^{N}\langle f,p_n\rangle p_n=f$ for all $f$, where the limit is taken with respect to the $L^2$ norm.

Fourier-Legendre Series and Closure


Alternative to TCP/IP for local program-to-program data streaming?

Question: I have a GNU C++ program and a python script that need to pass strings to each other quite frequently (~70-80 messages a minute). They will run local to each other in CentOS (hosted in the same environment). It feels that although TCP/IP can and will get the job done, what other options do I have?
Keep in mind that I cannot turn my C++ program into a SO and integrate it into my python script using ctypes, my C++ program must be compiled in 32bit, and my python script must be 64bit.
Comment: 70-80 messages per minute is such a low rate that spending any time optimizing the IPC mechanism is a waste of time.  Whatever you can code the fastest is the best choice.  I don't know what your C++ program is, but I would seriously reconsider whether you should just write the whole thing in python and avoid message passing altogether.
Comment: General curiousity and a nagging feeling that TCP/IP feels...unnecessary. You dont really need the whole flow control/delivery guarantees/ handshaking that the protocol provides.
Comment: What prompted your concern? Is there some reason why you are not satisfied with using TCP/IP? It will be hard to usefully recommend an alternative without knowing what problem you are having with TCP.
Answer: If you already have a TCP or UDP server, the easiest way will probably be to switch to UNIX domain sockets.
They come in "stream" and "datagram" modes, just like TCP/UDP sockets, and they're always local, as they use the filesystem namespace (instead of port numbers like TCP/UDP).
Comment: +1, I'm a fan of this approach because it allows you to easily separate the two processes onto different boxes in the future with a minimum of code rewrites.
Comment: But what advantage does using UNIX domain sockets have over using TCP/UDP sockets?
Comment: what are the pros and cons of using domain sockets over tcp/ip?
Comment: With TCP and UDP you use up a port. Sure, you can bind to localhost only, but it's still a port. If someone configures it wrong and makes it listen on all interfaces, it could be attacked from somewhere else. And then there's the IPv4/IPv6 switchover that's starting to happen. Headaches all around.

With UNIX domain sockets, you can just create more sockets anywhere in the filesystem where you have write access. And you can always rewrite it to use TCP/UDP if (and when!) the need arises.
Comment: @Rob: You can use UNIX permissions to control access to UNIX domain sockets; you can pass file descriptors over UNIX domain sockets; you can pass kernel-verified PID, UID and GID credentials; and you can use `SOCK_SEQPACKET` with UNIX domain sockets.
Answer: Named pipes are the standard method.  In Python:
<code>import os

os.mkfifo('/some/path')

# Reading process

with open('/some/path') as pipe:
    for line in pipe:
        # Do what you need

# Writing process

with open('/some/path', 'w') as pipe:
    while True: # Whatever looping process you have
        pipe.write('<data>' + '\n')
</code>
Note that, on modern systems, 70-80 messages / min is not all that high, TCP is still a viable option.  Also be careful that no one string is larger than the pipe buffer size (generally 64K).
Based on the suggestions in the comments, I've also added an example of UNIX domain sockets, which are more useful if you need bidirectional communication.
<code># Server Side

import socket

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.bind("/some/path")

sock.listen(1)
conn, addr = sock.accept()

while True:
    data = conn.recv(1024)
    if not data:
        break

    # Let's echo it back as an example
    conn.send(data)

conn.close()

# Client Side

import socket

sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
sock.connect("/some/path")

while True: # Your sending loop
    # In this case we send hello world, and print what we get back.
    sock.send('Hello, world')
    data = sock.recv(1024)

    print data

sock.close()
</code>
Comment: Named pipes are unidirectional though. UNIX domain sockets are bidirectional, so would probably be better for "exchanging messages".
Comment: would you know how it would look like on the c++ end? I'm not sure what library does this.
Comment: @user1040625 It's treated as a file, so you can use the standard fopen / fread / fwrite calls.  `mkfifo` is available in sys/stat.h.
Answer: http://tldp.org/LDP/tlk/ipc/ipc.html

Pipes
Named Pipes
TCP Sockets
UNIX-domain Sockets
Message Queues
Shared Memory

By far, I'd prefer TCP sockets.

You've already written the support for them,
They work equally well inter- as well as intra- machine.
There are wonderful tools to debug the communications channel.
There are libraries to assist in their use.
Answer: Maybe you can use named pipes?


Is it possible for $x^2=a \pmod p$ and $x^2=b \pmod p$ do not have solutions, but $x^2=ab \pmod p$ has a solution.

Question: Is this possible? Examples are appreciated
Comment: There is no solution to $x^2\equiv2\pmod 5$ or $x^2\equiv3\pmod 5$, but there is a solution to $x^2\equiv6\pmod 5$.  The term you want to Google is "quadratic residue".
Comment: Do you know [Euler's Criterion?](https://en.wikipedia.org/wiki/Euler%27s_criterion). If not, you should (assuming you haven't yet met the Legendre symbol).
Comment: Are you asking  for a proof of that property?  The usual argument is to count the squares.  There are exactly $\frac {p-1}2$ squares hence the same number of non-squares.  Now remark that a non-square times a square can not be a square.
Comment: Yeah I need a proof for this argument. I'm just trying to work through examples in my textbook for review but theres no answer key and I can't find videos so I'm struggling to teach myself.
Comment: wouldn't these be two nonsquares multiplied?
Comment: Yes, but you need the non-square times square case for counting.
Comment: What would be sufficient to show there is no solution to $^2$≡2(mod5) has no solution.
Comment: I have shown 0$^2$= 0(Mod 5), 1$^2$= 1(Mod 5), 2$^2$= 4(Mod 5),3$^2$= 4(Mod 5), 4$^2$= 1(Mod 5) but would I keep needing to test every number?
Comment: What is the rule behind why this has no solution?
Comment: Use `\pmod` for the parenthetical verion) and `\bmod` for the binary operator. Do not use `\mod`, because it gives the wrong spacing.
Comment: If $p\equiv 3\pmod{4}$, then $x^2\equiv -1\pmod{p}$ has no solutions, but $x^2\equiv (-1)(-1)\pmod{p}$ definitely does.
Answer: We start by noting that, since the integers $\pmod p$ form a field, and since $p$ is odd,  then there are exactly $\frac {p-1}2$ non-zero squares $\pmod p$.   Hence there are the same number of non-zero non-squares.
Let $N$ denote a non-zero non-square $\pmod p$ .  If we let $\{a_i\}_{i=1}^{(p-1)/2}$ run through the non-zero residues we remark that each of the products $N\times a_i$ must be distinct $\pmod p$.  If $a_1$, say, is a square then $N\times a_1$ can not also be a square since in that case we'd have $N\times a^2\equiv b^2\implies N\equiv \left(ba^{-1}\right)^2$.  Since there are $\frac {p-1}2$ squares we get all the $\frac {p-1}2$ non-squares as $N\times a^2$ for some $a$.  If $N'$ is a non-square (possibly equal to $N$) Then $N\times N'$ can not be a non-square, since all the non-squares are accounted for. Hence it must be a square, and we are done.
Comment: This is the only actual answer here so far, imo.
Answer: Do you know Legendre symbol? If $x^2\equiv a \pmod p$ for some $x$ we write $\Big({a\over p}\Big)=1$ else it is $-1$. There is a theorem $$\Big({a\over p}\Big)\Big({b\over p}\Big) =\Big({ab\over p}\Big) $$
and thus a conclusion.
Comment: No I'm not familiar. If there is a solution it is =1 if it has no solution it is =-1?
Comment: -1*-1=1? Can I substitute values for the fractions?


Invalid variable name: `--with-jpeg-dir' when compiling PHP7 on CentOS7

Question: I'm trying to configure PHP7 and I'm getting this error even though ./configure --help says that the variable name is --with-jpeg-dir. What am I missing? Here is my command:
./configure --with-apxs2=/usr/bin/apxs --with-mysqli --with-imap --with-imap-ssl --with-kerberos -- with-pdo-mysql --with-openssl --with-curl --enable-pcntl libdir=lib64 --with-zlib --enable-zip --enable-mbstring --enable-intl --with-readline --with-xsl --with-gd --with-jpeg-dir=/usr/lib64 --with-png-dir=/usr/lib64 --with-gmp --enable-bcmath --enable-opcache --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d
The exact error response is:
configure: error: invalid variable name: '--with-jpeg-dir'
Comment: You may have to run yum install libjpeg-devel first as per http://stackoverflow.com/questions/29532075/apache-configure-gives-error-invalid-variable-name-with-ssl
Comment: I've already got the latest version of libjpeg-devel installed
Comment: Is it an exact copy-paste of the configure command? There seems to be a few holes: -- with-pdo-mysql with a space, libdir=lib64 without --
Comment: Looks like that was the issue. Thanks, I didn't realize I had those errors in that command string. Now I get to try and figure out why I'm getting: "Cannot find imap library (libc-client.a)". Add that as an answer (or I can just delete the post since it was just a dumb mistake on my part)
Answer: There seems to be some typo's in your configure:
-- with-pdo-mysql with a space, libdir=lib64 without double hyphen --
This should work:
./configure --with-apxs2=/usr/bin/apxs --with-mysqli --with-imap --with-imap-ssl --with-kerberos --with-pdo-mysql --with-openssl --with-curl --enable-pcntl --libdir=lib64 --with-zlib --enable-zip --enable-mbstring --enable-intl --with-readline --with-xsl --with-gd --with-jpeg-dir=/usr/lib64 --with-png-dir=/usr/lib64 --with-gmp --enable-bcmath --enable-opcache --with-config-file-path=/etc --with-config-file-scan-dir=/etc/php.d

Also make sure all the packages have been installed and those paths are in fact correct.


When forecasting, is it better to remove the outliers or just to transform them?

Question: I am forecasting the number of logins. I have a dataset with the number of logins for each hour.
First, I use LOF (local outlier factor) to find the outliers and then I remove them.
Second, I use Kalman filter to forecast.
But as you can see in the plot, the prediction (blue) is displaced in time from the logins (red) and also from the future confidence interval (green).
So, would it be better to transform the outliers (maybe make them "normal") rather than completely removing them? Because right now I have some gaps in time. For example (the first monday), I have logins , for each hour, from 00h to 15h and the from 18h until the next day. So there is a gap of 2 hours.
Thank you
Answer: If the data are wrong, remove them regardless of whether or not they are outliers. If a data point is right but it is an outlier and you remove it, your analysis will be biased. This might even be the reason why your prediction desynchronizes with the trend. Transforming outliers is just a less extreme way of deleting them  that is also prone to bias.
The key point of the Kalman Filter is that it should be able to use the response history to inform the system state, but it doesn't seem that you are doing that. That means that at time $t$ you can use all of $t-1$ to generate predictions for $t$ and onward. Later, at time $t+k$ you can use all of $t+k-1$ to generate predictions for $t+k$ and onward.
So at the dotted line, are you showing your system forecasts for that time onward unconditional of the later response, and then superimposing the observed system state afterward? In that case, it's not surprising to see the forecast lose fidelity, that's the inevitable outcome: you just have to be clear about the target range for forecasts... nobody can predict the entire future in a statistical model.
The weights for the lagged response inputs are usually quite high, the best prediction of a system state is often the state it has most recently been in. When you run a forecast way out in the future, it is prone to desynchronizing. One way you can enforce a strictly seasonal adherence is to use the actual season as covariate inputs.
Comment: Can you talk a bit more about the 3rd paragraph? What I have after the green dotted line is my test set (inside the orange envelope. Around 12 days) and the forecast (green envelope. Around 1.5 days). As there is a displacement between logins and prediction; the metrics (RMSE and R2) give bad results)
Comment: @Aizzaac I think you've confirmed my suspicion. You should also make darn sure you haven't mapped the wrong time... common foible for R users who forget to supply the "time" as the "X" when superimposing curves. Your prediction is desynchronized with the trend... so what? It provides locally good prediction but bad forecasts to the point that 2 weeks out, the trend is offset a half a period. Maybe that isn't so bad, if you can monitor trend and react daily, you only need forecasts going out one day. It's a matter of refining your scientific question.
Answer: I would replace packets of contiguous missing values with hourly averages around the missing values. If the values are not missing but are anomalous either manually adjust them or estimate what they should have been via Intervention Detection which is essentially a forward prediction/fitted value for an anomaly.
Outliers represent effects/variables that are omitted from your model and if possible need to be identified and accounted for by adding additional/logical predictor series or worst case dummy indicators.


UPDATE update sem afetar todas as linhas em tabela sem ID

Question: Recebi uma tabela com informações de alguns clientes e precisava dar UPDATE porém como a tabela não tem ID e a maioria dos dados se repetem inclusive cpf existe alguma forma de dar o where apenas na linha selecionada?
Comment: Você projetou a tabela antes de cria-la? Fez o Diagrama de Entidades e Relacionamentos (DER)? Provavelmente se fosse bem projetada teria uma Chave Primária. Sugiro ver https://stackoverflow.com/questions/2186460/why-use-primary-keys
Answer: Colocando varias condições no WHERE e um limit em 1
EX:
<code>UPDATE usuarios set name = 'SEU NOME' WHERE CPF = '123' and IDADE = '13' and RG = '433' and SOBRENOME = 'SOBRENOME' LIMIT 1
</code>


$a_{n+1} = \sqrt{2 + a_n}$ Specific Theorem Needed

Question: I know this question has been asked many times, but I need a specific part of it.
When we get to the limit part, I had it written like this:
$\lim_{n \to +\infty} a_{n+1} = \sqrt{2+\lim_{n \to +\infty} a_n}$
What is the reason I am allowed to put the limit under the square root? Why am I just allowed to put it there? I know it's true, but I am not sure why. I need to justify that in order to receive credit. My instructor said it is a "special word." I have no idea what the word is.
Comment: Continuity. But you need to show that the limit exists first.
Comment: @OliverDiaz please read the question again! It clearly asks about "What is the reason I am allowed to put the limit under the square root" and starts with "I know this question has been asked many times"! Otherwise, it would have been closed as a duplicate of [this question](https://math.stackexchange.com/questions/115501/sqrtc-sqrtc-sqrtc-cdots-or-the-limit-of-the-sequence-x-n1-sq).
Comment: @OliverDiaz so you do agree that the question is about "What is the reason I am allowed to **put the limit under the square root**?" And "continuity" is the "special word"? "Limit exists" contains 2 words :)
Comment: @Sil: Though relevant, the OP is more nuanced than the simpler statement in the link you claim the OP is a duplicate of. The OP is more about fixed points of a given function.
Comment: @rtybase: I READ the question. Now if believe an question is a duplicate (in this case, it is) and the question should be closed, then at least the correct duplicate should be referenced. Sil's request points to a link that is related but does not fully addresses the OP.  The link you provide is more appropriate.
Comment: @rtybase: of course! but the continuity of $f(x)=\sqrt{2+x}$ is only part of the reason in this instance. The main justification being that the limit actually exists.
Answer: IF the limit exists, it will be a fixed point of the function $\sqrt{2+x}$, in other words a solution to the equation
$$x=\sqrt{2+x}$$
Here's why:
$$\lim_{n\to\infty}a_{n+1}=\lim_{n\to\infty}\sqrt{2+a_n}$$
Given two functions $f$ and $g$, as long as $f$ is continuous and $\lim_{x\to x_0}g(x)$ exists, then
$$\lim_{x\to x_0}f(g(x))=f\left(\lim_{x\to x_0}g(x)\right)$$
This can be shown fairly routinely with the $\epsilon ,\delta$ definition of the limit.
Since $\sqrt{2+x}$ is continuous on its domain,
$$\lim_{n\to\infty}\sqrt{2+a_n}=\sqrt{2+\lim_{n\to\infty}a_n}=\lim_{n\to\infty}a_{n+1}$$
Since $x:=\lim_{n\to\infty}a_{n+1}=\lim_{n\to\infty}a_n$, the initial statement follows.
Comment: @OliverDiaz The OP did not ask about the existence of the limit....
Comment: The interesting part is to show that the limit exists!
Comment: Your argument does not solve the important question of existence of the limit.
Comment: @K.defaoite: He asked for a justification. The mere continuity of $x\mapsto\sqrt{x+2}$ is not enough. Of course. if the limit exists (as you assume) things are honky dory, but the main part of the justification for $\lim_n a_{n+1}=\sqrt{2+\lim_na_n}$ here is existence. Otherwise there fixed point theorems would be a trivial thing.
Answer: We have a few claims:
Claim: The sequence $\{ a_{n}\}_{n = 1}^\infty$ is bounded above by $2$.
Proof. The proof can be done by induction. I'll just write the induction step
$k + 1$.
$$ a_{k + 2}^2 = 2 +  a_{k + 1} < 2 + 2 \implies a_{k + 2} < 2 $$
The rest is as goes with the formal writing.
Lemma: $\{ a_n\} = \left\{ 2 \cos \frac{\pi}{2^{n + 1}} \right\} $
Proof. Similar by induction.  Assume $$ a_k = 2\cos \left( \frac{\pi}{2^{k + 1}} \right) $$
Then $$ a_{k +1}^2 = 2 + 2 \cos\left( \frac{\pi}{2^{k + 1}} \right) = 2^2  \cos^2 \left( \frac{\pi}{2^{k + 2}} \right)  $$
$$ \implies a_{k + 1} = 2 \cos \left( \frac{\pi}{2^{k + 2}} \right) $$
Hence inductively we are done.
Now, we have a specific closed form. Then we have that $\lim\limits_{n \to \infty} a_n$ exists, as $\cos \left( \dfrac{\pi}{2^{n + 1}} \right) \to \cos 0 = 1 $, as $\cos$ is a continuous function on $\left[0, \dfrac{\pi}{2} \right]$.
Thus finally we have that
$$ \lim_{n \to \infty} a_n = \lim_{n \to \infty} 2\cos \left( \frac{\pi}{2^{n + 1}} \right) = 2 $$

Edit: I have tried to find a closed-form.


Blogger: Como exibir apenas as postagens de um marcador (label) específico na homepage do blog?

Question: Estou enfrentando sérias dificuldades em solucionar um problema na criação de um template que deveria ser simples de resolver, mas já está me consumindo muito tempo sem chegar a uma solução.
Ocorre que criei um template XHTML Strict do zero, para usar em um blog com dois DIVs padrões (id="div-1" e id="div-2") em forma de duas colunas que ocupam, cada uma, 50% da tela.
Na  principal da homepage, que está dentro do "div-1", são exibidas normalmente todas as postagens publicadas, das mais recentes para as mais antigas. Para isto, usei o seguinte código:

Até aí tudo bem.
Acontece que no "div-2", eu quero que sejam exibidas SOMENTE as postagens com um marcador específico, neste caso "Notícias".
Para isso tentei usar o seguinte código:

    <data:content/>

O código acima até exibe as postagens, mas de forma igual ao "div-1".
Mesmo revisando o código não consigo visualizar onde está o erro que impede das postagens serem exibidas APENAS com o marcador "Notícias".
Qualquer ajuda é bem-vinda, pois só falta isto para eu acabar o blog e já estou há dias tentando resolver isto, sem sucesso.
Comment: _Blogger_ não é uma linguagem de programação, mas sim uma terminologia referente à site de discussão ou informação [«1»](https://en.wikipedia.org/wiki/Blogger_%28service%29) [«2»](https://en.wikipedia.org/wiki/Blog), e são normalmente desenvolvidos utilizando várias linguagens web, não uma. Assim sendo, bom seria, se desta vez editasses a tua pergunta, não ignorando o título imposto, mas mudando algum ou mesmo todo conteúdo referente a _blogger language_. Porque assim as pessoas não te conseguem acompanhar.
Comment: Oi Edilson, obrigado pela observação. Eu quis formular a pergunta da forma mais específica possível, mas acabei errando a classificação da mesma como "blogger language". Na verdade, tentei me referir às "Tags de Elementos da Página" do Blogger, conforme descreve esta página: https://support.google.com/blogger/answer/46888?hl=pt-BR&ref_topic=12449 . Alterei o título, deixando apenas a referência ao nome do serviço (Blogger), pois se não a pergunta pode ficar ambígua em relação a outros serviços de blog (WordPress, WebNode, etc).
Answer: Consegui achar a solução!
O código do "div-2" deve ter algumas sequências condicionais de tags  que servirão para exibir as postagens filtradas de acordo com o marcador (label) que você deseja.
Como exposto na própria pergunta, o código para exibir todas as postagens de forma normal deve ser:
DIV-1 (Todas as postagens)

Já no "div-2", para não haver conflito com o primeiro div, deve ser usado o código abaixo:
DIV-2 (Somente postagens com o marcador "NOTÍCIAS")

        <data:post.dateHeader/>

Caso deseje incluir algum marcador personalizado do seu blog, basta substituir a palavra "NOTÍCIAS" no código acima pela palavra que preferir.
Assim, será possível exibir na mesma página da homepage uma seção com as postagens normais e outra com as postagens filtradas por uma determinada categoria.
Espero que esta pequena resposta consiga ajudar outras pessoas que estejam com o mesmo problema.
Obrigado. De nada!


Google Cloud Storage: what is the difference between WRITER and OWNER?

Question: This seems like a simple question, but I have not been able to find the answer online.  What specific actions can the OWNER of a bucket do that a WRITER of that bucket (or any object) cannot do?  The reason I ask is that I noticed that one of my "logs" buckets has email@example.com as an OWNER and I'm wondering if I can (and possibly should?) change this to WRITER -- is it the OWNER because it actually created the bucket for me?  if an Google app creates a bucket for me, would it be a good idea for it to them remove itself as an OWNER after making "project-owners" the OWNER?  Also, wouldn't it make more sense for the "role" of project-editors to be WRITER rather than OWNER so that there is a difference between a project "owner" and a project "editor"?
Answer: For complete details on the different permissions, there's a complete chart of the differences between Reader, writer, and owner for buckets and objects in the GCS documentation.
A reader of a bucket can list its contents. A writer of a bucket can also delete objects and insert new ones. An owner of a bucket can also edit bucket metadata and ACLs.
According to the Cloud Logging Docs, OWNER is the correct permission for firstname.lastname@example.com.


How do I select a tag with text between the tag and it's parent tag?

Question: How can I distinguish, using CSS, between a tag that, were it and its contents to be deleted, would leave its parent tag empty? I don't actually want to delete it, I just want to treat it differently.
For example, given the following sample code:

test one

My test two

My test three and test four text

Test five text

My test six text

The following CSS:
a:only-child { color: #668899; }

selects for all but tests three and four.
a:not(only-child) { color: #668899; }

selects for all, but I'd expect it to select only tests three and four.
How do I select all tests except test one using only CSS?
If I can't style only tests two through six with only CSS, can I style them with jQuery? If so, how?
Comment: If you add a colon in front of the only-child it works (tested in Chrome)
`a:not(:only-child) { color: #668899; }` The reason why it was not working before was due to :not() expecting a selector, and it could not find an **ELEMENT** named "only-child" (i.e no element named ).
Comment: Will your DOM always look like this? What is special about "test one"? would you be willing to just add an id to the desired element?
Answer: This probably isn't the most efficient solution, but it works — compare the text content of each  element with the text content of its parent. If they're the same, then apply a different style:

$('div a').each(function(){
  if ($(this).text()===$(this).parent().text()) {
    $(this).addClass('onlyChild');
  }
});
.onlyChild { color: #668899; }

test one

My test two

My test three and test four text

Test five text

My test six text

Comment: Thank you for the update. And my editor wants me to make that === or !==
Comment: Thank you; that's very helpful. Do I correctly presume I could flip that to style tests two through six but not test one by changing the == to != instead? (I probably would want to find a different class name.)
Comment: Yes, just change `==` to `!=` (actually this only works properly if you use `addClass()` instead of `toggleClass()`. I'll update the answer.)
Comment: @CharlesBelov Your editor makes good suggestions! I've edited the answer again.
Answer: Right now your rule is looking for a element called only-child
Use this selector rule
a:not(:only-child) { color: #668899; }
Sample demo

a:not(:only-child) { color: red; }

test one

My test two

My test three and test four text

Test five text

My test six text

Comment: That doesn't seem to select anything.


How to match last occurrence in a string with Regex

Question: Hi I am working on RoR project with ruby-2.5.0 and Rails 5. I have a pattern to find time from a string as follows:-
time_pattern = /(\d{2}\:\d{2}:\d{2}|\d{2}\:\d{2})/
time = mystr[time_pattern]

It retuns the first matching time in the string for example if there are two times are present in the string "14:04" and "14:05" it will always return the first one which is "14:04". i need to find the second one. Please help me to find the second match using regex. I have also tried the scan method like:-
time = params.to_s.scan(time_pattern).uniq.flatten.last

But my rubocop throws an error Methods exceeded maximum allowed ABC complexity (1)
Please help. Thanks in advance.
Comment: Suggestion for readability: `\d\d` does the same as `\d{2}` but is 1 character shorter + more readable IMO. Also, you should be able to do `/\d\d\:\d\d(\:\d\d)?/` (see here: http://rubular.com/r/UX13pdJZfm). Btw, with this Regexp, `99:99:99` is matched
Comment: @MrYoshiji but on the other side of the argument: `\d\d` adds unnecessary computation, but yes your second part is much better `\d{2}:\d{2}(?::\d{2})?` or even `\d{2}(?::\d{2}){1,2}`. Also, `:` doesn't need to be escaped.
Comment: With `scan`, you need the version with a non-capturing group, and I'd use a word boundary: `params.to_s.scan(/\b\d{2}:\d{2}(?::\d{2})?\b/).uniq.flatten.last`
Comment: And to answer how to match the last occurrence: `params.to_s[/.*(\d{2}:\d{2}(?::\d{2})?)/, 1]`
Comment: it still returns the first occurrence. please help
Answer: Last Regex Match
To get the last match you can simply call #last on the #scan result.
regex = /(\d{2}\:\d{2}:\d{2}|\d{2}\:\d{2})/ # original
# or
regex = /\d{2}(?::\d{2}){1,2}/ # kudos @ctwheels

string = '12:01, 12:02, 12:03:04, 12:05'

string.scan(regex).last
#=> "12:05"

ABC-Metric
The ABC Metric is more complex and would require having a look at your whole method. But here is a blog post that explains it pretty well: Understanding Assignment Branch Condition
Another options is to change the max ABC size in the RuboCop settings. Have a look at the RuboCop Configuration Documentation and the default configuration (Metrics/AbcSize max size is set to 15 by default).
Comment: Thanks but when i use scan with last it increase my codes complexity as i am using rspec-rubocop.
Comment: @awsmsid `string.scan(regex).last` is just 1 more branch than`string[regex]` and that doesn't do the job. Also the ABC size is not depended on that single call, you could also have a look at your other code (in that method) and see if there is room for optimization. Or maybe split up the method into multiple smaller methods.
Answer: Try using the following expression: /(\d{2}:\d{2}(:\d{2})?)/g.
Here is an example of it running in ruby:
re = /(\d{2}:\d{2}(:\d{2})?)/
str = ' "14:04" and "14:05"'

# Get matches
matches = str.scan(re)

# Get last match
matches = str.scan(re)

# Get last match
lastMatch = str.scan(re).last[0]

# Print last match
puts lastMatch.to_s
# OUTPUT => "14:05"

# Print the match result
str.scan(re) do |match|
    puts match.to_s
end

Comment: @WiktorStribiżew Sorry, I updated it. I had been looking at another PHP question.
Comment: @Tony although this is now ruby, it still doesn't answer the *whole* question.
Comment: @Tony that's better, you don't need to escape the `:` though
Comment: @Tony I'd also suggest dropping capture groups: `/\d{2}:\d{2}(?::\d{2})?/` or printing will print an array instead of just the matched string.
Comment: Hey my regex is working but its returns only the first match in the string i want the last match in the string please help. i also tried time = mystr[time_pattern] but the result is same.
Comment: @Tony it returns [nil]
Comment: @awsmsid `str.scan(re)` should return an array of matches. Just use the last one.
Comment: @awsmsid So the problem was because the regex was returning the 2nd capture group: `(:\d{2})?` and not the full match. To fix this i was able to wrap the expression in another group like this: `(\d{2}:\d{2}(:\d{2})?)`. Your matches will now return 2 elements. The first is the full capture group and the last is the seconds capture group.
Comment: Thanks let me try this.
Comment: This is still a dangerous answer since the regex is flawed. The group should be non-capturing. Currently when you call *#last* on the *#scan* result you get an array `["14:05", nil]` back.


Bootstrap table: is it possible to call the function which sorts rows by column from code (without clicking the header)

Question: http://jsfiddle.net/e3nk137y/4537/

            Item
            Date
            Type

Pear  	January	 Fruit

Carrot	March	   Vegetable

Apple 	February	Fruit

In this fiddle is an example of a table. When you click the header, the table is sorted by the column belonging to that header.
My question is, if it's possible to trigger that function in some other way - from some other function. More generally: can I explicitly call the functions which are called as callbacks from various bootstrap widgets?
Answer: Firing a click on the TH as @Jaydo suggested is a good option (I was about to suggest that myself). You won't be able to control the direction (e.g. ascending or descending) you want to sort though.
Have a look at this jsFiddle. It's more like a hack, not a solution.
Setting up some additional data on the TH will help to control the sorting direction.

var table = $('#bsTable'),
    targetTH = table.find('th[data-field="' + field + '"]'),
    targetTHInner = targetTH.children('.sortable');

if (table.bootstrapTable('getOptions').sortName === field && targetTH.data('order') === order) {
    console.log('Already sorted');
    return;
}
// ironically, we need to set the data value to the oposite direction to what we want
if (order === 'asc') {
    targetTH.data('order', 'desc');
} else {
    targetTH.data('order', 'asc');
}

targetTHInner.click();
Answer: You could programatically click the header. Does this achieve what you want?
$("th[data-field='fruit'] .sortable").click();

Fiddle
Comment: Yes, that's what I need. Functionally at least. Wonder if there's a way to do it without programatically  clicking the header. Either way, thanks for the answer!
Comment: The benefit of doing it this way is that it's simple and simulates what a user would be doing.
Comment: Yes... I don't really have any cogent objections to doing it this way, just seems kind of 'funky'.
Answer: You could also add data-sort-name="fruit" to your table element to specify a default sort column.
Add data-sort-order="desc" to change the sort order.
jsfiddle
Comment: Thanks for the tip, but I don't actually need the callback to get a default sort, but to sort the as a result of some other action.
Answer: On version 1.14, I was able to achieve this by using the "refreshOptions" method and passing the sortName and sortOrder option.
$('table').bootstrapTable('refreshOptions', {
    sortName:"fruit",
    sortOrder:"desc"
});

Comment: Case sensitive params! Thank you


Show profile2 fields on users page through panels

Question: I would like to select profile2 fields on users page.
Elements:

Profile2: artist + fields
User: role artist

If the user is being viewed is an artist the panel should show its fields.
Actions:

Created the profile2 for a custom user (if I do not panelize the user/%user page the user can view the profile2 fields).
Activated the user_view pane
Added relatioship with profile 2
Now the profile2 fields appears on the UI.
Select the field header_img
Save the pane

I must have forgotten something because the profile (panelized) fields does not show any content of the profile2 fields..
Attaching some screenshots!

Thanks!!
Answer: It looks like you are doing it ok, but there is an issue related that you can check at https://www.drupal.org/node/1011370#comment-9332247.
If you update to the latest dev version of profile2, it should work, and you could select the profile context and the profile type.


TypeError: Cannot read property '1' of null

Question: Eu estou com esse problema e não faço ideia de como resolver, quero salvar imagens no storage da Azure
const blobSvc = azure.createBlobService(config.containerConnectionString);

    let filename = guid.raw().toString() + '.jpg';
    let rawdata = req.body.image;
    let matches = rawdata.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/);
    let type = matches[1];
    let buffer = new Buffer(matches[2], 'base64');

await blobSvc.createBlockBlobFromText('images', filename, buffer, {
            contentType: type
        }, function (error, result, response) {
            if (error) {
                filename = 'default-product.png'
            }
        });

O erro e apontado aqui

let type = matches[1];

mas eu não consigo entender para resolver, e a mensagem de erro:

TypeError: Cannot read property '1' of null

não ajuda muito, alguém pode ajudar?
Comment: Esse erro provavelmente é porque o `match` é null. Ou seja, não encontrou nada com a regex usada.
Answer: Muito provável que seu rawdata.match está null.
Para não ocorrer erro verifique sua variável rawdata antes:
if (matches)
{
    let type = matches[1];
    let buffer = new Buffer(matches[2], 'base64');
}

Comment: Se o `rawdata` fosse `null` o erro seria: `TypeError: rawdata is null`.
Você teria que testar `matches` e não `rawdata.`
Comment: @fernandosavio, exato.. Escrevi uma coisa e coloquei no if outra.. Ajustado, grato!
Comment: Show! o -1 era meu pra evitar dar informação errada.
Já retirei! :D
Comment: @8biT, valeu funcionou, só tive que trocar let por var


Percentage Question - Sub operation within main operation percentage

Question: This is probably a really basic question but I'm trying to work out how to calculate a percentage complete of an operation that occurs as part of a larger operation.
If the main operation is 20% complete and I then start a sub operation within this main operation which iterates 5 times to calculate something and each of those iterations represents a 20% portion then how do I calculate the percentage completion of the sub operation relative to the main operation? Obviously I can't just calculate the sub operation's percentage out of 100% as it will start at 0% and not 20% which is where it should start. I hope that makes sense. If it needs more explanation then I'm happy to try and provide some more detail!
EDIT: Here's an example of what I'm trying to explain:-
Outer operation currently at 20%
Inner operation now starts at 0% and iterates 10 times (10%, 20%, 30%, etc). How do I scale/refactor the sub operation percentages to account for it being part of a larger operation? So I wouldn't want the inner operation to start at 0% but 20% and then each increment should reflect the fact that it is part of the outer operation. Does that make sense?
Comment: I think that it be better if you  give us an example that illustrate what you are asking
Comment: I've added an edit to try and explain the problem through an example
Answer: You need to assign a percentage to the sub operation.  You are currently $20\%$ done.  What percentage done will you be when the sub operation completes?  Maybe you will then be $50\%$ done, which says the sub operation is $30\%$ of the work.  If you do five run throughs, each one is then $6\%$ of the total, $\frac 15 \cdot 30\%$


Filtro Ajax no wordpress

Question: Ola, gostaria de saber se alguém já fez alguma funcionalidade igual a desse site, http://www.todeschinisa.com.br/pt/onde-encontrar filtrando os post usando um formulario e ajax para nao precisar dar o reload na pagina.
Estou com a seguinte situação, criei um custom post type revendas, onde ativei 'taxonomies'  => array( 'category' ), criei a categoria Brasil com os filhos como estados, e dentro de cada estado as cidades.
Mas nao estou conseguindo criar um formulario nem filtrar os post
[Brasil] [Estado] [Cidade] [Filtrar]

seria algo assim.
Comment: Crie as funções no functions.php e acesse usando ajax. Tipo assim: http://www.kenner.com.br/action-gel-explore/
Comment: show, bem isso, teria algum tutorial com o passo a passo para me basear?
Comment: Para adiantar, dá uma olhada nesse artigo que tem a função para incluir no functions.php e o código javascript para acessar a função que mais tarde quando eu chegar em casa monto uma resposta completa que facilitará o entendimento. https://codex.wordpress.org/AJAX_in_Plugins
Comment: Blz, vou ler o artigo. provavelmente amanhã vou retomar o desenvolvimento do projeto
Comment: Andre, você me deu uma baita luz, me diga uma coisa, sou bem novo na area, você recomenda fazer o filtro do pais estado cidade usando categoria, um um custom field com ACF crio os campos, Pais, estado e cidade
Comment: Patrick, nesse aí eu implementei com tabela nova no mysql porque advém de uma planilha enviada para a carga.
Answer: Por segurança, para que você não tenha requisições para vários arquivos php, aconselho você a criar as funções no functions.php e acessar as funções usando ajax.
Para esta implementação usei apenas uma tabela, mas você poderia montar usando o formato de armazenamento wordpress, depende do tempo e prazo. :)
No functions.php, criamos as funções e as ações para permitir a passar parâmetros:
// Ação de callback do Ajax
function get_cidade_from_uf() {
  global $wpdb;
  $query = " SELECT  distinct m.TXT_CIDADE FROM tb_lojas m
             WHERE m.COD_UF = '".$_GET['COD_UF']."' ORDER BY TXT_CIDADE ASC ";
  $cidades = $wpdb->get_results($query, OBJECT);
  die(json_encode($cidades));
}
add_action( 'wp_ajax_get_cidade_from_uf', 'get_cidade_from_uf' );
add_action( 'wp_ajax_nopriv_get_cidade_from_uf', 'get_cidade_from_uf' );

// Ação de callback do Ajax
function get_bairro_from_cidade_uf() {
  global $wpdb;
  $query = " SELECT  distinct m.TXT_BAIRRO FROM tb_lojas m
             WHERE m.COD_UF = '".$_GET['COD_UF']."'
               AND m.TXT_CIDADE = '".$_GET['TXT_CIDADE']."'
             ORDER BY TXT_BAIRRO ASC ";
  $bairros = $wpdb->get_results($query, OBJECT);
  die(json_encode($bairros));
}
add_action( 'wp_ajax_get_bairro_from_cidade_uf', 'get_bairro_from_cidade_uf' );
add_action( 'wp_ajax_nopriv_get_bairro_from_cidade_uf', 'get_bairro_from_cidade_uf' );

// Ação de callback do Ajax
function get_procurar_loja() {
  global $wpdb;
  $uf = $_GET['COD_UF'];
  $cidade = $_GET['TXT_CIDADE'];
  $bairro = $_GET['TXT_BAIRRO'];
  $query = " SELECT l.TXT_LOJA, l.TXT_ENDERECO, l.TXT_BAIRRO, l.TXT_CIDADE, l.COD_UF FROM tb_lojas l WHERE l.COD_UF = '".$uf."' ";
  if ( (isset( $cidade)) ) {
     if ( ($cidade !='') && ($cidade != 'undefined') && ($cidade != 'CIDADE') && ($cidade != 'SELECIONE UMA CIDADE') ){
       $query .= " AND l.TXT_CIDADE = '".$cidade."' ";
     }
  }
  if ( (isset( $bairro)) ) {
     if ( ($bairro !='') && ($bairro != 'undefined') && ($bairro != 'BAIRRO') && ($bairro!= 'SELECIONE UM BAIRRO') ){
         $query .= " AND l.TXT_BAIRRO = '".$bairro."' ";
     }
  }
  $query .= "   ORDER BY l.TXT_LOJA ASC ";
  $lojas = $wpdb->get_results($query, OBJECT);
  die(json_encode($lojas));
}
add_action( 'wp_ajax_get_procurar_loja', 'get_procurar_loja' );
add_action( 'wp_ajax_nopriv_get_procurar_loja', 'get_procurar_loja' );

No javascript você coloca os eventos e os tratamentos:
 $("#btnProcurar").click(function() {
    var inputUF = $("#txtUF").val();
    var inputCidade = $("#txtCIDADE").val();
    var inputBairro = $("#txtBAIRRO").val();
    $.ajax({
        url: '/wp-admin/admin-ajax.php',
        type: 'get',
        data: {
            'action': 'get_procurar_loja',
            'COD_UF': inputUF,
            'TXT_CIDADE': inputCidade,
            'TXT_BAIRRO': inputBairro
        },
        success: function( data ){
            var data = JSON.parse(data);
            var out = '
';
            jQuery.each(data, function(index, item) {
                var loja = item.TXT_LOJA.trim();
                 out += "
"+item.TXT_LOJA+"
"+item.TXT_ENDERECO+"
"+item.TXT_BAIRRO+" - "+item.TXT_CIDADE+" - " + item.COD_UF + "

";
              });
            out += '
';
            $('#hotsite-lojas').html(out);
            $('#hotsite-lojas').show();
        }
    });
  });
  $("#txtUF").change(function() {
    var inputUf = $("#txtUF").val();
    $.ajax({
        url: '/wp-admin/admin-ajax.php',
        type: 'get',
        data: {
            'action': 'get_cidade_from_uf',
            'COD_UF': inputUf
        },
        success: function( data ){
            var data = JSON.parse(data);
            var selectCidade = document.getElementById("txtCIDADE");
            selectCidade.innerText = null;
            var selecione = document.createElement("option");
            selecione.text = '  SELECIONE UMA CIDADE';
            selectCidade.add(selecione);
            jQuery.each(data, function(index, item) {
              var option = document.createElement("option");
              option.text = '  ' + item.TXT_CIDADE;
              if (option.text != 'undefined') {
                selectCidade.add(option);
              }
            });
        }
    });
  });
  $("#txtCIDADE").change(function() {
    var inputUF = $("#txtUF").val();
    var inputCidade = $("#txtCIDADE").val();
    $.ajax({
        url: '/wp-admin/admin-ajax.php',
        type: 'get',
        data: {
            'action': 'get_bairro_from_cidade_uf',
            'COD_UF': inputUF,
            'TXT_CIDADE': inputCidade
        },
        success: function( data ){
            var data = JSON.parse(data);
            var selectBairro = document.getElementById("txtBAIRRO");
            selectBairro.innerText = null;
            var selecione = document.createElement("option");
            selecione.text = '  SELECIONE UM BAIRRO';
            selectBairro.add(selecione);
            jQuery.each(data, function(index, item) {
              var option = document.createElement("option");
              option.text = '  ' + item.TXT_BAIRRO;
              if (option.text != 'undefined') {
                selectBairro.add(option);
              }
            });
        }
    });
  });

Espero que ajude.
Com Custom Type ficaria bem melhor, mas aí fica como desafio... e não esquece de compartilhar.
Grande abraço
Comment: fiz de outra maneira, vou postar assim que tiver um tempo, mas fiz com busca, a pessoa digita a localizacao ele diz se tem ou nao. Mas se puder ajudar a turma com custom post nao achei nenhum material explicando como fazer
Comment: show, irei tentara fazer aqui assim que tiver o resultado funcionando compartilho para a galera
Comment: Andre, voce quem desenvolve a mais tempo que eu pode me responder essa, saberia como criar uma forma dinamica para inserir as informacoes na tabela, por exemplo criar um custom post type e a apartir dele alguma tabela para posteriormente puxar essas informacoes. Nao quero perder o dinamismo do wordpress, toda vez que precisar adicionar uma revenda precisar editar a tabela
Comment: assim que parar um minuto (ou mais, rs) vou escrever com custom post types..

Filtro Ajax no wordpress


Get data from .CDB file

Question: i would like to get data from.cdb file. Is it possible to retrieve data from .cdb file without knowing keys names?
Answer: If you are talking about CDB constant database files, the cdbdump program will dump all data in cdbmake format on standard output.
Comment: Where will this cdbdump come from ?
Comment: Follow the 'CDB constant database' link above, then go to the 'How to install cdb ' link on that page.

Get data from .CDB file


MySQL / phpMyadmin: "many connection errors"

Question: My app no longer connects to its DB and phpmyadmin says #1129 - Host 'xxx.xx.xx.xx' is blocked because of many connection errors; unblock with 'mysqladmin flush-hosts'
mysql_error() prints out the same message. Could this be because of too many connections?
What causes this?
Answer:
Open a command prompt (or shell in Linux) with administrative privilleges
Flush all hosts in MySQL using mysqladmin:
mysqladmin flush-hosts -u root -p
Open my.cnf (Linux) or my.ini (Windows) and change max_connect_errors variable to a large number. I used:
max_connect_errors= 1000000
Restart MySQL server
Answer: From the manual: http://dev.mysql.com/doc/refman/4.1/en/blocked-host.html

The number of interrupted connect
  requests allowed is determined by the
  value of the max_connect_errors system
  variable. After max_connect_errors
  failed requests, mysqld assumes that
  something is wrong (for example, that
  someone is trying to break in), and
  blocks the host from further
  connections until you execute a
  mysqladmin flush-hosts command or
  issue a FLUSH HOSTS  statement. See
  Section 5.1.3, "Server System
  Variables".

You could be having network problems connecting to your database.
Answer: We had this problem when using monit to monitor our DB server. Monit will cause connection errors if your config is of the form:
if failed port 3306 with timeout 15 seconds 2 times within 3 cycles then alert

Rather than
if failed port 3306 protocol mysql with timeout 15 seconds 2 times within 3 cycles then alert

The lack of 'protocol mysql' causes the connection error count to notch up.


AngularJS: How can i make a page inactive for some time using a timer countdown stored in the cookie?

Question: I am storing a timestamp in the cookie, and after 3 failed login attempts by a user, i need to prevent the user from accessing the login page for sometime,say in this case 10seconds. I prevent the access to login page by poping up a counter modal for 10 seconds.
Everything works correctly, except when the user clicks on reload/refresh key, the timestamp is reset back to zero (0) and then he can access the login page.
How can i prevent this?
app.controller('LoginAttemptsController', function ($scope, $cookies, $log, $interval, $timeout) {

    var counter = 0;
    $scope.show = false;
    $scope.popup = false;
    $scope.newcounter;

    $scope.setcookie = function () {

        $cookies['myCookieArray'] = {
            'key1': 10
        };

        getmycookiesback = $cookies['myCookieArray'];
        $log.info(getmycookiesback.key1);

        stop = $interval(function () {
           $scope.setnewtimer( getmycookiesback.key1);
           getmycookiesback.key1 = $scope.newcounter;
            console.log(getmycookiesback.key1);
        }, 1000);

    };

    $scope.setnewtimer = function (timer){

        if(timer<=0) {
            $scope.popup = false;
            $scope.newcounter = 10;
            $interval.cancel(stop);
            return $scope.newcounter;
        }

        else {
        $scope.newcounter = timer - 1;
        return $scope.newcounter;
        }

    };

    $scope.timeoutInit = function () {
        $timeout.cancel($scope.timeOutSession);
        console.log('timeout handler invoked');

        $scope.timeOutSession = $timeout(function (timeOutValue) {
            $scope.startCountdown(); // initiates the countdown display
        }, $scope.timeOutValue);
    };

    $scope.checkAttempts = function () {

        var username = $scope.Username;
        var password = $scope.Password;

        if (username == 'kk' && password == 'kk') {
            window.location = "./home.html";
        } else if (username == 'kk' && password != 'kk') {
            $scope.show = true;
            $scope.alertMessage = "Sorry, we don't recognize this user";
            counter = counter + 1;

        } else if (username != 'kk' && password == 'kk') {
            $scope.show = true;
            $scope.alertMessage = "Sorry, we don't recognize this user";
            counter = counter + 1;

            /* empty the fields */
            $scope.username = '';
            $scope.password = '';
        } else if (username != 'kk' && password != 'kk') {
            $scope.show = true;
            $scope.alertMessage = "Sorry, we don't recognize this user";
            counter = counter + 1;
        }

        if (counter == 3) {
            counter = 1;
            $scope.popup = true;
            this.setcookie();
            /* window.location = '../login.html'; */
        }
    };

});

Comment: Login attempt throttling is not something that should be implemented on the client-side.
Comment: As @RobbyCornelissen said. It is not appropriate to do this client-side without also doing it on the server.
Comment: @RobbyCornelissen and phuzi 47 thanks for your  feedback. I understand  this is not the best implementation for this. However, i only need this for quick demo purposes without necessarily having to implement it on the server side. Is there a way to do this without the back-end implementation?
Answer: As mentioned in comments, you should not do this only server side. But as you said you need this only for demo purposes, you can store the value of your counter variable in a cookie and increment its value whenever user enters wrong credentials.
Set cookie:
    $cookies['myCounter'] = 0;

Then fetch the cookie and update it if the user enters invalid credentials:
$scope.checkAttempts = function () {

    var counter = $cookies['myCounter'];

    var username = $scope.Username;
    var password = $scope.Password;

    if (username == 'kk' && password == 'kk') {
        window.location = "./home.html";
    } else if (username == 'kk' && password != 'kk') {
        $scope.show = true;
        $scope.alertMessage = "Sorry, we don't recognize this user";
        $cookies['myCounter'] = counter + 1;

    } else if (username != 'kk' && password == 'kk') {
        $scope.show = true;
        $scope.alertMessage = "Sorry, we don't recognize this user";
        $cookies['myCounter'] = counter + 1;

        /* empty the fields */
        $scope.username = '';
        $scope.password = '';
    } else if (username != 'kk' && password != 'kk') {
        $scope.show = true;
        $scope.alertMessage = "Sorry, we don't recognize this user";
        $cookies['myCounter'] = counter + 1;
    }

    if (counter == 3) {
        counter = 1;
        $scope.popup = true;
        this.setcookie();
        /* window.location = '../login.html'; */
    }
};

Also you can use ngStorage  for storing the counter variable in localStorage
Answer: Thanks for your contributions. I however got the solution to this. For more details on the work around visit https://github.com/emmonmoses/AngularJS-Session-Captcha-Throttle/edit/master/controllers/LoginAttemptsController.js
var counter = 0;

$scope.setCookie = function(){
    mycookie = $cookies.getObject('time');
    if(mycookie){
        console.log("exists");
        if(mycookie.suspendedTime = 0){
            $scope.timeobj = {
                suspendedTime : 0,
                suspendedMinutes : 0,
                suspendedSeconds : 0
            }
            $cookies.putObject('time',$scope.timeobj);
        }
        else{
            cookietime = $cookies.getObject('time');
            cookiesuspendedtime = cookietime.suspendedTime;
            currenttime = new Date();
            console.log(cookiesuspendedtime);
            console.log(currenttime.getTime());
        var timedifference = (cookiesuspendedtime - currenttime.getTime()) / 1000;
        console.log(timedifference);
        var minutedifference = Math.floor(timedifference/60);
        var seconddifference = Math.floor(timedifference - (minutedifference * 60));
            if(timedifference < 120){
                $scope.timeobj = {
                    suspendedTime : cookiesuspendedtime,
                    suspendedMinutes : minutedifference,
                    suspendedSeconds : seconddifference
                }
                $cookies.putObject('time',$scope.timeobj);
                this.suspension();
            }
            else{
                $scope.timeobj = {
                    suspendedTime : 0,
                    suspendedMinutes : 0,
                    suspendedSeconds : 0
                }
                $cookies.putObject('time',$scope.timeobj);
            }
        }
    }
    else{
        $scope.timeobj = {
            suspendedTime : 0,
            suspendedMinutes : 0,
            suspendedSeconds : 0
        }
        $cookies.putObject('time',$scope.timeobj);
    }
}
$scope.suspension = function(){
    $scope.popup = true;
    mycookie = $cookies.getObject('time');
    if(mycookie.suspendedTime == 0){
        newsuspension = new Date();
        newsuspension2 = newsuspension.getTime();
        console.log(newsuspension2);
        newsuspendedtime = newsuspension2 + 120000;
        console.log(newsuspendedtime);
        $scope.timeobj = {
            suspendedTime : newsuspendedtime,
            suspendedMinutes :2,
            suspendedSeconds : 0
        }
        $cookies.putObject('time',$scope.timeobj);
        console.log("suspended");
    }

    stop = $interval(function () {
        getMyCookie = $cookies.getObject('time');
        $scope.suspendedtime = getMyCookie.suspendedTime;
        $scope.Minute = getMyCookie.suspendedMinutes;
        $scope.Seconds = getMyCookie.suspendedSeconds;
        $scope.countdown($scope.Minute, $scope.Seconds);
        $scope.timeobj = {
            suspendedTime : $scope.suspendedtime,
            suspendedMinutes :$scope.Minute,
            suspendedSeconds : $scope.Seconds
        }
        $cookies.putObject('time',$scope.timeobj);
     }, 1000);
}

$scope.countdown = function (minutes,seconds){
    if(minutes == 0 && seconds == 0){
        $interval.cancel(stop);
        $scope.popup = false;
        $scope.suspendedtime = 0;
        $scope.Minute = 2;
        $scope.Seconds = 0;
    }
    else if(minutes == 0 && seconds != 0){
        $scope.Seconds--;
    }
    else if(minutes != 0 && seconds == 0){
        $scope.Minute--;
        $scope.Seconds = 59;
    }
    else if($scope.minutes != 0 && $scope.seconds != 0){
        $scope.Seconds--;
    }
}

$scope.checkAttempts = function () {
    var username = $scope.Username;
    var password = $scope.Password;
    if (username == 'kk' && password == 'kk') {
        window.location = "./home.html";
    } else if (username == 'kk' && password != 'kk') {
        $scope.show = true;
        $scope.alertMessage = "Sorry, we don't recognize this user";
        counter = counter + 1;
        $scope.username = '';
        $scope.password = '';
    } else if (username != 'kk' && password == 'kk') {
        $scope.show = true;
        $scope.alertMessage = "Sorry, we don't recognize this user";
        counter = counter + 1;
        $scope.username = '';
        $scope.password = '';
    } else if (username != 'kk' && password != 'kk') {
        $scope.show = true;
        $scope.alertMessage = "Sorry, we don't recognize this user";
        counter = counter + 1;
        $scope.username = '';
        $scope.password = '';
    }
    if (counter == 3) {
        counter = 1;
        this.suspension();
    }
};


How to upgrade Ionic framework of my Ionic project?

Question: When I do ionic info, I see
Cordova Platforms  : android 7.0.0 browser 5.0.1
Ionic Framework    : ionic-angular 3.8.0
I want to upgrade it to
Cordova Platforms  : android 7.0.0 browser 5.0.3
Ionic Framework    : ionic-angular 3.9.2
I have used the command npm install -g ionic@latest but ionic framework has not updated. I have also remove -g still its not updated. What do I do ?
I need same configuration as my other project.
Comment: Possible duplicate of [Ionic 2: How to update Ionic library for an existing project?](https://stackoverflow.com/questions/42591456/ionic-2-how-to-update-ionic-library-for-an-existing-project)
Comment: You could take required dependencies from package.json of that other project then just npm install
Answer: You can go to your package.json file, it should be in the root directory of the app.
You will notice the versions of the app and several node modules that you are using.
Set appropriate version number, you can lookup the latest versions available here, search it here and update your package.json
https://www.npmjs.com/search?q=ionic
Once you are done updating package.json, then delete(backup) your node_modules directory and do
npm install
Make sure you read release notes and change log before updating version as they have breaking changes.


How to set the network profile of Windows 7 via group policy?

Question: We are deploying client computers and in testing noticed that the first time the user logs into the computer, it asks them if the location is a home, work, or public location. We are worried that some users in our workplace might misread it (or not read it at all) and click Public, thus likely denying our access to the computer and messing up security settings and such.
Can we set our network to be a "Work Network" location via group policy or some other mechanism of our Windows Domain so that the user is not prompted when connected to our network?
Also these are laptops, so we don't want every network they connect to be set as work network, and we have several access points (wired and three wireless) which our users often switch between so I'm not yet sure if it reprompts with each access point but I have the feeling it will, and I would like all of these to be set to the Work profile type.
Answer: Hey Ricket, I think I have your answer for you.
First off, in Windows 7, some hardware will ask you this, even though you've prespecified a domain for the machine to join. There is a hotfix that applies to this specific issue.
http://support.microsoft.com/kb/2028749/
and Secondly, if you'd like to set a Group Policy that will prevent the user from changing the network location, you can do that by following this:
Group Policy for Network Location >> Computer Configuration  / Windows Settings / Security Settings / Network List Manager Policies / All Networks. Change Network Location to User cannot change location.
Those two together should give you what you're looking for.
Comment: I think that hotfix applies to my exact situation; we are deploying these via Windows Deployment Services and so they are preconfigured with the Unattend.xml file. Thanks!
Comment: No problem, let me know if you have any other questions, or even if everything goes perfectly!