text:
Q: Dockerfile for a fastAPI app using Factory pattern with unicorn I am building a back-end service for a full-stack application using fastAPI and unicorn.
src/asgi.py
import uvicorn
from src import create_app

app = create_app()

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", log_level="info", reload=True)

src/init.py
from fastapi import FastAPI
from src.api.v1.auth import auth_router
from src.core.config import *

def create_app() -> FastAPI:
    root_app = FastAPI()
    root_app.include_router(
        auth_router,
        prefix="/api/v1",
        tags=["auth"],
    )
    return root_app

Dockerfile
FROM python:3.9

RUN mkdir /app
WORKDIR /app

RUN apt update && \
    apt install -y postgresql-client

COPY requirements.txt ./
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

How I am building and running:
docker build -t travian-back:v1 .
travian-back:v1 uvicorn asgi:app

There is no error at all, server is up at http://127.0.0.1:8000
Now I am trying to directly add the uvicorn asgi:app command to my Dockerfile. The reason is because I am going to use docker-compose at the end and it would be easier. This is what I have now:
Dockerfile
    RUN mkdir /app
    WORKDIR /app

    RUN apt update && \
        apt install -y postgresql-client

    COPY requirements.txt ./
    RUN pip install --no-cache-dir -r requirements.txt

    COPY . .

CMD ["uvicorn", "asgi:app"]

Now instead of doing travian-front:v1 uvicorn asgi:app I am doing travian-back:v1 uvicorn asgi:app , I have no error when building and running my docker image but the server can't be reached at http://127.0.0.1:8000

A: The thing is that you don't run the asgi file as main, since you use uvicorn to point to it. So it's not listening on 0.0.0.0 or better put, all those options are ignored.
Either invoke the asgi file directly, which I would not recommend, or drop the asgi file and use uvicorn with the --factory flag and point it to your app factory.
ENTRYPOINT ["uvicorn", "src.init:create_app", "--factory", "--host 0.0.0.0"]

I am using entrypoint here so that you can pass additional flags such as log level on run without overriding this.
docker run -p 8000:8000 myapp --log-level warning

That said, I am somewhat confused by your file name init.py. Do you mean __init__.py? If so I would not put the factory in this file, __init__.py is not meant to be used like this. Put it in a file named main.py or similar.


text:
Q: Can we give value inside input element which type is number? When I give the value then an error occurs. In profile page I want to display mobile number in value inside number input element.mobile number is display but in html section error display. The error is bad value for attribute value on element input.

<input type="number" class="form-control"  value="<?php echo $profileinfo[0]['mobile_number']; ?>" name="profile[mobileno]" pattern="^\d{10}$" required title="format : xxxxxxxxxx">

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trouble with the derivative of the delta function I am trying to evaluate the following integral with Mathematica:
\begin{align}
I = \int_{0}^{\infty}  da  \,    \frac{e^{-\frac{a ^2}{4s^2}} }{a^2} \mbox{sinc}\left(\tfrac{w}{2} a \right)   \delta' \left(  \frac{D^2}{a}- a \right),
\end{align}
where the prime on the delta function denotes differentiation with respect to the argument of the Delta function. When I evaluate this integral with Mathematica as:
Integrate[Exp[-a^2/(4 s^2)]/a^2 Sinc[w a / 2] Derivative[1][DiracDelta][D^2/a - a],{a,0,Infinity}, Assumptions -> s > 0 && w > 0 && D > 0]

I get the result:
\begin{align}
I_{Mathematica} = \frac{e^{-\frac{D^2}{4 s ^2}} }{4 D^4 s ^2 w } \left[\left(D^2+6 s ^2\right) \sin \left(\frac{D w }{2}\right)-D s ^2 w  \cos \left(\frac{D w }{2}\right)\right].
\end{align}
However, if I evaluate this integral analytically, using the fact that
\begin{align}
 \frac{d}{da} \delta\left( \frac{D^2}{a}- a \right) = - \delta' \left( \frac{D^2}{a}- a \right)  \left(\frac{D^2}{a^2}+1\right) \implies \delta' \left( \frac{D^2}{a}- a \right)  = - \left[\frac{d}{da} \delta\left( \frac{D^2}{a}- a \right) \right] \left(\frac{D^2}{a^2}+1\right)^{-1},
\end{align}
I get the following result:
\begin{align}
 I_{analytic} &=   \int_{0}^{\infty}  da  \,    \frac{e^{-\frac{a ^2}{4s^2}} }{a^2} \frac{\sin \left(\tfrac{w}{2} a \right) }{\tfrac{w}{2} a}  \delta' \left(  \frac{D^2}{a}- a \right)  \\
 &=-  \int_{0}^{\infty}  da  \,   \left[\frac{d}{da} \delta\left( \frac{D^2}{a}- a \right) \right] \left(\frac{D^2}{a^2}+1\right)^{-1}  \frac{e^{-\frac{a ^2}{4s^2}} }{a^2} \frac{\sin \left(\tfrac{w}{2} a \right) }{\tfrac{w}{2} a}    \\
  &=   \int_{0}^{\infty}  da  \,   \delta\left( \frac{D^2}{a}- a \right) \left[\frac{d}{da}   \left(\frac{D^2}{a^2}+1\right)^{-1}  \frac{e^{-\frac{a ^2}{4s^2}} }{a^2} \frac{\sin \left(\tfrac{w}{2} a \right) }{\tfrac{w}{2} a} \right]  \\
   &=   \int_{0}^{\infty}  da  \,   \frac{\delta\left( D - a \right)}{2} \left[\frac{d}{da}   \left(\frac{D^2}{a^2}+1\right)^{-1}  \frac{e^{-\frac{a ^2}{4s^2}} }{a^2} \frac{\sin \left(\tfrac{w}{2} a \right) }{\tfrac{w}{2} a} \right]  \\
   &= - \frac{e^{-\frac{ D^2 }{ 4s^{2}}}}{4 D^{4} s^{2} w} \left[ \left(D^{2}+4 s^{2}\right)\sin\left( \frac{ Dw}{2} \right) - D s^{2} w \cos \left( \frac{ Dw}{2} \right)  \right],
\end{align}
which differs from $I_{Mathematica}$ by an overall negative sign and the prefactor in front of $s^2$ in the first term.
I'm not sure if the issue is with the way Mathematica handles the derivative of the delta function or if I've made a mistake in my analytic calculation. Any help would be much appreciated, I've been staring at this for days!

A: Let's talk about the Dirac $\delta$-"function". Strictly speaking, it's a linear functional
$$\delta:C^\infty(\mathbb R)\to\mathbb R\qquad\qquad\delta(f)=f(0).$$
However, we usually use the notation
$$\int_{-\infty}^\infty\delta(x)f(x)dx$$
to denote the evaluation $\delta(f)$. The derivative of the $\delta$-"function" is computed via formal integration by parts:
$$\delta'(f)=\int_{-\infty}^\infty\delta'(x)f(x)dx=-\int_{-\infty}^\infty\delta(x)f'(x)dx=-f'(0).$$
Your integral has the additional complications that there is a function inside the argument of $\delta'(x)$, and that the integral is not taken over all of $\mathbb R$. Composing distributions with functions is, in general, not possible, but in this case we can appeal to a theorem of Hormander:
Theorem: Suppose $f:M\to N$ is a smooth function whose differential is everywhere surjective. Then there is a linear map $f^*:\mathscr D(N)\to\mathscr D(M)$ such that $f^*u=u\circ f$ for all $u\in C(N)$.
For our purposes, this means $\int_{-\infty}^\infty\delta'(f(x))g(x)dx$ makes sense provided $f(x)$ is smooth and $f'(x)$ never vanishes. Similarly, reducing the domain of integration is, in general, not possible, but we have:
Theorem Suppose $E_1$ and $E_2$ are disjoint closed sets, and let $\mathscr D_{E_i}$ denote the set of distributions which coincide with a smooth function on $E_i^c$ for $i=1,2$. Then there is a bilinear map
$$m:\mathscr D_{E_1}\times\mathscr D_{E_2}\to\mathscr D(\mathbb R^n)$$
such that $m(u,v)=uv$ when $u$ and $v$ are continuous.
In our case, we would like to compute the integral
$$\int_0^\infty\delta'\left(\frac{D^2}{x}-x\right)g(x)dx=\int_{-\infty}^\infty\chi_{(0,\infty)}(x)\delta'\left(\frac{D^2}{a}-a\right)g(x)dx,$$
where $\chi_{(0,\infty)}$ is the characteristic function of the half-line $(0,\infty)$. The theorem says that the product
$$\chi_{(0,\infty)}(x)\delta'\left(\frac{D^2}{x}-x\right)$$
makes sense whenever the singular support of $\chi_{(0,\infty)}$, namely $\{0\}$, does not intersect the singular support of $\delta'\left(\frac{D^2}{x}-x\right)$, namely $\{D,-D\}$. Thus when $D\neq 0$, our integral makes sense and
$$\int_0^\infty\delta'\left(\frac{D^2}{x}-x\right)g(x)dx=\begin{cases}g'(D),&D>0\\g(-D),&D<0\end{cases}.$$
To compute your integral, just plug in your particular function $g(x)$. When you're working with distributions (like $\delta$) you need to be very careful about what you do with them. I don't know how Mathematica conceptualizes the $\delta$-distribution, but I wouldn't be inclined trust that it would go through the necessary analytical reasoning and get the right answer.
TL;DR: Do your distributional calculus by hand.

A: Here my attempt to solve the integral Integrate[f[a] Derivative[1][DiracDelta][d^2/a - a],{a,0,Infinity}]:
f[a_] := Exp[-a^2/(4 s^2)]/a^2 Sinc[w a/2]

Substitution u[a]=d^2/a-a (integrationlimits change to u[0]=Infinity],u[Infinity]=-Infinity)
u[a_] := d^2/a - a

sola = Solve[u == d^2/a - a, a][[2]] (*solution a>0*)

Now Mathematica is able to solve the integral
int=Integrate[f[a/.sola] Derivative[1][DiracDelta][u]/u'[a]/.sola ,{u, Infinity,-Infinity}]

(*(E^(-(d^2/(4 s^2))) (d s^2 w Cos[(d w)/2] - (d^2 + 4 s^2) Sin[(d w)/2]))/(4 d^3 Sqrt[d^2] s^2 w)*)

Hope it helps solving your problem!

A: My previous answer and comments were wrong. I didn't notice the argument of the δ function was not linear in the integration variable (and I wasn't even drunk).
In the Wikipedia page, there is this paragraph

In the integral form the generalized scaling property may be written as
       $∫_{-∞}^∞ f ( x ) δ ( g ( x ) ) d x = ∑_i f ( x_i ) / | g ′ ( x_i ) | $.

The Jacobian of the transformation is 1/g'(x). Please note the absolute value in the denominator.
Basically, find the zeroes of the argument of the δ, and integrate around them (by parts if necessary). Also,

The distributional derivative of the Dirac delta distribution is the distribution δ′ defined on compactly supported smooth test functions φ by
  $δ ′ [ φ ] = − δ [ φ ′ ] = − φ ′ ( 0 )$ .

(1) Finding the zeroes:
Solve[-a + Δ^2/a == 0, a]

