Alternendo for differentials : can a differential denominator be zero?

Question: If $\frac{dA(x)}{dx} = \frac{dB(t)}{dt} $
I can write
$\frac{dA}{dB} = \frac{dx}{dt}$
for which dB must be non-zero. But, since dB is a differential (= infinitesimal but finite) the above relation must hold true always.
Am I wrong in my reasoning?
Comment: It depends on the framework. In the standard framework this reasoning isn't valid, but can be cleaned up to give valid reasoning. In any framework you should really be careful about what this means: what is $\frac{dA}{dB}$ a function of? Is it a function of $B$?
Comment: what I take from this is that, dB, for it to be zero or non-zero, is first related to A or equivalently dA. We have to get to that function as you have said. If that dA/dB is indeed a function of B then?
Answer: You are absolutely right in your reasoning. $dB$ will tend to 0 but will always be non-zero. And if this did not hold, we would not be able to solve differential equations by mere separation and certain other methods.


Adding Microsoft's Emotion API to HTML website

Question: I'm trying to simply create a HTML webpage that gives me emotions from images input by the user.
Using Microsoft's documentation I created a HTML file below:
<code><!DOCTYPE html>
<html>
<head>
    <title>JSSample</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
    $(function() {
        $.ajax({
            url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","my-key");
            },
            type: "POST",
            // Request body
            data: {"url": "https://oxfordportal.blob.core.windows.net/emotion/recognition1.jpg"},
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function() {
            alert("fail");
        });
    });
</script>
</body>
</html>
</code>
My understanding is that this should work without the need of a server, however, I am always getting 'fail' message on loading the website.
Any help would work, thank you!
Comment: Can't use ajax in `file://` protoocol without changing browser security settings which is not typically a good idea. Can set up a local server very quickly though with numerous different packages to do it
Comment: I'm quite a novice at this type of thing, could you please let me know how I could possibly build this HTML page and let me work? Thank you!
Comment: open the page on a server . That server can be a localhost right on your computer. How to set it up is an easy web search
Comment: Hi, tried this however it still doesn't work.
Answer: Use the API testing tool we (Microsoft) have on over here:
https://dev.projectoxford.ai/docs/services/5639d931ca73072154c1ce89/operations/563b31ea778daf121cc3a5fa/console
Ensure you can make a correct request and you are actually setting your api key and not sending my-key on over.
If your key is invalid you'll get an error in the javascript console: 'Access-Control-Allow-Origin' header is present on the requested resource.
If your key is valid but your data is not escaped, you'll get a 400 bad request error. Update your data field to wrap with ''. See my example here (fill in your key) http://jsfiddle.net/w3npr1ue
<code>$(function() {
        $.ajax({
            url: "https://api.projectoxford.ai/emotion/v1.0/recognize",
            beforeSend: function(xhrObj){
                // Request headers
                xhrObj.setRequestHeader("Content-Type","application/json");
                xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key","SetYourKey");
            },
            type: "POST",
            // Request body
             data: '{"url": "http://1.bp.blogspot.com/-dWka6rPeHZI/UL7newH9TnI/AAAAAAAAAQI/OfU3TW0dDBE/s220/Asa%2Band%2BDada%2Bin%2Bst.%2Bpetersburg%2BSmall.jpg"}',
        })
        .done(function(data) {
            alert("success");
        })
        .fail(function(error) {
            console.log(error.getAllResponseHeaders());
            alert("fail");
        });
    });
</code>
Comment: weird, whats happening is a CORS issue - browser security. I'll see what I can find out, meanwhile you can try a C# or other alternative to get you going. I'll post more details here when I get a reply back.
Comment: Hey! Thank you so much, that worked fine. I was wondering however, if I'm able to make this into a HTML file? I actually need to do this as part of my final year engineering project.
Comment: It's an issue the team is looking into it :)
Comment: Thanks for your help! Please let me know when I'll be able to generate a working HTML file! :)
Comment: Hi, would you please be able to let me know how to display the result, i.e. the emotions as an output? Thanks.
Comment: What do you want to show? The results returned give you the pixel locations of faces and then the emotions


Prove or disprove that the following group makes a vector space

Question: So, this question has me completely stumped. I'm supposed to either prove or disprove that the following group makes a vector space. Here are the conditions I must prove:
V$\mathbb{=F=C}$ with regular addition of $\mathbb{C}$ and with the following scalar multiplication:
∀α ∈ F, v ∈ V | α$\boxdot$v = (Reα)v
Comment: Calling this a group is confusing. _Without_ the multiplication it is indeed an additive group, but that is not what the question is about.
Answer: No.
Scalar multiplication must be compatible with the multiplication rule in the field.  Thus we require that $$a(b\vec v)=(ab)\vec v$$
For all $a,b\in \mathbb F$.
Alas, this fails in your example.  Take, say, $a=b=i$.
Comment: Just clarifying: why would'nt we have Re(a)(Re(b)v)=0=Re(a)Re(b)v? Is it that it would actually be Re(a)(Re(b)v)=0, Re(ab)v=-1v?
Comment: If $a,b\in \mathbb R$ then the compatibility holds.  However if we take $a=b=i$ and $\vec v$ any non-zero vector, we get that $i\boxdot \vec v=\vec 0$ so the left hand is $\vec 0$.  The right hand, however, is $-\vec v$
Comment: Ok. so basically,:  (a*b)⊡$\vec v$=Re(a)*Re(b)*$\vec v$?
Comment: What?  Why would that be? $(a* b)\boxdot \vec v=Re(a* b)\vec v$.  I mean, it's your definition.
Comment: All I am doing is following your definition.  If $b=i$ then $b\boxdot \vec v=i\boxdot \vec v = Re(i)\vec v =\vec 0$.  And so on.
Comment: I'm sorry but doesn't Re(i∗i)=-1? The proof with just b=i makes sense to me, but not with the a.
Comment: Let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/58347/discussion-between-user3250068-and-lulu).


The equivalence of "enumerate" in cython

Question: If one defines a pointer vector in cython, what is the similar function or procedure as enumerate in python to go through both indexes and values of elements in the pointer array in a loop inside a C declared type function?
test.pyx
#cython: wraparound=False
#cython: boundscheck=False
#cython: cdivision=True
#cython: nonecheck=False
from cpython cimport array
import cython
import numpy as np
import ctypes
cimport numpy as np
cdef extern from "math.h":
     cpdef double log(double x)
     cpdef double exp(double x)

def void initial(int *ns, int *m, double *emax, double* x, double* hx, double*
        hpx, int *lb, double *xlb, int *ub, double *xub, int* ifault, int* iwv,
        double* rwv):
      cdef int nn, ilow, ihigh, i
      cdef int iipt, iz, ihuz, iscum, ix, ihx, ihpx
      cdef bint horiz
      cdef double hulb, huub, eps, cu, alcu, huzmax

      eps = exp(-emax[0])
      ifault[0] = 0
      ilow = 0
      ihigh = 0
      nn = ns[0]+1

      if (m[0] < 1):
         ifault[0] = 1

      huzmax = hx[0]
      if not ub[0]:
         xub[0] = 0.0

      if not lb[0]:
         xlb[0] = 0.0

      hulb = (xlb[0]-x[0])*hpx[0] + hx[0]
      huub = (xub[0]-x[0])*hpx[0] + hx[0]
      if (ub[0] and lb[0]):
         huzmax = max(huub, hulb)
          cu = exp((huub+hulb)*0.5-huzmax)*(xub[0]-xlb[0])
      else:
         cu = 0.0
         if (m[0] < 2):
             ifault[0] = 1

      if (cu > 0.0):
          alcu = log(cu)
      #set pointers
      iipt = 5
      iz = 8
      ihuz = nn+iz
      iscum = nn+ihuz
      ix = nn+iscum
      ihx = nn+ix
      ihpx = nn+ihx
      iwv[0] = ilow
      iwv[1] = ihigh
      iwv[2] = ns[0]
      iwv[3] = 1
      if lb[0]:
         iwv[4] = 1
      else:
         iwv[4] = 0

      if ub[0]:
         iwv[5] = 1
      else:
         iwv[5] = 0

      if ( ns[0] < m[0]):
         ifault[0] = 2

      iwv[iipt+1] = 0
      rwv[0] = hulb
      rwv[1] = huub
      rwv[2] = emax[0]
      rwv[3] = eps
      rwv[4] = cu
      rwv[5] = alcu
      rwv[6] = huzmax
      rwv[7] = xlb[0]
      rwv[8] = xub[0]
      rwv[iscum+1] = 1.0
      for i from 0 <= i < m[0]:
         rwv[ix+i] = x[i]
         rwv[ihx+i] = hx[i]
         rwv[ihpx+i] = hpx[i]
      i = 0
      while (i < m[0]):
            update(&iwv[3], &iwv[0], &iwv[1], &iwv[iipt+1], &rwv[iscum+1], &rwv[4],
                    &rwv[ix+1], &rwv[ihx+1], &rwv[ihpx+1], &rwv[iz+1],
                    &rwv[ihuz+1], &rwv[6], &rwv[2], lb, &rwv[7], &rwv[0], ub,
                    &rwv[8], &rwv[1], ifault, &rwv[3], &rwv[5])
            i = iwv[3]

def void update(int *n, int *ilow, int *ihigh, int* ipt, double* scum, double
        *cu, double* x, double* hx, const double* hpx, double* z, double* huz,
        double *huzmax, double *emax, int *lb, double *xlb, double *hulb, int *ub,
        double *xub, double *huub, int* ifault, double *eps, double *alcu):

      n[0] = n[0]+1
      print "number of points defining the hulls", n[0]
      print " values of x: " , x[0],x[1],x[n[0]]
      print "index of the smallest x(i)", ilow[0]
      print " values of x: " ,x[ilow[0]]
      print "Update z,huz and ipt   "

def foo(int ns, int m, double emax,
         np.ndarray[ndim=1, dtype=np.float64_t] x,
         np.ndarray[ndim=1, dtype=np.float64_t] hx,
         np.ndarray[ndim=1, dtype=np.float64_t] hpx,
         int num):

    cdef np.ndarray[ndim=1, dtype=np.float64_t] rwv
    cdef np.ndarray[ndim=1, dtype=np.int64_t] iwv
    # initializing arrays
    rwv = np.zeros(ns*6+15, dtype=np.float64)
    iwv = np.zeros(ns+7, dtype=np.int64)
    cdef double xlb = np.min(x)
    cdef double xub = np.max(x)
    cdef int lb=0
    cdef int ub=0
    cdef int ifault = 0
    cdef double beta = 0.

    initial(&ns, &m, &emax,
            &x[0],
            &hx[0],
            &hpx[0],
            &lb,
            &xlb,
            &ub,
            &xub,
            &ifault,
            <int *>(&iwv[0]),
            &rwv[0]
            )

python code
import numpy as np
from test import foo

m = 3
ns = 100
emax = 64

x = np.zeros(10, float)
hx = np.zeros(10, float)
hpx = np.zeros(10, float)

x[0] = 0
x[1] = 1.0
x[2] = -1.0
print x
def normal(x):
    return -x*x*0.5,-x

hx[0], hpx[0] = normal(x[1])
hx[1], hpx[1] = normal(x[2])
hx[2], hpx[2] = normal(x[3])
print hpx

num = 20
foo(ns, m, emax, x, hx, hpx, num)

