text:
Q: equilateral triangle; $3(a^4 + b^4 + c^4 + d^4) = (a^2 + b^2 + c^2 + d^2)^2.$ In equilateral triangle ABC of side length d, if P is an internal point with PA = a, PB = b, and PC = c, the following pleasingly symmetrical relationship holds:
$3(a^4 + b^4 + c^4 + d^4) = (a^2 + b^2 + c^2 + d^2)^2.$
Please prove this identity.
source: http://www.qbyte.org/puzzles/p117s.html

A: A Cayley-Menger determinant gives the volume of "tetrahedron" $PABC$:
$$288\; V^2 = \left|\begin{array}{ccccc}
0 & 1 & 1 & 1 & 1 \\
1 & 0 & d^2 & d^2 & a^2 \\
1 & d^2 & 0 & d^2 & b^2 \\
1 & d^2 & d^2 & 0 & c^2 \\
1 & a^2 & b^2 & c^2 & 0
\end{array}\right| = d^2 \left( \left( a^2+b^2+c^2+d^2 \right)^2-3\left(a^4+b^4+c^4+d^4\right) \right)$$
Since the tetrahedron is flat, its volume is zero.

A: An explanation and derivation without calculations follows.
That a relation exists can be inferred by a parameter count.  (In an equilateral triangle there are two dimensions of freedom to select a point, and three distances to the vertices.)
What the relation is, can be discovered by writing down Euler's formula for $288 V^2$ of a tetrahedron as a function of the squared edge lengths, and setting volume to zero.  (The Cayley-Menger determinant is the $n$ dimensional generalization and organization of this formula.)
The puzzle is to explain the $S_4$ symmetry of the relation, that allows exchange of $d$ with $a$,$b$ or $c$.  The determinant is symmetric in $a,b,c$ only.
A 60 degree rotation of the triangle around $A$ moves $P$ to $P'$ so that $APP'$ is an equilateral triangle with side $a$, whose vertices have distances $d,b,c$ to point $B$ (and $d,c,b$ to point $C$).  Hence we also have symmetries that permute $d$ with the other variables.
Conclusion: the degree $4$ polynomial relation from the Euler-Cayley-Menger determinant (which is a quadratic polynomial in the squares of $a,b,c,d$), is symmetric in all its variables.  Any such relation can be written as $A(a^2+b^2+c^2+d^2)^2 + B(a^4+b^4+c^4+d^4) = 0$.  In this problem, neither coefficient can be zero, and it is harmless to assume $A=1$.   All that is left is to pin down $B$, and by moving $P$ toward $\infty$, the relation should be consistent with $a=b=c$ and $d=0$, so that $B=-3$.
The same works in $n$ dimensions, with $(\sum a^2)^2 = (n+1)\sum a^4$.
Another way to say all this is that looking at the formula, we know it must be homogeneous, symmetric in $a,b,c$, valid for $(1,1,1,0)$, and it is not so surprising that it be of degree $4$.  The surprise is that the symmetry includes $d$, and this additional "hidden symmetry" then dictates the formula.

A: Here's a brute-force approach:

Abbreviating the measures of angles surrounding point $P$ thusly,
$$\alpha := |\angle BPC| \qquad \beta := |\angle CPA| \qquad \gamma := |\angle APB|$$
we have
$$\cos\gamma = \cos\left(2\pi - \alpha - \beta\right) = \cos\left(\alpha+\beta\right) = \cos\alpha \cos \beta - \sin\alpha \sin\beta $$
so that
$$\left( \cos\alpha \cos\beta - \cos\gamma \right)^2 = \left(1-\cos^2\alpha\right)\left(1-\cos^2\beta\right)$$
Now, substitute-in these relations from the Law of Cosines
$$\cos\alpha = \frac{b^2+c^2-d^2}{2bc} \qquad
\cos\beta = \frac{c^2+a^2-d^2}{2ca} \qquad
\cos\gamma = \frac{a^2+b^2-d^2}{2ab}$$
and do a bit of algebra.

A: Please see my answer to https://mathoverflow.net/q/40058, which is reproduced below.
Here's an example in planar euclidean geometry. Consider an equilateral triangle of side $a$ and a general point in the plane distant $b$, $c$, and $d$ from the respective vertices. Then
$$3(a^4+b^4+c^4+d^4)=(a^2+b^2+c^2+d^2)^2.$$
This is an an awful slog to get by planar trigonometry. Even harder to do by trig in three dimensions is the corresponding result for the regular tetrahedron. However, it's easy to get the $(n−1)$-dimensional result for a regular $(n−1)$-dimensional simplex of side $d_0$, with vertex distances $d_1 ,..., d_n$ :
$$n(d^4_0+\cdots+d^4_n)=(d^2_0+\cdots+d^2_n)^2.$$
You can do this by embedding the euclidean $(n−1)$-dimensional space as the hyperplane of points $(x_1,...,x_n)$ in euclidean $n$-space such that $x_1+\cdots+x_n=d_0/\sqrt2.$ The vertices of the simplex can then be represented as the points $(d_0/\sqrt2)(1,0,...,0), ... , (d_0/\sqrt2)(0,...,0,1)$ in the hyperplane, and the result drops out in a few lines.
Edit: Following the prompting of "zyx", here are the details. Let $\bf x$ be a general point in the hyperplane such that $|\mathbf x-a\mathbf e_i|=d_i\;(i=1,...,n),$ where $a=d_0/\sqrt2$. Then, writing $s=a^2+x_1^2+\cdots+x_n^2,$ we have $$d_i^2=\sum_{j=1}^n(x_j-\delta _{ij}a)^2=s-2ax_i\quad(i=1,...,n).$$Since $x_1+\cdots+x_n=a,$ it follows that $d_0^2+\cdots+d_n^2=ns$ and also $$d_0^4+\cdots+d_n^4=4a^4+\sum_{i=1}^n(s^2-4sax_i+4a^2x_i^2)=ns^2,$$giving the required result.


text:
Q: Available iPhone Web Application JavaScript UI Library/Frameworks I'm starting a web application that will target Mobile Safari on iPhone/iPod Touch.  I'm evaluating the available client-side JavaScript/CSS libraries/frameworks that are currently out there.
These are the ones I'm currenlty aware of:

*

*iUI

*CiUI

*UiUIKit

*WebApp.Net

*iWebKit

*Apple's Dashcode Application - not really a standalone library/framework, but it provides/generates JavaScript, CSS, and images that conform to the native iPhone UI metaphors.

Are there any others out there?  I want to make sure I'm not missing any before I make a decision.  I'm only looking for client-side JavaScript/CSS solutions and building one from scratch isn't an option because of time constraints.  No server-side PHP, Ruby, Python, Java, etc. solutions.
I am aware of the iPhone web applications, templates, frameworks? question that was asked, but this only mentioned iUI and UiUIKit.
Thank you

A: My personal preference is jQTouch. It's a great framework to work with and includes both javascript and CSS assets to make web applications that really give the feel of native applications.
For accessing the lower level functionality of the native device, you can always wrap your HTML files, JS + CSS + jQTouch assets into a native app using something like phonegap, rhomobile or appcelerator, however, this does require a mac to compile and deploy the native application to the appstore.
Certainly most of the things I am looking at are just web applications, so jQTouch does the job nicely.  Did a blog post combining my thoughts in my detail on my blog, link below:
iPhone and Android Web Application Frameworks

A: QuickConnectiPhone has what you are asking for.  There is a custom project type for Dashcode that allows you to quickly create your app.  If you then want to run it installed on an iPhone or touch you can then drop it into Xcode and compile it up.
It includes wrappers for AJAX and the SQLite database that exists within the Safari browser on the iPhone and touch.
You can get it at
http://sourceforge.net/projects/quickconnect/
More information is available at
http://tetontech.wordpress.com

A: JQTouch is not really an app dev framework..it is a style and animation "wrapper".
QuickConnect provides start to finish app development on iphone, droid, and blackberry. The iphone is the most complete.
It can incorporate JQTouch for look and feel and is well-documented.
PhoneGap can be used in conjunction with JQTouch as well but in my experience PG documentation and instruction is harder to find.

A: I would second jQTouch. It uses native CSS animations and behaves reasonably smoothly on my iPod Touch.

A: I second jQTouch being a great full featured solution. But if you are just looking for a JavaScript library I'd recommend XUI.  The syntax is based on jQuery but the library is tuned for mobile development.

A: Old question, but still relevant. Sencha (the new name of the company behind ExtJs) just released the mobile app platform Sencha Tounch for iPhone, iPod, iPad and Android:
http://www.sencha.com/products/touch/
Blog post that explains the difference between jQTouch and Sencha Touch:
http://9-bits.com/post/723711597/jqtouch-and-sencha-touch
Update: John Resig recently announced that the jQuery team is working on a mobile UI library. Looks promising: http://jquerymobile.com/2010/08/announcing-the-jquery-mobile-project/

A: PhoneGap isn't exactly what you're asking about, but is something you might want to be aware of. It's a wrapper for making iPhone apps using HTML/CSS/JavaScript.

A: The folks at DHTMLX also have a mobile library
DEMOS: http://dhtmlx.com/touch/samples/

A: use http://jquerymobile.com/  it is well supported by industry leaders

A: I like Uranium. It's a lightweight set of widgets. (It also includes the XUI framework). I find jQuery too bloated for mobile use. I need a smaller library. Uranium is a bunch of pre-defined widgets, which I find pretty useful for most functions I want to perform on a mobile site.

A: There is also jPint

redpajama_set_name: RedPajamaStackExchange


text:
Q: Should a function be used in try block that has to be executed in finally block try
{
  OpenConnection();
  RowsAffected = cmd.ExecuteNonQuery();
  CloseConnection(true); //should I use this function call here
  //as well, when I am using it in finally
  //block. For closing database connection.
}
catch (SqlException ex)
{ throw ex; }
finally
{ CloseConnection(true); }

Or Should I write it this way
try
{
  OpenConnection();
  RowsAffected = cmd.ExecuteNonQuery();
}
catch (SqlException ex)
{ throw ex; }
finally
{ CloseConnection(true); }

A: No, the finally block gets always executed, regardless of the success or failure of the code in the try block. In your first example the connection would be closed twice on success.
You say that you are checking for the connection state so that means you don't get an exception when closing the connection twice. Still, I think it is more appropriate to try to close it only when necessary.

A: In this particular example, you can in fact do this:
using (var conn = new SqlConnection(...)) {
    // Do work
}

What the compiler does with that statement is essentially:
SqlConnection conn;
try {
  conn = new SqlConnection(...)
} finally {
  conn.Dispose();
}

Or thereabouts... the finally block is always exected, ensuring that a using block always calls Dispose.
The downside of this approach is that you can't catch the SqlException that could be thrown, so you end up doing something like this:
try {
  using (var conn = new SqlConnection(...)) {
    // Do work.
  }
} catch (SqlException ex) {

}