(2) Finding the Jacobian:
jac = Solve[Dt[-a + Δ^2/a == u[a]], u'[a]]
  /. Dt[Δ] → 0 /. a → Δ // FullSimplify

(3) Evaluating the integral by parts (don't forget the minus sign in front):
v1 = -D[(E^(-(a^2/(4 s^2))) Sinc[(a w)/2])/a^2, a] / Abs[jac]
  /. a → Δ // FullSimplify

(4) Divide the integral by the Jacobian (the previous division was because of the integration by parts, this one because of the scaling):
v1 / Abs[ jac ]

The answer is the same as $I_{MMA}$. By the way, MMA is simply using
Integrate[ f[a] DiracDelta'[2 a], {a, -∞, ∞}]
(*-(1/4) f'[0]*)

Prove that analytically and you will find the error in your analytic calculation.

A: speculation:
Mathematica cannot handle Derivative[1][DiracDelta][1/x-x]in a right way?
Here I'll give a simplified example which perhaps shows that Mathematica gives a wrong result, when applied to Derivative[1][DiracDelta][1/x-x]!
Let's consider the integral
Integrate[Derivative[1][DiracDelta][1/x - x], {x, 0, Infinity} ]
(*0*)

which MMA (v12)  evaluates to zero!
Alternatively integration with substitution u=1/x-x, x=-u/2+Sqrt[1+(u/2)^2]
(see my first answer)
us=D[1/x-x,x]/. x->-u/2+Sqrt[1+(u/2)^2];
Integrate[ Derivative[1][DiracDelta][u]/us, {u, Infinity,-Infinity} ]
(*1/4*)

To "proof" the last result I'll consider the deltadistribution as a well known limit
dirac = Function[x, Exp[-(x^2/(2 eps))]/Sqrt[2 Pi eps]] (* eps->0 *)

int=Integrate[dirac'[1/x - x], {x, 0, Infinity} ]

(*(E^(1/eps) (-BesselK[0, 1/eps] + BesselK[1, 1/eps]))/(eps^(3/2) Sqrt[2 \[Pi]])*)

eps->0
Simplify[ Normal[Series[int, {eps, 0, 0}]], eps > 0]

(*1/4*)

Why can't Mathematica find this result? What's wrong here?


text:
Q: Как организовать работу слоя посредников (Middleware)? Пытаюсь разобраться как работают посредники, хотя бы на не самом низком уровне. Для экспериментов взял готовый компонент для работы с HTTP, роутер, компонент для отправки/вызова посредников.
Пример того, что получилось
$request = Zend\Diactoros\ServerRequestFactory::fromGlobals();
$routerContainer = new Aura\Router\RouterContainer();
$map = $routerContainer->getMap();
$matcher = $routerContainer->getMatcher();

// коллекция роутов приложения
$map->get('main', '/', new App\Controllers\HomeController());
$map->get('about', '/about', new App\Controllers\AboutController());

// добавляем посредников
$delegate = new Moon\HttpMiddleware\Delegate([
    new App\Middlewares\TestMiddleware(),
  ],
  function() {
    new Zend\Diactoros\Response\HtmlResponse('
alert!
');
  }
);
$delegate->handle($request);

// поиск текущего роута и формирование ответа
$route = $matcher->match($request);
$response = ($route->handler)($request);

// отправка ответа на клиент
$emitter = new Zend\HttpHandlerRunner\Emitter\SapiEmitter();
$emitter->emit($response ?? new Zend\Diactoros\Response\EmptyResponse());

Такой способ приводит к ошибкам в недрах класса Delegate, которые не могут быть разрешены в попытках исправить их "в лоб".
Допускаю, что какой-то этап пропущен, но какой - никак не могу найти.

A: Привожу пример со своего проекта
$app = new MiddlewarePipe(); // Zend\Stratigility\MiddlewarePipe
$app->pipe(new MiddlewareException($container->get(LoggerInterface::class), $prototype));
$app->pipe($container->get(MiddlewareSettings::class));
$app->pipe($container->get(MiddlewareStats::class));
$app->pipe(new MiddlewareRoute($router, $container, $prototype));
$response = $app->process($request, new MiddlewareNotFound($prototype));

надеюсь слишком много пояснять не нужно?


text:
Q: How to prevent textarea from overlapping list I have created a messenger app working but there is one problem that the textbox overlaps the messages. My HTML:

  <form onsubmit="return sendMessage();">

  <textarea id="message" placeholder="Enter message..." rows="3" cols="195"></textarea>
  <input type="submit" id="submitibtn">

  </form>

CSS:
#message {
     resize: none;
     position: fixed;
     bottom: 0;
     height: 70px;
 }

 #message:hover {
     border: 2px solid black;
 }

 #submitibtn {
     background-color: cornflowerblue;
     width: 1580px;
     height: 30px;
     position: fixed;
     bottom: 0;
 }

 #submitibtn:hover {
     border: 2px solid blue;
 }

Website if you want to see it for yourself:
https://messengerwebapp.firebaseapp.com/
(Login as anonymous and send a message then see the textarea overlapping the messages)

A: Change your CSS. This is what is causing the issue
#message {
     resize: none;
     position: fixed;
     bottom: 0;
     height: 70px;
 }

Try this
#message {
     resize: none;
     height: 70px; /* THE HEIGHT SHOULD INHERIT YOUR ROWS ON THE TEXTAREA */
 }

A: In your particular case this would work, although I would suggest you study html and css a little more and you will arrive to a much more clean and better structure:

#messages {
    bottom: 76px;
    overflow: hidden;
    position: fixed;
    top: 100px;
    left: 15px;
    right: 15px;
}

A: Instead of fixed positioning, you can give the div holding the messages a fixed height and overflow scroll. You will just need to play with the VH heights.

#message {
         resize: none;
         height: 25vh;
       width: 100%;
     }

     .messages-wrapper{
        height:60vh;
        overflow-y:scroll;
        overflow-x:none;
     }

     #message:hover {
         border: 2px solid black;
     }

     #submitibtn {
         background-color: cornflowerblue;
         width: 100%;
         height:15vh;
     }

     #submitibtn:hover {
         border: 2px solid blue;
     }

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

aaaa

      <form onsubmit="return sendMessage();">

      <textarea id="message" placeholder="Enter message..." rows="3" cols="195"></textarea>
      <input type="submit" id="submitibtn">

      </form>


text:
Q: How to bundle a python server with pyinstaller for AppStore as 64bit only? Context:
I am trying to put an electron app on the App Store. The app features a web frontend and a python backend. Nothing fancy so far.
The backend however features a separate server written in python. This server is a standalone application.
The electron app bundles the main app together with the python standalone server.
The problem:
When building the server as an executable I use pyinstaller on a python 3.5 development environment. Upon uploading to the AppStore I receive the following error:
1 package(s) were not uploaded because they had problems:
/var/folders/39/3v0phzy173s3qxkbxzvcpd5c0000gn/T/82AB662A-44C8-41E9-A213-8BF672F3DF10/1443777291.itmsp - Error Messages:
    ERROR ITMS-90240: "Unsupported Architectures. Your executable contained the following disallowed architectures: '[i386 (in com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/AppKit._AppKit.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/AppKit._inlines.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/CoreFoundation._CoreFoundation.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/CoreFoundation._inlines.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/Foundation._Foundation.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/Foundation._inlines.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/PIL._imaging.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/PIL._imagingtk.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/PIL._webp.so, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/libjpeg.9.dylib, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/libopenjp2.2.1.0.dylib, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/libtiff.5.dylib, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/libwebp.7.dylib, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/libwebpdemux.2.dylib, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/libwebpmux.3.dylib, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/libz.1.2.11.dylib, com.ShapeRobotics.FableMac.pkg/Payload/Fable.app/Contents/Resources/app/app/app/server/objc._objc.so)]'. New apps submitted to the Mac App Store must support 64-bit starting January 2018, and Mac app updates and existing apps must support 64-bit starting June 2018."

We tried building the server using this:
pyinstaller server.spec --distpath ../app/app --noconfirm

It didn't work.
Another incantation I use to bundle the python server trying to force 64bit is:
arch -64 python ~/anaconda3/envs/shape/bin/pyinstaller server.spec -s --osx-bundle-identifier com.ShapeRobotics.FableMac --distpath ../app/app --noconfirm"

Why I'm sure it's the server:
I was successful in signing the app and getting it uploaded to the AppStore w/o the server packed in.
After packing in the server the 'i386' architecture error popped up.
Consequently my efforts so far have been focused to eliminate any shred of 32bit code in the server.
I assume that in order to do this I must properly configure the .spec file used by pyInstaller.
Does this make sense?
Is there a way to configure the spec file to force exclusive 64bit on anything bundled inside?
Is there some clear cut way to make the AppStore upload not vomit the 'i386' error?
Thank you!


text:
Q: Using a consistent ODM for both PHP and Python First question so please excuse any formalities I miss.
I am developing a system - the backend in Python, the frontend in PHP. The system will leverage a MongoDB database for a number of reasons. I plan to use an Object Document Mapper to make database lookups, and relationships, between pieces of data relatively trivial.

Adding this information as requested
The plan I envision is that the PHP interface would allow users to view the data, and navigate through to connected information, leveraging the relationship defined in the database. For example
Organisation > IP Ranges > IPs > TCP ports open on this IPs
The Python side is the system collecting this information, entering it into the database, and defining/establishing the relationship between the data (i.e. this IP range belongs to this organisation)

I can see that there are many options for both PHP, and Python, independently - but there dont appear to be any solutions that support both PHP and Python at the same time. Is there a way I can utilise the same ODM across both languages to ensure that data can be referenced/'looked up' in the same manner - or, is there a better solution for this that I am unaware of?

perhaps the simplified version of the question is - is there a language agnostic way I can/should be querying data, with defined relationships in that data, with mongodb?

Thanks! :-)


text:
Q: Why does max-height not work with tables? I want the parent containers of a table to expand as per the height of the table. I tried setting height:auto; to the parent containers but it didn't work.
My target is to keep the table shape in square and expand height of the container depending on the height of the table.
The following is what I tried:
HTML

CSS
.playground {
    margin-top: -20px;
    margin-bottom: 0;
    height: auto;
}
.boardContainer {
    height: auto;
}
#boardGrid {
    margin: 0 auto;
    max-width: 620px;
    max-height: 620px;
}
#boardGrid td {
    width: 33.33%;
    height: 33.33%;
    vertical-align: middle;
    cursor: pointer;
}
.comments {
    height: 200px;
}
@media (min-width: 768px) {
    .boardContainer {
        margin-left: 15%;
        margin-right: 15%;
    }
}
@media (min-width: 992px) {
    .scoreboard {
        position: fixed;
        right: 10px;
    }
    .playground {
        margin-top: 35px;
    }
    .boardContainer {
        margin-left: 20%;
        margin-right: 20%;
    }
}
@media (min-width: 1200px) {
    .boardContainer {
        margin-left: 25%;
        margin-right: 25%;
    }
}

A: would this work for you?
https://jsfiddle.net/wb4ovbsb/2/
.playground {
    margin-top: 0px;
    margin-bottom: 0;
    height: auto;
}
.boardContainer {
    height: 0;
    width:100%;
    padding-bottom:100%;
    margin: auto;
    position:relative;
}
#boardGrid {
    margin: 0 auto;
    max-width: 620px;
    max-height: 620px;
}
#boardGrid td {
    width: 33.33%;
    height: 33.33%;
    vertical-align: middle;
    cursor: pointer;
}
.comments {
    height: 200px;
}
.strecher{position:absolute; top:0; bottom: 0; right:0;left:0;}
table{width:100%; text-align:center; height:100%; vertical-align: middle; }
@media (min-width: 768px) {
    .boardContainer {
        width: 70%;
        padding-bottom:70%;
    }
}
@media (min-width: 992px) {
    .scoreboard {
        position: fixed;
        right: 10px;
    }
    .playground {
        margin-top: 35px;
    }
    .boardContainer {
        width: 60%;
        padding-bottom:60%;
    }
}
@media (min-width: 1200px) {
    .boardContainer {
        width: 50%;
        padding-bottom:50%;
    }
}*emphasized text*


text:
Q: Boxshadow inset can't recreate from Photoshop So, here is what it needs to look like