Comment: A good ol' `for` loop over the indices, in which the first step is to get the pointer at index `i`?
Comment: a for loop over indexes?
Comment: @DanielSanchez I want to get both values and indexes of the pointer array in a loop.
Comment: @Dalek, use a normal for loop and then get the pointer with that index
Comment: @DanielSanchez for instance if I give `index=1` to the pointer it returns the third element of the pointer in my code. I want to see what is going on..
Comment: @Dalek, post your code then.
Comment: as a tip you shold visit and post on codereview, you will learn a lot. https://codereview.stackexchange.com
Comment: This doesn't look like a codereview question.  It's not asking for improvements in code organization and style.  Plus there are more `cython` eyes here.
Answer: A simple for loop would suffice, like this:
for(int i = 0; i < vecSize; ++i)
    printf("Index = %d, Value = %d\n", i, vec[i]);

where i is the current index, vec[i] is the current element's value.
PS: I assume that vec stores ints for this example and its size if vecSize.


Errors with Selenium and Python and Using Chrome Driver after upgrade to a version >89

Question: I have the following configuration, which works perfectly in it's current form.
I can use any chrome/chromedriver under v89 without any issues
Once I pass the v89 mark, it does not work anymore, giving the below error
Any help would be appreciated, since I am going crazy with this.
I tried different approaches, like using the automatic webdriver-manager installer, but failed in each attempt.
Traceback (most recent call last):\n  File \"/opt/program/src/steps/start_browser_step.py\", line 30, in handle\n    browser = self.browser(options, service)\n  File \"/opt/program/src/steps/start_browser_step.py\", line 105, in browser\n    browser = ChromeBrowser(options=options, service=service)\n  File \"/opt/bitnami/python/lib/python3.8/site-packages/selenium/webdriver/chrome/webdriver.py\", line 81, in __init__\n    super().__init__(\n  File \"/opt/bitnami/python/lib/python3.8/site-packages/selenium/webdriver/chromium/webdriver.py\", line 106, in __init__\n    super().__init__(\n  File \"/opt/bitnami/python/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py\", line 288, in __init__\n    self.start_session(capabilities, browser_profile)\n  File \"/opt/bitnami/python/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py\", line 381, in start_session\n    response = self.execute(Command.NEW_SESSION, parameters)\n  File \"/opt/bitnami/python/lib/python3.8/site-packages/selenium/webdriver/remote/webdriver.py\", line 444, in execute\n    self.error_handler.check_response(response)\n  File \"/opt/bitnami/python/lib/python3.8/site-packages/selenium/webdriver/remote/errorhandler.py\", line 249, in check_response\n    raise exception_class(message, screen, stacktrace)\nselenium.common.exceptions.WebDriverException: Message: unknown error: Chrome failed to start: crashed.\n  (chrome not reachable)\n  (The process started from chrome location /opt/program/bin/chrome-linux/chrome is no longer running, so ChromeDriver is assuming that Chrome has crashed.)\nStacktrace:\n#0 0x00400084a262 <unknown>\n#1 0x00400083b133 <unknown>\n#2 0x004000545ce1 <unknown>\n#3 0x00400056cf1c <unknown>\n#4 0x004000568c4e <unknown>\n#5 0x0040005ae38d <unknown>\n#6 0x0040005a4d83 <unknown>\n#7 0x004000573552 <unknown>\n#8 0x00400057478c <unknown>\n#9 0x0040007f33f6 <unknown>\n#10 0x004000809858 <unknown>\n#11 0x0040008090ff <unknown>\n#12 0x00400080a015 <unknown>\n#13 0x004000810cd3 <unknown>\n#14 0x00400080a39b <unknown>\n#15 0x0040007e51e7 <unknown>\n#16 0x004000827848 <unknown>\n#17 0x00400082798f <unknown>\n#18 0x004000835256 <unknown>\n#19 0x004002768fa3 start_thread\n#20 0x004002d244cf clone

This is the version I am trying to use, which does not work. I also tried with 110, 100, 90 ... all of them failed
ARG CHROME_URL="https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2F1109227%2Fchrome-linux.zip?alt=media"
ARG CHROMEDRIVER_URL="https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2F1109227%2Fchromedriver_linux64.zip?alt=media"

The below code works perfectly. The issue happens only when I use the above drivers.
FROM public.ecr.aws/bitnami/python:3.8.12

ARG CHROME_URL="https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2F843831%2Fchrome-linux.zip?alt=media"
ARG CHROMEDRIVER_URL="https://www.googleapis.com/download/storage/v1/b/chromium-browser-snapshots/o/Linux_x64%2F843831%2Fchromedriver_linux64.zip?alt=media"
ARG

RUN apt-get update -y
RUN apt-get install python3-pip -y
RUN apt-get install python3-dev -y
RUN apt-get install gcc g++ -y
RUN pip install --upgrade pip

RUN apt-get update -y
RUN apt-get install -y wget
RUN apt-get install -y unzip
RUN apt-get install -y nginx
RUN apt-get install -y git
RUN apt-get install -y xvfb
RUN apt-get install -y packagekit-gtk3-module
RUN apt-get install -y libx11-xcb1
RUN apt-get install -y libdbus-glib-1-2
RUN apt-get install -y libxt6
RUN apt-get install -y libnss3-dev
RUN apt-get install -y libgbm-dev
RUN apt-get install -y libasound2
RUN apt-get install -y ca-certificates
RUN apt-get install -y vim
RUN apt-get install -y software-properties-common apt-transport-https
RUN apt-get install -y fonts-indic
RUN apt-get install -y fonts-noto
RUN apt-get install -y fonts-noto-cjk

RUN mkdir -p /opt/program
RUN mkdir -p /opt/program/data
RUN mkdir -p /opt/program/bin/tmp

RUN wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
RUN echo "deb http://dl.google.com/linux/chrome/deb/ stable main" >> /etc/apt/sources.list.d/google.list

RUN wget $CHROME_URL -O /opt/program/bin/tmp/chrome.zip
RUN unzip /opt/program/bin/tmp/chrome.zip -d /opt/program/bin

RUN wget $CHROMEDRIVER_URL -O /opt/program/bin/tmp/chromedriver.zip
RUN unzip /opt/program/bin/tmp/chromedriver.zip -d /opt/program/bin

ENV PYTHONUNBUFFERED=TRUE
ENV PYTHONDONTWRITEBYTECODE=TRUE
ENV PATH="/opt/program:${PATH}"

COPY . /opt/program
WORKDIR /opt/program

RUN pip install -r requirements.txt

CMD ["python", "-v"]

autopep8==1.5.5
beautifulsoup4==4.10.0
black==20.8b1
boto3==1.17.2
Faker==11.3.0
flake8==3.8.4
html5lib==1.1
ImageHash==4.2.1
importlib-metadata==4.11.3
mergedeep~=1.3.4
mock==4.0.3
moto==1.3.14
numpy==1.22.4
Pillow==9.3.0
pre-commit==2.10.1
pytest==6.2.4
pytest-cov==2.12.0
pytest-env==0.6.2
pytest-pythonpath==0.7.0
python-dotenv==0.15.0
pyYAML==5.4.1
requests==2.25.1
requests-mock==1.9.3
scipy==1.8.1
selenium==4.6.0
webdriver-manager==3.8.5

from selenium.webdriver import Chrome as ChromeBrowser
from selenium.webdriver.chrome.options import Options as ChromeOptions
from selenium.webdriver.chrome.service import Service as ChromeService

options = ChromeOptions()
options.binary_location = '/opt/program/bin/chrome-linux/chrome'

user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/605.1.15 (KHTML, like Gecko) ' \
             'CriOS/85 Version/11.1.1 Safari/605.1.15'
options.add_argument(f'user-agent={user_agent}')
options.add_argument('--single-process')
options.add_argument('--allow-running-insecure-content')
options.add_argument('--ignore-certificate-errors')
options.add_argument('--disable-gpu')
options.add_argument('--hide-scrollbars')
options.add_argument('--window-size=1400,1080')
options.add_argument('--disable-cache')
options.add_argument('--headless')
options.add_argument('--no-sandbox')
options.add_argument('--disable-dev-shm-usage')
options.add_argument('--start-maximized')
options.add_argument('--kiosk')

service = ChromeService(executable_path='/opt/program/bin/chromedriver_linux64/chromedriver')

browser = ChromeBrowser(options=options, service=service)

Comment: The error was thrown in:  `browser = self.browser(options, service)` so may be some options are messed up. I wonder if it because of the `user-agent`. It should be: `options.add_argument(f'--user-agent={user_agent}')
`
Comment: @TamTam nop, same thing unfortunately. As I was saying, the above code works with chrome <=v89 ..
Answer: It seems that this whole thing happened because I have a M1 processor. For some reason, up till v89, the above scripts work with my processor as well. After that, they dont anymore ... but on Intel processors, everything is fine.
Pretty weird to be honest, but ...


Why logarithm of a negative number to a negative base is not defined?

Question: I have studied that the numbers of the form N=aˣ can be written as $\log_aN=x \;\forall N>0, a>0, a\not=1.$
Let's take $N=-8$ and $a=-2$ then $-8=(-2)^3$ and $\log_{(-2)}-8 = 3$.
Why there are restrictions on the number and the base even though $\log_{(-2)}-8 = 3$ is defined? Is there something I'm missing as I'm only learning the propaedeutics of mathematics?
Comment: Full understanding of problem you will get, if you read about complex logarithms.
Comment: Questions about logs with negative bases have been asked and answered here many times already. Please see the list under Related for some of them, doubtless there are many others you can find by doing a search.
Comment: Welcome to MSE. For some basic information about writing mathematics at this site see, *e.g.*, [basic help on mathjax notation](/help/notation), [mathjax tutorial and quick reference](//math.meta.stackexchange.com/q/5020), [main meta site math tutorial](//meta.stackexchange.com/a/70559) and [equation editing how-to](//math.meta.stackexchange.com/q/1773).
Comment: It does make sense to assert that $\log_{(-2)} [-8] = 3$, but what about $\log_{(-2)} [-4]$ or, for that matter $\log_{(-2)} [-8.01]$?  The point of logarithms is to solve problems.  What problem solving is facilitated by defining base $(-2)$ logarithms for isolated numbers, such as $-2, -8,$ or $-32$?
Comment: @user2661923 Logarithms exist regardless of whether they're of any use to us.
Comment: And what the heck are propaedeutics?
Comment: If you're now unable to see my answer [here](https://math.stackexchange.com/q/4364613), and you still want to read it, let me know by pinging me here.
Answer: If $a>0$, then $a^x$ is defined for every real number $x$ and, if $y>0$, what we denote by $\log_ay$ is the only $x\in\Bbb R$ such that $a^x=y$.
But if $a<0$ then $a^x$ is defined only for some numbers $x$; for instance, $a^{1/2}$ is undefined. That's why we don't talk about $\log_ay$; it's undefined for most numbers $y$.
Comment: @user21820 It's gone.
Comment: Thanks a lot! =)
Answer: In the special case when the given number and base both are real negative, log is well defined in terms of complex numbers and there are no restrictions.
$$ \log _{-a}(-N)=\frac{\log (-N)}{\log (-a)}= \frac{\log (N) + i \pi}{\log (a)+ i \pi} $$
$$=\frac{\pi-i\log (N)}{\pi-i\log (a)}$$
which is a complex number. The new unlabeled base can be again any real number b.
EDIT1:
If new base $b$ is positive then there is no problem but if negative we again have
$$ b= - |b|,\quad \log _{\;b} N =\frac {\log N }{\log b}=\frac {\log N }{i \pi+ \log |b|} $$
and the nestings / branch cuts of log can  propogate continuously depending on the sign of newly chosen/introduced bases.
Comment: I think you will find that the final expression you have written down is NOT independent of the choice of (positive, real) base. They also depend on the choice of branch of logarithm you chose when you wrote $\log(-a)=\log(a)+i\pi$.
Comment: Thanks, edited to include choice of sign of new base, hope OK.
Comment: I guess I wasn't clear. Pick some positive numbers $a$ and $N$. Pick two different positive bases, $b$ and $b'$. Calculate $(\pi-i\log_bN)/(\pi-i\log_ba)$ and $(\pi-i\log_{b'}N)/(\pi-i\log_{b'}a)$. Are they the same?
Comment: And there's still the matter of choosing a branch for $\log_b(-N)$.
Comment: In short, this answer is wrong, Narasimham. Why is it still here?