But the compiled code ends up representing:
try {
  SqlConnection conn;
  try {
    conn = new SqlConnection(...);
  } finally {
    conn.Dispose();
  }
} catch (SqlException ex) {

}

To be honest though it probably won't make any difference performance wise, as anytime you throw an exception, its going to be a performance hit.  It does ensure that Dispose is always called.

A: Your finally block is always getting executed. Using Close functions like Dispose(), CLose() should be using in finally block

A: You should write in the second Way
                try
                {
                    OpenConnection();
                    RowsAffected = cmd.ExecuteNonQuery();
                }
                catch (SqlException ex)
                { throw ex; }
                finally
                { CloseConnection(true); }


text:
Q: Prime number proof Given that $n>2$. Prove that if $2^n-1$ is prime then $2^n+1$ is composite or vice versa.
I looked on wikipedia on Fermat number and Mersenne prime, but I still don't know how they work.

A: Hint $\ a\mid (a\!-\!1)^n\!\pm 1\ $ since $ $ mod $\ a\!:\ (a\!-\!1)^n \equiv (-1)^n\equiv \pm 1$
e.g. $\,\ 10\mid 9^n\pm1\, $ is a well-known case (power's of $9$ end with digit $1$ or $9)$
Your case can be viewed as the analogy in radix $\,3.$

A: Clearly you can't prove that $2^n-1$ composite implies $2^n+1$ is prime.  Take $n=6$, for example.  Going the other way, think about divisibility by $3$.

A: At least one of $2^n-1$ and $2^n+1$ must be divisible by $3$, and neither of them is $3$. Thus, at least one of them is composite.


text:
Q: UPDATE new table JOIN two other tables? I am going nuts trying to figure this out....please help :(
I have three tables and I am updating a table from the data of two other tables.
Update table: set_colors
columns: setcolors_id (primary), art_id(int), baseimage_id(int), color_id(int)
Two tables I am getting information from
Table name: art
columns: id(primary), artname(varchar), series_code(varchar)
table name: baseimage
columns: id(primary), base_folder(varchar), graphic, image_type(varchar), layer(int)
example data:
The series_code from the art table and the base_folder from the baseimage table have identical values but where the art table can have hundreds of duplicate series codes and baseimage may only have 5 max if the same base_folder name but has different layers.
example data:

I want to UPDATE the set_colors table with the art table [id], baseimage [id], and where the baseimage = "B", so what it needs to do is iterate through the art table "layer" column-- the color_id will be updated by another sql query so some rows may be an int or NULL
So the result should look something like this:

what I came up with is this but it does not work, No error message. it just does not populate the table. What am I missing??
$result_array = mysql_query("
 UPDATE set_colors
 JOIN art
 JOIN baseimage
 ON  art.series_code = baseimage.base_folder
 SET set_colors.school_art_id = art.id,
set_colors.baseimage_id = baseimage.id,
set_colors.baseimage_layer = baseimage.layer
WHERE baseimage.image_type = 'B'"
);
 return !empty($result_array) ? array_shift($result_array) : false;

A: I'd recommend looking over the MySQL UPDATE documentation here.  I believe your update needs to be restructured based upon MySQL syntax.

A: First, when you say "populate the table", are you expecting this query to insert new rows?  An update query will not create new rows, only update rows that already exist in the table.
Second, it looks like you are expecting mysql_query to return an array.  This function only returns true or false when executing insert or update queries depending if the query executed correctly.

A: Based on the comments, I think your insert statement should look something like this:
INSERT INTO set_colors
    (art_id, baseimage_id)
    SELECT a.id, b.id
        FROM baseimage b
            INNER JOIN art a
                ON b.base_folder = a.series_code
        WHERE b.image_type = 'B'


text:
Q: ¿como imprimir en tkinter? (no en un cuadro sinó en la impresora) Buenoa, llevo intentando un buen rato encontrar algo que me ayude a imprimir una información desde el tkinter del python pero cada vez que busco "Imprimir" sale que para plasmarlo en un cuadro o algo así. Lo que necesito es que agarre una informción de una listbox y la imprima como si se tratara de un documento de Word o algo similar
Les agradezco su ayuda de antemano
PD: mi python es versión 3.8 y está en el sistema operativo Windows

A: segun tengo entendido no se puede imprimir directamente, tendrias que crear una funcion y esta agregarla a un boton de tkinter.
Para agregarla seria algo asi
import tempfile
import win32api
import win32print

def __init__(self):
    tk.Button(frame, text='imprimir', command=self.imprimir).grid(
        row=2, columnspan=2, sticky="we")

def imprimit(self):
       archivo = tempfile.mktemp (".txt")
open (archivo, "w").write ("Esto es una prueba") <- aqui puedes agregar los valores de tu listbox (o puedes crear un documento .docx)
win32api.ShellExecute (
  0,
  "printto",
  filename,
  '"%s"' % win32print.GetDefaultPrinter (),
  ".",
  0
)

lo que usas aqui es la libreria de win32 y esta ya manda llamar a windows, recuerda que tomara la impresora por default


text:
Q: Create top-down slide animation using `Transition` from `@headlessui/react` using Tailwind CSS I want to create the following effect:

Currently, I have this weird effect:

I am using Transition from @headlessui/react.
My code looks like:
<Transition
    show={app.theme !== 'light'}
    enter="transition ease duration-700 transform"
    enterFrom="opacity-0 -translate-y-full"
    enterTo="opacity-100 translate-y-0"
    leave="transition ease duration-1000 transform"
    leaveFrom="opacity-100 translate-y-0"
    leaveTo="opacity-0 -translate-y-full"
>

How do I achieve it?

A: I solved it. It doesn't show the animation on Codesandbox as Tailwind animations don't work on Codesandbox (it is their bug) but the code is tested locally & it works fine.
{theme.type !== "light" && theme.color !== null && (

            Dim
            <input
                type="radio"
                name="darkOption"
                className="w-4 h-4"
                value="dim"
                checked={theme.color === "dim"}
                onChange={() => {
                    updateTheme({
                        color: "dim",
                    })
                }}
            />

            Lights Out
            <input
                type="radio"
                name="darkOption"
                className="w-4 h-4"
                value="lights-out"
                checked={theme.color === "lights-out"}
                onChange={() => {
                    updateTheme({
                        color: "lights-out",
                    })
                }}
            />

)}

Codesandbox → https://codesandbox.io/s/headless-ui-theme-animated-cbft1

A: This is how I created a similar animation for a disclosure panel:
<Transition
    enter="transition ease duration-500 transform"
    enterFrom="opacity-0 -translate-y-12"
    enterTo="opacity-100 translate-y-0"
    leave="transition ease duration-300 transform"
    leaveFrom="opacity-100 translate-y-0"
    leaveTo="opacity-0 -translate-y-12"
 >

A: I know this is some time ago but i managed to do something like the wanted behavior. I wrapped a Disclosure.Panel element in Transition:
<Transition
    className="transition-all duration-500 overflow-hidden"
    enterFrom="transform scale-95 opacity-0 max-h-0"
    enterTo="transform scale-100 opacity-100 max-h-96"
    leaveFrom="transform scale-100 opacity-100 max-h-96"
    leaveTo="transform scale-95 opacity-0 max-h-0"
>

If your content is taller than max-h-96 (height: 24rem; /* 384px */). You will have to customise the tailwind config to include a higher max-h.
You can also use max-h-['number'px] like so:
<Transition
    className="transition-all duration-500 overflow-hidden"
    enterFrom="transform scale-95 opacity-0 max-h-0"
    enterTo="transform scale-100 opacity-100 max-h-[1000px]"
    leaveFrom="transform scale-100 opacity-100 max-h-[1000px]"
    leaveTo="transform scale-95 opacity-0 max-h-0"
>

Show the animation, horrible quality


text:
Q: Angular.js (possible bug) - objects attribute return undefined on a single item view i have a poll application with 2 views, list view and single item view. these are the init functions in the angular client controller
        // Poll List
        $scope.pollList = function(){
            $scope.votes = Votes.query({
                userId:Authentication.user._id
            });
            $scope.polls = Polls.query();
        };

        // View Poll
        $scope.findOne = function(){
            $scope.votes = Votes.query({
                userId:Authentication.user._id
            });
            $scope.poll = Polls.get({
                pollId: $stateParams.pollId
            });
            $scope.categories = Categories.query();
            $scope.languages = Languages.query();
            $scope.pollItem($scope.poll);
        };

        // Poll Item
        $scope.pollItem = function(poll){
            $scope.pollVoted(poll);
            $scope.countPollVotes(poll);
            for (var i = 0; i < poll.poll_options.length; i++){
                $scope.optionItem(poll,poll.poll_options[i]);
            };
        };

both the list view and the single view initiate a pollItem function in each poll object. in the list view everything works good - each poll object passes the pollItem function without an error. but in the single poll view im recieveing errors, namely, that the diffrent attributes of the poll (i.e user, comments, poll_options) are returning undefined! allthough when i console.log the poll object i can see them all there. please help! im aware to the fact that it sounds a bit vague but im not sure which other details to provide.. im stuck a couple of days on this problem and no answer to be found.


text:
Q: Input random string into text field I'm trying to input a random generated string into a web text field.
I got this to generate the string:
def get_random_string(length):
letters = string.ascii_lowercase
result_str = ''.join(random.choice(letters) for i in range(length))
email = result_str
extension = "@gmail.com"
print(email+extension)

And I'm trying to enter it like this:
last = web.find_element("xpath", '//*[@id="email-input"]')
last.send_keys(get_random_string(5))

It's showing "get_random_string" in the terminal but not the text field for some reason..?


text:
Q: A Christmas tree has the shape of the conical helix. Find the length of the Christmas tree. A Christmas tree has the shape of the conical helix. The helix has the circular base of 1 foot diameter,
and it rises three complete turns. Find the length of the Christmas tree.
Image the goes with the problem
Please explain the steps. Thanks!

A: Here's a start: a (cylindrical) helix could be written as $x(t) = \cos t$, $y(t) = \sin t$, $z(t) = t$.  You should check that this helix actually lies on the cylinder $x^2 + y^2 = 1$.  We want to modify this so that the helix instead lies on the cone $(1-z)^2 = x^2 + y^2$.  See here, your "tree" should lie on the portion of this cone between $z=0$ and $z=1$.
We can modify so that the helix lies on the cone: $x(t) = (1-t)\cos t$, $y(t) = (1-t)\sin t$, $z(t) = t$, where $t$ ranges from $0$ to $1$.  You should check that this actually lies on the cone.  However, it does not make three rotations from $0$ to $1$.  We can adjust this by adjusting the arguments inside cosine and sine, since these affect the speed of the rotation:
$$x(t) = (1-t)\cos(6\pi t),$$
$$y(t) = (1-t)\sin(6\pi t),$$
$$z(t) = t,$$
$$ 0 \leq t \leq 1.$$
You should make sure you understand why this lies on the cone, and why it makes three rotations from $t=0$ to $t=1$.  (See here to visualize).
Now all that's left is to compute the arc length of this curve, which you can do with the formula:
$$\int_0^1 \sqrt{x'(t)^2 + y'(t)^2 + z'(t)^2} \ dt.$$


text:
Q: delete directory older than 7 days I have backup files created daily in its own directory:
2020-04-01
2020-04-02
2020-04-03

so on
How can I write a code to delete older directory and its content. I have below code so far, it's deleting the directory but it's not smart enough. Because if I copy files in the directory to another another directory the modified date will change:
find ~/delete/* -type d -ctime +6 -exec rm -rf {} \;

A: To delete the directories by their names with bash:
#!/bin/bash

shopt -s nullglob
date=$(date -d '-7 day' '+%F')
for path in ~/delete/[0-9][0-9][0-9][0-9]-[01][0-9]-[0-3][0-9]; do
  if [[ -d $path && ${path##*/} < $date ]]; then
    echo rm -rf "$path"
  fi