You see that nice white effect on the center, I tried to recreate that, but with no succes here is my code:
  article .txt:after{
    position:absolute;
    content:'';
    width:50px;
    height:50px;
    top:50%;
    left:35%;
 -webkit-box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.1);
    -moz-box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.1);
    box-shadow: inset 0px 0px 10px rgba(255, 255, 255, 0.1);
  }

A: You're missing a spread radius in your CSS declaration. That is, it should look something more like this (notice that in each of the box-shadow definitions there is a new "20px" number):
article .txt:after{
    position:absolute;
    content:'';
    width:50px;
    height:50px;
    top:50%;
    left:35%;
    -webkit-box-shadow: inset 0px 0px 10px 20px rgba(255, 255, 255, 0.1);
    -moz-box-shadow: inset 0px 0px 10px 20px rgba(255, 255, 255, 0.1);
    box-shadow: inset 0px 0px 10px 20px rgba(255, 255, 255, 0.1);
}

I also did a quick mockup in JSFiddle, you can see it here:
http://jsfiddle.net/ZEuZ6/

A: From the image, it looks like what you want is not really a shadow, but a gradient.
Some good information on gradients: http://davidwalsh.name/css-gradients

A: If what you want to reproduce is the white highlight on the device, try using a transparent PNG to achieve the effect, and absolutely position it over top of the image of the device.
An example would look like this
<figure class="frame">
    <img src="mobile-device.jpg" />
</figure>

CSS:
.frame { display: block; position: relative; }
.frame:after {
    display: block;
    content: "";
    background: url('highlight.png');
    width: xx;
    height: yy;
    top: 0; left: 0;
 }


text:
Q: How does the CSGO Map Raffle at the ESL touraments work? I'm asking how the system works where the teams at the ESL touraments (Katowice, Cologne, etc.) choose the maps at the group. Please tell me a lot of details because I'm developing this system for amateur clans which doesn't have the oppurnity to use the official system.

A: It's a bit late, but the ESL uses these rules for their championships:
(The accepted answer is a bit inaccurate.)
Best of One:

Ban A - Ban B - Ban A - Ban B - Randomized map out of the three remaining

(Teams select 4 maps not to be played and the map to be played will be a random map from the remaining ones.)

Best of Three:

Ban A - Ban B - Pick A - Pick B - Randomized 3rd map out of the three remaining

(Teams select one map each not to be played, then pick a map to be played. If a decider is needed it will be randomly selected from the remaining maps in the pool.)

A: For the most recent competition, ESL One Cologne, Maps were chosen as so:
In this example, we will use two teams, team A and team B, and all the maps in this pot will be in active duty.
Team A will ban a map from the raffle, in this case, let's say they ban Cobblestone.
Team B does the same thing. let's say they ban off Dust 2.
Team A repeats, banning cache.
Team B follows, banning Inferno.
Team A bans Mirage.
Team B bans Train.
There should only be one map remaining, and this map would be
Overpass.
Therefore, Overpass is the selected map.
In a nutshell, you ban off maps until one remains, and that will be the map you play on. The maps that you ban should be maps which you think the opposing team is good at.
If I'm not wrong, another way of doing this is to ban off maps until 3 are left, and picking one randomly from the three.
There are many ways to go about doing this, and there are no real limits to do it, but the two methods stated above are the most common (mostly the first one)


text:
Q: Limit of segments ratio in partition of an arc of circle Consider an arc $(AB)$ of a circle $C$ and the partition $(A_i^n)$, where $A_0^n=A$,$A_n^n=B$. The measure of $A_{i-1}^n A_{i}^n$ will be denoted $h_n$.
Now consider the following: Trace the bissector of each angle $A_{i-1}OA_{i}$ and mark the medium point $B_{i}^n$ of the arc $(A_{i-1}^n A_{i}^n)$, then the tangente line $r_i$ to $C$ through $B_i^n$. Consider then the points
$V_{i}^{n}$ where the line $r_i$ intersects the ray $OA_i^n$, and denote $v_n$ the measure of $V_{i-1}^n V_{i}^n$.
Show that $\displaystyle\lim_{n \to \infty}  \frac{v_n}{h_n} = 1$ .
I believe that if $n \to \infty$, then $V_i^n = A_i^n$ and the limit will be trivial, but I don't quite see how to formalize this argument.
Thanks.

A: By similar triangles you have (see diagram below):
$$
{v_n\over h_n}={R\over\sqrt{R^2-h_n^2/4}},
$$
where $R$ is the radius of $C$.
But $h_n\to 0$ when $n\to+\infty$, so that:
$$
\lim_{n\to+\infty}{v_n\over h_n}=
\lim_{n\to+\infty}{R\over\sqrt{R^2-h_n^2/4}}=1.
$$


text:
Q: Apache spark distributed matrix operations? For class : https://spark.apache.org/docs/1.2.1/api/scala/index.html#org.apache.spark.mllib.linalg.DenseMatrix
Are Matrix operations distributed in same way as RDD ? From reading the docs's this does not appears to be the case (as it is not mentioned).
So if I run :
      package worksheets

import org.apache.spark.mllib.linalg._
import org.apache.spark.mllib.linalg.distributed._
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf
import org.apache.spark.rdd.RDD

object matrix {
  println("Welcome to the Scala worksheet")       //> Welcome to the Scala worksheet

  val conf = new org.apache.spark.SparkConf()
    .setMaster("local")
    .setAppName("filter")
    .setSparkHome("C:\\spark-1.1.0-bin-hadoop2.4\\spark-1.1.0-bin-hadoop2.4")
    .set("spark.executor.memory", "512m");        //> conf  : org.apache.spark.SparkConf = org.apache.spark.SparkConf@1faf8f2

  val sc = new org.apache.spark.SparkContext(conf)//> Using Spark's default log4j profile: org/apache/spark/log4j-defaults.propert
                                                  //| ies
                                                  //| 15/03/30 13:33:33 INFO SecurityManager: Changing view acls to: user
                                                  //| 15/03/30 13:33:33 INFO SecurityManager: Changing modify acls to: user
                                                  //| 15/03/30 13:33:33 INFO SecurityManager: SecurityManager: authentication disa
                                                  //| bled; ui acls disabled; users with view permissions: Set(user); user
                                                  //| Output exceeds cutoff limit.

  // make an RDD from the resultant sequence of Vectors, and
  // make a RowMatrix from that.
  val dm: DenseMatrix = new DenseMatrix(3, 2, Array(1.0, 3.0, 5.0, 2.0, 4.0, 6.0))
                                                  //> dm  : org.apache.spark.mllib.linalg.DenseMatrix = 1.0  2.0
                                                  //| 3.0  4.0
                                                  //| 5.0  6.0

  val md: DenseMatrix = new DenseMatrix(2, 3, Array(1.0, 3.0, 5.0, 2.0, 4.0, 6.0))
                                                  //> md  : org.apache.spark.mllib.linalg.DenseMatrix = 1.0  5.0  4.0
                                                  //| 3.0  2.0  6.0

  dm.multiply(md)                                 //> 15/03/30 13:33:42 WARN BLAS: Failed to load implementation from: com.github
                                                  //| .fommil.netlib.NativeSystemBLAS
                                                  //| 15/03/30 13:33:42 WARN BLAS: Failed to load implementation from: com.github
                                                  //| .fommil.netlib.NativeRefBLAS
                                                  //| res0: org.apache.spark.mllib.linalg.DenseMatrix = 7.0   9.0   16.0
                                                  //| 15.0  23.0  36.0
                                                  //| 23.0  37.0  56.0
}

Spark does not appear to distribute this operation?
This Jira appears to hint that this may be supported in future : https://issues.apache.org/jira/browse/SPARK-3434 . If matrices are to be stored as distributed block matrices then operations on them will be distributed ?

A: This could be worth a look :
http://apache-spark-developers-list.1001551.n3.nabble.com/Matrix-Multiplication-of-two-RDD-Array-Double-s-td6656.html
Hi Liquan,

There is some working being done on implementing linear algebra algorithms
on Spark for use in higher-level machine learning algorithms.  That work is
happening in the MLlib project, which has a
org.apache.spark.mllib.linalgpackage you may find useful.

See
https://github.com/apache/spark/tree/master/mllib/src/main/scala/org/apache/spark/mllib/linalg

From my quick look (never read this code before and not familiar with
MLlib) both the IndexedRowMatrix and RowMatrix implement a multiply
operation:

aash@aash-mbp~/git/spark/mllib/src/main/scala/org/apache/spark/mllib/linalg$
git grep
'def multiply'
distributed/IndexedRowMatrix.scala:  def multiply(B: Matrix):
IndexedRowMatrix = {
distributed/RowMatrix.scala:  def multiply(B: Matrix): RowMatrix = {
aash@aash-mbp~/git/spark/mllib/src/main/scala/org/apache/spark/mllib/linalg$

Can you look into using that code and let us know if it meets your needs?

Thanks!
Andrew

On Sat, May 17, 2014 at 10:28 PM, Liquan Pei <[hidden email]> wrote:

> Hi
>
> I am currently implementing an algorithm involving matrix multiplication.
> Basically, I have matrices represented as RDD[Array[Double]]. For example,
> If I have A:RDD[Array[Double]] and B:RDD[Array[Double]] and what would be
> the most efficient way to get C = A * B
>
> Both A and B are large, so it would not be possible to save either of them
> in memory.
>
> Thanks a lot for your help!
>
> Liquan
>
... [show rest of quote]


text:
Q: Configuring Howdy in Ubuntu, what is the IR camera path for the XPS 13 Plus 9320 when I run v4l2-ctl --list-devices, I get:
ipu6 (pci:pci0000:00): /dev/media0
Intel MIPI Camera (platform:v4l2loopback-000) /dev/video0
None of them work when I try to setup Howdy or configure the IR Emitter with the linux-enable-ir-emitter tool.


text:
Q: How to limit number of stacktrace lines from nested Exceptions Lets have an Exception stacktrace with multiple 'caused by' sections:
my.Exception1: Bad luck
  at ...
Caused by: my.Exception2
  at ...
Caused by: my.Exception3
  at ...
Caused by: my.Exception4
  at ...

each caused by section can span multiple lines. There is a JVM parameter
-XX:MaxJavaStackTraceDepth

but this affects the stacktrace as a whole - it will cut everything below for example Exception3 (the inner most Exception will be out). I would like to keep every 'caused by' section, but limit each part to for example 20 lines. One possible solution I'm aware of is ThrowableRenderer from log4j. Is there something else? The goal is to preserve as much useful information from stacktraces as possible in an limited environment (maximum size in bytes for one log entry).

A: ThrowableRenderer would be the way to go.  There is also the FilteredPatternLayout from openutils-log4j.
The heavy handed approach would be to get the throwable stacktrace, filter out frames, and reassign the filtered stacktrace for each throwable in the cause chain before you log the exception chain.  Which could be applied in a custom log filter class but that is bending the rules a bit because the filter shouldn't really modify the throwable chain. Those frames would be lost forever so there would be risk there.
Logback has support for filtering of stackframes. See also Filtering the Stack Trace From Hell for some ideas on what information is worth keeping.


text:
Q: Decay of real continuous algebraic functions at infinity Let $f$ be a real valued continuous algebraic function on $\mathbb R^n$. Suppose the zero set of $f$ is bounded, i.e., if $|x|$ is large enough, $f(x)\neq 0$. Is there any estimate of the sort $|f(x)|\ge c(1+|x|)^{-N}$ for some $c>0$ and $n\in\mathbb N$? A prototypical example of such an inequality is $\sqrt{1+x^2}-x\ge c(1+|x|)^{-1}$, but I would appreciate general estimates along this line that apply to algebraic functions of $n$ variables.

A: Update: As pointed out by Igor, this is not convincing. I only show that if $p(x,f)=0$ and $p(x,0)\not=0$ for $|x|>R$, then the claim holds. However, the OP only assumes that $f\not=0$ for $|x|>R$ (I mixed up the two originally).
Original answer: Yes, this works. If we had $|f(x_N)|\lesssim |x_N|^{-N}$ for arbitrarily large $N$, then the constant coefficient $p=a_0$ in the equation $\sum a_jf^j=0$ solved by $f$ would have the same property.
So it suffices to show that if a polynomial satisfies $p(x)>0$ for $|x|>R$, then in fact $|p(x)|\gtrsim |x|^{-N}$ for some $N$. This follows from the Positivstellensatz, which says, in our setting, that
$$
p(x) = \frac{1 + (|x|^2-R^2)F(x)+G(x)}{(|x|^2-R^2)H(x)+K(x)} \ge \frac{1}{(|x|^2-R^2)H(x)+K(x)} \gtrsim |x|^{-N} ;
$$
here, $F,G, H, K$ are sums of squares of polynomials.
(I suspect there must be a much more elementary argument.)

A: Well it's true in dimension $1$, and I think the following argument
should reduce the case $n>1$ to the $n=1$ statement.
Let $r_0 = \max_{f(x) = 0} \| f(x) \|$.  Then $f$ has constant sign on
$\| x \| > r_0$ (continuous function on a connected set),
and we may assume the sign is positive (else replace $f$ by $-f$).
For $r \geq r_0$, define
$$
F(r) := \min_{\|x\| = r} f(x).
$$
This is an algebraic function of $r$ because it is the value of
the algebraic function $f(x_1,\ldots,x_n)$ on the algebraic variety
(typically a curve) in ${\bf R}^{n+2}$ specified by the following
equations on $r$, $x_1,\ldots,x_n$, and $c$:
$$
\sum_{i=1}^n x_i^2 = r^2, \quad
\forall i: \frac{\partial f}{\partial x_i} = c x_i.
$$
But by hypothesis $F(r) \neq 0$ for $r > r_0$, so there exists $N<\infty$
such that $f(r) \gg |r|^{-N}$ for large r, as claimed.

A: Your function $f$ is, in particular, a continuous semi-algebraic function on $\mathbf R^n$, i.e., its graph is a semi-algebraic subset of $\mathbf R^{n+1}$. Such functions are known to have sub-polynomial growth. More precisely (cf. Bochnak, Coste, Roy: Real algebraic geometry, Proposition 2.6.2, p. 43):
Let $S\subseteq\mathbf R^n$ be a closed semi-algebraic subset, and let $f\colon S\rightarrow \mathbf R$ be a continuous semi-algebraic function. Then there are $c\in\mathbf R$ and $N\in\mathbf N$ such that
$$
|f(x)|\leq c(1+||x||^2)^N
$$
for all $x\in S$.
Apply this to the inverse $1/f$ of your function on the closed semi-algebraic subset $||x||\geq A$, where $A\in\mathbf R$ is such that all zeros of $f$ have norm $<A$.


text:
Q: Display data (fetched from DB) into InputTextarea Blazor I am trying to display some data fetched from database into a Textarea of my Razor page.
I have tried out something like this. Is this the correct way of displaying the data for view only?
Razor page code snippet:
 @if(summaryProjection != null)
            {

                    <div> Seller Data</div>
                    <textarea>
                       @summaryProjection.tradeSummary.articleCurrency
                    </textarea>
            }

cs side code:
public Models.SummaryProjection summaryProjection = new Models.SummaryProjection();
        protected override async Task OnInitializedAsync()
        {
            string Id = TID;
            summaryProjection = await Http.GetFromJsonAsync<Models.SummaryProjection>($"api/T/summary?Id=" + Id);

        }

A: If it's a block of text you want to display then textarea is as good a solution as any other (with some css formatting to make it pretty).  You will need to add disabled to prevent editing.  In your example you appear to want to display a currency value.  for that it's not the best - just use a suitably styled input, again with disabled set.
<textarea disabled>
    @summaryProjection.tradeSummary.articleCurrency
</textarea>


text:
Q: Get All Products by Category ID or Name API I am asking this, but with some addition.
Getting Products by category id! Magento 2.1 REST
I am getting All Categories with ( I am using Magento 2 sample data )
http://www.myshop.com/rest/V1/categories
In that result for example i took Female Tops category which has id of 21 and ran request
http://www.myshop.com/rest/V1/categories/21/products
this returns me all products (50) with their SKU, But i need all data from products.
Now i tried couple of things to achieve this:
1. Get all products by their SKU which i get from their category
http://www.myshop.com/rest/V1/products?
searchCriteria[filter_groups][0][filters][0][field]=sku&searchCriteria[filter_groups][0][filters][0][value]=MH01&searchCriteria[filter_groups][0][filters][1][field]=sku&searchCriteria[filter_groups][0][filters][1][value]=MH02&searchCriteria[filter_groups][0][filters][2][field]=sku&searchCriteria[filter_groups][0][filters][2][value]=MH03 ...
It works, But the problem with this is it might get HTTP Error 414 URL is too long
(if there are too many products) and i think is not very efficient.
2. Get all products by their category ID
http://www.myshop.com/rest/V1/products?
searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=21
This returns me 0 Products and I think I understand why, its because they are not in this category rather they are in child category (i saw that in custom_attributes key category_ids (this is in fact where they "belong")), And also this will return me all products not just bundled as I want.
Is there a better way of getting products by their categories? Without writing new APIs. I just started using magento 2 APIs and maybe i overlooked something.

A: If you want specificate a search by category_id:
GET http://<magento_host>/index.php/rest/V1/products?searchCriteria[filter_groups][0][filters][0][field]=category_id&searchCriteria[filter_groups][0][filters][0][value]=14&searchCriteria[filter_groups][0][filters][0][condition_type]=eq

A: If you want to perform a search by SKU (first case) in a better way, you could use the LIKE condition as in the example in the official guides
GET http://<magento_host>/index.php/rest/V1/products?
searchCriteria[filter_groups][0][filters][0][field]=name&
searchCriteria[filter_groups][0][filters][0][value]=%25Leggings%25&
searchCriteria[filter_groups][0][filters][0][condition_type]=like

To perform a search by category ids you can use the category Interface i.e.
GET /V1/categories/{categoryId}/products


text:
Q: hashing function lambda failing to compile with unordered_map The following code is failing to compile with

error C3497: you cannot construct an instance of a lambda`:

    auto hasher = [&](const cv::Vec3b& color) -> size_t {
        std::hash<int> int_hasher;
        return int_hasher(color[0]) + int_hasher(color[1]) + int_hasher(color[2]);
// the above code is probably a wrong way of constructing a hash,
// but I'd like to get it to compile first
    };

std::unordered_map<cv::Vec3b, int, decltype(hasher)> color_counts(10, hasher);

I noticed sometimes this happens when headers are not included. These are the included headers:
#include <unordered_map>
#include <functional>
#include "opencv2/core/core.hpp"

Note: I use the same technique for a comparator for priority queues in VS 2013, and it works. I see there's an alternative using std::function but I'd like to make this method work.
EDIT: Complete error log
 error C3497: you cannot construct an instance of a lambda
2>          E:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xhash(164) : while compiling class template member function 'OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824> std::_Hash_oper1<false,_Hasher>::_Gethash(void) const'
2>          with
2>          [
2>              _Hasher=OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824>
2>          ]
2>          E:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xhash(242) : see reference to function template instantiation 'OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824> std::_Hash_oper1<false,_Hasher>::_Gethash(void) const' being compiled
2>          with
2>          [
2>              _Hasher=OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824>
2>          ]
2>          E:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xhash(198) : see reference to class template instantiation 'std::_Hash_oper1<false,_Hasher>' being compiled
2>          with
2>          [
2>              _Hasher=OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824>
2>          ]
2>          E:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xhash(220) : see reference to class template instantiation 'std::_Hash_oper2<false,_Hasher,_Keyeq>' being compiled
2>          with
2>          [
2>              _Hasher=OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824>
2>  ,            _Keyeq=std::equal_to<cv::Vec3b>
2>          ]
2>          E:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\unordered_map(23) : see reference to class template instantiation 'std::_Uhash_compare<_Kty,_Hasher,_Keyeq>' being compiled
2>          with
2>          [
2>              _Kty=cv::Vec3b
2>  ,            _Hasher=OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824>
2>  ,            _Keyeq=std::equal_to<cv::Vec3b>
2>          ]
2>          E:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\xhash(255) : see reference to class template instantiation 'std::_Umap_traits<_Kty,_Ty,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>' being compiled
2>          with
2>          [
2>              _Kty=cv::Vec3b
2>  ,            _Ty=int
2>  ,            _Hasher=OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824>
2>  ,            _Keyeq=std::equal_to<cv::Vec3b>
2>  ,            _Alloc=std::allocator<std::pair<const cv::Vec3b,int>>
2>          ]
2>          E:\Program Files (x86)\Microsoft Visual Studio 12.0\VC\include\unordered_map(81) : see reference to class template instantiation 'std::_Hash<std::_Umap_traits<_Kty,_Ty,std::_Uhash_compare<_Kty,_Hasher,_Keyeq>,_Alloc,false>>' being compiled
2>          with
2>          [
2>              _Kty=cv::Vec3b
2>  ,            _Ty=int
2>  ,            _Hasher=OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824>
2>  ,            _Keyeq=std::equal_to<cv::Vec3b>
2>  ,            _Alloc=std::allocator<std::pair<const cv::Vec3b,int>>
2>          ]
2>          oslsegmentation.cpp(42) : see reference to class template instantiation 'std::unordered_map<cv::Vec3b,int,OSLSegmentation::read_images::<lambda_52090ebe4a9b9afa82eb49e6ee9eb824>,std::equal_to<_Kty>,std::allocator<std::pair<const _Kty,_Ty>>>' being compiled
2>          with
2>          [
2>              _Kty=cv::Vec3b
2>  ,            _Ty=int
2>          ]

What am I doing wrong here?

A: Figured it out after Kerrek's comment:
change this:
auto hasher = [&](const cv::Vec3b& color) -> size_t {
        std::hash<int> int_hasher;
        return int_hasher(color[0]) + int_hasher(color[1]) + int_hasher(color[2]);
// the above code is probably a wrong way of constructing a hash,
// but I'd like to get it to compile first
    };

to (note the reference):
auto& hasher = [&](const cv::Vec3b& color) -> size_t {
        std::hash<int> int_hasher;
        return int_hasher(color[0]) + int_hasher(color[1]) + int_hasher(color[2]);
// the above code is probably a wrong way of constructing a hash,
// but I'd like to get it to compile first
    };


text:
Q: How can I force VB6 to enter the debugger from the execution of a program without a break point? I'm trying to watch the execution of a VB6 app and I'm running into an issue because once I enter the debugger and then hit Continue, it no longer lets me step through the code until I hit another break point.  I want to be able to execute a program without  stepping through something until I hit a point where I want to watch it execute.  Ideally this would be something to the effect of holding a key down while I pressed a button to 'step into' that function.
Thanks in advance!
[EDIT]: I'm aware that I can use break points to stop the execution.  To be more clear, the problem is that I don't know where the execution is going to, so I can't set the break point there (because I don't know where there is).  That's why I essentially want to be able to say, 'after this next thing that I do, break, no matter what'.  It sounds like this functionality does not exist, but I'm still keeping my fingers crossed.

A: While the code is running, press ctrl+break (or the 'VCR pause' button in the IDE) then press F8 (or choose 'Step Into'from the Debug menu in the IDE) to continue running the app.  The next action will cause execution to break.
Note that the which causes the break will not always be the one you hoped it would be. Particularly annoying is the _MouseOver event which prevents you from doing a mouse down or a timer firing quckier than you can perform your action. Some breaks may even be fatal as regards running your app e.g. where Windows messages have been hooked (subclassing). Also consider there may not be an event handler in code (yet) for your action where it can break. But usually this technique identifies where you should be setting your breakpoint.

A: There is a Stop statement available for use in VB6 that will drop to the debugger when the statement is executed from code running through the IDE.  (Just be sure to remove the all of the Stop statements from the code when compiling a release build.)

A: There are several techniques you can use.
These two have been mentioned
Using F8 and Shift-F8 to step through the program
Adding Stops (and later removing)
Others
Use a global variable to create a collection. Use it as a stack and have the subroutines you are interested in push and and pop strings. Conversely don't pop anything and you will get a trace.
Use Watches to monitor and break at selection conditions. You can setup just about any condition to break.
Make a Global String and have your procedures set when you enter them. Monitor it through a Watch.
Use Debug.Print in your code. Also Unlike Stop you can leave these in without effecting the production code.
Use the File System Object to create a text file to act as a log.
Sometimes problem only occurs in the Complied version then you need to use MsgBox or log to a text file. MsgBox can alter the behavior of complex user interactions with forms.
These are all techniques I used in debugging an application. If I had to monitor an application I would use Debug.Print. If that doesn't do the trick compile then log to a text file.
If you have something really complex going on then I recommend moving all your code out of the events into classes implementing a Command Pattern. Your commands classes should interact with the form through and interface.
In the Execute method of the command classes you will something like
<save the current state>
<Do your original code>
<save the modified state>
<push the command onto a stack>

What will happen is that you wind up with a list of all the commands you have executed (even things like mouseover) with the state they encountered and the modified state. You can then examine each object in turn to see what is happening. This is nearly the equivalent of creating Undo/Redo
Note however things like MouseOver can push a lot of classes on the command stack so you will have to structure your tests carefully or be overloaded with information. Remember you can always skip pushing the command onto the stack.
The downside of using commands is that you gone beyond debugging into redesigning. You will to decide whether the problem is worth doing this.

A: You can press the F8 key to step through the code line by line.  Alternatively, you can press SHIFT-F8 to step through line by line.
F8 will step you in to a function, where SHIFT-F8 will step you over the function.  If you click on the DEBUG menu in the VB IDE, you will see other options too.
EDIT:
You can also put a permanent break point in your code by using:
Debug.Assert False

By doing it this way, the 'breakpoint' is saved in your code.  When you compile the app, debug code is ignored.


text:
Q: Exponential family and conjugate priors Is a distribution that belongs to the exponential family necessarily conjugate prior?

A: "If the likelihood function belongs to the exponential family, then a conjugate prior exists", not the other way around. For example, many popular discrete distributions come from exponential family and have conjugate priors, but are not conjugate priors for other distributions, because the parameters of most distributions are not discrete.

A: A bit of reverse engineering: for the likelihood function associated with an exponential family, with natural parameterisation $\theta$ and sufficient statistic $x$
$$\ell(\theta|x)\propto \exp\{\theta^\prime x-\tau(\theta)\}\quad x\in\mathcal X,\ \theta\in\Theta$$
a family of conjugate priors is made of distributions with densities
$$\pi(\theta|x_0,\lambda)\propto \exp\{\theta^\prime x_0-\lambda\tau(\theta)\}\quad x_0\in\mathcal X_0,\ \lambda\in\Lambda$$
with respect to an arbitrary dominating measure $\text d\nu$ on $\Theta$, provided

*

*$\mathcal X_0+\mathcal X\subset\mathcal X_0$

*$\Lambda+\mathbb N \subset \Lambda$

*$\int_\Theta \exp\{\theta^\prime x_0-\lambda\tau(\theta)\}\,\text d\nu(\theta) <\infty$ for all $x_0\in\mathcal X_0,\ \lambda\in\Lambda$.

It clearly defines an exponential family with sufficient statistic $(\theta,\tau(\theta))$.
The reverse problem is to start from an exponential family density on $\theta$
$$\pi(\theta|\xi)\propto\exp\{T(\theta)^\prime\xi-\delta(\xi)\}\propto\exp\{T(\theta)^\prime\xi\}$$
and to identify a likelihood enjoying the above as a conjugate family. This means first breaking $T(\theta)^\prime\xi$ into $\theta^\prime x_0-\lambda\tau(\theta)$ and second finding  a measure $\text dμ$ on $\mathcal X$ such that
$$\int_{\mathcal X} \exp\{θ′x\}\text dμ(x)=\exp\{τ(θ)\}$$
This is an issue when considering for instance the Poisson distributions
$$\pi(\theta|\xi)\propto\exp\{\theta\xi-\log(\theta!)\}\mathbb I_\mathbb N(\theta)$$
because $\theta$ and $\xi$ are unidimensional. One would thus need to embed the Poisson family into a two-dimensional family
$$\pi(\theta|\xi,\lambda)\propto \exp\{\theta\xi-\lambda\log(\theta!)\}\mathbb I_\mathbb N(\theta)$$
and then check if there exist $\lambda_0\in\mathbb R$,  a set $\mathcal X\subset\mathbb R$, and a measure $\text d\mu$ on $\mathcal X$such that
$$\int_\mathcal X \exp\{\theta x\} \,\text d\mu(x)=\exp\{\lambda\log(\theta!)\}\quad \forall\theta\in\mathbb N$$


text:
Q: How can I extract packets from txt file? I have a file as trace.txt which consists of packets and I want to extract each packet from it.
The file as follows:
IP (tos 0x0, ttl 64, id 42387, offset 0, flags [none], proto UDP (17), length 364)
    10.30.23.135.17500 > 255.255.255.255.17500: UDP, length 336
IP (tos 0x0, ttl 64, id 35677, offset 0, flags [none], proto UDP (17), length 364)
    10.30.23.135.17500 > 10.30.31.255.17500: UDP, length 336
IP (tos 0x0, ttl 128, id 28996, offset 0, flags [none], proto UDP (17), length 78)
    10.30.12.151.137 > 10.30.15.255.137: NBT UDP PACKET(137): QUERY; REQUEST; BROADCAST
IP (tos 0x0, ttl 128, id 10723, offset 0, flags [none], proto UDP (17), length 78)
    10.30.11.184.137 > 10.30.15.255.137: NBT UDP PACKET(137): QUERY; REQUEST; BROADCAST
IP (tos 0x0, ttl 1, id 16034, offset 0, flags [none], proto UDP (17), length 50)
    10.30.17.171.53709 > 224.0.0.252.5355: UDP, length 22
IP (tos 0x0, ttl 64, id 60954, offset 0, flags [none], proto UDP (17), length 44)
    10.30.12.163.50558 > 10.30.15.255.8612: UDP, length 16
IP (tos 0x0, ttl 1, id 17167, offset 0, flags [none], proto UDP (17), length 44)
    10.30.12.163.50183 > 224.0.0.1.8612: UDP, length 16
.
.
.

How can I classify them where it is a SYN or ACK packet? And How can I determine whether a packet belongs to IP addresses of websites?

A: In short, you need to

*

*Open the file

*Split the text into packets

*Check whether the desired string is in the packet with python's in.

In this example, we'll search for the strings SYN, ACK, and a google IP.

import re

def get_packets(filename):
    with open(filename) as f:
        text = f.read()

    # Based on the sample file, packet continuations are over multiple lines
    # So split packets based on starting with a newline and then non-space char
    text_packets = re.findall(r'\n\S[\s\S]*(?=\n\S)', text)
    print("Packets found are", text_packets)

def find_info(text_packets):
    # Keep track of the ith packet to print that number
    ith = 1
    # Let's use one of google's IP for the example
    google_ip = "172.217.1.142"

    for tp in text_packets:
        if "SYN" in tp:
            print(ith, "packet contains SYN")
        if "ACK" in tp:
            print(ith, "packet contains ACK")
        if google_ip in tp:
            print("Traffic to google found")
        ith += 1

def main():
    text_packets = get_packets("temp")
    find_info(text_packets)


text:
Q: Javascript form data not updating Mysql database EDIT
Ive now got the following - but still it does not work

=================================================================
ORIGINAL QUESTION FOLLOWS
I'm trying to take in data using a form and send some of this to a Mysql database. I cant use the action keyword in the form as that is being used to complete authentication therefore I am trying to use ajax and jquery. I have got to a point where I know I am close to cracking it but I'm not sure what is wrong. Please see my files below. First off the main file login.php is below:
Form Follows (login.php)
<?php
   $mac=$_POST['mac'];
   $ip=$_POST['ip'];
   $username=$_POST['username'];
   $linklogin=$_POST['link-login'];
   $linkorig=$_POST['link-orig'];
   $error=$_POST['error'];
   $chapid=$_POST['chap-id'];
   $chapchallenge=$_POST['chap-challenge'];
   $linkloginonly=$_POST['link-login-only'];
   $linkorigesc=$_POST['link-orig-esc'];
   $macesc=$_POST['mac-esc'];
if (isset($_POST['postcode'])) {
    $postcode = $_POST['postcode'];
}
if (isset($_POST['email'])) {
    $email = $_POST['email'];
}
?>

**SOME HTML HERE**

                <form name="login" action="<?php echo $linkloginonly; ?>" method="post" onSubmit="return doLogin()" >
                        <input type="hidden" name="dst" value="<?php echo $linkorig; ?>" />
                        <input type="hidden" name="popup" value="true" />

login
                                <input style="width: 80px" name="username" type="text" value="<?php echo $username; ?>"/>

password
                                <input style="width: 80px" name="password" type="password"/>

Postcode
                                <input style="width: 80px" name="postcode" type="text" />

Email
                                <input style="width: 80px" name="email" type="text" />

                                <button><input type="submit" value="OK" /></button>

                </form>

and called file database.php is as follows:
<?php

if ((isset($_POST['postcode'])) && (isset($_POST['email']))) {

   $postcode = $_POST['postcode'];
   $email = $_POST['email'];

  $connect= new mysqli_connect('xx','xx','xx','xx');

  if ($conn->connect_errno) {
    echo "There was a problem connecting to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
  }

  if (!($sql = $conn->prepare("INSERT INTO visitors(postcode,email) VALUES(postcode,email)"))) {
    echo "Prepare failed: (" . $conn->errno . ") " . $conn->error;
  }

  //NOTE: the "ss" part means that $postcode and $email are strings (mysql is expecting datatypes of strings). For example, if $postcode is an integer, you would do "is" instead.

  if (!$sql->bind_param("ss", $postcode, $email)) {
    echo "Binding parameters failed: (" . $sql->errno . ") " . $sql->error;
  }

  if (!$sql->execute()) {
    echo "Execute failed: (" . $sql->errno . ") " . $sql->error;

  }

} else {

  echo 'Variables did not send through ajax.'; // any echoed values would be sent back to javascript and stored in the 'response' variable of your success or fail functions for testing.

}

?>

Please help - all assistance greatly appreciated


text:
Q: How to use list comprehensions for for-loop with additional operations I want to simplify this construction with list comprehensions:
words = {}
counter = 0

for sentence in text:
    for word in sentence:
        if word not in words:
            words[word] = counter
            counter += 1

If there was something like post-increment, it could be written like:
words = {word: counter++ for sentence in text for word in sentence if word not in words}

How should I do it in pythonic way?
For example:
text =
[
['aaa', 'bbb', 'ccc'],
['bbb', 'ddd'],
['aaa', 'ccc', 'eee']
]

Desired result:
words = {'aaa': 1, 'bbb': 2, 'ccc': 3, 'ddd': 4, 'eee': 5}

Order does not matter.
UPD:
I found an interesting solution:
words = {}
counter = (x for x in range(10**6))

[words.update({word: counter.next()}) for sentence in text for word in sentence if word not in words]

update method allows to check if word in dictionary already.
Maybe I should use len(words) instead of counter.next(), but I thought that counter will be faster (O(1) vs. O(dict_size)).

A: There are many ways to do this. This one is without using any external modules, one liner:
s = "a a a b b a a b a b a b"
d = [[(out, out.update([(v, out.get(v, 0) + 1)])) for v in s.split()] for out in [{}]][0][0][0]
print(d)

Prints:
{'a': 7, 'b': 5}

A: You use a dictionary, then you should use its setdefault method, it makes this kind of tasks trivial.
words = {}
for sentence in text:
    for word in sentence:
        words[word] = words.setdefault(word, 0) + 1

A: You can't initialise variables inside a list/dictionary comprehension. But you could always do it in two steps using a list then a dictionary comprehension :
# We list the different words in the text
list_words = [word for word in sentence for sentence in text]

# Using numpy's unique function and the count()
# function we use a dictionary comprehension
dict_words = {word : list_words.count(word) for word in np.unique(list_words)}

A: If you really want to use list comprehension, this one works:
def countWords(content):
    allWords = [word for words in content for word in words]
    return {word: allWords.count(word) for word in set(allWords)}

A: This was kinda fun to play with.  You really can't do it in one line (and that's ok, 1 line solutions aren't always the best), but you can do it with all comprehensions.
d={}
s = "a a a b b a a b a b a b"
x = [(word, 1) for word in s.split()]
d = {word: sum(cnt for w,cnt in x if w == word) for word,_ in x if not word in d.keys()}

d is the destination dictionary that will hold the word counts. s is one of the sentences (you can expand this to extract at more than one level if you have a list of sentences).  x is an intermediate list that holds a pair for each word that is ('word', 1), and then we use that to sum across the pairs to get the final count.
At the end, the value of x and d is:
>>> x
[('a', 1), ('a', 1), ('a', 1), ('b', 1), ('b', 1), ('a', 1), ('a', 1), ('b', 1), ('a', 1), ('b', 1), ('a', 1), ('b', 1)]
>>> d
{'a': 7, 'b': 5}


text:
Q: SQLite check constraint using char I am currently using SQLite Studio and was having trouble adding a check constraint on a column of type char. The column is a list of unique code of characters of length 5. I want the check constraint to not include the letters S , I and Z anywhere in the code. This is the code that I have written up so far,
CHECK(length(VIN) = 5) AND substr(VIN, 1, 5) NOT IN ('S','I','Z')
The code above does nothing and the letters can still be included in the code, so I decided to do the opposite although a bit longer.
(length(VIN) = 5) AND substr(VIN, 1, 5) IN ('A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'J', 'K', 'L', 'M', 'N','O', 'P','Q', 'R', 'T', 'U', 'V', 'W', 'X', 'Y')
In the code above the check constraint works but no 5 length code is 'allowed' to be inserted by the constraint. Any helps on this issue would be great. Thanks in advance

A: substr(VIN, 1, 5) NOT IN ('S','I','Z') will always be true, because you're checking to see if a 5-character long string is not equal to one-character long strings, which will always be the case. You want a GLOB match instead:
sqlite> CREATE TABLE example(vin TEXT CHECK (length(vin) = 5 AND vin NOT GLOB '*[sSiIzZ]*'));
sqlite> INSERT INTO example(vin) VALUES ('aaaaaa'); -- Too long
Error: CHECK constraint failed: example
sqlite> INSERT INTO example(vin) VALUES ('aaaaa'); -- Just right
sqlite> INSERT INTO example(vin) VALUES ('aaaza'); -- Forbidden character
Error: CHECK constraint failed: example


text:
Q: How use group complement in Python? I am looking for something like r"[^\1]" in Python.
For example, I want to match words like "hello" in a text where every letter has been replaced by one other (ex: "a" by "z", "b" by "r", ...). "hello" can be "zcuuj", "prvva", ... I want to say to Python: "find me a word which begins with [a-z], then a letter which is not like the first, then the same two letters, then a letter wich is different of the others.
I've tried this pattern:
r"([a-z])([^\1])([^\1\2]){2}([^\1\2\3])"

(doesn't work)
This one:
r"([a-z])((?!\1))((?!\1|\2)){2}((?!\1|\2|\3])"

(doesn't work)

A: Try this here
^([a-z])(?!\1)([a-z])(?!(?:\1|\2))(([a-z])\4)(?!(?:\1|\2|\4))[a-z]

I tested it online here on rubular
The problem with your second example is, the negative lookahead assertion are non consuming. That means you need to consum the characters after you checked them. I do this here after every lookahead with the . and the references.
The problem with your first example is, that you cant put those references in character groups.
UPDATE: I updated my regex and the rubular link, because the first version would have allowed other characters than [a-z] after the first one.

A: According to the documentation you can use (?P<name>...) to create a named group that you can later reference using (?P=name).


text:
Q: Eclipse Scala IDE code not compiling I downloaded eclipse scala ide from scala-ide.org site and trying to compile my first scala word count program. But its gives error "object not a member of package org" in the following import command
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._

After some research I found that I need to add the jar file spark-assembly-1.0.0-hadoop2.2.0.jar to overcome this issue
But after doing lot of research I could not locate this jar. Can anyone help here  ?

A: Scala is not a simple language/env to learn. It is important you learn how scala works and then move into spark.
There are tons of material available on web. A proper learning path will be to learn
SBT > SCALA > Use Scala for Spark
The dependency that you mentioned, can be put in he sbt's build.sbt. You can also use maven, but I recommend learning sbt as way of learning scala. Once you have resolved, the dependency using SBT, your simple code should work fine. But still, I recommend doing a "hello world" first than doing a "word count" :-)
Ando to answer your question, in your SBT you should be adding following library,
libraryDependencies += "org.apache.spark" % "spark-assembly_2.10" % "1.1.1"

This was for spark assembly 1.1.1 for hadoop 2.10. I see you need a different version, you can find the proper version at
Maven Repo details for spark/hadoop
Here's the pure eclipse solutions (I had to download and setup eclipse just to answer this question)

*

*Get Scala IDE (it comes with inbuilt Scala Compiler version 2.10.5 and 2.11.6)

*Create a new project Scala Wizard > Scala Project

*Right click "src" in the scale project , select "Scala Object", give it a name - I gave WordCount

*Right click project > Configure > Convert to Maven Project

*In the body of word count object (I named the object as WordCount) paste the text from Apache Spark Example which finally looks like

```
import org.apache.spark.SparkContext
import org.apache.spark.SparkContext._
import org.apache.spark.SparkConf

object WordCount {
    val sparkConf = new SparkConf().setAppName("SampleTest")
    val spark = new SparkContext(sparkConf)
    val textFile = spark.textFile("hdfs://...")
    val counts = textFile.flatMap(line => line.split(" "))
                                   .map(word => (word, 1))
                                   .reduceByKey(_ + _)
    counts.saveAsTextFile("hdfs://...")
}

```
6. Add following to your maven
```
<dependency>
    <groupId>org.apache.spark</groupId>
    <artifactId>spark-core_2.10</artifactId>
    <version>1.4.0</version>
</dependency>

```

*Right click on "Scala Library Container", and select "Latest 2.10 bundle", click ok

*Once I was done with these, there was no error message displayed on my "problems" list of Eclipse...indicating that it compiled as expected.

*Obviously, this example won't run as I haven't provided enough info for it to run...but this was just to answer to the question, "how to get the code compiled".

Hope this helps.

A: *

*Install the SBT Scala build+dependency tool

*Create an empty directory. Name it spark-test or whatever you want to name your project.

*Put your source code in the sub-directory src/scala/main. If you have Main.scala in package scalatest, it should be src/scala/main/scalatest/Main.scala

*Make a build.sbt file with the following contents
name := """sparktest"""
version := "1.0-SNAPSHOT"
scalaVersion := "2.11.7"
libraryDependencies ++= Seq(
  "org.apache.spark" %% "spark-core" % "1.4.0"
)

*Configure the SBT Eclipse plugin. Create ~/.sbt/0.13/plugins/plugins.sbt, with:
addSbtPlugin("com.typesafe.sbteclipse" % "sbteclipse-plugin" % "4.0.0")

*Generate an Eclipse project with sbt eclipse

*Import your project into eclipse.

*Run :)


text:
Q: Product of characters in representation theory Is it true that if $\phi_1$ and $\phi_2$ are characters then $\phi_1\phi_2$ is a character of a representation?
I think this is true, say for instance if $R_1$ is a matrix representation with character $\phi_1$ of $G$ and $R_2$ is a matrix representation of $H$ with character $\phi_2$, then we can say $\phi_1\phi_2$ as the character of the matrix representation of $G\times H$ if we define $\phi_1\phi_2(g, h)=\phi_1(g)\phi_2(h)$. Will this suffice to prove our claim?

A: Suppose $G$ acts on a vector space $V$ with character $\phi_1$, and $H$ acts on a vector space $W$ with character $\phi_2$.  Then $G \times H$ acts on the vector space $V \otimes W$ with character $\Phi(g,h) = \phi_1(g)\phi_2(h)$. Moreover every irreducible complex representation of $G \times H$ is a tensor product of an irreducible representation of $G$ with one of $H$. This is what is often called the external tensor product of representations. It is external since it takes in representations of two groups and spits out a representation of a third.
There is also an internal tensor product of representations which takes in two representations of $G$ and spits out a third.  It is related to the external tensor product as follows: We take two representations of $G$ and get a representation of $G \times G$ via the external tensor product, then we restrict this representation to the diagonal copy of $G$ in $G \times G$.  Understanding how these internal tensor products decompose is a much subtler problem, which is referred to in general as the Clebsch-Gordan problem.


text:
Q: Gtk-Message: Failed to load module "canberra-gtk-module" Unable to connect to dbus - Sublime text I'm working on a remote server (Ubuntu 14.04) through SSH -X. I have installed Sublime Text and when I try to open it I get
Gtk-Message: Failed to load module "canberra-gtk-module"
Unable to connect to dbus

How do I solve this?

A:
sudo apt-get install libcanberra-gtk*

if you run that install it will get 120+ mb of libs, mostly.  to get rid of that module error, you only need to install 70k.  i fixed the same error with this single package:
sudo apt-get install libcanberra-gtk-module

that should do the trick.  if that doesnt work try installing only the canberra libs, you don't need all those Xlibs, or you'd have them already ;)
here's just canberra packages apt listed:
libcanberra-gtk-common-dev libcanberra-gtk-dev libcanberra-gtk-module
  libcanberra-gtk-module-dbg libcanberra-gtk0 libcanberra-gtk0-dbg
  libcanberra-gtk3-0-dbg libcanberra-gtk3-dev libcanberra-gtk3-module-dbg
  libcanberra-dev
10 total packages, instead of over 100 packages with that * wildcard. save space, boot time, sys speed etc, always, if you can :)

A: As I found at the end of this thread, it appears to be a problem with the libcanberra dependencies, I stumbled upon this and the solution worked for me on Sublime Text 2/Debian 8.
So try running this:
sudo apt-get install libcanberra-gtk*

This got rid of the GTK message, but the "Unable to connect to dbus..." stuff disappeared when I executed sublime as a non-root user.

A: On Debian Stretch:
sudo apt install libcanberra-gtk-module

This will install:

The following additional packages will be installed:
    libcanberra-gtk0
  The following NEW packages will be installed:
    libcanberra-gtk-module libcanberra-gtk0


text:
Q: How would I pass data to an external script loaded with $.getScript()? So I'm trying to load a javascript remotely using jquery's $.getScript, but I'm puzzled on how I can pass data to the external script.
I've tried setting variables before the call but they aren't available in the script that gets loaded, and when I try to send/retrieve them using the query string, the remote script tries to read the querystring of the base file that it gets called from, not itself. Is there any other way to do this? Or is it possible to have a javascript file read its own querystring rather than the file it's called from (that's loaded in the browser)?
// editor ini
var editor_ini = { page: current_page, action: 'edit' };
var foo = 'bar';
// load the editor
$.getScript('assets/desktop/desklets/'+launcher.config.editor+'/execute.js', function(){});

In the execute.js file, the editor_ini and foo are both unavailable, I get the same result with:
// load the editor
$.getScript('assets/desktop/desklets/'+launcher.config.editor+'/execute.js', { page: current_page, action: 'edit', foo: 'bar' }, function(){});

because the remote script seems to be getting the query string from the original document rather than the one used when calling the file.
If it matters, I was trying to use the query object plugin for jquery for reading the query string.

A: global variable declared in inline javascript is accessible in external javascript page loaded using $.getScript().

A: I bet that your var foo='bar' is inside a function, so not visible in global scope. Try:
window.foo = 'bar'

A: Truly global variables will be accessible to your script.  So, if they aren't, then it's probably because your variables that you think are global actually aren't.  You can either move them to the top level scope or set them on the window object like Alexei suggested.
There are other ways to share data.
1) You can put an id on the <script> tag that loads the code and then have the code get the .src value from that tag and get the query string off the script's actual URL.  I like this option, but I don't know if you can do it using jQuery.getScript() since I don't think it exposes that as an option.
2) You can have the loading script call a function that you provide and return an object with the desired data from that function.
3) Once the new script is loaded, you can call a setXXX() function in that script to set the state that it needs.
4) You can set information into a cookie that the other script can read.
5) You can encode data into a URL hash value that the other script can read.


text:
Q: Why is Latex not writing all my bibliography references? I've been writing a paper with BibTex bibliography but suddenly the .tex stop writing all the references I have in the .bib file, they are 15 cites (all used) and it only writes 9, why is so? Whay am I missing? Thanks
Here's the code I have in the .tex file:
\newpage
\bibliography{Bibliografia_1}
\bibliographystyle{acm}
\addcontentsline{toc}{chapter}{Bibliografía}

And these are my references:
@article{WHODiabetes,
  title={Diabetes},
  author={Organización Mundial de la Salud},
  journal={World Health Organization},
  year={2015},
  publisher={World Health ORganization}
}

@article{DiabetesFMD,
  title={Diferentes tipos de diabetes y sus tratamientos},
  author={Fundación Mexicana de Diabetes, A.C.},
  journal={Fundación Mexicana de Diabetes, A.C.},
  year={2008},
  publisher={Fundación Mexicana de Diabetes, A.C.}
}

@article{AtlasIDF,
  title={IDF Diabetes Atlas, Sixth Edition},
  author={International Diabetes Federation},
  journal={International Diabetes Federation},
  number={6},
  year={2014},
  publisher={International Diabetes Federation}
}

@book{GlucosiladaBD,
  title={Hemoglobina Glucosilada... La Prueba de la Verdad},
  author={BD},
  volume={},
  year={2015},
  publisher={Centro de Aprendizaje BD}
}

@article{tratamiento,
  title={Recomendaciones para el tratamiento farmacol{\'o}gico de la hiperglucemia en la diabetes tipo 2},
  author={Torre, E Men{\'e}ndez and Tejedor, J Lafita and Men{\'e}ndez, S Artola and N{\'u}{\~n}ezfiCort{\'e}s, J Mill{\'a}n and Garc{\'\i}a, A Alonso and Domingo, M Puig and Solans, JR Garc{\'\i}a and Guisasola, F {\'A}lvarez and Alegr{\'\i}a, J Garc{\'\i}a and Bravo, J Mediavilla and others},
  journal={Avances en diabetolog{\'\i}a},
  volume={26},
  number={5},
  pages={331--338},
  year={2010},
  publisher={Elsevier Doyma}
}

@article{bergman1979,
  title={Quantitative estimation of insulin sensitivity.},
  author={Bergman, Richard N and Ider, Y Ziya and Bowden, CHARLES R and Cobelli, Claudio},
  journal={American Journal of Physiology-Endocrinology And Metabolism},
  volume={236},
  number={6},
  pages={E667},
  year={1979},
  publisher={Am Physiological Soc}
}
@article{bergman1981,
  title={Physiologic evaluation of factors controlling glucose tolerance in man: measurement of insulin sensitivity and beta-cell glucose sensitivity from the response to intravenous glucose.},
  author={Bergman, Richard N and Phillips, Lawrence S and Cobelli, Claudio},
  journal={Journal of Clinical Investigation},
  volume={68},
  number={6},
  pages={1456},
  year={1981},
  publisher={American Society for Clinical Investigation}
}
@article{hovorka2002,
  title={Partitioning glucose distribution/transport, disposal, and endogenous production during IVGTT},
  author={Hovorka, Roman and Shojaee-Moradie, Fariba and Carroll, Paul V and Chassin, Ludovic J and Gowrie, Ian J and Jackson, Nicola C and Tudor, Romulus S and Umpleby, A Margot and Jones, Richard H},
  journal={American Journal of Physiology-Endocrinology and Metabolism},
  volume={282},
  number={5},
  pages={E992--E1007},
  year={2002},
  publisher={Am Physiological Soc}
}
@article{hovorka2004,
  title={Nonlinear model predictive control of glucose concentration in subjects with type 1 diabetes},
  author={Hovorka, Roman and Canonico, Valentina and Chassin, Ludovic J and Haueter, Ulrich and Massi-Benedetti, Massimo and Federici, Marco Orsini and Pieber, Thomas R and Schaller, Helga C and Schaupp, Lukas and Vering, Thomas and others},
  journal={Physiological measurement},
  volume={25},
  number={4},
  pages={905},
  year={2004},
  publisher={IOP Publishing}
}
@phdthesis{sorensen1985,
  title={A physiologic model of glucose metabolism in man and its use to design and assess improved insulin therapies for diabetes},
  author={Sorensen, John Thomas},
  year={1985},
  school={Massachusetts Institute of Technology}
}
@article{quiroz2007,
  title={On hyperglicemic glucose basal levels in Type 1 Diabetes Mellitus from dynamic analysis},
  author={Quiroz, G and Femat, R},
  journal={Mathematical biosciences},
  volume={210},
  number={2},
  pages={554--575},
  year={2007},
  publisher={Elsevier}
}
@article{man2007meal,
  title={Meal simulation model of the glucose-insulin system},
  author={Man, Chiara Dalla and Rizza, Robert and Cobelli, Claudio and others},
  journal={Biomedical Engineering, IEEE Transactions on},
  volume={54},
  number={10},
  pages={1740--1749},
  year={2007},
  publisher={IEEE}
}
@article{cobelli2009,
  title={In silico preclinical trials: a proof of concept in closed-loop control of type 1 diabetes},
  author={Kovatchev, Boris P and Breton, Marc and Dalla Man, Chiara and Cobelli, Claudio},
  journal={Journal of diabetes science and technology},
  volume={3},
  number={1},
  pages={44--55},
  year={2009},
  publisher={SAGE Publications}
}

@incollection{regierer2013future,
  title={Future of medicine: models in predictive diagnostics and personalized medicine},
  author={Regierer, Babette and Zazzu, Valeria and Sudbrak, Ralf and K{\"u}hn, Alexander and Lehrach, Hans and ITFoM Consortium and others},
  booktitle={Molecular Diagnostics},
  pages={15--33},
  year={2013},
  publisher={Springer}
}

@article{kitano2002systems,
  title={Systems biology: a brief overview},
  author={Kitano, Hiroaki},
  journal={Science},
  volume={295},
  number={5560},
  pages={1662--1664},
  year={2002},
  publisher={American Association for the Advancement of Science}
}


text:
Q: Simplifying H-bridge circuit I am currently trying to build a PWM H-bridge. It has a power line of 12 V and the Arduino Uno provides the PWM. The MOSFETs I have are: IRLZ44S (N-channel) and FQD11P06TM (P-channel). Basically, the P-type MOSFETs go in the upper side of the circuit and the N-channel ones go at the bottom.
I would be building 6 of these circuits to run 6 motors in an ROV. At the moment I am using this circuit (see image below), but I have been told that it might have problems due to problems of shoot-through currents which could burn the MOSFETS so I would have to add some capacitors. I honestly don't know which resistor values I should use and where to place the capacitors (or their values). Any help will be appreciated.
I am more than welcome to accept a different H-bridge circuit which is simpler than the other one as it uses BJTs and, ideally, I would only like to use a simple circuit with only 4 transistors (the MOSFETs).

A:
simulate this circuit – Schematic created using CircuitLab
This h-bridge cannot have shoot through because the upper transistors are switched off before the lower ones are turned on and vice-a-versa.
There will not be quite +12V across the motor because of the transistor Vbe drops so it will run a little slower.
Don't forget to add the back emf snubbing diodes.


text:
Q: Where is the websolr log files stored (when using Heroku)? I am getting this error message, when reindexing, and I want to inspect the internal server error it reports.

[2014-12-11 10:37:43 +0000] Start Indexing Error - RSolr::Error::Http
  - 500 Internal Server Error - retrying... Error - RSolr::Error::Http - 500 Internal Server Error - ignoring... [2014-12-11 10:37:44 +0000]
  Completed Indexing. Rows indexed 850. Rows/sec: 36.41987405255847
  (Elapsed: 1.372876796 sec.)

A: Websolr support here. Websolr doesn't (yet) provide user-accessible logs. The best bet is to send an email to support@websolr.com and we can get you the info you need.

A: run something like
locate solr.log

The log files are normally located in the root of your installation of solr instance inside a folder called logs.


text:
Q: planning between 2 models I yet have a problem with my planning. My frist model is Revision with as informations following:
The date_revision_start on 12/09/2019 to 14/09/2019 then hour_start & hour_end from 07:00 to 09:00 and the bike 000001.
Below, I have no problem...

Now, in my model Training if I want to enter a training on 14/09/2019 from 10:00 to 12:00 for the bike 000001.
I have an error message ?? Normally, the recording is correct...

Do you have an idea for better compare my hour_start &  hour_end?
$date_seance = $request->get('date_seance');
$hour_start = $request->get('hour_start');
$hour_end = $request->get('hour_end');
$fk_motorbike = $request->get('fk_motorbike');
$fk_student = $request->get('fk_student');
$fk_former = $request->get('fk_former');
$fk_typeseance = $request->get('fk_typeseance');

$conflictTraining = Training::where('fk_motorbike', $request->get('fk_motorbike'))
        ->whereDate('date_seance', "=" , $date_seance)
        ->where('hour_start', "<=" , $request->get('hour_start'))
        ->where('hour_end', ">=" , $request->get('hour_end'))
        ->where('fk_former', $request->get('fk_former'))
        ->first();

$conflictRevision = Revision::where('fk_motorbike', $fk_motorbike)
            ->whereDate('date_revision_start', "<=" , $date_seance)
            ->whereDate('date_revision_end', ">=", $date_seance)
            ->first();

$conflictRevision1 = Revision::where('fk_motorbike', $fk_motorbike)
            ->whereDate('date_revision_start', "<=" , $date_seance)
            ->where('hour_start', "<=" , $request->get('hour_start'))
            ->where('hour_end', ">=" , $request->get('hour_end'))
            ->first();

$conflictRevision2 = Revision::where('fk_motorbike', $fk_motorbike)
            ->whereDate('date_revision_end', "<=" , $date_seance)
            ->where('hour_start', "<=" , $request->get('hour_start'))
            ->where('hour_end', ">=" , $request->get('hour_end'))
            ->first();

$conflictFormer = Training::where('fk_former', $fk_former)
            ->whereDate('date_seance', "=" , $date_seance)
            ->where('hour_start', "<=" , $request->get('hour_start'))
            ->where('hour_end', ">=" , $request->get('hour_end'))
            ->first();

$conflictMotorbike = Training::where('fk_motorbike', $fk_motorbike)
            ->whereDate('date_seance', "=" , $date_seance)
            ->where('hour_start', "<=" , $request->get('hour_start'))
            ->where('hour_end', ">=" , $request->get('hour_end'))
            ->first();

Thank you for your help and your time.

A: The reason you have a conflict error message that the motorbike is in revision is that you are comparing against days only in your first $conflictRevision query.  There is no time there in that first query, so it matches against the day only for any given hour -- thus ALL hours of the day will fail / be in conflict.
You have three queries that are doing similar things:
$conflictRevision = Revision::where('fk_motorbike', $fk_motorbike)
        ->whereDate('date_revision_start', "<=" , $date_seance)
        ->whereDate('date_revision_end', ">=", $date_seance)
        ->first();

$conflictRevision1 = Revision::where('fk_motorbike', $fk_motorbike)
        ->whereDate('date_revision_start', "<=" , $date_seance)
        ->where('hour_start', "<=" , $request->get('hour_start'))
        ->where('hour_end', ">=" , $request->get('hour_end'))
        ->first();

$conflictRevision2 = Revision::where('fk_motorbike', $fk_motorbike)
        ->whereDate('date_revision_end', "<=" , $date_seance)
        ->where('hour_start', "<=" , $request->get('hour_start'))
        ->where('hour_end', ">=" , $request->get('hour_end'))
        ->first();

The first query above is the one that is causing you the unwanted error message.  Remove the $conflictRevision query because it will match to any time.  Remove the $conflictRevision2 query because it is a duplicate of the one above it.  However, you will need to add the end date to the $conflictRevision, or it will never work.  You have an open-ended end or start date using it as you have it above.  Using conflict1 the way you have it, everything in your database with a revision starting before the $date_seance will conflict since there is no end date for that query):
$conflictRevision1 = Revision::where('fk_motorbike', $fk_motorbike)
    ->whereDate('date_revision_start', "<=" , $date_seance)
    ->whereDate('date_revision_end', ">=" , $date_seance) // <--Note I changed the operator
    ->where('hour_start', "<=" , $request->get('hour_start'))
    ->where('hour_end', ">=" , $request->get('hour_end'))
    ->first();

And... the motorbike in revision issue should be solved.


text:
Q: If $ n = a b $ and $ a < b $, show that $ a < \sqrt{n} $. For an integer $n\ge 2$, suppose that $n = ab$, where $a, b$ are integers and $a \le b$. Prove that $a\le \sqrt{n}$
For $a=b$, $n=a*a=a^2$ and $\sqrt{n}=\sqrt{a^2}=a\le a$ which is true since $a=a$. How would I go about proving for $a\not=b$? I tried proof by induction, with the base case of $n=2, a=1, b=2$ true since $1\lt \sqrt2$, but the inductive step isn't working well, since it can be true for $n=3, 4, ... k-1$, but the argument of $k-1$ doesn't help prove $k$ from what I can see.

A: Assume $a,b$ are natural numbers (if not the result is trivial). Now, since $a\leq b$, $a^2\leq ab$. Because of the square root function is increasing this implies $\sqrt{a^2}\leq\sqrt{ab}$, i.e. $a\leq\sqrt{n}$.

A: From $a\le b$ we deduce $a^2\le ab=n$ (multiplying both members by $a$), hence $a\le\sqrt n$ (taking the square root).


text:
Q: Clear textbox after auto complete select in jquery I have implemented the autocomplete using JQuery, when I select the data, it gets stored in the result table, after selecting, I need to clear the autocomplete textbox which i'm not able to. Searched for the same and got this Clear text box in Jquery Autocomplete after selection, but i did not know where to place it and also in the firebug, I got error at function(event,ui).
Pls help... my code is as follows.
$(function() {
    function log( message ) {

        $( "<div>" ).text( message ).prependTo( "#log" ).click(function(o){
            $(this).remove();
        });
        $( "#log" ).scrollTop( 0 );

    }

    $( "#poolName" ).autocomplete({
        source: function( request, response ) {
            $.ajax({
                url: "/DataWeb/getPoolName",
                type : 'post',
                dataType: 'json',
                data: { name_startsWith: request.term },
                success: function( data ) {
                    console.log(data);
                     response( $.map( data, function( item ) {
                        return {
                             label: item.poolName,
                             value: item.poolName
                        }
                    }));
                }
            });
        },
        minLength: 1,
        select: function( event, ui ) {
            log( ui.item ?
                  ui.item.label :
                "Nothing selected, input was " + this.value);
        },
        open: function() {
            $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
        },
        close: function() {
            $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
        }

    });

});

A: $( "#poolName" ).autocomplete({
    source: function( request, response ) {
        $.ajax({
            url: "/DataWeb/getPoolName",
            type : 'post',
            dataType: 'json',
            data: { name_startsWith: request.term },
            success: function( data ) {
                console.log(data);
                 response( $.map( data, function( item ) {
                    return {
                         label: item.poolName,
                         value: item.poolName
                    }
                }));
            }
        });
    },
    select: function (e, i) {
       $('#poolName').val('');
       return false;
    }

    ,minLength: 1,
    select: function( event, ui ) {
        log( ui.item ?
              ui.item.label :
            "Nothing selected, input was " + this.value);
    },
    open: function() {
        $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
    },
    close: function() {
        $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
    }

});

});

A: try using return false; inside select: clause,
select: function( event, ui ) {
            log( ui.item ?
                  ui.item.label :
                "Nothing selected, input was " + this.value);
            return false;
        },

A: I tried with this document.getElementById("poolName").value=""; and it is working.
function log( message ) {
        document.getElementById("poolName").value="";

        $( "<div>" ).text( message ).prependTo( "#log" ).click(function(o){
            $(this).remove();
        });
        $( "#log" ).scrollTop( 0 );

    }

A: The problem with the other answers is that it didn't had the preventDefault call.
This will work:
select: function (e, i) {
   e.preventDefault();
   $('#poolName').val('');
   return false;
}

A: I found that I had to do both clear the field and return false
select: function(ev, ui) {
  console.log(this, ui.item)
  $(this).val('')
  return false
},


text:
Q: scale down kubernetes deployments to 0 and scale back to original number of replica sets I have written a bash script to get  all deployments on a kubernetes cluster.
I have a command to scale all the deployments to zero.
The challenge I am having is that, I want to be able to loop through all the deployments and save their name and number of replicas so I scale them back to the original after scaling down.
How do I achieve that?
this is what I have done so far.
$ kubectl get deployments
$ kubectl scale deploy -n default  --replicas=0 --all

A: You could annotate resources for the previous state of replications. Then you could use the below commands to change replicas.
# annotate first
kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl annotate --overwrite deploy "}{@.metadata.name}{" previous-size="}{@.spec.replicas}{" \n"}{end}' | sh

# scale to 0
kubectl scale --replicas=0 $(kubectl get deploy -o name)

## scaleback
kubectl get deploy -o jsonpath='{range .items[*]}{"kubectl scale deploy "}{@.metadata.name}{" --replicas="}{.metadata.annotations.previous-size}{"\n"}{end}' | sh

A: You could save the output into a bash array:
declare -A arr
for i in $(kubectl get deployment -o name)
do
  arr+=( [$i]="$(kubectl get $i -o=jsonpath='{.spec.replicas}')")
done

And then use that again to scale up:
for key in ${!arr[@]}
do
  kubectl scale deploy $key --replicas=${arr[${key}]}
done

A: First get a list of all deployments, this is important, because you need it to scale back up when needed:
kubectl get deploy -A --no-headers | grep -v 'kube' > deploy_state_before_scale.txt

Scale all non k8s system related deployments to 0:
kubectl get deploy --no-headers -A | grep -v 'kube' | awk '{print $1}' | while read  DEPLOY; do kubectl scale --replicas=0 deployment/$DEPLOY -n $DEPLOY; done

To scale cluster back to how it was before you scaled to 0. Make sure to use 'deploy_state_before_scale.txt' that was created before scaling to 0:
awk '{print $1,$4}' deploy_state_before_scale.txt | while read DEPLOY SCALE; do kubectl scale --replicas=$SCALE deployment/$DEPLOY -n $DEPLOY; done


text:
Q: Using  and  within a
* list After coding with XHTML for a number of years, I'm finally jumping into HTML5 to build a simple portfolio website.
The website I'm building displays 12 thumbnails on the homepage. When you rollover a thumbnail it displays a caption. Both the image and caption link to a post.
The old XHTML way

Portfolio item 1

The new way

Portfolio item 1

For the new code, I've used a list for each portfolio item. Within the list I've created an article and then used the figure tag for the image and image caption.
My question
Is this HTML5 semantic overkill? There's lots more code than the original XHTML version and I'm wondering whether it would be better to loose the list completely.
Looking forward to your feedback.

A: firstly, no need for the article tag; this is an image, not a block of text.
secondly, unless you have more than one list to style (besides your nav li) you won't need the class style, just your regular ol li {}, so no need to class the list.
lastly, i've just run a page through the W3.org validator and have been told that one cannot place a figure within an ordered list. no reasons are given, so i cannot say why, but as robertc says, your old XHTML method will work just fine, now and forever (just use the HTML5 doctype).
PS, when using HTML5 doctype your img tag could be simplified, with figcaption added to generate a searchable caption:
figure

captionated text

/figure


text:
Q: Where to place entities that are global to an app? I'm working on a large Symfony2 app that has the following bundles (all under the same vendor name): Login, Register, Blog, Forum. The official docs say that forum related entities belong in the Forum bundle, and Blog related entities belong in the Blog bundle. But what about my User and Account entities? Both are created during the registration process, and User is used during the login process. I consider those entities to be global to the app b/c their use isn't limited to one feature (again, per Symfony docs, one 'feature' per bundle.) I'm wondering what the best practice for this would be.

A: You can create UsersBundle and in future store other code, related to users in this bundle.


text:
Q: Null reference exception not all paths return a value in a Exit Function On the code below the Exit Function shows a green line under it saying
Null reference exception not all paths return a value.
How do I exit and on exit make it return something?
Can you please help?
    Protected Sub Page_Load()

        test()

    End Sub

    Function test() As String

        Exit Function

        Return ""

    End Function

A: Just remove the Exit Function line and return what you want.  Or do you want to exit the program entirely?  They're two different things.

A: You usually just use Return to exit a Function or Sub and to return a value from a Function.
Function MyMethod() As String
    Return "Some Stuff"
End Function

If you want to use Exit to return a value from a Function, you have to "assign" a value to your Function (actually, the compiler will create a variable internally which will be returned):
Function MyMethod() As String
    MyMethod = "Some Stuff"

    Exit Function
End Function

However, you should just use Return. The Exit statement is just an old, deprecated VB6 legacy.

A: Calling Return also exits the function. You don't need to call (actually, you should never call) Exit Function. Also, you need to assign the result of the function to a variable if you want to use it.
Protected Sub Page_Load()

    Dim result As String = test()
    'Do something with result

End Sub

Function test() As String

    Return "test string"

End Function


text:
Q: String formatting need a solution How do I format this string:
'Item:       Intel NUC onboard PC\n'

so I get this output:
Intel NUC onboard PC

thanks

A: Try this:
'Item:       Intel NUC onboard PC\n'.split(':')[1].strip()
>> 'Intel NUC onboard PC'

A: One approach might be to partition on the : and then strip the result:
>>> print(s.partition(':')[2].strip())
Intel NUC onboard PC

Note that this assumes that you won't have a : in the Item part of the string (i.e. the leftmost : will be the partition point, so any remaining :s will be in the final string, not in the part that got chopped off).