How do I stop loading additional assets each time I click on a link to load a new page?

Question: I have a weird problem, when I click on a link in my project, I get an extra package of assets, each click  = +1 extra package of assets. 10 clicks = 10 copies of the assets. (10 images, 10 css files 10 js files instead of 1). All my jquery events triggered by 10 times. I do not even know where to look for a solution. I will be grateful for any help.
my app.js
<code>    //= require jquery
    //= require jquery_ujs

    //= require foundation

    //= require turbolinks
    //= require jquery.easing.1.3.js
    //= require_tree .

    $(function(){
        $(document).foundation();
    });

    $(document).ready(function () {
        var $main_container = $("#main_container");
        var $menu_link = $('#menu-link');
        var $s_menu = $("#s-menu");

        $menu_link.click(function () {
            $main_container.animate({"margin-left": "-200px"}, 100);
            $s_menu.animate({"margin-right": "0"}, 100);
        });

        $(".container-fluid").on("click", function(){
            $main_container.animate({"margin-left": "0"}, 100);
            $s_menu.animate({"margin-right": "-200px"}, 100);
        });

        $('input[type="submit"]').focus(function(){
            $(this).blur();
        });

    });
</code>
============
After some experimenting (I removed all js from my project)  it seems to me that problem lies in rails caching. Because each click is forcing browser to download new package of assets.
============
I found out that my problem is in turbolinks gem, it caches assets each time and then download new package of assets. But how I can fix this?
Answer: Where are you loading
<code><%= javascript_include_tag "application" %>
</code>
If you are loading it at the bottom of the page within the body turbolinks refreshes the whole body tag, which could be causing your multiple loading assets when you click a link. Move it to the top within the head.
Comment: I instead realised I was calling other scripts within the `body` tag


Google Analytics BigQuery get the time difference between two different pages by user

Question: I'm trying to get the difference in time by user between the first step checkout and final purchase. This is my query:
SELECT transactionid1,MAX((t1.hit_moment1-t2.hit_moment2)) as diff_hits,MAX(t2.checkout_step_2) as day  FROM ((SELECT clientId as client1_id,
hits_1.page.pagePath as page_event1,
hits_1.eventInfo.eventAction as action_event1,
hits_1.transaction.transactionId as transactionId1,
TIMESTAMP_SECONDS(visitStartTime) as checkout_step_1,
hits_1.hour as hour1,
hits_1.minute as minute1,
(hits_1.hour*60+hits_1.minute) as hit_moment1
from `616180.ga_sessions_*`  ,
UNNEST(hits) as hits_1 where hits_1.page.pagePath like '%/buy1/suscription%' and  hits_1.eventInfo.eventAction="Transaction" and hits_1.transaction.transactionId is not null)t1 INNER JOIN (SELECT clientId as client2_id,
hits_2.page.pagePath as page_event2,
hits_2.eventInfo.eventAction as action_event2,
TIMESTAMP_SECONDS(visitStartTime) as checkout_step_2,
hits_2.hour as hour2,
hits_2.minute as minute2,
(hits_2.hour*60+hits_2.minute) as hit_moment2
from `616180.ga_sessions_*` ,UNNEST(hits) as hits_2 where hits_2.page.pagePath like '%/buy4/suscription%' and  hits_2.eventInfo.eventAction="Checkout" )t2 on t1.client1_id=t2.client2_id) where (t1.hit_moment1-t2.hit_moment2)>0 and (t1.hit_moment1-t2.hit_moment2)<180 group by transactionId1 order by transactionid1

Where pagePath contains  /buy1/suscription represents the transaction event and pagePath equal to buy4/suscription represents the first checkout step. I get results, but many of them are extremely large periods of time. Have i made a mistake?
Thank you.
Comment: Please provide sample data and desired results.
Answer: I don't fully follow what the sample data looks like or exactly the format your want for the result set.
That said, you can use aggregation to do the calculation you want.  The following assumes that the checkout is after the transaction, but it gives the basic idea:
select s.transaction_id,
       max(hit.hour * 60 + hit.minutes) - min(hit.hour * 60 + hit.minutes) as diff_minute
from `616180.ga_sessions_*` s cross join
     unnest(s.hits) as hit
where (hit.page.pagePath like '%/buy1/suscription%' and
       hit.eventInfo.eventAction = 'Transaction' or
      ) or
      (hit.page.pagePath like '%/buy4/suscription%' and
       hit.eventInfo.eventAction = 'Checkout'
      )
group by s.transaction_id;


What key is correct when guitars are half step down?

Question: I see many charts for praise and worship songs charted in sharp keys (A#, F#) major. One song is charted F# Major. I would think the guitars are tuned a half step down and they are playing like it is in G Major. Would it be more appropriate to be in Gb Major?
It looks so odd to see so many sharps in pop/rock transcriptions. Looking at cycle of fifths the Gb seems more prevalent then F#. What is the preferred or correct key when the song has guitars a half step down?
Comment: I would say that a practical answer to your question is that if you like playing in E, then put a capo on the second fret and finger your chords the same way as you would in E, just one step up.  Whether you think of it as Gb or F#, you would do the same.
Answer: When it comes to choosing a key signature, there is no standard. Except that most players are loathe to read music in keys with more than 7 sharps or flats. Aside from a few diehards who insist that F# is a different key than Gb (and it was, before the equal temperament system was developed), one rule of thumb is to use the key most commonly used for the instrumentation, or just to use the key with the least accidentals if there is any doubt.
Since Gb and F# have the same number of accidentals, then you want to consider the conventions for guitar. Since the open strings of the guitar fit into the keys of C, G, D and E major, guitar music is very often written in a key signature with sharps. From this perspective, a guitar player is used to reading in keys with four or five sharps, so adding one or two more may be easier for some guitar players to read than switching the whole key to flats. By this logic, I would probably choose F# over Gb for guitar music, unless there was something in the music itself that would be notated more comfortably in Gb. For instance, if the music has alot of raised notes, that could be difficult to read in F# and I might opt for Gb.
Comment: Sure there are. You've got G# major, Gb minor, etc. In fact theoretically there are an unlimited number of keys and an unlimited number of sharps and flats.
Comment: Well, it's hard to get away with because your band will throw the music right back at you. So that's probably why we don't see it. But you can also have more than 7 not just in the key signature but by combining the key signature and the music. For instance if you write a tune in F# major, then take a quick trip to the relative D# minor, and now you start to use the leading tone (C##), so now you're at seven. One more funny move and your total sharp load could be 8 or more! :)
Comment: Yes, you're right about that.  I just don't think it's possible, though, since seven is a hard limit to the number of symbols in a key signature.  I suppose that there's a theoretical component that would allow you to have infinitely sharped notes in the signature, though.  Here's an interesting link on the subject, by the way: [extremes of conventional musical notation](http://www.informatics.indiana.edu/donbyrd/CMNExtremes.htm).  They give a few examples of triple sharps and triple flats as accidentals, but don't go beyond 7 sharps or flats in their key signature examples.
Comment: By which you mean 5 sharps and two double sharps?  Ok then.  I wouldn't put it past my alma mater's harmony professors either, at least the one who left in my freshman year.  He was a bit of an avant garde evangelist.  LOL
Comment: There aren't any keys with more than 7 sharps or flats.  (?)
Comment: I suppose that's true, sort of.  It would be nitpicky of me to say that six sharps and one double sharp is less than 7 sharps!  LOL  However, show me how you explain that in terms of most players being "loath (that is the correct spelling of the word, if I may say so) to read music with more than 7 sharps or flats", given that no music that I am aware of exists that is written with such.  :)
Comment: Well, I thought you were just talking about key signatures, not accidentals.  Since you started your answer with "when it comes to choosing a key signature..." and all.  See, I was confused because there are only 7 notes referenced in the key signature.  I think I still am confused, actually...  :P  But kidding aside, you have a point.  You can get even more confusing than 7 sharps in a key signature if you want to.  Heck, you could do that with naturals, too.  :)
Comment: Well, my answer would still be that you can have infinite sharps or flats in your key signature, but that most people think it's extremely silly to use more than 6 or 7. :) If you're wondering how that would look, check out the symbol for double sharp or double flat. For instance G# major would look like C# major (7 sharps) except the first one would be a double-sharp symbol. What a headache!
Comment: I would amend this to EVERYONE thinks it's extremely silly to do this.  In fact, it's simply not done in my not inconsiderable experience.  But that aside, how would you get more than 7 x's in a key signature, which to your way of thinking is 14 sharps?  Ok, ok, there really is a triple-sharp symbol #x (Alkan, whose raison d'etre was to write the most difficult music possible, used them a few times), but then how do you get more than 21 without inventing more symbols?
Comment: Why would anyone want to do that? Just because it's possible that doesn't make it advisable. It's theoretically possible but as you say it's not in practice. And as you said, nobody writes key signatures with more than 7 sharps, which is why I suggested not going over that boundary in choosing a key signature. I think our extended discussion may be confusing to anyone whose head hurts when they see F##. :)
Comment: I understand your feeling, because it's not used in practice. But since it's theoretically possible, I can just see in my mind's eye the picture of my alma mater's harmony professors smiling smugly while putting down a piece of music with 9 sharps in the key signature as the exam begins.
Comment: They really can be incorrigible.
Answer: Not sure whether you mean if a tune is in, say, F#, but the guitar is tuned differently, what key should that part be written in. If so,the guitar is in G.
Or, do you mean is Gb a better key than F#.Pretty well as bad/good as each other.But if a piece HAS to be in one of those, it begs the question why? Most songs will not have such a great range of notes (low to high) that they need to be written to within a semitone. So a song in Gb/F# would be just as playable in G or F, both with a far less crowded space after the clef sign.And far less to remember to adjust.
Another reason may be the other instruments in an orchestration. With Eb saxes, or Bb trumpets/clarinets, the original key for them may be easier.Used to play Pretty Woman, written in Ab. Good for the horns, rubbish for guitar - particularly the intro, which had to be played (in standard tuning) almost an octave above the original. Sounded terrible !
Answer: Another way of looking at it in these situations (since you are on a guitar) is to ask yourself, "What common key starts just below the chords as written?"
Enter the capo.
Here, you can clearly see that the key of E is two semi-tones below F#, so you can capo on the 2nd fret and play in the key of E.  Or play in D (four semi-tones below F#), with the capo on the 4th fret.
Answer: I very much doubt you've ever seen a chart written in A#, unless it was written down by a guitarist with a very narrow grasp of music theory and notation.   But I'll believe F# major.
Now, once you're past the elementary stage, one chord's as easy as any other for a guitarist.  If a singer finds F a bit low, G a bit high but F# just right, a professional band will have no problem at all in playing in F#.  Maybe the music your praise band has is designed to match a professional recording.
A less advanced player may want to avoid those frightening-looking F# and C# chords, preferring to play in E, capo two frets up to F#.   It's rather less likely that a player would choose to play in G, detuned down a half-step. It's easier to shift a capo than to re-tune the whole instrument!
Comment: I doubt very much a contemporary worship band would play songs that are in any key of A# or F#. They are tuned a half step down. The transcriber doesn't realize it and prints the sheet music off in the odd keys.
Comment: Remember that guitarists who work out notes by fret-counting often speak of A# when Bb would be more appropriate!
Answer: The preferred key depends largely on the instrumentation for the arrangement.
If a song is written to include (or arranged to include) brass instruments the preferred key will usually be the one that uses flats in the signature.  That's because brass instruments use one, two, or three sharps to play in the key of concert C... if you're in a flat key they'll use one, two, or three fewer flats than a C instrument.  So the guitar part for a tune like "Take Five" will almost certainly be in Gb, because the sax part will be written in Eb (or Ab if it's arranged to use tenor, or trumpet).
If it's just for C instruments you see F# more often than Gb.
As a guitarist it makes no difference to me.  Six accidentals is six accidentals.