done

This loops over the pathnames matching the YYYY-MM-DD pattern and skips non-directories and directories
whose names don't sort lexicographically before the current date - 7 days.
With nullglob enabled the pathname pattern expands to a null string if there are no matching files/directories
and the code inside the loop is not executed.
Remove the echo if the output looks as intended and run the script again to really delete those directories.

A: Your title is a bit misleading since you cannot actually use timestamps, and have to trust the names.
A possible solution
keepAfter=$(date -d '-6 days' +'%F')
for d in */
do
    [[ "$d" < "$keepAfter"/ ]] && echo rm -rf $d
done

Remove the echo when happy with the results

A: Another solution:
d=/path/to/deleted;
printf '%s\n' $d/*/ | awk -v upTo="$d/$(date -d '-6 days' +%F)" '$0<=upTo {print}' | xargs rm -r

In slo-mo:

*

*printf '%s\n' $d/*/ generates a stream where each line is a subdirectory of /path/to/deleted (this line contains a full path: /path/to/deleted/2020-04-12)

*this is passed to awk with

*

*-v upTo="$d/$(date -d '-6 days' +%F)": creates an upTo variable which is the most recent directory to erase (with full path: /path/to/deleted/2020-04-12)

*'$0<=upTo {print}' is a awk program that only prints out the input lines that are lexicographically smaller or equal to the upTo contents, so this filters out the directories after the break date.

*xargs rm -r applies rm -r to all lines from stdin (ie, the directories that were not filtered out)

The advantage of this code is that there is no shell loop, and rm is likely called only once for all the directories.
If you cd /path/to/deleted first, the code is a bit simpler (you no longer need the $d variable).
printf '%s\n' */ | awk -v upTo="$(date -d '-6 days' +%F)" '$0<=upTo {print}' | xargs rm -r


text:
Q: Python error decoding a base64 string of a hazmart Cipher I have a function that encodes an encrypted string (using hazmat Cipher) in base64 representation, but when I try to decrypt it later using a different function I am getting an error:
web_1  |   File "/code/cart/models.py", line 58, in decrypt_hash_id
web_1  |     int_id = int(padded_id.decode('utf-8').lstrip(' '))
web_1  | UnicodeDecodeError: 'utf-8' codec can't decode byte 0x86 in position 0: invalid start byte

My encryption function is:
from django.conf import settings
from base64 import urlsafe_b64encode, urlsafe_b64decode
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

def url_safe_encrypted_id(self):
    backend = default_backend()
    key = settings.URL_ENCRYPTION_KEY
    iv = settings.URL_ENCRYPTION_IV
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
    encryptor = cipher.encryptor()
    ct = encryptor.update(str(self.id).rjust(16).encode()) + encryptor.finalize()
    return urlsafe_b64encode(ct)

However when I try to decrypt this base64 string I am sometimes getting an error. My method for decrypting is:
def decrypt_hash_id(hash):
    # Decode order_id
    backend = default_backend()
    key = settings.URL_ENCRYPTION_KEY
    iv = settings.URL_ENCRYPTION_IV
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
    decryptor = cipher.decryptor()
    padded_id = decryptor.update(urlsafe_b64decode((hash + '===').encode())) + decryptor.finalize()
    int_id = int(padded_id.decode().lstrip(' '))

    return int_id

Can anyone help to see where the problem might lie? Probably 99% of the time it's working correctly, but occasionally I will get the error shown above.

A: I got the problem you have. It is in the line:
 padded_id = decryptor.update(urlsafe_b64decode((hash + '===').encode())) + decryptor.finalize()

just modify it to:
padded_id = decryptor.update(urlsafe_b64decode(hash.decode())) + decryptor.finalize()

Here is a full example code, but with some modification to run:
from base64 import urlsafe_b64encode, urlsafe_b64decode
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

class settings:
    URL_ENCRYPTION_KEY=b'1234567890123456'
    URL_ENCRYPTION_IV=b'1234567890123456'

def url_safe_encrypted_id(text):
    backend = default_backend()
    key = settings.URL_ENCRYPTION_KEY
    iv = settings.URL_ENCRYPTION_IV
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
    encryptor = cipher.encryptor()
    ct = encryptor.update(text.rjust(16).encode()) + encryptor.finalize()
    return urlsafe_b64encode(ct)

def decrypt_hash_id(hash):
    # Decode order_id
    backend = default_backend()
    key = settings.URL_ENCRYPTION_KEY
    iv = settings.URL_ENCRYPTION_IV
    cipher = Cipher(algorithms.AES(key), modes.CBC(iv), backend=backend)
    decryptor = cipher.decryptor()
    padded_id = decryptor.update(urlsafe_b64decode(hash.decode())) + decryptor.finalize()
    int_id = int(padded_id.decode().lstrip(' '))

    return int_id

text='10'
enc=url_safe_encrypted_id(text)
dec=decrypt_hash_id(enc)
print(text)
print(enc)
print(dec)
# output:
# 10
# b'l5DfiYydiPUCzGK7eLXOFQ=='
# 10

Good Luck

A: You can try this:
import base64

def encrypt():
    string = "Hello world this is a sample string"
    str_bytes = sample_string.encode("ascii")

    base64_bytes = base64.b64encode(str_bytes)
    base64_string = base64_bytes.decode("ascii")
    print(f"Encoded string: {base64_string}")

def decrypt():
    base64_string =" R2Vla3NGb3JHZWVrcyBpcyB0aGUgYmVzdA =="
    base64_bytes = base64_string.encode("ascii")
    sample_string_bytes = base64.b64decode(base64_bytes)
    sample_string = sample_string_bytes.decode("ascii")

    print(f"Decoded string: {sample_string}")


text:
Q: collection to be generated from all the sub-folders into one How to create a collection to be generated from all the sub-folders into one.
For example:
/src/article/2011/
            /2012/
            /2013/

=>
/out/article/

The usual way of sub-folders does not take:
posts: (database) ->
    database.findAll({relativeOutDirPath:'posts'},[date:-1])

A: To get all the documents inside sub-directories of the article directory, like /article/2011/post.html, you could use:

insideSubfolder: (database) ->
    database.findAll({relativeOutDirPath:/article[\/\\]\w+/},[date:-1])

If you also want to accept documents inside article, like /article/index.html, you could use:

insideSubfolder: (database) ->
    database.findAll({relativeOutDirPath:/article/},[date:-1])

If you want say src/documents/article/2011/post.html to be outputted to out/article/post.html please say so in a comment and I'll figure out what is needed. Thanks.


text:
Q: Dismiss presented view controller, after the presenting view controller has been released I am working on some old code that I didn't write, and it's really not architected well...
The situation is that a view controller presents a custom view controller modally, however every 30 seconds the presenting view controller is recreated.
The issue here is that if the modal is on screen when this happens, then any effort to dismiss it results in odd behaviour (such as a white screen).
I have tried calling [self.presentedViewController dismissViewControllerAnimated]; on the newly recreated controller, but presentedViewController is nil as you would expect.
I have also tried keeping a weak reference to the modal view controller, then when the presenting VC is reloaded, setting this value to that of the old VC. This has allowed me to call self.customModalVC dismissViewControllerAnimated]; but this is causing the aforementioned white screen, perhaps because it's presenting VC is no longer in the stack?
Any and all suggestions appreciated.

A: Try passing the navigation controller to newly presented ViewController:
    presentedVC.navigation = self.navigationController

Add this to newly created one for dismissing
    self.dismiss(animated: false) {
                _ = self.navigation?.popViewController(animated: true)
            }


text:
Q: What is bearer token or basic token metioned in HTTP Authorization header? I can see HTTP Authorization headers used like this:
Authorization: Basic some_string
Authorization: Bearer some_string
Authorization: MAC some_string

I assume some_string is some sort of token used for Authentication purpose. So what does these words like Basic, Bearer and MAC before token means? Are they some types of tokens? If they are some types, what are all the possible types/values can be there in HTTP Authorization header?
Additionally, what are the use cases for each of these types? Any link or explanation would be appreciated.


text:
Q: Subtitle at top of tcblower has spurious space above I am using \tcbsubtitle to place a title at the top of a tcblower and want a different background color on the two portions. This results in an unwated space above the subtitle:

How do I eliminate this undesired space?
References:

*

*Breaking tcolorbox between upper and lower part

*subtitles in tcolorbox like in mdframed
Code:
\documentclass{article}

\usepackage[many]{tcolorbox}

\newcommand{\LoremIpsum}{%
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.%
}

\tcbset{My Box Style/.style={
    colback=green!20,
    bicolor,
    colbacklower=yellow!60,
    %segmentation at break=false,% No effect
    %middle=0pt,% <-- This isn't it!
}}

\newtcolorbox{example}{My Box Style}

\begin{document}
\begin{example}
    \LoremIpsum
    \tcblower
    \tcbsubtitle{Subtitle}
    \LoremIpsum
\end{example}
\end{document}

A: Second attempt
It seems to be controlled by middle and boxsep. If we set them both to be zero the we get:

It's not immediately clear to me that this is better than the previous manual adjustment. First, there is a faint hint of a yellow line above the subtitle line. Secondly, as explained on page 11 of the manual, boxsep is added all over the place, which is why this kills off the space at the bottom of the green box and the height of the subtitle.
\documentclass{article}

\usepackage[many]{tcolorbox}

\newcommand{\LoremIpsum}{%
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.%
}