Advice for categorizing content?

Question: I'm new to Drupal 7 and UberCart and loving it.
I'm working on a site that is automotive based and am having a problem wrapping my head around the catalog.
I have 4 different parent catagories, then year/make/model and part category.  A product can be anywhere and belong to multiple categories.
Right now I have a vocabulary that contains parent category/make/model/part category and another that contains year.
I need the menu to work like

Parent Category 1

Make 1

model 1

year
sub-cat
model 2

year
sub-cat

Make 2

model 1

year
sub-cat
model 2

year

sub-cat

Am I making this too complicated?
The sub-cats would be unique to the Parent Category but make/model/year could belong to any Parent Category and subcat.
Can anybody give me any advice?  Thanks in advance.
edit I guess I'm asking If I put year make model together in a vocabulary and Parent Category and subcat together in a vocabulary (which I think would work well), how can I incorporate that into UberCart catalog menu?
Answer: @Drupality was right...It does require custom coding.
I installed Multi Term Views which will allow nodes to be filtered that contain different, multiple taxonomies from different vocabularies.
So you could have a filtered view at taxonomy/term/27+35 which will show all nodes in term id 27 and 35 or you can have taxonomy/term/27,35 which will show all nodes that are exclusively in both 27 and 35.  After that was set up I just wrote a custom menu and put it in a block in the sidebar.
So I have 3 vocabularies that are Year, Make/Model, and Type.  Make/Model is two terms deep.
Not the best solution - but if a highly customized menu is needed then apparently this is what must be done.
Thanks @Drupality for your help.

Advice for categorizing content?


Rails3 environment running very slow on Windows XP, Ubuntu 9.04, Ubuntu 9.10

Question: I've tried all three (granted the Ubuntu versions were via VirtualBox with XP as a host, but I  gave the images all the available RAM my system has).
Loading the rails environment is taking 30-60 seconds. rails console, rake test:units - anything that requires rails to load up. And not just on the first go - every time. I've even used autotest to see if it helps with execution time for unit tests, but it doesn't. Any time I change one test, it still takes 30 seconds to load them, and then about 4 seconds to execute.
Has anyone else come across this issue? Has anyone figured out any way to fix this?
Comment: "I gave the images all the available RAM my system has," be careful: giving too much RAM to a virtual machine is a common mistake that will kill performance by depriving the host OS. Rails runs fine in Unix environments with very little RAM, as evidenced by the abundant availability of perfectly functional Rails-optimized hosted virtual servers with only 256MB of RAM. You probably have no reason to cut it quite that thin, but giving your VM more than a gig of RAM is highly unlikely to yield a significant performance advantage in a development/test environment.
Answer: checkout http://github.com/rdp/faster_require or alternatively run it in a virtualbox running linux.
Comment: The original poster has tried running it in a virtual Linux machine, and it's made no difference.
Comment: Yeah but that library looks like it might help. Thankfully I'm no longer stuck in the awful world of developing ruby on Windows, so I can' try it out. Thanks for the answer though!
Answer: The time taken to load can be affected by the number of dependencies which must be loaded. Perhaps your rails application depends on a lot of gems, which can slow down load time considerably.
The solutions generally used to mitigate this problem are:

for production instances (which handle web traffic), many web servers (eg. unicorn) can eager load and fork using copy on write so that loading is only done once (additional instances will reference the same memory until they start to alter the contents). This is often done so that restarting one of the processes (possibly due to a crash) does not use excessive amounts of additional server resources
for testing purposes, see Fast Rails Commands, which suggests the use of zeus, spring or spork gems. This keeps a background copy of a ruby/rails process running to handle your rails tests.


Java Unicode CJK | Programmatically distinguish fallback chars

Question: Hello I am trying to print some CJK unicode characters to a .txt file based on their unicode code number.
Is there a way to distinguish between the fallback characters (box with four digits) and the "printable" characters? (i.e. when the CJK characters appear as they should look like)
I would like to end up with something like
<code>if(!isFallback(myChar)) { printToFile(); }