\tcbset{My Box Style/.style={
    colback=green!20,
    bicolor,
    colbacklower=yellow!60,
    middle=0mm,
    boxsep=0mm,
    subtitle style={}
    %segmentation at break=false,% No effect
    %middle=0pt,% <-- This isn't it!
}}

\newtcolorbox{example}{My Box Style}

\begin{document}
\begin{example}
    \LoremIpsum
    \tcblower
    \tcbsubtitle{Subtitle}
    \LoremIpsum
\end{example}
\end{document}

First attempt
I have a feeling that I have seen this before but I cannot find it.
The \tcbsubtitle command actually inserts a new tcolorbox that contains the subtitle, so I suspect that this gap is caused by some skip above this box. There should be some way to remove this but I have not found it.
The following hack adds a manual \vspace command above the subtitle, but there should be a better solution:
\documentclass{article}

\usepackage[many]{tcolorbox}

\newcommand{\LoremIpsum}{%
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.%
}

\tcbset{My Box Style/.style={
    colback=green!20,
    bicolor,
    colbacklower=yellow!60,
    subtitle style={before={\vspace*{-3.1mm}}}
    %segmentation at break=false,% No effect
    %middle=0pt,% <-- This isn't it!
}}

\newtcolorbox{example}{My Box Style}

\begin{document}
\begin{example}
    \LoremIpsum
    \tcblower
    \tcbsubtitle{Subtitle}
    \LoremIpsum
\end{example}
\end{document}

Here is the output:

You could also use \tcbsubtitle[before={\vspace*{-3.1mm}}]{Subtitle}, but using the style command seems more elegant.


text:
Q: Calling export reports as Pdf for entire dashboard widgets programmatically Cognos Cognos provides option to export each widget in dashboard but not entire dashboard.
My question is that is it possible to export all dashboard widgets as Pdf using cognos sdk for java. If not, is there a way to get each widget reports as pdf and then merge it using utility. Kindly help on this whether cognos sdk would suit the need..


text:
Q: Forecasting Hourly Time Series based on previous weeks and same period in previous year/s The Problem
I have been tasked with a similar problem to that described in Forecasting hourly time series with daily, weekly & annual periodicity. My data shows the number of times that one of 384 different events has occurred per hour between 01/01/2005 and 31/12/2013. I have been asked to provide a 28 and  84 day forecast showing the number of each type of event expected per hour.
My Experience
Before I go on I will clarify that I am a bit of a newbie in R (and statistics) and while I realise that this is not at all a simple task (nor possibly one that R is best suited to) I don't have access to any other tools and there is no one else in my organisation that is prepared to tackle this problem.
What I have tried so far
So I have restricted myself to just one event type and have tried using auto.arima and HoltWinters on the entire 75,000 hourly datapoints using timeseries ts(data,frequency=8760), ts(data,frequency=8760/12), and ts(data,frequency=8760/52.1xxxx). I excluded ets because it doesn't cope with frequencies above 24. The results from these tests were pretty much flat line which isn't suitable for what I want to use the forecast for.
Because each week is closely related to the previous week/s I tried to simplify things by only forecasting based on the previous 4 and 8 weeks using ts(data, frequency=168) (treating it as weekly data).
The results from the HoltWinters experiment look promising and I have discarded ARIMA because it is still producing a straight line. Over a 28 day period in 2013 the total of the HoltWinters "forecasted" values based on the previous 4 weeks is within 10% of the actual values which is close but I think I could get closer. (This is probably not the best way to test the values but it seems like a good indicator.)
My Planned next steps
I am now wanting to try and factor in the same period for the year/s previous. That is, if I am forecasting for December 2013 I will use November 2013 and December 2012, 2011, etc.
The Questions:

*

*How do I forecast using the previous weeks and the same period for the previous years?

*Is there a better way of doing this? (I am open to suggestions here, I am really only getting by, by testing and refining my method and am conscious of the fact that there is probably much better ways of doing this.)

*It is quite likely that occurrences of different event types are linked (i.e. if event a is happening a lot event b will likely be happening a lot too, and event c will probably not happen). As a next step is it possible be find and then factor in these correlations?
Sorry that I have not been able to attach my data but the computer system at work does not allow us to access places like dropbox and I cant see any other way of attaching a csv to this question. If it is required to answer my questions then I will take a copy home and upload it from there.


text:
Q: Raphaël convert drag callback coords relative to canvas I'm trying to create a circular gauge with a 360 indicator that can be moved with the mouse using Raphaël.
I'm wondering how I can get the absolute coordinates for the main panel. My example works out everything relative the created canvas. However, the callbacks set on Element.drag give me the co-ordinates relative to the browser window rather than the canvas.
I need to work out where the canvas is so I can work out what the new angle of the indicator. Can anyone explain how this is done?
<!DOCTYPE html>

        <meta charset="utf-8">
        <title>Example using Raphaël</title>

A: You can try using jQuery's offset() method.
var holderOffset = $("#holder").offset();
//now dx and dy would become
dx -= holderOffset.left;
dy -= holderOffset.top;

A: I don't see why this is needed, everything in Raph should be set as needed as you are only using Raph methods.
Firstly in this case, you don't need dx/dy as you don't actually need to use the differences, you can just figure it out from x,y which is passed into the onmove function as the 3,4 parameters.
Raph also has an angle method, to calculate that. So we can add a small bit of code, and remove the dx,dy stuff..
So all you need is...
angle = Raphael.angle( x, y, PANEL_MID, PANEL_MID)
this.transform('r'+(angle+90)+','+PANEL_MID+','+PANEL_MID)

jsfiddle (drag hand)
You can also then get rid of the onstart/onend methods, as they aren't needed either.


text:
Q: voldemort vs. couchdb I am trying to decide whether to use voldemort or couchdb for an upcoming healthcare project.  I want a storage system that has high availability , fault tolerance, and can scale for the massive amounts of data being thrown at it.
What is the pros/cons of each?
Thanks

A: Project Voldemort looks nice, but I haven't looked deeply into it so far.
In it current state CouchDB might not be the right thing for "massive amounts of data". Distributing data between nodes and routing queries accordingly is on the roadmap but not implemented so far. The biggest known production setups of CouchDB use "tables" ("databases" in couch-speak) of about 200G.
HA is not natively supported by CouchDB but can build easily: All CouchDB nodes are replicating the database nodes between each other in a multi-master setup. We put two Varnish proxies in front of the CouchDB machines and the Varnish boxes are made redundant with CARP. CouchDBs "build from the Web" design makes such things very easy.
The most pressing issue in our setup is the fact that there are still issues with the replication of large (multi MB) attachments to CouchDB documents.
I suggest you also check the traditional RDBMS route. There are huge issues with available talent outside the RDBMS approach and there are very capable offerings available from Oracle & Co.

A: Not knowing enough from your question, I would nevertheless say Project Voldemort or distributed hash tables (DHTs) like CouchDB in general are a solution to your problem of HA.
Those DHTs are very nice for high availability but harder to write code for than traditional relational databases (RDBMS) concerning consistency.
They are quite good to store document type information, which may fit nicely with your healthcare project but make development harder for data.

*

*The biggest limitation of most stores is that they are not transactionally safe (See Scalaris for an transactionally safe store) and you need to ensure data consistency by yourself - most use read time consistency by merging conflicting data). RDBMS are much easier to use for consistency of data (ACID)

*Joining data is much harder too. In RDBMs you can easily query data over several tables, you need to write code in CouchDB to aggregate data. For other stores Hadoop may be a good choice for aggregating information.

Read about BASE and the CAP theorem on consistency vs. availability.
See

*

*http://www.metabrew.com/article/anti-rdbms-a-list-of-distributed-key-value-stores/

*http://queue.acm.org/detail.cfm?id=1394128

A: Is memcacheDB an option? I've heard that's how Digg handled HA issues.


text:
Q: Why specializing a type_trait could result in undefined behaviour? Discussion
According to the standard §20.10.2/1 Header <type_traits> synopsis [meta.type.synop]:

1 The behavior of a program that adds specializations for any of the class templates defined in this subclause is undefined unless otherwise specified.

This specific clause contradicts to the general notion that STL should be expandible and prevents us from expanding type traits as in the example below:
namespace std {
template< class T >
struct is_floating_point<std::complex<T>> : std::integral_constant
         <
         bool,
         std::is_same<float, typename std::remove_cv<T>::type>::value  ||
         std::is_same<double, typename std::remove_cv<T>::type>::value ||
         std::is_same<long double, typename std::remove_cv<T>::type>::value
         > {};
}

LIVE DEMO
where std::is_floating_point is expanded to handle complex number with underlying floating point type as well.
Questions

*

*What are the reasons that made the standardization committee decide that type-traits should not be specialized.

*Are there any future plans for this restriction to be retracted.

A: Adding to Howard's answer (with an example).
If users were allowed to specialize type traits they could lie (intentionally or by mistake) and the Standard Library could no longer assure that its behavior is correct.
For instance, when an object of type std::vector<T> is copied an optimization that popular implementations do is calling std::memcpy to copy all elements provided that T is trivially copy constructible. They might use std::is_trivially_copy_constructible<T> to detect whether the optimization is safe or not. If not, then the implementation falls back to the safe but slower method which is looping through the elements and call T's copy constructor.
Now, if one specializes std::is_trivially_copy_constructible for T = std::shared_ptr<my_type> like this:
namespace std {
    template <>
    class is_trivially_copy_constructible<std::shared_ptr<my_type>> : std::true_type {
    };
}

Then copying a std::vector<std::shared_ptr<my_type>> would be disastrous.
This would not be the Standard Library implementation's fault but rather the specialization writer's. To some extend, that's what the quote provided by the OP says: "It's your fault, not mine."

A: For the primary type categories, which is_floating_point is one, there is a design invariant:

For any given type T, exactly one of the primary type categories has
  a value member that evaluates to true.

Reference: (20.10.4.1 Primary type categories [meta.unary.cat])
Programmers can rely on this invariant in generic code when inspecting some unknown generic type T:  I.e. if is_class<T>::value is true, then we don't need to check is_floating_point<T>::value.  We are guaranteed the latter is false.
Here is a diagram
representing the primary and composite type traits (the leaves at the top of this diagram are the primary categories).
http://howardhinnant.github.io/TypeHiearchy.pdf
If it was allowed to have (for example) std::complex<double> answer true to both is_class and is_floating_point, this useful invariant would be broken.  Programmers would no longer be able to rely on the fact that if is_floating_point<T>::value == true, then T must be one of float, double, or long double.
Now there are some traits, where the standard does "say otherwise", and specializations on user-defined types are allowed.  common_type<T, U> is such a trait.
For the primary and composite type traits, there are no plans to relax the restriction of specializing these traits.  Doing so would compromise the ability of these traits to precisely and uniquely classify every single type that can be generated in C++.