private boolean isFallback(char c) { // return true if the system will resort to fallback characters}
</code>
Answer: Does the canDisplay() method do what you're looking for?
It might not - especially if you really are talking about using the fallback-font display behaviour of the Java logical fonts (which your question implies you are).
Are you running this on OSX, by chance?
If the canDisplay() method is not what you're looking for - you'll need to give a bit more info about what you're doing - platform, JDK version, font you've selected (or none?), example code (SSCCE would be best).


How to solve recurrence equation $f(n) = f(n-5) + f(n-10)$?

Question: How to solve recurrence equation $f(n) = f(n-5) + f(n-10)$? For something like fibonacci sequence $f(n+1) = f(n) + f(n-1)$ I can solve for the quadratic equation $x^2-x-1=0$ then $f(n) = A x_1 + A^\prime x_2$. But what should I do for this one?
Comment: $x^{10}-x^{5}-1=0$
Answer: In this case it is exactly Fibonacci recurrences, except separate ones for $n$ congruent to $0$ modulo $5$, $n$ congruent to $1$ modulo $5$, and so on up to $n$ congruent to $4$ modulo $5$. Knowing the values of $f(0)$ and $f(5)$ will let you compute $f$ at multiples of $5$, and nowhere else. Similarly, knowing $f(1)$ and $f(6)$ will let you compute $f(11)$, $f(16)$, $f(21)$, and so on, but nowhere else. So it is natural to separate the problem into cases.
So let $g_0(n)=f(5n)$, We have the familiar recurrence $g_0(n)=g_0(n-1)+g_0(n-2)$.
Let $g_1(n)=f(5n+1)$. We have the familiar recurrence $g_1(n)=g_1(n-1)+g_1(n-2)$.
And so on.  For a concrete solution we will need initial values $f(0)$ up to $f(9)$.
Remark: You could however proceed "as usual," getting the characteristic equation $x^{10}-x^5-1=0$. This is a quadratic in $x^5$. Solve for $x^5$. We get the usual roots. For the values of $x$, take the ordinary fifth roots of the equation $y^2-y-1=0$, and multiply by fifth roots of unity (four of these are non-real.) After a while, one can get a general formula that will involve sines and cosines of $2n\pi/5$.  However, this is very much less pleasant than the division into cases suggested above.
Comment: Hi, could you take a glance on my attempt below? much appreciated
Answer: Although a topic in Discrete math, I attempted this question using the tools I learned in linear algebra.
Rewrite it as $f(n+10) = f(n+5) +f(n)$, this can be represented as
\[ \left( \begin{array}{c}
f_{n+10} \\
f_{n+5} \end{array} \right) = \left( \begin{array}{cc}
1 &1 \\
1& 0 \end{array} \right) \left( \begin{array} {c}
f_{n+5} \\
f_n \end{array} \right)
 \]
\[ \left( \begin{array}{c}
f_{n+10} \\
f_{n+5} \end{array} \right) = \left( \begin{array}{cc}
1 &1 \\
1& 0 \end{array} \right)^{n+5} \left( \begin{array} {c}
f_{1} \\
f_{-4} \end{array} \right)
 \]
Then diagonalize  $\left( \begin{array}{cc}
1 &1 \\
1& 0 \end{array} \right)$ to find eigenvalues, which is the same as the ones for fibonacci, $1/2 (1-\sqrt5), 1/2 (1+\sqrt5)$
then $f_{n+5} = \alpha (1/2 (1-\sqrt5))^{n+5} +\beta (1/2 (1+\sqrt5))^{n+5} $
Is this correct? If not please advise.
Comment: The second displayed line of matrices is not correct. The idea *will* work, but there needs to be either a separation into cases, or a *much* larger matrix, I think a $10\times 10$, except that there will be stuff only near the diagonal, essntially a string of five $2\times 2$ Fibonacci matrices, with $0$'s elsewhere. The general solution is a $10$-parameter solution, not the two parameter solution you obtained ($\alpha$, $\beta$).
Answer: I am not quite sure if this is what you were looking for but as was answered previously if you begin at $n=0,5,10,15,20,25,30,...$ and use the Binet form below you get the Fibonacci Numbers
$$\frac{1}{\sqrt{5}}\left(\sqrt[5]{\frac{1}{2}+\frac{\sqrt{5}}{2}}\right)^{n+5}-\frac{1}{\sqrt{5}}\left(\sqrt[5]{\frac{1}{2}-\frac{\sqrt{5}}{2}}\right)^{n+5}$$
If you use Excel you can paste the formula below in for A1=0, A2=5, A3=10..... and verify that you get the Fibonacci Numbers
<code>(((1/2+SQRT(5)/2))^(1/5)^(A1+5)-((1/2-SQRT(5)/2))^(1/5)^(A1+5))/SQRT(5)
</code>


R package for fixed-effect logistic regression

Question: I'm looking for an R package for estimating the coefficients of logit models with individual fixed-effect (individual intercept) using Chamberlain's 1980 estimator. It is often known as Chamberlain's fixed-effect logit estimator.
It's a classic estimator when dealing with binary outcome panel data (at least in econometrics), but I just don't find anything related to it in the CRAN.
Any clue?
Comment: Here is another try: http://stats.stackexchange.com/questions/10141/discrete-choice-panel-models-in-r/13417
Comment: I'm dealing with the same situation, did you find a solution/package/code?
Answer: Conditional logistic regression (I assume that this is what you refered to when talking about Chamberlain's estimator) is available through clogit() in the survival package. I also found this page which contains R code to estimate conditional logit parameters. The survey package also includes a lot of wrapper function for GLM and Survival model in the case of complex sampling, but I didn't look at.
Try also to look at logit.mixed in the Zelig package, or directly use the lme4 package which provide methods for mixed-effects models with binomial link (see lmer or glmer).
Did you take a look at Econometrics in R, from Grant V. Farnsworth? It seems to provide a gentle overview of applied econometrics in R (with which I am not familiar).
Comment: Actually, "conditional logit" is a very ambiguous term. It some contexts (mainly when dealing with panel data), it is equivalent to Chamberlain's estimator, but it is very unfrequent. Most of the times, it refers to a cross-sectional model where the outcome variable can take more than 2 values. All your proposals actually refers to packages that consider this last possibility. The same with mixed-logit: it is not a fixed-effect logit. I've already taken a look at Farnsworth's overview, but it is not exhaustive enough to speak about this estimator. Anyway, thank you for your answer !
Comment: Yup, but the conditional logit model can (as I said) take more than 2 values, which differentiates it easily from Chamberlain's model, just like the fact that Chamberlain is designed specifically for panel data. This is thus a relevant information ; precise description of the usual conditional logit isn't (and the description of both would take more than 600 chars).
Comment: "Conditional logit" does *not* refer to having more than two outcome levels. Some functions might extend it to that situation, but that is not the point.
Answer: You can run the Chamberlains model using glmer. It is basically a RE model but with more variables:
glmer(y~X + Z + (1|subject), data, model=binomial("probit"))

X are the variables you consider explain your fixed effect model (a simple case it is the mean of Z)
Z are your exogenous variables
Subject is the variable where the heterogeneity comes from

I hope this helps.
Comment: I think that would restrict heterogeneity to be orthogonal to X and Z while the requested estimator allows for it.
Comment: No is ramdon effects. It is not chamberlain model which si fixed effects
Answer: The mclogit package seems to implement conditional logit of the Chamberlain variant.


Volume of solid in polar coordinates

Question: I find this kind of questions in a calculus course and I've been trying to figure out what is the sequence of steps to follow in order to solve these.
Consider the following solid, defined in terms of polar coordinates: $0≤r≤R$; $0≤θ≤2π$; $0≤z≤r$. Can you describe this shape? Compute its volume.
(There are no equations given, only this constraints.)
I know it is related to the definite integral, but I don't know how to use it without an explicit function for the radius r. I really appreciate it if someone could help me into dealing with this type volume calculations problems.
Comment: Have you tried drawing it?
Comment: Answer 2/3πR^3, question, why...
Comment: I did draw it...
Answer: The volume of a body $B$ in $n$-dimensional Cartesian coordinate system is $$\iiint\limits_B\mathrm dx_1\,\mathrm dx_2\ldots\mathrm dx_n.$$
Thus, by the change-of-variables theorem, the volume of $B$ in cylindrical coordinate system is $$\iiint\limits_B r\;\mathrm dz\,\mathrm dr\,\mathrm d\theta.$$
So, the given solid has volume $$\int_0^{2\pi}\int_0^R\int_0^rr\;\mathrm dz\,\mathrm dr\,\mathrm d\theta=\frac{2πR^3}3.$$
Comment: Thank you very much!, now it is much more clear
Comment: @EduardoMarín Also, do take a look at [this answer](https://math.stackexchange.com/a/4339062/21813).
Answer: Hint:

The volume of a cylinder of height $R$ and base of radius $R$ is $\pi R^3$.

The volume of a cone of height $R$ and base of radius $R$ is $\frac{1}{3}\pi R^3$.

Draw a cylinder of such dimensions and subtract the ice-cream.
Comment: Thanks as well!

Volume of solid in polar coordinates


Procurar sem ter que dar SUBMIT

Question: Tenho o seguinte código e nao sei como fazer ele pesquisar sem eu precisar de dar submit, alguem me pode ajudar?
HTML

    <title>Data Searching Without Page Refresh</title>

<form name = "form">

Enter name then click the Search Button or just press Enter

    <input type="text" name="name" id="fn" />

    <input type="submit" value="Search" id="search-btn" />
</form>

PHP FILE
<?php
include_once("config_open_db.php");

//define index
isset( $_REQUEST['name'] ) ? $name=$_REQUEST['name'] : $name='';

// just to escape undesirable characters
$name = mysql_real_escape_string( $name );

if( empty( $name )){
    // this will be displayed if search value is blank
    echo "Please enter a name!";
}else{
    // this part will perform our database query
    $sql = "select * from TBL where COLUMN like '%$name%'";

    $rs = mysql_query( $sql ) or die('Database Error: ' . mysql_error());
    $num = mysql_num_rows( $rs );

    if($num >= 1 ){
        // this will display how many records found
        // and also the actual record
        echo "
$num record(s) found!
";

        while($row = mysql_fetch_array( $rs )){
            echo "
" . $row['firstname'] . " " . $row['lastname'] ."
";
        }
    }else{
        // if no records found
        echo "Name not found!";
    }
}
?>

Comment: Você quer que a função `showValues()` seja executada sem que tenha que clicar no botão? Em qual evento então deveria realizar a pesquisa? Pode explicar melhor?
Comment: O que quero é que, enquanto estou a escrever, ele vai pesquisando automaticamente sem eu ter que fazer submit ou clicar no botao do submit.. Apenas escrever..
Answer: Pode atribuir uma função ao eventp KeyUp do textbox:
$("#fn").keyup(function() {
    if($(this).val().length >= 3) // só começa a pesquisa após digitar três caracteres
        showValues();
});

Eu adicionei uma verificação se a quantidade de caracteres digitados é maior que três, para não "forçar" demais o servidor. Se quiser altere a quantidade ou remova o if completamente conforme sua necessidade.
Comment: O Keyup do javascript nesse caso substitui o submit. Parabéns MarcusVinicius

Procurar sem ter que dar SUBMIT


What is property in hasOwnProperty in JavaScript?

Question: Consider:
if (someVar.hasOwnProperty('someProperty') ) {
 // Do something();
} else {
 // Do somethingElse();
}

What is the right use/explanation of hasOwnProperty('someProperty')?
Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty?
What is a property in this case?
What property does this JavaScript check?
Comment: http://stackoverflow.com/questions/2600085/hasownproperty-in-javascript
Comment: When I asked this question I thought it was a function that checked some html. Now I see it checking a javascript object or method for a 'variable' within that object or method. thnx!
Comment: Have a look at https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Object/HasOwnProperty
Answer: hasOwnProperty returns a boolean value indicating whether the object on which you are calling it has a property with the name of the argument. For example:
var x = {
    y: 10
};
console.log(x.hasOwnProperty("y")); //true
console.log(x.hasOwnProperty("z")); //false

However, it does not look at the prototype chain of the object.
It's useful to use it when you enumerate the properties of an object with the for...in construct.
If you want to see the full details, the ES5 specification is, as always, a good place to look.
Comment: Bonus points for prototype chain. Still trying to figure out what its calling on when its not called on an object... its not `window`
Comment: @KristofferSHansen - I was wondering that too, but the question has been edited so it's now being called on an object. When it's not, an error is thrown.
Comment: I suppose that changes things. No error when run from console in Chrome though.
Comment: @KristofferSHansen - I think that's because of how the console runs code (it's run as `eval` code rather than global or function code). I tried it in a blank HTML page and get a "cannot convert null to object" error.
Comment: @KristofferSHansen see Kunal Vashist answer when it is called on a class method
Comment: @scubaFLY my comment was based on the original question where it wasn't used as a class method.
Answer: Here is a short and precise answer:
In JavaScript, every object has a bunch of built-in key-value pairs that have meta information about the object. When you loop through all the key-value pairs using for...in construct/loop for an object you're looping through this meta-information key-value pairs too (which you definitely don't want).

Using hasOwnPropery(property) filters-out these unnecessary looping through meta information and directly checks that is the parameter property is a user-given property in the object or not.
By filters-out, I mean, that hasOwnProperty(property) does not look if, property exists in Object's prototype chain aka meta information.
It returns boolean true/false based on that.
Here is an example:

var fruitObject = {"name": "Apple", "shape": "round", "taste": "sweet"};
console.log(fruitObject.hasOwnProperty("name"));  //true
console.log(Object.prototype.hasOwnProperty("toString")) // true because in above snapshot you can see, that there is a function toString in meta-information

I hope it's clear!
Comment: >"you're looping through this meta-information key-value pairs too"
But when I run `for (var key in fruitObject) { ... }` js only cycle's through non-prototype keys anyway, am I missing something or did JS runtime change the way they handle for key-in-object loops?
Comment: at last line of your example you write `console.log(Object.prototype....`; did you mean `console.log(fruitObject.`? fruitObject or Object ?
Answer: It checks:
Returns a Boolean value indicating whether an object has a property with the specified name
The hasOwnProperty method returns true if the object has a property of the specified name, false if it does not. This method does not check if the property exists in the object's prototype chain; the property must be a member of the object itself.
Example:
var s = new String("Sample");
document.write(s.hasOwnProperty("split"));                        //false
document.write(String.prototype.hasOwnProperty("split"));         //true

Comment: I gave a -1 because your initial answer was a short and utterly incoherent sentence, which was then updated to a slightly longer, slightly more coherent, but entirely inaccurate sentence.
Comment: @amnotiam- but i think its much clear now...its because my internet issue i cannot able to post more..........
Answer: Summary:
hasOwnProperty() is a function which can be called on any object and takes a string as an input. It returns a boolean which is true if the property is located on the object, otherwise it returns false. hasOwnProperty() is located on Object.prototype and thus available for any object.
Example:

function Person(name) {
  this.name = name;
}

Person.prototype.age = 25;

const willem = new Person('willem');

console.log(willem.name); // Property found on object
console.log(willem.age); // Property found on prototype

console.log(willem.hasOwnProperty('name')); // 'name' is on the object itself
console.log(willem.hasOwnProperty('age')); // 'age' is not on the object itself

In this example a new Person object is created. Each Person has its own name which gets initialized in the constructor. However, the age is not located on the object but on the prototype of the object. Therefore hasOwnProperty() does return true for name and false for age.
Practical applications:
hasOwnProperty() can be very useful when looping over an object using a for in loop. You can check with it if the properties are from the object itself and not the prototype. For example:

function Person(name, city) {
  this.name = name;
  this.city = city;
}

Person.prototype.age = 25;

const willem = new Person('Willem', 'Groningen');

for (let trait in willem) {
  console.log(trait, willem[trait]); // This loops through all properties, including the prototype
}

console.log('\n');

for (let trait in willem) {
  if (willem.hasOwnProperty(trait)) { // This loops only through 'own' properties of the object
    console.log(trait, willem[trait]);
  }
}
Answer: You use object.hasOwnProperty(p) to determine if an object has an enumerable property p-
An object can have its own prototype, where 'default' methods and attributes are assigned to every instance of the object. hasOwnProperty returns true only for the properties that were specifically set in the constructor, or added to the instance later.
To determine if p is defined at all, anywhere, for the object, use if(p instanceof object), where p evaluates to a property-name string.
For example, by default all objects have a 'toString' method, but it will not show up in hasOwnProperty.
Answer: hasOwnProperty is a proper way of checking an object has a property or not. someVar.someProperty cannot be used as an alternative to this situation. The following condition will show a good difference:
const someVar = { isFirst: false };

// The condition is true, because 'someVar' has property 'isFirst'
if (someVar.hasOwnProperty('isFirst')) {
  // Code runs
}

// The condition is false, because 'isFirst' is false.
if (someVar.isFirst) {
  // Code does not runs here
}

Hence someVar.isFirst cannot be used alternative to someVar.hasOwnProperty('isFirst').
Answer: hasOwnProperty is a normal JavaScript function that takes a string argument.
In your case, somevar.hasOwnProperty('someProperty'), it checks the somevar function has somepropery or not - it returns true and false.
Say
function somevar() {
    this.someProperty = "Generic";
}

function welcomeMessage()
{
    var somevar1 = new somevar();
    if(somevar1.hasOwnProperty("name"))
    {
        alert(somevar1.hasOwnProperty("name")); // It will return true
    }
}

Answer: 2021 - Object.hasOwn as a replacement for Object.hasOwnProperty()
As other answers indicated, hasOwnProperty will check for an object own properties in contrast to in which will also check for inherited properties.
There is a new alternative method called Object.hasOwn() and is intended to be a replacement for Object.hasOwnProperty()
Object.hasOwn() is a static method which returns true if the specified object has the specified property as its own property. If the property is inherited, or does not exist, the method returns false.

const person = { name: 'dan' };

console.log(Object.hasOwn(person, 'name'));// true
console.log(Object.hasOwn(person, 'age'));// false

const person2 = Object.create({gender: 'male'});

console.log(Object.hasOwn(person2, 'gender'));// false

It is recommended to this method use over the Object.hasOwnProperty() because it also works for objects created by using Object.create(null) and for objects that have overridden the inherited hasOwnProperty() method. Although it's possible to solve these kind of problems by calling Object.prototype.hasOwnProperty() on an external object, Object.hasOwn()  overcome these problems, hence is preferred (see examples below)

let person = {
  hasOwnProperty: function() {
    return false;
  },
  age: 35
};

if (Object.hasOwn(person, 'age')) {
  console.log(person.age); // true - the remplementation of hasOwnProperty() did not affect the Object
}

let person = Object.create(null);
person.age = 35;
if (Object.hasOwn(person, 'age')) {
  console.log(person.age); // true - works regardless of how the object was created
}

More about Object.hasOwn can be found here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn
Browser compatibility - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn#browser_compatibility
Answer: What is the right use/explanation of hasOwnProperty('someProperty') ?
The hasOwnProperty() method returns a boolean indicating whether the object has the specified property as its own property (as opposed to inheriting it).

const someVar = {};
someVar.someProperty = 'Foo';

console.log(someVar.hasOwnProperty('someProperty'));
// expected output: true

console.log(someVar.hasOwnProperty('someProperty1'));
// expected output: false

Why can't we simply use someVar.someProperty to check if an object someVar contains property with name someProperty ?
someVar.someProperty will return the property value, You can not check that this property is available in the object or not via someVar.someProperty.
Now in ES2022, A new method has been introduced which is Object.hasOwn(<object reference>, <property name>) this method is intended as a replacement for Object.hasOwnProperty() which overcome some limitations of .hasOwnProperty().
Answer: Scene A:
const objA = { a: 1, b: 2 }
for (const key in objA) {
  if (objA.hasOwnProperty(key)) {
    console.log(objA[key])
  }
}

    Output

    1
    2

Scene B:
const objB = {
  a: 1,
  b: 2,
  hasOwnProperty() {
    return false
  }
}

for (const key in objB) {
  if (objB.hasOwnProperty(key)) {
    console.log(objB[key])
  }
}

    Outputs nothing

Because JavaScript doesn't protect the property of hasOwnProperty.
So you can use it like this:
for (const key in objB) {
  if (Object.prototype.hasOwnProperty.call(obj, key)) {
    console.log(objB[key])
  }
}

Answer: For this case someVar is Object. Object has a prototype calls 'hasOwnProperty'. Property means a value for key in Object.
For example:
const objectTest = {key1: property1, key2: property2}
If (objectTest.hasOwnProperty('key1')) {
return true
}
else { return false }

In this case we got true, because key1 has property1.
If you want to check more information for this prototype, you can read there
Answer: It checks if an object has a property. It works the same as if(obj.prop), as far as I know.
Comment: The problem is when `prop` has false value. `if(obj.hasOwnProperty('prop'))` will be `true` while `if(obj.prop)` will be `false`.
Comment: `obj.prop` follows the prototype chain, `hasOwnProperty` does not


How do I plot a rate?

Question: How do I plot a rate? I've got a rate of exponential growth per year and I want to plot this, and see where it gets to in 10 years, or a thousand years.
Comment: Plot the derivative!
Answer:
You could plot the function $e^{rt}$ for different values of $t$ with $r$ being your annual exponential growth rate. Then you could evaluate this function at $t=10$ or $t=1000$.  Is this what you were looking for?
Answer: Plot in with a log scale on the y axis. Then the line will be straight and it will be easy to see where it is going.

How do I plot a rate?


Alguém pode dar uma ajuda com meu código de Paginação com php PDO

Question:
Olá bom dia, alguem poderia me ajudar com esse código de paginação com php e PDO ele funciona normalmente mas so me da a opção de ir para a primeira pagina e para a última. Não consigo ir para proxima pagina e nem para a pagina anterior.
OBS: Mas quando estou na última página e clico em proxima página, ela vai para a primeira pagina.

<?php
 /* Constantes de configuração */
 define('QTDE_REGISTROS', 3);
 define('RANGE_PAGINAS', 3);

 /* Recebe o número da página via parâmetro na URL */
 $pagina_atual = (isset($_GET['page']) && is_numeric($_GET['page'])) ? $_GET['page'] : 1;

 /* Calcula a linha inicial da consulta */
 $linha_inicial = ($pagina_atual -1) * QTDE_REGISTROS;

 /* Cria uma conexão PDO com MySQL */
 $opcoes = array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES UTF8');
 $pdo = new PDO("mysql:host=localhost; dbname=sistema_escolar;", "root", "", $opcoes);

 /* Instrução de consulta para paginação com MySQL */
 $sql = "SELECT id, titulo, descricao FROM posts LIMIT {$linha_inicial}, " . QTDE_REGISTROS;
 $stm = $pdo->prepare($sql);
 $stm->execute();
 $dados = $stm->fetchAll(PDO::FETCH_OBJ);

 /* Conta quantos registos existem na tabela */
 $sqlContador = "SELECT COUNT(*) AS total_registros FROM posts";
 $stm = $pdo->prepare($sqlContador);
 $stm->execute();
 $valor = $stm->fetch(PDO::FETCH_OBJ);

 /* Idêntifica a primeira página */
 $primeira_pagina = 1;

 /* Cálcula qual será a última página */
 $ultima_pagina  = ceil($valor->total_registros / QTDE_REGISTROS);

 /* Cálcula qual será a página anterior em relação a página atual em exibição */
 $pagina_anterior = ($pagina_atual > 1) ? $pagina_atual :-1 ;

 /* Cálcula qual será a pŕoxima página em relação a página atual em exibição */
 $proxima_pagina = ($pagina_atual < $ultima_pagina) ? $pagina_atual :+1 ;

 /* Cálcula qual será a página inicial do nosso range */
 $range_inicial  = (($pagina_atual - RANGE_PAGINAS) >= 1) ? $pagina_atual - RANGE_PAGINAS : 1 ;

 /* Cálcula qual será a página final do nosso range */
 $range_final   = (($pagina_atual + RANGE_PAGINAS) <= $ultima_pagina ) ? $pagina_atual + RANGE_PAGINAS : $ultima_pagina ;

 /* Verifica se vai exibir o botão "Primeiro" e "Pŕoximo" */
 $exibir_botao_inicio = ($range_inicial < $pagina_atual) ? 'mostrar' : 'esconder';

 /* Verifica se vai exibir o botão "Anterior" e "Último" */
 $exibir_botao_final = ($range_final > $pagina_atual) ? 'mostrar' : 'esconder';

 ?>
 <!DOCTYPE html>

 <meta charset='utf-8'>
 <title>Paginação - William Programação</title>
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
 <link rel="stylesheet" href="css/estilo.css">

Paginação de Dados

    <?php if (!empty($dados)): ?>

        Código
        Título
        descricao

       <?php foreach($dados as $artigo):?>

        <?=$artigo->id?>
        <?=$artigo->titulo?>
        <?=$artigo->descricao?>

       <?php endforeach; ?>

       <a class='box-navegacao <?=$exibir_botao_inicio?>' href="outro2.php?page=<?=$primeira_pagina?>" title="Primeira Página">Primeira
       <a class='box-navegacao <?=$exibir_botao_inicio?>' href="outro2.php?page=<?=$pagina_anterior?>" title="Página Anterior">Anterior

      <?php
      /* Loop para montar a páginação central com os números */
      for ($i=$range_inicial; $i <= $range_final; $i++):
        $destaque = ($i == $pagina_atual) ? 'destaque' : '' ;
        ?>
        <a class='box-numero <?=$destaque?>' href="outo2.php?page=<?=$i?>"><?=$i?>
      <?php endfor; ?>

       <a class='box-navegacao <?=$exibir_botao_final?>' href="outro2.php?page=<?=$proxima_pagina?>" title="Próxima Página">Próxima
       <a class='box-navegacao <?=$exibir_botao_final?>' href="outro2.php?page=<?=$ultima_pagina?>" title="Última Página">Último

    <?php else: ?>

Nenhum registro foi encontrado!

    <?php endif; ?>

Comment: Tentei mas também não funcionou.
Answer: Acredito que por vc não estar alterando o valor dar paginas nos ifs nada acontece. Tente assim:
/* Cálcula qual será a página anterior em relação a página atual em exibição */
 $pagina_anterior = ($pagina_atual > 1) ? $pagina_atual : $pagina_atual-1 ;

 /* Cálcula qual será a pŕoxima página em relação a página atual em exibição */
 $proxima_pagina = ($pagina_atual < $ultima_pagina) ? $pagina_atual : $pagina_atual+1 ;

Espero que tenha ajudado.


Get a subset of lines from a big text file using PowerShell v2

Question: I'm working with a big text file, I mean more than 100 MB big, and I need to loop through a specific number of lines, a kind of subset so I'm trying with this,
$info = Get-Content -Path $TextFile | Select-Object -Index $from,$to
foreach ($line in $info)
{
,,,

But it does not work. It is like if it only gets the first line in the subset.
I don't find documentation about the Index attribute, so is this possible or should I try using a different approach considering the file size?
Answer: PS> help select -param index

-Index <Int32[]>
    Selects objects from an array based on their index values. Enter the indexes in a comma-separated list.

    Indexes in an array begin with 0, where 0 represents the first value and (n-1) represents the last value.

    Required?                    false
    Position?                    named
    Default value                None
    Accept pipeline input?       false
    Accept wildcard characters?  false

Based on the above, '8,13' will get you just two lines. One thing you can do is pass an array of numbers, you can use the range operator:
Get-Content -Path $TextFile | Select-Object -Index (8..13) | Foreach-Object {...}

Answer: Are the rows of fixed length? If they are, you can seek to desired position by simply calculating offset*row length and using something like .Net FileStream.Seek(). If they are not, all you can do is to read file row by row.
To extract lines m, n, try something like
# Open text file
$reader = [IO.File]::OpenText($myFile)
$i=0
# Read lines until there are no lines left. Count the lines too
while( ($l = $reader.ReadLine()) -ne $null) {
    # If current line is within extract range, print it
    if($i -ge $m -and $i -le $n) {
        $("Row {0}: {1}" -f $i, $l)
    }
    $i++
    if($i -gt $n) { break } # Stop processing the file when row $n is reached.
}
# Close the text file reader
$reader.Close()
$reader.Dispose()

Answer: The below is working for me.
It extract all the content between 2 lines.
$name     = "MDSinfo"
$MDSinfo  = "$PSScriptRoot\$name.txt" #create text file
$MDSinfo  = gc $MDSinfo

$from =  ($MDSinfo | Select-String -pattern "sh feature" | Select-Object LineNumber).LineNumber
$to =  ($MDSinfo  | Select-String -pattern "sh flogi database " | Select-Object LineNumber).LineNumber

$i = 0
$array = @()
foreach ($line in $MDSinfo)
{
foreach-object { $i++ }
    if (($i -gt $from) -and ($i -lt $to))
    {
    $array += $line
    }
}
$array

Answer: Try this code:
Select-String $FilePath -pattern "FromHere" | Out-Null

$FromHereStartingLine = Select-String $FilePath -pattern "FromHere" | Select-Object LineNumber

$UptoHereStartingLine = Select-String $FilePath -pattern "UptoHere" | Select-Object LineNumber

for($i=$FromHereStartingLine.LineNumber; $i -lt $UptoHereStartingLine.LineNumber; $i+=1)
{
    $HoldInVariable += Get-Content -Path $FilePath | Foreach-Object { ($_  -replace "`r*`n*","") } | Select-Object -Index $i
}

Write-Host "HoldInVariable : " $HoldInVariable

Answer: The Get-Content cmdlet has a readcount and totalcount parameters. I would play around with those and try to set it up so that the lines your interested in get assigned to an object, then use that object for your loops.


I am using `react-i18next` for translation and I need to give style to a certain part of string, how can I do that?

Question: I have this string in my en.json file "outOf100": "{{val}} out of 100" and I am using it like this {t('outOf100', {val:
22.45
})} in JSX.
Can anyone please tell me how to make the val look like an h6 whereas all other part of string as normal.
Answer: You need to use the Trans component to format your string with different HTML-tags. It will look something like this:
  //inside React-component
  return (
    <Trans i18nKey="outOf100">

{{val}}
 out of 100.
    </Trans>
  );

  //in en.json
  "outOf100": "<0>{{val}}</0> out of 100"

For more info about the Trans component, please see the docs.


If you roll a single dice 7 times, what's the chance that the highest number rolled is 4?

Question: I tried (4/6)^7, but it doesn't seem to be correct.
Answer: You need to ensure that 4 appears at least once. The probability will be $(4/6)^7-(3/6)^7$.
Comment: Can you walk me through the process if it's not too much trouble?
Comment: $(4/6)^7$ includes the case 1213111, for example, in which case maximum is 3, not 4. So, we have to subtract the cases where maximum is less than 4, which is $(3/6)^7$.
Comment: $(4/6)^7$ is the probability that all of the dice are less than or equal to 4. So you need to subtract off the probability that all of the dice are strictly less than 4, which is what @Ayaka is saying


MailCore2 Search Expression with more than two parameters?

Question: How can I search mailcore2 with more than two expressions?
My example below includes exprSinceLastTime as well as exprFrom and exprSubject. But, searchAdd only has room for two parameters.
How can I add additional search expressions such as exprSinceLastTime?
<code> NSTimeInterval oneHour = 3600;
 NSDate *now = [NSDate dateWithTimeIntervalSinceNow:oneHour];
 MCOIMAPSearchExpression * exprSinceLastTime = [MCOIMAPSearchExpression searchSinceReceivedDate:now];

MCOIMAPSearchExpression * exprFrom = [MCOIMAPSearchExpression searchFrom: @"apple"];
MCOIMAPSearchExpression * exprSubject = [MCOIMAPSearchExpression searchSubject: @"cloudkit"];
MCOIMAPSearchExpression * expr = [MCOIMAPSearchExpression searchAnd: exprFrom other: exprSubject];

MCOIMAPSearchOperation* searchOperation = [session searchExpressionOperationWithFolder: folder expression: expr];
</code>
Answer: I post the answer below. It was very simple. I had to sleep on the question to think of the obvious answer :-)
<code> NSTimeInterval oneHour = 3600; // magic number! 60 seconds
 NSDate *now = [NSDate dateWithTimeIntervalSinceNow:oneHour];
 MCOIMAPSearchExpression * exprSinceLastTime = [MCOIMAPSearchExpression searchSinceReceivedDate:now];

MCOIMAPSearchExpression* exprFrom = [MCOIMAPSearchExpression searchFrom: @"youtube"];
MCOIMAPSearchExpression* exprSubject = [MCOIMAPSearchExpression searchSubject: @"video"];
MCOIMAPSearchExpression* expr = [MCOIMAPSearchExpression searchAnd: exprFrom other: exprSubject];
MCOIMAPSearchExpression* expr2 = [MCOIMAPSearchExpression searchAnd: exprSinceLastTime other: expr];

MCOIMAPSearchOperation* searchOperation = [session searchExpressionOperationWithFolder: folder expression: expr2];
</code>


AWS Elastic Beanstalk worker process leaves SQS message in flight

Question: I have a NodeJS Elastic Beanstalk worker tier environment which takes messages from an SQS queue and posts them to an external url. The code below works as expected, but the message remains "in flight" in SQS. I can't see any documentation about how I inform SQS the message has been processed successfully?
var http = require('http'),
    request = require("request"),
    fs = require('fs');

http.createServer(function (req, res) {

    req.on('data', function (data) {
        var jsonObj = JSON.parse(data);
        var jsonString = JSON.stringify(jsonObj);

        log("Processing " + jsonString);

        request.post('http://example.com', {
            json: true,
            body: jsonString,
            headers: {
                "content-type": "application/json",
            }
        }, (error, res, body) => {
            if (error) {
                log(`Error ${error}`);
                return;
            }

            returnResponse(res, JSON.stringify(body));
        })
    });
}).listen(process.env.PORT || 3000);

function returnResponse(httpResponse, message) {
    log(`Response status code  ${httpResponse.statusCode} - ${message}`);
    httpResponse.writeHead(httpResponse.statusCode);
    httpResponse.write(message);
    httpResponse.end();
}

var log = function (entry) {
    fs.appendFileSync('/tmp/output.log', new Date().toISOString() + ' - ' + entry + '\n');
};

Comment: No, this is the correct code. The code is configured as a worker tier environment within Elastic Beanstalk. https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/using-features-managing-env-tiers.html
Answer: This is the fixed code:
var http = require('http'),
    request = require("request"),
    fs = require('fs');

http.createServer(function (req, res) {

    req.on('data', function (data) {
        var jsonObj = JSON.parse(data);
        var jsonString = JSON.stringify(jsonObj);

        log("Processing " + jsonString);

        request.post('http://example.com', {
            json: true,
            body: jsonString,
            headers: {
                "content-type": "application/json",
            }
        }, (error, response, body) => {
            if (error) {
                log(`Error ${error}`);
                return;
            }

            returnResponse(res, response.statusCode, JSON.stringify(body));
        })
    });
}).listen(process.env.PORT || 3000);

function returnResponse(res, statusCode, message) {
    log(`Response status code  ${statusCode} - ${message}`);
    res.writeHead(statusCode, {'Content-Type': 'text/plain'});
    res.write('Complete');
    res.end();
}

var log = function (entry) {
    fs.appendFileSync('/tmp/sample-app.log', new Date().toISOString() + ' - ' + entry + '\n');
};

From https://www.edureka.co/blog/aws-elastic-beanstalk/

The daemon pulls requests sent from an Amazon SQS queue. Based on the queue's priority, SQS will send the message via a POSTrequest to the HTTP Path of the Worker Environment. The worker on receiving the message executes the tasks and sends an HTTP response once the operation is done. SQS on receiving response message deletes the message in the queue. If it fails to receive a response, it will continuously retry sending the messages.

The issue was that my previous code wasn't correctly returning an http status code.
Answer: Message being in flight means that it was consumed by a consumer, but not yet deleted from the queue. If it's not deleted by the consumer during queue's visibility timeout, it will be put back into the queue by SQS again.
You should delete messages from the queue if you successfully process them. If you are familiar with AMQP 0-9-1, this action is similar to acknowledging messages.
Since, you are using Node.js, this is the method from official SDK, that you should use to achieve your goal.


How can I have conditional content within page body that is dependent upon the domain?

Question: We are planning to use Domain Access to manage 5 different domains that will share content.  The majority of our pages will be shared across all 5 domains and will look identical on each domain. Domain Access makes it trivial to handle this use case. However, on some of the pages, 95% of the content will be identical and 5% of the content will be dependent upon the domain that is serving the page.
One possible solution is to create a unique page for each domain and publish it to the appropriate domain.  Although this works, it is difficult to maintain because we would need to maintain changes to the identical content across 5 unique pages.
Another option would be to embed PHP in the page, such as
shared content for all 5 sites here.

<?php if ($_SERVER['HTTP_HOST'] === 'domain1.example.com') { ?>

domain1 specific content here

<?php } else if ($_SERVER['HTTP_HOST'] === 'domain2.example.com') { ?>

domain2 specific content here

<?php } ?>

Again, this would work, but has several disadvantages.  I am looking for a way to share the identical content across the domains and yet have site specific content within a page in a way that makes it feasible to maintain and easy for content editors (non-technical users) to edit. Does anyone have any suggestions?
Answer: The sites module has support for multiple domains and managing content across those domains.
https://www.drupal.org/project/sites
If you are using the same template file for the page where you are displaying your content, then you can implement the 'hook_site_access()' from the sites module in the template file, and gather the content you desire to display based on the domain name.
In addition, depending on the type of content you are displaying, you might be able to get away with simply using the Views or Context integration from the Sites module, rather than editing your template file manually.
Another option is to use Drupal's taxonomies to classify your content. Then, you could use any of the solutions above (custom code in page template, Views, or Context) to filter only the content which is categorized to be displayed on the domain you are on.
In any case, if you want two different versions of the same page to display on different domains, you will need two different nodes, and they will need to be classified accordingly. I'm not sure if there is any way around maintaining multiple nodes if the content varies by domain.
However, when the same node is to be displayed on multiple domains, this kind of architecture will allow you to display it only on a specific subset of domains you choose.
Answer: Using the Domain Access module, you can put this in your template.php file:
function YOURTHEMENAME_preprocess_page(&$vars) {
  global $_domain;
  $vars['current_domain'] = $_domain['domain_id'];
}

Once this is done, you'll have a variable you can use in your .tpl-files. The code above provides the domain's ID, which you can find in admin/structure/domain by hovering over the "edit domain" link.
You can use it like this:
<?php if (isset($current_domain)): ?>
    <?php if ($current_domain == 1): ?>

Welcome to my primary website

    <?php elseif ($current_domain == 2): ?>

Welcome to another website

    <?php endif; ?>
<?php endif; ?>

(Source)


Not able to run viewer

Question: I am developing website with help of autodesk api . Viewer was working properly yesterday but it is showing error now. Please help me
This is error
developer.api.autodesk.com/viewingservice/v1/items/urn:adsk.viewing:fs.file…TVEVQ/output/1/battery%20holder.svf?domain=http%3A%2F%2Flocalhost%3A3000:1
GET https://developer.api.autodesk.com/viewingservice/v1/items/urn:adsk.viewing…i5TVEVQ/output/1/battery%20holder.svf?domain=http%3A%2F%2Flocalhost%3A3000 404
onLoadModelError() - errorCode:5
Comment: The error code 5 stands for `The derivative file has been moved or deleted`.  Please check your file is still in your Forge bucket, or check your access token has the right scope and the right permission.
Answer: The error code 5 stands for The derivative file has been moved or deleted. Please check your file is still in your Forge bucket, or check your access token has the right scope and the right permission.
If you still stuck on this issue, please contact with the firstname.lastname@example.com.

Not able to run viewer


convert LPTSTR to string

Question: I am getting text from a Window and it returns in LPTSTR. I have to turn it into string or else I have to rewrite a lot of my code. Also What is a LPTSTR and how is it different from a string?
Comment: LPTSTR can be either `char*` or `wchar_t*` depending on whether or not you are using Microsoft's idea of Unicode
Comment: Part of the reason to just use wide strings in the first place.
Answer: LPTSTR is a string, it's just not constant.
You can use it like a regular char * if as long as you don't define UNICODE in your application. The difference between a unicode and normal string is the length of the character. In unicode it is either 2 or 4 and in standard programs it is 1 byte.
As some people might point out, you're not the only one to ask this question. This is usually a topic of confusion for people learning to program in the Windows environment. See this for some clarification, from MSDN. I'd also recommend viewing their desktop API reference for a lot of useful information that may help you with future inquiries.

convert LPTSTR to string


Do products $AB$ and $BA$ of rectangular matrices contain the same information?

Question: I have data measuring two events in space and in time. More precisely, I have two rectangular data matrices $A$ and $B$ which both have $20$ time rows and $1\text{M}$ space columns.
I want to analyse the interaction between these two events. In particular, I want to do a Canonical-Correlation Analysis (CCA) on their product. I could calculate the product $A^{T}B$, which is a large $1\text{M}$ by $1\text{M}$ matrix. Or I could calculate $BA^{T}$, which is a small $20$ by $20$ matrix.
I know the rank of both types of products is the same (see Math Stack Exchange). This leads me to think the resolution of the information contained in both products is the same. I also know that the eigenvalues for $A^{T}B$ and $BA^{T}$ are identical (see Math Stack Exchange). However, the singular values need not be the same (see Math Stack Exchange).
Is there a way to exploit these facts to analyse the smaller $BA^{T}$ product and still get all relevant information about the large $A^{T}B$ product? Relevant in terms of the CCA. In particular, I would like to avoid the computationally intensive SVD of $A^{T}B$, yet still determine its Principal Components.
Comment: The "amount of information" is not the same.  Consider A and B with only row.  One product would just give the dot product, the other product would be the outer product which contains the information about the directions of both A and B (though loses their individual magnitudes).  The amount of information you're interested in might be the same of course.
Comment: What exactly is amount of information in matrix (or in product of matrixes)?
Comment: I think it's entirely clear what you mean by AB and BA, however there should be some transposes in there somewhere so that matrices are composable.
Comment: @Nik I am not sure about a precise formulation, but my intuition tells me it is related to the number of elements which can vary independently. Therefore, related to the rank and to the (number of) eigenvalues. If anyone can make this more precise, or give a counter-example, that would be helpful.
Comment: @JamesGriffin Okay :) Though the eigenvalues are still the same. Can this be exploited somehow?
Comment: Please explain what you mean by "all relevant information about ... $A^\prime B$."  Clearly you cannot recover $A^\prime B$ in general from the matrix $BA^\prime$, so the meaning of "relevant"--whatever it might refer to--is crucial to understanding this question.
Answer: The following does not answer the OP's question directly, but does solve the issue of performing an SVD on a large matrix product $AB$. This is based on https://arxiv.org/abs/0909.4061v2 and its references.
The large rectangular $m \times n$ matrices $A$ and $B$ with $n << m$ can be projected to a subspace of dimensions equal to the smallest side, $n$, without losing much/any of its action.
In the case of the OP, $A$ and $B$ are both $20 \times 10\text{M}$, while the new $\tilde{A}$ and $\tilde{B}$ are only $20 \times 20$.
Steps:

Generate two random $n \times n$ matrices $\Omega_i$ from a Gaussian distribution with $\mu = 0$ and $\sigma = 1$
Form the $m \times n$ matrix $Y_1 = AΩ_1$
Form the $m \times n$ matrix $Y_2 = BΩ_2$
Construct two $m \times n$ matrices $Q_i$ whose columns form an orthonormal
basis for the range of $Y_i$, e.g. using the QR factorization $Y_i = Q_iR_i$
Form the $n \times n$ matrix $\tilde{A} = Q_1^{∗}A$
Form the $n \times n$ matrix $\tilde{B} = Q_2^{∗}B$

Now, the product $\tilde{A} \tilde{B}$ is $n \times n$. The singular values for this product are very close to the largest singular values of the product $AB$.
The difference between the real $A$ and its approximation $\tilde{A}$ is given by $||A-Q_1\tilde{A}||$. Likewise for $B$.
I do not have proof of exactly this, though similar steps are proven in the reference above. I am not sure this will work in all cases, but some quick tests seem to suggest it works.


Generate random values using an empirical cumulative distribution function

Question: I have a set of data points that I have used to generate my empirical CDF which looks like this (to simplify things I have reduced the number of points for this question but it shouldn't matter):

Given this data and plot I need to somehow generate random values which follow this distribution. I admit that I am quite rusty when it comes to probability, but as far as I understand I need to first generate the PDF and then from there I can do what I want. Is that accurate? Or what is the best way to get what I want?
If interested in giving an example for the answer, here are the X and Y array for the data points of the ECDF plot. I am using Python but I guess a language agnostic answer would also be really helpful
x = [107.6697676209896, 430.70331251794784, 1975.0646306785532, 7793.524079329409, 27569.66699567533, 62566.73646946178, 222847.1449910263, 832591.8949493016, 2827054.7454871265, 10000733.572934577]

y = [0.001603113424267999, 0.04812202549318534, 0.09825964339269633, 0.14190143419466905, 0.27204351414405636, 0.46590411495145756, 0.6008552899988212, 0.6796719668120879, 0.8400864397710662, 0.9427752938262692]

Thanks a lot!
Comment: You generate such a random variable by sampling randomly from the data.
Answer: To generate a random variable from an empirical distribution, you just sample at random from the data used to create that distribution.  So, if you have sample values $\mathbf{x} = (x_1,...,x_n)$ you can generate independent random values $\tilde{X}_1,...,\tilde{X}_m$ from the empirical distribution for this sample by taking:
$$\tilde{X}_i \equiv x_{I_i}
\quad \quad \quad \quad \quad
I_1,...,I_m \sim \text{IID U} \{ 1,...,n \}.$$
It is simple to show that $\tilde{X}_1,...,\tilde{X}_m \sim \text{IID }F_\mathbf{x}$ (i.e., the values are independent draws from the empirical distribution for $\mathbf{x}$).
Answer: Given samples $X_1,X_2,\ldots,X_N$, a empirical distribution $d$ is defined as $d(x)=\frac{1}{N}\sum_{i=1}^N\delta_{X_i}(x)$. This is just a categorical distribution you can easily sample from. However, I believe what you are seeking is a smoothed version of the empirical distribution. Then, you should use kernel density estimation, $\hat d(x)=\frac{1}{N}\sum_{i=1}^NK_h(x-X_i)$, where $K$ is the kernel function. Some valid kernel functions are shown here.
The following code fits the data with the scikit-learn package. Since the data scale is across multiple magnitudes, it is better to fit it on the log domain. Once you get a fitted density function $kde$, you can sample from it by calling its method sample(n_samples).
from sklearn.neighbors import KernelDensity
import numpy as np
import matplotlib.pyplot as plt
X = np.array([107.6697676209896, 430.70331251794784, 1975.0646306785532, 7793.524079329409, 27569.66699567533, 62566.73646946178, 222847.1449910263, 832591.8949493016, 2827054.7454871265, 10000733.572934577]
).reshape(-1,1)

# Bandwidth controls the smoothness of the density. The larger, the smoother.
kde = KernelDensity(kernel='exponential', bandwidth=3e6).fit(X)
x = np.linspace(0, 1e7, 1000).reshape(-1,1)
y = np.exp(kde.score_samples(x))
plt.subplot(2, 1, 1)
plt.plot(x, y)

log_X = np.log(X) # Transform the data into log domain
log_kde = KernelDensity(kernel='gaussian', bandwidth=2.0).fit(log_X)
log_x = np.linspace(3, 17, 1000).reshape(-1,1)
log_y = np.exp(log_kde.score_samples(log_x))
plt.subplot(2, 1, 2)
plt.plot(log_x, log_y)
plt.subplots_adjust(hspace=0.5)

Comment: Thanks! I see that you are not using my Y values, how does that make sense? My X values are not actual values. I obtained the X and Y values simply by extracting them from a plot in a paper. They are just equally distant points (pixel wise) which were extracted using a software.
Comment: @Tommy95 An empirical CDF is a step function. Therefore, the CDF you obtained is actually a linearly interpolated CDF.  Its Y-value is not necessary for density estimation. All you need is just the set of data points.  However, you can also use the interpolated CDF to generate a density function, for which the density is just the slope in the CDF.
Comment: but then how would it be able to work without having an idea of the Y values? Let's say the second x point has an actual y value of 0.98 and then all the other points are slowly increasing towards 1. Then if I just use the x values (let's assume I have 10 of them), how would it know that 98% of the values are lower than the second x value?
Comment: @Tommy95 By data points, I mean the raw dataset you have. It's meaningless to use some equally distant points. In the raw dataset, roughly 98% of data points are below the 0.98-quantile.


Why do some hockey players kneel as they take a shot?

Question: I was watching the Rangers vs Islanders game, and McDonaugh scored a goal while down on one knee, a bit like .
Here is video of the goal at NHL website and on youtube.
I've seen lots of players do this before, often when someone passes across the goal on a 2 on 1.
Is there any reason why they do it? Do you get more control/accuracy like that?
Answer: I asked my friend, who played hockey in college, and she said that it is a combination of a few things:

You turn some of your momentum into shot speed/power, if you do it in a single motion.  Your push off the back skate can be stronger when going down to a knee, and some of that is transferred into your lower stick arm (the right arm in the above picture).
You are able to use more of your strength from the lower hand/arm/shoulder in that position.
Some players may feel they have a higher degree of accuracy, but my friend wasn't sure whether this is true or not.

I also found that it specifically allows a shot that is higher in the net with power; for example, this hockey tutorial shows how to do it.  They credit Brett Hull with popularizing it, and I can't say I know whether that's true or not (as my hockey watching days date to basically early Brett Hull but not before).
Answer: It is simply because Ryan McDonaugh was not in the greatest position relative to the puck so rather than stopping the puck for a moment to position himself he got the shot off as quickly as possible in order to surprise Halák.


Puppet/Foreman - Hostgroups and classes