text:
Q: How to capture http POST requests with browsermob-proxy and selenium Hello trying to capture the actual POST data in an HTTP POST request using browsermob proxy + selenium test framework. So basically i'm running an automated test using selenium and I want to capture the key/value pairs and the actual POST data of a HTTP POST request during the test. Using the following logic I can only capture the key/value pairs of the POST header but not the actual POST data (aka the form field id values). Is there a way to actually capture the POSTDATA (like sniffing applications do such as tamper/live headers in firefox)?
ProxyServer proxyServer = null;
proxyServer = new ProxyServer(9101);
proxyServer.start();

proxyServer.setCaptureContent(true);
proxyServer.setCaptureHeaders(true);

Proxy proxy = proxyServer.seleniumProxy();
proxy.setHttpProxy("localhost:9101");

//selenium test config code, omitted for brevity

proxyServer.addRequestInterceptor(new HttpRequestInterceptor() {
public void process(HttpRequest request, HttpContext context) throws  HttpException,  IOException {
   Header[] headers = request.getAllHeaders();
   System.out.println("\nRequest Headers\n\n");
       for(Header h : headers) {
           System.out.println("Key: " + h.getName() + " | Value: " + h.getValue());
       }

   }
});

An alternate way I read about but could not get to work was to configure the following flags in the browsermob proxy server to true:
proxyServer.setCaptureContent(true);
proxyServer.setCaptureHeaders(true);

Then output the actual HAR file:
Har har = proxyServer.getHar();
Date date = new Date();
har.writeTo(new File("c:\\tmp\\har_" + date.getTime()));

To see the key/value pairs, POST Data, and actual content of the response... but when I parse the HAR file... I only see the key/value pairs of the POST header again... no POST data... no response content. I am only interested in the actual POST data though.

A: I also had same problem. As a solution, I captured all the data, converted the HAR file into JSON, and then filtered out only POST requests from the JSON file.


text:
Q: Matlab spilt one txt file to several files I have a .txt file like this,which is tab delimiter.
nr  Time    Lx  Ly  Lz  Rx  Ry  Rz  Mark
1   32874.4114  0.4 -0.2    0.7 0.2 0   -0.7    0
2   32874.4213  0.4 -0.2    0.4 0.2 0   -0.7    0
3   32874.4313  0.4 -0.2    0.4 0.2 0   -0.9    1
4   32874.4413  0.4 -0.2    0.4 0.2 0   -0.9    0
5   32874.4514  0.2 -0.2    0.4 0.2 0   -0.9    1
6   32874.4613  0.2 -0.2    0.4 0.2 0   -0.9    0
7   32874.4713  0.2 -0.2    0.4 0.2 0   -0.9    1
8   32874.4813  0.2 -0.2    0.7 0.2 0   -0.9    0

I want to use Matlab to code and to spilt this .txt into three separate .txt files according to the Mark (when detect Mark = 1, then spilt it into a new .txt file)
following is the code:
  function splitdata(filename)

thelist=find(filename(:,9)==1)
thelist=[1; thelist];
n=length(filename);
m=length(thelist)
for i=2:m
    out=zeros(thelist(i-1)-thelist(i),9);
    out=filename(thelist(i-1):thelist(i)-1,:);
    thename=['output' num2str(i-1,'%03i') '.txt']
    dlmwrite(thename,out,'\t');
end
if thelist(m)<n
    out=filename(thelist(m):n,:);
    thename=['output' num2str(m,'%03i') '.txt']
    dlmwrite(thename,out,'\t');
end

The problem is: in the output file, the time column , the number after the decimal point is missing... anyone got some ideas how to keep the number after the decimal point?

A: This solution below should do the trick (at least it does for the simplified version you put above.
fi = fopen('myFile.txt','r');
fileCount = 1;
fo = fopen(['output',num2str(fileCount),'.txt'],'w');
header = fgets(fi);
fprintf(fo,header);
tline = header;
first = true;
mark_index = 8;
while ischar(tline)
    if (~first)
        values = cell2mat(textscan(tline,'%f '));
        if values(mark_index) == 1
           fclose(fo);
           fileCount = fileCount+1;
           fo = fopen(['output',num2str(fileCount),'.txt'],'w');
           fprintf(fo,header);
        end
        fprintf(fo,tline);
        tline = fgets(fi);

    else
        first = false;
        tline = fgets(fi);
    end
end

fclose(fo);
fclose(fi);

It will read the original file line by line, and look for a mark, if it sees the mark being set to 1, it creates a new output file and closes off the old one. This will keep repeating until there are not more files in the original document.
It will also place the same "header" into all create output files.


text:
Q: Linux (OS) on Custom Hardware (Custom Motherboard) We are designing and producing our custom high-speed boards consisting of FPGA and gigabit ethernet signals. Hence, we are not professional for high-speed motherboard design but know some issues like signal integrity and other PCB design staff.
We have a new control application and this time we are planning to design our own motherboard. The first prototype is made by using a raspberry pi and an Arduino mega boards. We programmed both devices in order to control some slave devices. We used the well known Raspbian OS based on Debian and wrote scripts for it.
We have never designed a motherboard before, but fortunately, there are many fully open-source motherboard PCB designs (including Raspberry except firmware).
I guess we may not be able to use the same Debian (like Raspbian) and kernel on our custom hardware since kernel must be changed because of the GPIO and other registers, instructions etc.. We will not clone any of the board designs, we will modify maybe the microprocessor brand or indeed the core architecture (like not A53 but A9) or using NXP brand relying on the base design.
Question is, (I am not a software guy, hence I connect the wires, calculate impedances, lengths etc but not load anything on those devices), might generic distributions of Linux and the related kernel and bootloaders be used for our custom motherboard (like Ubuntu or Debian?)? I searched and heard something about Yocto Project, which says have no dependency on the embedded system. I am still searching for this.
Could anybody explain in some more details and concepts on this issue?
Kind regards.

A: This is too broad a question to answer, but in general software will be a killer. You only need to look at the low take up of the higher powered Raspberry Pi clones to see that the software and community is really what makes the Raspberry Pi so successful.
Realistically, you will need to a hire a professional developer if you want to make this design from scratch. If you don't want to or can't do that, an off the shelf solution (for example the RasPi Compute Module) will be the best way to go unless you're willing to learn a lot about the internals of the kernel.

A: I recommend using a COTS System on Module (SOM) to help with your problem. A SOM (sometimes called Computer on Module--COM) is a small board that has all of the essentials like the processor and supporting ICs as well as some connections to an external carrier board.
In my experience, it is much easier to design a carrier board and develop custom software on top of the base software package provided by the SOM vendor. Usually the vendor takes care of setting up the OS, and you can add your business value on top of that.
Here's a current handful of vendors that offer SOMs (NOT at all a complete list!):

*

*LogicPD

*EmCraft

*Variscite

*Gumstix

*eInfoChips


text:
Q: Multi select in form? I am trying to auto populate two drop down fields in form with two rows of same table.
Getting confused on JavaScript

    Card
    <select name="cardid" >
            <option value="">Select</option>
            <option value="1000">1000</option>
            <option value="1001">1001</option>
            <option value="1002">1002</option>
            <option value="1003">1003</option>
            <option value="1004">1004</option>
        </select>

And i want to auto populate select 1000,1001,1002 for Center USA 1003 1004 for Center UK

    Center
    <select name="center">
            <option value="USA">USA</option>
            <option value="UK">UK</option>
        </select>

Any help pl

A: Try this:
HTML:

    Card
    <select id="cardid" name="cardid" >
        <option value="">Select</option>
        <option value="1000">1000</option>
        <option value="1001">1001</option>
        <option value="1002">1002</option>
        <option value="1003">1003</option>
        <option value="1004">1004</option></select>

    Center
    <select id="center" name="center">
    <option value="USA ">USA </option>
    <option value="UK "> UK </option>
    </select>

Javascript:
var usa = "1000,1001,1002";
var uk = "1003,1004";
$(function(){
    $('#cardid').change(function(){
        if(usa.indexOf($(this).val()) != -1){
            // found usa
            $('#center').val($('#center > option:first-child').val());
        }
        else if(uk.indexOf($(this).val()) != -1){
            //found uk
            $('#center').val($('#center > option:last-child').val());
        }
    });
});

Here is demo


text:
Q: How to capture python https traffic in fiddler? Python throws in errors when ever I try to do some data fetching task.
This only happens when I set fiddler to decrypt https traffic.
I have tried routing python traffic through 127.0.0.1:8888 and same with mozilla inorder to catch its traffic.
I also installed the certificate and trusted it via fiddler, I am not sure where I am going wrong.
    raise SSLError(e, request=request)
    requests.exceptions.SSLError: HTTPSConnectionPool(host='google.com', port=443):
    Max retries exceeded with url: / (Caused by SSLError(SSLError(1, '[SSL: CERTIFIC
    ATE_VERIFY_FAILED] certificate verify failed (_ssl.c:748)'),))

This above is the error I get whenever I try to fetch a page with requests.

A: TL;DR The requests library does not use the windows certificate store, it has it's own one (as per https://bugs.python.org/issue28547). This means that your fiddler MITM certificate is not available to python requests by default.
Your options are

*

*Disable SSL verification (verify=False)

*Add your cert via the REQUESTS_CA_BUNDLE environment variable

*Add your fiddler cert explicitly (verify='\path\to\cert')

More details can be found at http://docs.python-requests.org/en/master/user/advanced/#ssl-cert-verification
On a side note, it does feel a little strange for requests to be using it's own cert bundle, rather than the platform supplied one - especially given all the browsers are happy to use the platform ones.

A: As pointed out by polhemic and Eric Aronesty, for testing purposes, you can set temporarily "CURL_CA_BUNDLE" to an empty string.
import os
os.environ['CURL_CA_BUNDLE'] = ''


text:
Q: Custom Button Android that increases percentage on touch event I need to achieve this UI in Android. When sliding right, it increases the percentage and the blue view increases in both ways, and when sliding left it decreases it, both view and percentage in TextView. Any ideas I can do that? Thanks
enter image description here

A: I used the library that has almost the same design that you need. If it's not convenient for you can check implementation and create your own custom view. Basically you would need to track touch events in OnTouchListener and draw on Canvas with coordinates that you got from OnTouch.


text:
Q: Basic HTML progress bar implementation for REST call I want to implement a progress bar or spinner for a upload file REST request till it finishes. My HTML code looks like:

        <form action="http://localhost:8080/services/rest/fileupload" method="post" enctype="multipart/form-data">
            Upload Supported Files:
            <input type="file" name="file" id="file" />
            <input type="submit">
        </form>

I am able to upload the file properly once started, but I must stay on the same page until the upload finishes. I want to implement a "Please wait..." kind of popup message or progress bar from start till the POST request finishes. How can I achieve this with minimal use of libraries.
Thank you in advance.

A: You can try this link describe how to implement a progress bar..
$.ajax({
    xhr: function() {
        var xhr = new window.XMLHttpRequest();

        // Upload progress
        xhr.upload.addEventListener("progress", function(evt){
            if (evt.lengthComputable) {
                var percentComplete = evt.loaded / evt.total;
                //Do something with upload progress
                console.log(percentComplete);
            }
       }, false);

       // Download progress
       xhr.addEventListener("progress", function(evt){
           if (evt.lengthComputable) {
               var percentComplete = evt.loaded / evt.total;
               // Do something with download progress
               console.log(percentComplete);
           }
       }, false);

       return xhr;
    },
    type: 'POST',
    url: "/",
    data: {},
    success: function(data){
        // Do something success-ish
    }
});

A: You can do this using ajaxForm.
You need to include this script for ajaxForm

ajaxForm Documentation
$(function() {

    var bar = $('.bar');
    var percent = $('.percent');
    var status = $('#status');

    $('form').ajaxForm({
        beforeSend: function() {
            status.empty();
            var percentVal = '0%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        uploadProgress: function(event, position, total, percentComplete) {
            var percentVal = percentComplete + '%';
            bar.width(percentVal);
            percent.html(percentVal);
        },
        complete: function(xhr) {
            status.html(xhr.responseText);
        }
    });
});

 <form action="http://localhost:8080/services/rest/fileupload" method="post" enctype="multipart/form-data">
        Upload Supported Files:
        <input type="file" name="file" id="file" />
        <input type="submit">
    </form>

0%


text:
Q: Performing raster cleanup in ArcObjects? I am working on Raster cleanup tool and using below but is the output rectangle or block?
http://edndoc.esri.com/arcobjects/9.2/ComponentHelp/esriArcScan/IConnectedCells_LocateByDiagonalOfEnvelope.htm
Private Sub LocateByDiag()

    Dim pMxDoc As IMxDocument
    Dim pConCell As IConnectedCells
    Dim pFoundBlock As INotifySelectionBlock

    Set pConCell = Application.FindExtensionByName("ESRI ArcScan Tools")
    Set pMxDoc = ThisDocument
    Set pFoundBlock = New FoundBlock

    pConCell.LocateByDiagonalOfEnvelope 100, True, True, True, pMxDoc.ActiveView.Extent, pFoundBlock, Nothing, Nothing

End Sub

Place the following code into a class and name it FoundBlock
Implements INotifySelectionBlock
Private Sub INotifySelectionBlock_SelectionBlock(rectangle As tagRECT, ByVal block As Variant, ByVal cancel As ITrackCancel)
    Debug.Print "Found block"
End Sub


text:
Q: Is it possible to disable Xcode's calling home connections? Every few minutes Xcode creates a https connection to developer.apple.com, also the build files connect sometime to this address during debugging.
Is it possible to disable this functionality?

A: Open XCode -> Preferences and uncheck this checkbox, then your XCode will not go to check and download for updates automatically. Similarly uncheck under "Documentation" tab.


text:
Q: Netbeans zf2 run configs Im setting up a ZF2 project on netbeans 7.4. pressing run project showed just folder like that instead of running straight to public . teach me how. thank you all

A: Maybe you can add some plugins to your netbeans

*

*http://plugins.netbeans.org/plugin/46432/php-zend-framework-2

*http://plugins.netbeans.org/plugin/51969/netbeans-zf2-module-creator

A: To be able to run and debug a web site, you first need to edit the
site's properties. To do that, in NetBeans' Projects pane, right-click
on the project's name, and from context menu select Properties item.
The project's Properties dialog will appear (shown in figure below).

In the left pane of the dialog that appears, click the Sources node. In the right pane,
edit the Web Root field to point to your web site's APP_DIR/public directory.
You can do this by clicking the Browse button to the right of the field. Then,
in the dialog, click on the public directory and then click Select Folder button
(shown in figure below).

Next, click the Run Configuration node in the left pane. The right pane should display
the run settings for your site (see figure below).

In the right pane, you can see that the current configuration is "default". As an option, you can
create several run configurations.
Edit the fields as follows:

*

*In the Run As field, select "Local Website (running on local web server)".

*In the Project URL field, enter http://localhost. If you configured your virtual
host to listen on different port (say, on port 8080), enter the port number like this http://localhost:8080.

*Keep the Index File field empty, because Apache's mod_rewrite module will mask
our actual index.php file.

*In the Arguments field, you can specify which GET parameters to pass to your site through
the URL string. Typically, you keep this field empty.
Finally, click the OK button to close the Properties dialog.
Running the Web Site
Running the web site means opening it in your default web browser. To launch
the site, press the Run button on the Run Toolbar (see figure below). Alternatively,
you can press F6 button on your keyboard.

If everything is OK with your run configuration, the default web browser
will be launched, and in the browser window, you will be able to see the Home page of
the web site.
For additional information about using NetBeans with ZF2, I would recommend you to read the Using Zend Framework 2 book.


text:
Q: How to allow installation only to a specific folder? I would like to install my setup content only to one specific directory, so I want to have the Next button on directory selection page disabled, unless the user chooses the right folder to install to.
How can I disable the Next button on directory selection page and enable it right after user chooses a specific directory ?

A: The following sample shows how to disable the Next button when you reach the SelectDir page and enable it only when you enter (or choose from the browse directory dialog) the C:\MySecretDir folder (the MySecretDir constant). The comparing is case insensitive since user can enter whatever he (or she) wants.
[Setup]
AppName=My Program
AppVersion=1.5
DefaultDirName={pf}\My Program

[Code]
const
  MySecretDir = 'C:\MySecretDir';

procedure OnDirEditChange(Sender: TObject);
begin
  WizardForm.NextButton.Enabled := CompareText(WizardDirValue, MySecretDir) = 0;
end;

procedure CurPageChanged(CurPageID: Integer);
begin
  if CurPageID = wpSelectDir then
    OnDirEditChange(nil);
end;

procedure InitializeWizard;
begin
  WizardForm.DirEdit.OnChange := @OnDirEditChange;
end;

Or if you want to enable the Next button only if there's a specific file MyUniqueFile.exe in the chosen directory, modify the code in OnDirEditChange event handler this way:
procedure OnDirEditChange(Sender: TObject);
begin
  WizardForm.NextButton.Enabled := FileExists(AddBackslash(WizardDirValue) +
    'MyUniqueFile.exe');
end;

A: You could stop users from changing the install directory, by disabling the directory selection page. When disable the page will not be shown during the install.
[SETUP]
DisableDirPage=yes


text:
Q: Self-hosted сервис и работа с HTTPS Есть self hosted приложение. Необходимо все его перевести на протокол HTTPS, сертификат SSL есть. На деплое к сервису обращаются через 80 порт.
Проблема в том что такое решение :

add sslcert ipport=0.0.0.0:80
  certhash=989a847890s82ae6d76c2dd4779eb3a13as41f08
  appid={ba77e2bd-7499-44ee-bfb0-b45188f94e7f}

Выбивает постоянную ошибку - The parameter is incorrect.
Какие еще есть методы решения?


text:
Q: Prompt the user to type in a character/string and tell whether the input is in a given string I need to create two functions, to request the user to type in a character and a string.
The inputs are matched with a given string.
Then tell the user, if the input character/string is found in the default given string.
So far I have created the basics to get the user inputs, but couldn't find any method to implement the javascript functions.
Any help would be highly appreciated.
Here's my code so far..!

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width shrink-to-fit=no initial-scale=1">
        <title>Web Programming is fun!</title>

        <link rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
            integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
            crossorigin="anonymous"
        >

Web Programming is Fun!

Lets use the above heading string to demonstrate inbuilt methods.

            Please type a character:
            <input type="text" id="inputCharacter">
            <button onclick="matchCharacter()">Match Character</button>

            Please type a string:
            <input type="text" id="inputString">
            <button onclick="matchString()">Match String</button>

A: I think you have inverted the parameters. Instead of char.indexOf you should use text.indexOf.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf

        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width shrink-to-fit=no initial-scale=1">
        <title>Web Programming is fun!</title>

        <link rel="stylesheet"
            href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css"
            integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l"
            crossorigin="anonymous"
        >

Web Programming is Fun!

Lets use the above heading string to demonstrate inbuilt methods.

            Please type a character:
            <input type="text" id="inputCharacter" maxLength="1">
            <button onclick="matchCharacter()">Match Character</button>

            Please type a string:
            <input type="text" id="inputString">
            <button onclick="matchString()">Match String</button>

A: Inside your javascript you can replace innerHTML to value attribute to access user input and then match that character.
And also you are calling indexOf on character but you have to call it on the text variable that you have created.


text:
Q: Set svn keywords recursively on *.cpp and *.h files I need to set from command line (cmd or powershell) some svn keywords recursively on ALL .h and .cpp files. How can I do it? I tried
svn propset svn:keywords "My keywords" -R *.cpp *.h

without success, it says me:

svn: warning: '.cpp' is not under version control
svn: warning: '.h' is not under version control

A: You can use find and xargs for the purpose:
find . -name \*.cpp -or -name \*.h -print0 | xargs -0 svn propset svn:keywords "My keywords"

EDIT I see that you are on Windows. I don't know what's the find/xargs equivalent on windows but you could install Cygwin and get these utilities, if needed.

A: Solved, I used THIS script for powershell


text:
Q: Execution sequence of static, constructor and blocks in java It's a Interview Question, manually write the output of code below:
public class StaticTest {

    public static int k = 0;
    public static StaticTest t1 = new StaticTest("t1");
    public static StaticTest t2 = new StaticTest("t2");
    public static int i = print("i");
    public static int n = 99;
    public int j = print("j");

    {
        print("Constructor Block");
    }

    static {
        print("Static Block");
    }

    public StaticTest(String str) {
        System.out.println((++k)+":"+str+" i="+i+" n="+n);
        ++n;
        ++i;
    }
    public static int print(String str) {
        System.out.println((++k)+":"+str+" i="+i+" n="+n);
        ++i;
        return ++n;
    }

    public static void main(String[] args) {
        StaticTest t = new StaticTest("init");
    }

}

Output:
1:j i=0 n=0
2:Constructor Block i=1 n=1
3:t1 i=2 n=2
4:j i=3 n=3
5:Constructor Block i=4 n=4
6:t2 i=5 n=5
7:i i=6 n=6
8:Static Block i=7 n=99
9:j i=8 n=100
10:Constructor Block i=9 n=101
11:init i=10 n=102

Very Confused why execute print first, which even starts with j?
I think static field and blocks are executed when class loading, so at least it should execute public static int i = print("i"); before public int j = print("j");.

A: JVM executes static blocks before the main method at the time loading a class.
And static block will execute only once when class gets loaded. But Instance Initialization blocks and Constructor will run every time object of a Class gets created.
Static initialization blocks are static and hence they belong to a particular class and not to the instances of class.Instance initialization blocks do not belong to a class and they are executed every time a new instance of the class is created.
When we execute above class, StaticTest class is loaded into JVM.
First thing it does is, executing all static blocks even before main() method gets executed .Thus the first 8 lines of your output will be executed even before your main method is triggered.
In the order of existence  public static StaticTest t1 = new StaticTest("t1") will be executed after public static int k = 0.
As there is a new instance initialization,

*

*Line 1 indicates  the execution of public int j = print("j")

*Line 2 indicates the execution of  print("Constructor Block")

*Line 3 indicates the execution of constructor StaticTest("t1") when    creating object.

Instance Initialization blocks are executed whenever the class is initialized and before constructors are invoked . Thus  print("Constructor Block") executed before the constructor. And print("j") precedes everything.
Like the above scenario  public static StaticTest t2 = new StaticTest("t2") also follows the same execution flow which correspond to Line  4,5, and 6.
Then  public static int i = print("i") which correspond to Line  and 8.

*

*Line 9 indicates  the execution of public int j = print("j")

*Line 10 indicates the execution of  print("Constructor Block")

*Line 11 indicates the execution of constructor StaticTest("init") when    creating object.


text:
Q: How to pre-select ALL options in a jquery mobile dropdown data-bound by knockout? Could someone please show me how to preselect all items in a knockout data-bound select with multiple selection tag set?
I've tried using this code:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"></script>
<script type="text/javascript" src="js/knockout-2.0.0.debug.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta charset="utf-8" http-equiv="X-UA-Compatible" content="IE=9" />
<meta http-equiv="CACHE-CONTROL" content="NO-CACHE" />
</head>
<body>
Choose a company: <select id="companies" data-role="select" data-bind="options: companies,
optionsCaption: 'Choose...',
optionsText: 'companyName',
optionsValue: 'companyValue',
selectedOptions: chosencompanies" data-native-menu="false" multiple></select>
<input data-bind="value: chosencompanies"></input>
<script type="text/javascript">
$(document).ready(function () {
  function company(name, value) {
      this.name = ko.observable(name);
      this.value = ko.observable(value);
  }
  var viewModel = {
      companies: ko.observableArray([
              { companyName: "test", companyValue: 0 },
              { companyName: "test1", companyValue: 1 },
              { companyName: "test2", companyValue: 2 },
              { companyName: "test5", companyValue: 5 },
              { companyName: "test7", companyValue: 7 },
          ]),
      chosencompanies: ko.observableArray(),
      resetcompanies: function () { this.chosencompanies(null) }
  };
  ko.applyBindings(viewModel);

  $("#companies option").prop('selected', true);
  $("#companies").selectmenu();
  $("#companies").selectmenu('refresh', 'true');

});
</script>
</body>
</html>

Even though I'm using $("#companies option").prop('selected', true) it seems to only affect the visual appearance of the dropdown control and not the data-bound chosenCompanies varialbe which is what I need set? :(whose value you can see also since it is data-bound to the input field beneath the dropdown) And before someone proposes please, I realize that I could initialize the observableArray with a comma separated value list, but what when my selection options are dynamic and I don't know with what values I should preinit the observableArray?
TIA

A: Your select element binds optionsValue to companyValue, so to preselect the option you should push company values to your choosencompanies array like this:
var source = [
              { companyName: "test", companyValue: 0 },
              { companyName: "test1", companyValue: 1 },
              { companyName: "test2", companyValue: 2 },
              { companyName: "test5", companyValue: 5 },
              { companyName: "test7", companyValue: 7 },
          ];

var viewModel = {
      companies: ko.observableArray(source),
      chosencompanies: ko.observableArray([]),
      resetcompanies: function () { this.chosencompanies(null) }
  };
  ko.applyBindings(viewModel);

for(var i = 0; i < source.length; i++) {
   viewModel.chosencompanies.push(source[i].companyValue);
}

In this case after initialization all companies will be preselected except "Choose company" and values will be displayed in textbox delimited by coma.


text:
Q: Correct way to deploy laravel project I'm trying deploy my first laravel project on live server.

*

*Should i deploy with composer.lock from local project?

*Should i deploy with local vendor?

What i did::
When i deploy without composer.lock composer install command not installing packages on live server. I tried upload composer.json and run composer update didnt work and got out of memory error. Then i removed composer.lock from .gitignore is that correct?
What is correct way to deploy?

A: *

*Yes you should use your local composer.lock file to make sure that the live environment uses the same package versions as local.

*You can but usually you do composer install on your live environment. But if you do upload the vendor directory you don´t need composer install at all.

There is no "correct" way of doing your deployment. It usually depends on your needs.

A: *

*You can use your local "composer lock" file. But laravel recommend not use local "composer lock", after "composer update" command its generate new lock file and it works fine.

*you can use local vendor. But laravel recommend not to use local vendor file, when you run "composer udpate" command laravel generate vendor folder again and this process is better. Also laravel add this "vendor" folder to gitignore file also to avoid unnecessary files to push.


text:
Q: Code First versus Database First? Estou acostumado a criar projetos no asp.net-MVC com Entity Framework Database First.
A partir de uma modelagem, é criado o banco de dados e o sistema.
Porém, vejo uma grande quantidade de programadores preferir Code First, onde o banco de dados depende do sistema.
Qual as diferenças entre as duas?
Digo no sentido prático, qual os prós e contras de cada abordagem?
O que muda na arquitetura de um projeto e na maneira de desenvolver o sistema?

A: Diferenças

*

*Code First: O código é escrito primeiro. O banco de dados é gerado a partir do código;

*Database First: O banco de dados é escrito primeiro. O código da aplicação é gerado a partir do banco de dados.

Prós e Contras
Code First
Prós

*

*Pode trabalhar independente da tecnologia do banco de dados;

*As validações de dados não estão estritas a uma tecnologia;

*Pode construir e destruir bancos de dados gerados em instantes, através de Migrations;

*Ideal para novas aplicações;

Contras

*

*Não se acopla bem a um banco de dados já existente;

*Depende de um bom ORM, como o Entity Framework e o NHibernate, por exemplo;

*Exige constante otimização, pois a abstração de dados para alguns bancos nem sempre tem um bom desempenho;

*Validação em banco de dados é limitada. A geração do banco de dados pela aplicação nunca é 100%;

*Fraca segurança de banco de dados.

Database First
Prós

*

*Ideal para desempenho e esquemas já existentes;

*Aplicação pode ser feita em cima de um banco de dados que já existe;

*Segurança a nível de banco mais bem ajustada;

Contras

*

*Geração de ambientes é limitada; Complexo para determinar mudanças incrementais tanto do banco de dados quanto da aplicação;

*Totalmente dependente da tecnologia de banco;

*Limitação de providers de banco que podem gerar a aplicação (ODBC ajuda, mas não resolve completamente o problema);

*Validação de dados gerada para a aplicação limitada;

O que muda na arquitetura de um projeto e na maneira de desenvolver o sistema?
Creio que os ítens anteriores respondam bem esta pergunta. Tudo depende da realidade em que o novo sistema é construído, com mais alguns adendos.
No Code First, o banco de dados acompanha o crescimento do sistema. No Database First, todo o sistema precisa ser gerado de uma vez, e toda implementação incremental precisa ser manual.
Em contrapartida, um sistema Code First é verde quanto à segurança e desempenho do banco de dados. A maioria dos problemas são resolvidos por boas práticas, mas ainda assim sempre alguma coisa deixa a desejar, como uma tabela enorme ou peculiar, que exija otimização extra.


text:
Q: Matplotlib Add a background image without corrupting the data I have created a graph with matplotlib with data, I would like to add a background image but the data changes depending on the image data. I want this with an image on the background, like this :
What I want
So the graphic and the one created by this code :
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = [datetime.datetime(2020, 7, 17, 0, 0) + datetime.timedelta(hours=i) for i in range(24)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
ax = plt.subplot()
ax.plot(x,y, lw=4)
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.gca().set_axisbelow(True)
plt.gca().grid(color='gray', linestyle='dashed')
plt.savefig("chart.png", transparent=True, dpi=80)

But when I try to add an image with this code :
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

x = [datetime.datetime(2020, 7, 17, 0, 0) + datetime.timedelta(hours=i) for i in range(24)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
ax = plt.subplot()
imageFile = cbook.get_sample_data('/root/image.png')
image = plt.imread(imageFile)
ax.imshow(image)
ax.plot(x,y, lw=4)
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.gca().set_axisbelow(True)
plt.gca().grid(color='gray', linestyle='dashed')
plt.savefig("chart.png", transparent=True, dpi=80)

This gives me this :
Wrong graphic

A: Sample with correct extent values:
import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

ax = plt.subplot()
x = [datetime.datetime(2020, 7, 17, 0, 0) + datetime.timedelta(hours=i) for i in range(24)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]
ax.plot(x, y, lw=4)

img = plt.imread('img.png')
x0,x1 = ax.get_xlim()
y0,y1 = ax.get_ylim()
ax.imshow(img, extent=[x0, x1, y0, y1], aspect='auto')

myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)
plt.gca().set_axisbelow(True)
plt.gca().grid(color='gray', linestyle='dashed')

plt.savefig("chart.png", transparent=True, dpi=80)


text:
Q: Displaying images in scrollable div I have an array of images (src url for them) and I want to display them in a line, like so:
[Image1] [image2] [image3]
If there are a lot images I'd want the
 they are in to become scrollable, on the x-axis, so that the images are still in a line.
This is what I've got now:

I do see the 'scroll' on the div, but faded. And my images are like this:
[Image1] [Image2] [Image3]
[Image4]
What am I missing here?

A: Here you go:
http://jsfiddle.net/danhaswings/nndhjp67/
HTML

CSS
#slide {
    width: auto;
    height: 100px;
    overflow-x: scroll;
    overflow-y: hidden;
    white-space: nowrap;
}

A: Add white-space: nowrap:

A: Try adding these CSS rules to your wrapper div.
overflow-x: scroll;
overflow-y: hidden;
width:100%;


text:
Q: Given an algebraic group $G$ is $G^0$ (connected component including the identity) unique? I have two basic questions regarding connected components including the identity of algebraic groups.

*

*Given an algebraic group $G$ is $G^0$ (connected component including the identity) unique?

*Let $H$ be an algebraic subgroup of $G$. Does it then always follow that $H^0$ is contained in $G^0$?
Thank you very much!


text:
Q: Can I sell my own PyQt4 app built with cx_freeze? I know PyQt4 has GPL licence. But I'm confused:
How can I sell my app built with cx_freeze?
Can I do it legally?
what should I do otherwise?
Do compiled py files also mean source code?
I don't want to change my code for PySide, which has LGPL. I want to sell PyQt4 built with cx_freeze if it is legal.

A: IANAL but here is a quick summary.

*

*Yes, you can sell it even though it is GPL.

*However, since PyQt4 is GPL, then your entire application is also GPL which means anyone who receives a copy (e.g., purchases it) is legally allowed to redistribute it for free or for money and there is nothing you can do to prevent it.

*Unless you purchase a commercial license for PyQt4 in which case you can maintain your proprietary license so long as you also follow the licensing restrictions/rules of any third-party libraries that you also use.


text:
Q: Vue.js: How to open external links in already opened tab? I am building an SPA using Vue.js 2. The app sends emails containing links to the app and push notifications to users from time to time.
Now, when the user click on links in the email or click on the push notification a new tab is opened with the given url.
Since the app is an SPA, I want new links to be opened in the already opened tab if exists any and don't open a second one.
links that I send to users look like this (if this can help):
https://app.com/#/user/123456789

How can I do that, is it something related to the app code, to the browser or to the links I am sending ?

A: The body you send to your user should be in HTML and it should use the default target by the a tag (_self).
For example

or


text:
Q: Help in Entity Framework  4.1 Query I need help in writing a query, below i have written classes with  needful properties for this example only (i have not shown  DB tables that e.f. generates)
//this class will create a unique id for each location may be country,
 state or city
public  class Location
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Discriminator{get;set;}

    public int? ParentLocationId { get; set; }
    public Location ParentLocation { get; set; }

    public ICollection<Location> ChildLocations { get; set; }
}

Sample Locations data
Id | Name | Discriminator | ParentLocationId
1 | India | Country | null
2 | Karnatka | State | 1
3 | Maharashtra | State | 1
4 | Banglore | City | 2

//this will contain all product categories + products itself
public class Category
{
    public int Id { get; set; }
    public string Name { get; set; }
    public Category ParentCategory { get; set; }
    public int? ParentCategoryId { get; set; }

    public ICollection<Category> ChildCategories { get; set; }
}

Sample category Data
Id | Name | ParentCategoryId
1  | Electronics | Null
2  | Mobiles | 1
3 | Apple | 2
4 | Nokia | 2
5 | I phone-4 | 3
6 | Nokia-Some Model | 4

I have used a variable of Type=User in below class but i have'nt shown 'User' class here as it doesn't contain any thing spl
public class Purchase
{
    public int Id { get; set; }

    public User User { get; set; }
    [Required]
    public int UserId { get; set; }

    public Category Category { get; set; }
    [Required]
    public int CategoryId { get; set; }

    public Location Location { get; set; }
    [Required]
    public int LocationId { get; set; }
}

Note for a successful purchase order locationId must be cityId and categoryId should be lowest in hierarchy, eg categoryId cant be Mobile, it should  be iphone-4 or nokia-some-model
Sample Purchase Orders Data
Id | CategoryId | LocationId | UserId
1  | 5 | 4  | 1
1  | 5 | 4  | 2
1  | 5 | 4  | 3

Till now every thing is working fine for me, Below is my question
Iam creating filtering mechanism where i provide 2 things locationId(this location may be ID of country,state or city) and product id(this product may be any where in hierarchy, eg this value may be id of electronics or mobile or apple or iphone) and get a list of all purchases made that satisfies this
eg: sample filters that i may make

*

*a> find all mobile sale in a state (pass categoryId of mobile and locationId of a particular state)

*b>    find all nokia sale in a country (pass categoryId of nokia and locationId of a particular country)
and so    on..

I am open to any suggestions also you can let me know if there is anything that's not been properly explained in this question.

A: That are hierarchical queries which are IMHO impossible to do effectively in linq-to-entities because linq-to-entities doesn't have any support for recursion needed to navigating through hierarchy.
These queries work best with some support from database - in case of SQL Server 2005 and newer you can use CTE and hierarchical queries. CTEs can be used in database views which can in turn be mapped to entity in EF but it will still not allow you to create filtering criteria you need because view can have only static structure.
For example you can use CTE to define view returning CityId and its CountryId in single record. You can then use this view and join it to purchases and filter by CountryId. But what if you need to search by StateId? Your view currently doesn't have StateId column defined - you can add it as another column but it will only complicate everything - you will have to know if you must filter by country or by state. What if you have another level? And one more? What if you cannot say upfront how many levels do you have? That is exactly what can happen with categories. View will not help you.
This would be probably possible, if EF had support for table valued functions - you would create a table valued function for Locations (it would dynamically return all cities belonging to passed LocationId) using CTE internally and similar function for Categories and you would map that functions in EDMX and use them in joins in linq-to-entities queries. There is one problem - EF doesn't support mapping table valued functions yet - it is planned for next major release.
If you need this kind of search you need plain old SQL + CTE.


text:
Q: Hazelcast: force map to load I'm looking for a way to force map initialization. I'm using Spring integration and MapStore implementation and I noticed that before business logic tries to touch a map they are not initialized, i.e. loadKeys() method is not called and even no map exists under the category. Is there a property to make maps non-lazy? Or an API to call initialization?

A: for me it worked using myMap.values()


text:
Q: Is there Saiku Reporting plugin for Pentaho BI Server 5.0.1? Saiku Reporting 1.0-GA is available here: http://mgiepz.github.io/saiku-reporting
As mentioned in the installation instructions:

To put Saiku-Reports under the ACL, add .adhoc to the acl-files in
  pentaho.xml

I have the previous release 4.8 and in the pentaho.xml file there is a block.
/biserver-ce/pentaho-solutions/system/pentaho.xml:
<!--
  acl-files tag was added in support of PPP-130

  * Allow specification of ACLs on .url files

  * Allow specification of files acl-able to be
    in the configuration

  Usage: List the file extensions of files allowed to have
  acls. This is a performance tuning exercise since any file
  with an extension in this list can have ACLs applied.
-->

<acl-files>xaction,url,prpt,prpti,xdash,xcdf</acl-files>

For version 5.0.1 this block is missing.
I did as instructed, but the plugin Saiku Reporting is not available in
Pentaho BI Server CE 5.0.1.
In the upper right corner of the screen on the page /pentaho/Home I see the following:

Thank you!
Our Kickstarter for Saiku Reporting has been fully funded. This is
  great news for the Saiku platform and will allow us to build out a
  great new Saiku Reporting product with the help from our community.
  Stay tuned for more updates.

Does that means that while the plugin is not available?
Where can I find Saiku Reporting plugin for Pentaho BI Server 5? Maybe there is some other way to install?

A: you need to download & install saiku plugin from marketplace.
after reaching marketplace don't select download button directly. default it has selected for enterprise version.
so select community from drop-down and then start downloading.
once you download you need to follow the instruction for configuring it.
simple steps like register it and place the licence file into respected folder.(you will get one pop-up with detail instruction) follow that.
after doing this changes you will get saiku option while you will click on create new.


text:
Q: Sweetalerts in laravel, always showing the alerts twice So, I have the uxweb/sweet-alert package for Laravel and I've got a page that is loading an alert.
I'm running into a trouble whereby whenever I browse to the next page after loading the alert, it will load it again.
Is there any way around this or a way I can diagnose the problem?
TicketController.php
<?php

namespace App\Http\Controllers\Frontend;

use DB;
use Alert;
use App\Tickets;
use App\Http\Requests;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class TicketController extends Controller
{
    public function index()
    {
        $tickets = DB::table('tickets')->get();

        Alert::success('Tickets retrieved!');

        return view('frontend.tickets')->with('tickets', $tickets);
    }
}

My route file
Route::group(['middleware' => 'auth'], function() {
    Route::get('tickets', 'TicketController@Index');
});

My master layout
    <link rel="stylesheet" type="text/css" href="css/sweetalert.css">
</head>

and
<script src="js/sweetalert.js"></script>

@include('sweet::alert')

@include ('alertcancel')

A: Probably a session problem. remove the sweet_alert key from the session so that it flashes only one time.
        @include('sweet::alert')

        <?php Session::forget('sweet_alert'); ?> <-- insert this
    </body>
</html>


text:
Q: cassandra Selection of groupwise max values I have created a table 'statistics' under covid19 keyspace:
    CREATE TABLE statistics(country_name text, dt date, confirmed_cases bigint, deaths bigint,
    PRIMARY KEY(deaths))with clustering order by (deaths DESC);

I want to retrieve top deaths country wise. To do this, i tried:
    select * from statistics per partition limit 1;

and it is returning:
    country_name  | deaths | confirmed_cases | dt
    ---------------+--------+-----------------+------------
    BANGLADESH    |      43 |      8354      | 2022-02-08
    UNITED STATES |    3635 |    555623      | 2022-01-26
    GERMANY       |     455 |     219972     | 2022-02-16

but i need the result like following:
    country_name  | deaths | confirmed_cases | dt
    ---------------+--------+-----------------+------------
    UNITED STATES |    3635 |    555623      | 2022-01-26
    GERMANY       |     455 |     219972     | 2022-02-16
    BANGLADESH    |      43 |      8354      | 2022-02-08

Here is my sample input:
    BEGIN UNLOGGED BATCH INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('GERMANY','2022-02-17',235626,261); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('GERMANY', '2022-02-16', 219972, 455); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('GERMANY', '2022-02-15', 159217, 243); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('GERMANY', '2022-02-14', 76465, 246); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values ('GERMANY', '2022-02-13', 62841, 42); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('BANGLADESH', '2022-02-16', 3929, 15); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('BANGLADESH', '2022-02-15', 4746, 34); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('BANGLADESH', '2022-02-14', 4692, 19); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('BANGLADESH', '2022-02-13', 4838, 28); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('BANGLADESH', '2022-02-12', 5023, 20); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('BANGLADESH', '2022-02-11', 5268, 27); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('BANGLADESH', '2022-02-10', 7264, 41); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('BANGLADESH', '2022-02-09', 8016, 33);INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('UNITED STATES', '2022-02-05', 204770, 1761); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('UNITED STATES', '2022-02-04', 306311, 2811); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('UNITED STATES', '2022-02-03', 306317, 3279); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('UNITED STATES', '2022-02-02', 325193, 3412); INSERT INTO statistics (country_name,dt,confirmed_cases,deaths)values('UNITED STATES', '2022-02-01', 312473, 3582);

A: Unfortunately, Cassandra will only allow for enforcement of sort order by clustering keys within a partition.  Querying across partitions will always produce unordered results.  This is also why Cassandra isn't a good fit for OLAP or reporting use cases.
Distributed querying tools like Spark (on top of Cassandra) does allow for ordering on arbitrary columns, as was shown in this recent question:
Saving information to Cassandra keeps no order