Question: I successfully set up foreman and puppet. Now I'm trying to configure host groups which should contain a specific configuration.
My example: Host group "Basic" should get a special MOTD.
I installed a MOTD-module for puppet:
puppet module install puppetlabs-motd

Now I imported the class to foreman - works also fine.
Next step was adding a new host group:

Okay, fine. Now I'm adding my new motd-class:

Okay, now it would be fine if all hosts belonging to the host group "Basis" would show a MOTD-text "Hello World". If I configure another host group "Test" which is also using the motd-module the text should be "Bye, bye world".
How can I specify parameters for each host group this way?
Answer: The motd module you downloaded has a "content" parameter on the motd class that controls what's in the /etc/motd file.  This is shown at https://forge.puppetlabs.com/puppetlabs/motd#usage.
By default, Foreman doesn't set the value of any class parameters.  Go to Configure > Puppet classes (sorry, you'll have to translate to German), click on the class and go to the Smart class parameters tab.
The known (imported) smart class parameters are listed on the left, click content, tick the Override checkbox and either enter a default value for it or tick the Use Puppet default box if you prefer.
When editing a host or host group with the class assigned, the content parameter will now be listed on the Parameters tab and can be overridden.  Click the override button to set a value on the host group and save it.  Host overrides take precedence over a host group override.
More information on these overrides is in the Smart Matchers part of the Foreman manual.  They can be configured in more detail on the Puppet classes page above.

Puppet/Foreman - Hostgroups and classes


Is there a way to always disable keyboard in a page?

Question: I have a page where users can choose either they want to connect with social media or login with email. This page does not need any user input. So there is no need for keyboard.
<code>  return Scaffold(
  body: Stack(
    fit: StackFit.expand,
    children: <Widget>[
      Container(
        alignment: Alignment.center,
        decoration: BoxDecoration(
            gradient: LinearGradient(colors: [
          Colors.deepPurple,
          Colors.purple[700],
          Colors.purple
        ], begin: Alignment.topCenter, end: Alignment.bottomCenter)),
        padding: EdgeInsets.all(30.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            _withSocialMedia,
            _or,
            _withEmail,
            SizedBox(height: 50.0),
          ],
        ),
      ),
    ],
  ),
);
</code>
I have 2 questions related to this page.

Is there a way that i can always disable keyboard from popping up in
this page?
Is there a way for me to make the page does not push
all the elements in the page to the top to accommodate keyboard?

Hopefully you guys can help me on this. Thank you.
Comment: I don't see any focusable widget in your code. What is causing the keyboard to show up?
Comment: The keyboard is coming from the previous page
Answer: Put this in a utility file somewhere and call whenever you need to dismiss the keyboard programmatically. In your case, it would be just before navigating away from the previous screen.
<code>import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

/// Hides the onscreen keyboard
void hideKeyboard(BuildContext context) {
  SystemChannels.textInput.invokeMethod('TextInput.hide');
  FocusScope.of(context).requestFocus(FocusNode());
}
</code>