text:
Q: Uploading image file to S3 using API gateway NodeJS I'm trying to upload an image file to S3 using API Gateway. So it's a POST method where the body takes the image file using form-data. I wrote the lambda in TypeScript with the help of lambda-multipart-parser. It works fine locally but when i deploy it in AWS, the file size changes a bit and it seems the original file was not really uploaded properly.
my lambda code is
import * as parser from 'lambda-multipart-parser'
import { s3Upload } from '../helper/common'

export const test = async (event) => {
  console.log('starting------')
  console.log('EVENT', event)
  const result = await parser.parse(event)
  console.log(result.files)
  const file = result.files[0]
  console.log('FILE', file)

  const s3Params = {
    Bucket: process.env.AWS_BUCKET,
    Key: `${Date.now().toString()}-${file.filename}`,
    Body: file.content,
    ContentType: 'image/png',
    ACL: 'public-read',
  }
  console.log('S3 PARAMS', s3Params)
  const s3Content = await s3Upload(s3Params)
  console.log('S3 CONTENT', s3Content)
}

where i'm just calling the s3Upload from helper
import { S3 } from 'aws-sdk'

export const s3Upload = async function (params) {
  let s3: S3
  if (process.env.IS_OFFLINE) {
    s3 = new S3({
      accessKeyId: process.env.AWS_ACCESS_KEY,
      secretAccessKey: process.env.AWS_SECRET_KEY,
    })
  }
  return new Promise((resolve) => {
    s3.upload(params, (err, data) => {
      if (err) {
        console.error(err)
        resolve(err)
      } else {
        resolve(data)
      }
    })
  })
}

this looks like a problem of the node package itself but i'm not sure! what are the other working ways i can achieve this objective which is to upload an image file to S3 using API gateway written in typescript?

A: Can you provide more information about your issue??
I took your code for testing locally. I found out that you need to instanciate the s3 again after the if is_offline.
import { S3 } from 'aws-sdk'

export const s3Upload = async function (params) {
  let s3: S3
  if (process.env.IS_OFFLINE) {
    s3 = new S3({
      accessKeyId: process.env.AWS_ACCESS_KEY,
      secretAccessKey: process.env.AWS_SECRET_KEY,
    })
  }

  // Here is the change

  s3 = new S3({
    region: 'us-east-1', // for example
  });
  return new Promise((resolve) => {
    s3.upload(params, (err, data) => {
      if (err) {
        console.error(err)
        resolve(err)
      } else {
        resolve(data)
      }
    })
  })
}

at least that worked for me. Also inside the lambda, also for local with serverless-offline, and also with an API Gateway, all with Typescript.
Hope this helps!
Regards!

A: It is probably because the module is not included in the lambda, try to do npm init and install the package in the folder where the lambda or the other option is, and it is more advisable to create a layer and put the package there.
Here the documentation: https://docs.aws.amazon.com/cdk/api/v1/docs/aws-lambda-readme.html#layers


text:
Q: Nuxt Auth Module - Multiple redirect options after logout I have a website where the user logs in and then gets access to a dashboard. The user can log in and out from their dashboard as well as from the home page. Now I want that when the user logs out from the dashboard, he gets directed to a different page than when he logs out from the home page. Is this somehow possible with the auth module in Nuxt? I haven't found a way so far.
my nuxt.config.js looks like this at the moment:
auth: {
    redirect: {
      home: "/",
      login: "/"
    },
    strategies: {
      local: {
        endpoints: {
          login: { url: "/api/session", method: "post" },
          logout: { url: "/api/session", method: "destroy" },
          user: { url: "/api/settings", method: "get", propertyName: false }
        },
        tokenType: 'Bearer'
      }
    },
    redirect: {
      login: '/',
      logout: '/',
      home: false,
    },
  }

And then there is the button from the home page:

<button
  @click="$auth.logout()"
  v-scroll-to="'#login'"
  >Logout</button>

and the button from the Dashboard:
<button
  @click="$auth.logout()"
>
Logout
</button>

A: nuxt auth module didn't provide multiple redirect options for different scenarios.
but there are two inelegant ways to achieve this:
Method One: change target redirect url with onRedirect
write a plugin plugins/auth.js with content:
export default function({ $auth }) {
 $auth.onRedirect((to, from) => {
   if(from === '/dashboard'){return '/another-logout'}
 })
}

register the plugin in nuxt.config.js:
{
  auth: {
    plugins: [ '~/plugins/auth.js' ],
    strategies: {}
  }
}

Method Two: override watchLoggedIn logic, add logoutWith method

*

*First, disable default watch login:

{
  auth: {
    watchLoggedIn: false, // add this line
    strategies: {}
  }
}

*listen loggedIn and extend 'logoutWith' for $auth
create a plugin plugin/auth.js with content:

function routeOption (route, key, value) {
  return route.matched.some((m) => {
    if (process.client) {
      return Object.values(m.components).some(component => component.options && component.options[key] === value)
    } else {
      return Object.values(m.components).some(component => Object.values(component._Ctor).some(ctor => ctor.options && ctor.options[key] === value))
    }
  })
}
export default function ({ $auth }) {
  $auth.$storage.watchState('loggedIn', (loggedIn) => {
    if (!routeOption($auth.ctx.route, 'auth', false)) {
      let redirectKey = loggedIn ? 'home' : 'logout'
      if (redirectKey == 'logout') {
        const logout_type = $auth.$storage.getUniversal('logout_type')
        if (logout_type) {
          redirectKey = 'logout_' + logout_type
          // delete to ensure use only once
          $auth.$storage.removeUniversal('logout_type')
        }
      }
      $auth.redirect(redirectKey)
    }
  })
  $auth.logoutWith = (logout_type, ...args) => {
    $auth.$storage.setUniversal('logout_type', logout_type)
    $auth.logout(...args)
  }
}

dont forget register the plugin in nuxt.config.js

*update you redirect options and call logoutWith in any page:

{
  auth: {
    watchLoggedIn: false,
    plugins: [ '~/plugins/auth.js' ],
    redirect: {
      login: '/login',
      logout: '/logout',
      logout_dash: '/another_logout',
      home: '/home'
    },
  }
}

in page dashboard.vue:
<button @click="$auth.logoutWith('dash')"></button>

By the way, if you want to redirect to another login page based on the  route, maybe method one is more suitable

A: I think you can simply use $router.push('/dashboard'):
<button @click="$auth.logout();$router.push('/dashboard')">
    Logout
</button>

A: why don't you just set redirect to false
redirect: false,

and manually redirect with router to whatever page you want after logout for different pages

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I change selection list with an editor I have 2 selection lists
<select Multiple name="SelectOut" id="SelectOut" size="15">
<select Multiple name="SelectIn" id="SelectIn" size="15">

In between I have two buttons <-- & -->. Using this button I can move the list left to right or right to left.
User inconvenience is that copy and paste is not working with selection lists. He wants to replace the right selection list SelectIn with a text editor. He paste the content to that editor (Usually a big columns o). After pasting it should exactly behave like the selection list. He should be able to move the list item to left, add more items from left, should be sort it etc....
How can I achieve this?
In the right side instead of a selection list, I need a text editor. Or I should be able enable the copy and paste enable in the right section list:). For the user major inconvience is he has to select one ore more list items from the left selection list to right. Insted he should be able to cut and past the list from an excel sheet column to the editor. One more work around , I can see is , paste the content to an extra text editor and pressing a button that editor content should appear as a list item in right selection list exactly same as in the Excel sheet column.
TIA
-Philip-

A: do you want something like this
demo
JS
function shiftRight()
{
    var selItem = document.forms[0].list1.selectedIndex;
    if (selItem == -1)
    {
        window.alert("Select Item From List")
    }
    else
    {
        document.forms[0].list2.add(document.forms[0].list1[selItem], null);
    }
}

function shiftLeft()
{
    var selItem = document.forms[0].list2.selectedIndex;
    if (selItem == -1)
    {
        window.alert("Select Item From List")
    }
    else
    {
        document.forms[0].list1.add(document.forms[0].list2[selItem], null);
    }
}


text:
Q: Multiple NULL values in column with UNIQUE index We have a table that has a unique index on a column that can accept null values. Problem is that we found out this structure can only accept one row with NULL value. If we try to add second row with NULL value we get an error like.
"can not insert duplicate key row in object…."
Is there anything we can do to keep the index on this column and the ability to add NULL values to more than one row?

A: Yes, you can use filtered index to support this. Just drop your existing index and create new index like this
CREATE UNIQUE INDEX Index_Name ON TableName(ColumnName)
WHERE ColumnName IS NOT NULL

This will allow you to have duplicates of NULL values. Here is an in depth article if you need more details on this.
http://blog.sqlauthority.com/2008/09/01/sql-server-2008-introduction-to-filtered-index-improve-performance-with-filtered-index/


text:
Q: How do I solve an arithmetic sequence? How does:
(1 + 2 + ... + N) / N =  (N + 1) / 2
or
(1 + 2 + ... + N + N) / N = (N + 3) / 2
My textbook says this is elementary math but I have forgotten the method for finding the answer.

A: The example you gave is called an arithmetic sequence, not a geometric sequence.
A simple way to convince yourself that the result is correct is to write the same sequence backwards, add it to itself, and divide by 2:
   1 +   2 +   3 + ... + N-1 +  N  = S
+  N + N-1 + N-2 + ... +   2 +  1  = S
 --------------------------------------
 N+1 + N+1 + N+1 + ... + N+1 + N+1 = 2S
 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
            N terms

= (N+1)*N                              = 2S

(N+1)*N/2                              = 2S/2 = S =
**S = (N+1)*N/2**

A: Mathematical induction. http://en.wikipedia.org/wiki/Mathematical_induction#Example
The second claim you stated follows from the first by just adding N / N = 1 = 2 / 2.

A: Sum of n natural numbers is denoted by n(n+1)/2.
So the given the first problem you have correctly mentioned the output will (n+1)/2.
for the second problem.
the solution is (n(n+1)/2n)+n/n = (n+1)/2 +1 = (n+3)/2. You would observer actual series is sum of n natural numbers plus n. So thats how i split the terms.


text:
Q: How can I add a png or svg icon to the navbar of a website? I'm trying to learn how to create and update a basic website using R-Markdown following this guide: https://www.andreashandel.com/posts/2021-01-11-simple-github-website/index.html#starter-files
By now I've been able to create the HTML documents that I'd need and I've added the connexions between HTML in the navbar (.yml) of my website. In the case of some links, like GitHub or LinkedIn I've been able to add their icons this way:
 - icon: fa-github fa-lg
   ref: https://github.com/username

The problem is that for some webs there's no fa-lg icon available, so I've downloaded the icon as .png and .svg to add them to the navbar, but it creates an error.
This is the code line I've tried, but I can't get to do it:
- icon: ![](path/to/icon.png)
  href: https://orcid.org/
  ##OR
- image: ![](path/to/icon.png)
  href: https://orcid.org/

AND whatching other examples from How to add svg icon to a button with a text
  - icon: "https://upload.wikimedia.org/wikipedia/commons/0/06/ORCID_iD.svg"
    href: https://orcid.org/

I've recently started to learn R, so this may be a simple thing, but if someone can help me I'd be so grateful.
UPDATE
Following this question's recommendations: How to add a browser tab icon (favicon) for a website?
I've converted my .svg archive to a 32x32 pixels .ico archive, but I still can't insert it into my navbar.


text:
Q: Not Displaying the Validation Message for Login Error in PHP I have login form with username and password.If i am entering wrong username or password it is showing blank page not displaying any error messages.it just showing in URL as website.com/Admin/#. Here is the code which i have written:
<form action="#" method="post" role="form" enctype="multipart/form-data">
    <?php if ( $msg != '' ) { ?>

            <?php echo $msg; ?>

    <?php } ?>

Email

        <input type="text" placeholder="User Name" id="username" name="user_name" required>

Password

        <input type="password" placeholder="Password" id="password" name="password" required>

            <input type="submit" name="submit_login" value="Sign In" class="theme-btn btn-style-one">

</form>

PHP Code:
<?php
session_start();
include 'db.php';
if ( isset( $_POST['submit_login'] ) ) {
    if ( !empty( $_POST['user_name'] ) && !empty( $_POST['password'] ) ) {
        $get_user_name = mysqli_real_escape_string( $conn, $_POST['user_name'] );
        $get_password = mysqli_real_escape_string( $conn, $_POST['password'] );
        // Encrypting the password from text//
        $get_password = md5( $get_password );
        $sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'";
        if ( $result = mysqli_query( $conn, $sql ) ) {
            while ( $rows = mysqli_fetch_assoc( $result ) ) {
                if ( mysqli_num_rows( $result ) == 1 ) {
                    $_SESSION['user'] = $get_user_name;
                    $_SESSION['password'] = $get_password;
                    $_SESSION['user_role'] = $rows['user_role'];
                    if ( $_SESSION['user_role'] === 'admin' ) {
                        header( 'Location:property-list.php' );
                    }
                } else {
                    $msg = 'User name or Password was Wrong!';
                    $msgclass = 'bg-danger';
                }
            }
        } else {
            $msg = 'There is somekind of Database Issue!';
            $msgclass = 'bg-danger';
        }
    } else {
        $msg = 'User name or Password was empty!';
        $msgclass = 'bg-danger';
    }
} else {
}
?>

If i give correct username and password its working fine their was no issue in that the only problem is with if i enter wrong username or password or else submitting directly without giving any data it is not displaying message

A: You need to echo the $msg all the time remove the if in the form then declare mgs and msgclass before the submit action then just echo
<?php
    session_start();
    include 'db.php';

    $msg =""; // declare message
    $msgclass =""; //classs

    if(isset($_POST['submit_login'])){
        if(!empty($_POST['user_name']) && !empty($_POST['password'])){
            $get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
            $get_password = mysqli_real_escape_string($conn,$_POST['password']);
           // Encrypting the password from text//
           $get_password=md5($get_password);
            $sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
       if($result = mysqli_query($conn,$sql)){
        while($rows = mysqli_fetch_assoc($result)){
            if(mysqli_num_rows($result) == 1){
                $_SESSION['user'] = $get_user_name;
                $_SESSION['password'] = $get_password;
                $_SESSION['user_role'] = $rows['user_role'];
                if($_SESSION['user_role'] === 'admin'){
                    header('Location:property-list.php');
                }
                }
             else{
                 $msg = 'User name or Password was Wrong!';
                 $msgclass='bg-danger';
                 }
                 }
                  }
            else {
                $msg = 'There is somekind of Database Issue!';
                 $msgclass='bg-danger';
            }
        } else {
        $msg = 'User name or Password was empty!';
                 $msgclass='bg-danger';
        }
    }else {
    }
    ?>

Then
<form action="#" method="post"  role="form" enctype="multipart/form-data">
    <div class="alert <?php echo $msgclass;?>">
        <?php echo $msg;?>

Email

        <input type="text"  placeholder="User Name" id="username" name="user_name" required>

Password

        <input type="password" placeholder="Password" id="password" name="password" required>

        <input type="submit" name="submit_login" value="Sign In" class="theme-btn btn-style-one">

</form>

NB : You should use prepared statements to prevent sql injections.
  Never use md5() as means of password encrption rather use
  password_hash() and password_verify()

A: If the user enters a wrong password or blank one you are not redirecting it to anywhere.
see updated code.
<?php session_start();
include 'db.php';
if(isset($_POST['submit_login'])){
    if(!empty($_POST['user_name']) && !empty($_POST['password'])){
        $get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
        $get_password = mysqli_real_escape_string($conn,$_POST['password']);
       // Encrypting the password from text//
       $get_password=md5($get_password);
        $sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
   if($result = mysqli_query($conn,$sql)){
    while($rows = mysqli_fetch_assoc($result)){
        if(mysqli_num_rows($result) == 1){
            $_SESSION['user'] = $get_user_name;
            $_SESSION['password'] = $get_password;
            $_SESSION['user_role'] = $rows['user_role'];
            if($_SESSION['user_role'] === 'admin'){
                // redirect to members area or login area
                header('Location:property-list.php');
                exit();
            }
            }
         else{
             $msg = 'User name or Password was Wrong!';
             $msgclass='bg-danger';
             }
             }
              }
        else {
            $msg = 'There is somekind of Database Issue!';
             $msgclass='bg-danger';
        }
    } else {
    $msg = 'User name or Password was empty!';
             $msgclass='bg-danger';
    }
}else {
}
// redirect to error page or login page..
header("redirect:error.php?msg=$msg&c=$msgClass");
exit();
?>

Some developers pass the variables with get others set a session and read the session. Is your choice I prefer sessions, but if you use GET or POST please always sanitize the user input.
On the query you should update your code to use prepared statements to eliminate possibilities of SQL injection.
On the password you are using MD5 if you are going to use it or either hashing protocol you should salt it so your passwords are stronger in case your sql is expose and the hashes are obtain.
$salt = "s0meRand0mStr1ng..Long..difficult...etc."; // must be longer than 20 chars at least.
$get_password=md5($get_password . $salt);

A: First you need to target your php file in the action attribute of your form
action="/path/tofile.php"

Most user friendly validation is done with javascript, so the page doesn't have to reload,
but if you really want to use PHP, one way to do it is with sessions.
You can add the $msg and $msgclass to the session variable:
$_SESSSION['response'] = ['message' => $msg, 'class' => $msgclass];

After that use header function to redirect back to your html:
header('Location: /pathtoformfile');
exit;

Note: be careful not to echo or print anything in the script before header.
Finally, in the form file do this:
// add this at THE TOP of the file
session_start();

// check session variable
if(!empty($_SESSION['response']) {
   // display the message
   echo $_SESSION['response']['message'];
}

A: Redirect to your login page again. Suppose, LoginForm.php
Updated code:
<?php session_start();
include 'db.php';
if(isset($_POST['submit_login']))
{
    if(!empty($_POST['user_name']) && !empty($_POST['password']))
    {
        $get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
        $get_password = mysqli_real_escape_string($conn,$_POST['password']);
       // Encrypting the password from text//
       $get_password=md5($get_password);
        $sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password'" ;
        if($result = mysqli_query($conn,$sql))
        {
            while($rows = mysqli_fetch_assoc($result))
            {
                if(mysqli_num_rows($result) == 1)
                {
                    $_SESSION['user'] = $get_user_name;
                    $_SESSION['password'] = $get_password;
                    $_SESSION['user_role'] = $rows['user_role'];
                    if($_SESSION['user_role'] === 'admin')
                    {
                        header('Location:property-list.php');
                    }
                }
                else{
                    $msg = 'User name or Password was Wrong!';
                    $msgclass='bg-danger';
                }
            }
        }
        else {
            $msg = 'There is somekind of Database Issue!';
            $msgclass='bg-danger';
        }
    } else {
    $msg = 'User name or Password was empty!';
            $msgclass='bg-danger';
    }
    header("Location:Login.php");
}
?>

A: This worked fine for me
<?php session_start();
include 'db.php';

if(isset($_POST['submit_login'])){
    if(!empty($_POST['user_name']) && !empty($_POST['password'])){
        $get_user_name = mysqli_real_escape_string($conn,$_POST['user_name']);
        $get_password = mysqli_real_escape_string($conn,$_POST['password']);
        // Encrypting the password from text//
        $get_password=md5($get_password);
        $sql = "SELECT * FROM users WHERE username = '$get_user_name' AND user_password = '$get_password' limit 0,1" ;
        $result = mysqli_query($conn,$sql);
        $row = mysqli_fetch_assoc($result);
        if(mysqli_num_rows($result) == 1){
            $_SESSION['user'] = $get_user_name;
            $_SESSION['password'] = $get_password;
             $_SESSION['user_role'] = $row ['role'];
            if($_SESSION['user_role'] === 'admin'){
                header('Location:property-list.php');
                exit;
            }

         }
         else{
            header('Location:index.php?msg=1');
            exit;
         }
    } else {
            header('Location:index.php?msg=3');
            exit;
    }
}

if(isset($_GET['msg']) && !empty($_GET['msg'])){
    if($_GET['msg']==1){
        $msg = 'User name or Password was Wrong!';
        $msgclass='bg-danger';
    }else if($_GET['msg']==2){
        $msg = 'User name or Password was empty!';
        $msgclass='bg-danger';
    }

}
?>


text:
Q: What is the "manifest blob unknown: blob unknown to registry" error I'm trying to push a multi-arch docker image to docker hub and run into errors (opened docker issue at https://github.com/docker/distribution/issues/3100):
❯ docker build -t andig/evcc:latest-amd64 -f linux-amd64-.Dockerfile .
❯ docker build -t andig/evcc:latest-arm.v6 -f linux-arm-6.Dockerfile .
❯ docker push andig/evcc:latest-amd64
❯ docker push andig/evcc:latest-arm.v6
❯ docker manifest create --amend andig/evcc:latest andig/evcc:latest-amd64 andig/evcc:latest-arm.v6
❯ docker manifest annotate andig/evcc:latest andig/evcc:latest-amd64 --os=linux --arch=amd64
❯ docker manifest annotate andig/evcc:latest andig/evcc:latest-arm.v6 --os=linux --arch=arm --variant=v6
❯ docker manifest push andig/evcc:latest

failed to put manifest docker.io/andig/evcc:latest: errors:
manifest blob unknown: blob unknown to registry
manifest blob unknown: blob unknown to registry
manifest blob unknown: blob unknown to registry
manifest blob unknown: blob unknown to registry
manifest blob unknown: blob unknown to registry

Searching around shows error might be related to "foreign layers" (https://issues.sonatype.org/browse/NEXUS-11865) but it's unclear how that might happen building an image based on Alpine.
As the docker github ticket and a forum question didn't get any response- what else could I do for further analysis? E.g., how could I find out which layer it's complaining about?

A: As I suspected a problem with a somehow corrupted manifest that I might have pushed to docker hub I've started retrying the process with a clean, local registry. Following the steps led me to the same error message.
At this stage I've started another round of googling which not only suggested to use --purge for cleaning the manifest locally (which didn't help with this issue) but also to remove the local manifest cache by deleting ~/.docker/manifests.
After removing the manifests folder both registry pushes- local and docker hub- started working.

A: You should try the buildx feature of CLI.
Let's say the Dockerfile is as below:
FROM alpine
ARG TARGETPLATFORM
ARG TARGETOS
ARG TARGETARCH
ARG TARGETVARIANT

ARG BUILDPLATFORM
ARG BUILDOS
ARG BUILDARCH
ARG BUILDVARIANT

RUN echo "Image target platform details :: "
RUN echo "TARGETPLATFORM    : $TARGETPLATFORM"
RUN echo "TARGETOS          : $TARGETOS"
RUN echo "TARGETARCH        : $TARGETARCH"
RUN echo "TARGETVARIANT     : $TARGETVARIANT"

RUN echo "Image build platform details :: "
RUN echo "BUILDPLATFORM     : $BUILDPLATFORM"
RUN echo "BUILDOS           : $BUILDOS"
RUN echo "BUILDARCH         : $BUILDARCH"
RUN echo "BUILDVARIANT      : $BUILDVARIANT"

docker build command -
docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t sujaypillai/multiarc:latest --push .

*

*The --platform flag informs buildx to generate Linux images for AMD 64-bit, Arm 64-bit, and Armv7 architectures.

*The --push flag generates a multi-arch manifest and pushes all the images to Docker Hub.

docker buildx build --platform linux/amd64,linux/arm64,linux/arm/v7 -t sujaypillai/multiarc:latest --push .
[+] Building 78.1s (40/40) FINISHED
 => [internal] booting buildkit                                                                                14.1s
 => => pulling image moby/buildkit:buildx-stable-1                                                                                13.3s
 => => creating container buildx_buildkit_meetupbuilder0                                                                                0.7s
 => [internal] load .dockerignore                                                                                0.0s
 => => transferring context: 2B                                                                                0.0s
 => [internal] load build definition from Dockerfile                                                                                0.0s
 => => transferring dockerfile: 618B                                                                                0.0s
 => [linux/arm/v7 internal] load metadata for docker.io/library/alpine:latest                                                                                25.9s
 => [linux/amd64 internal] load metadata for docker.io/library/alpine:latest                                                                                28.4s
 => [linux/arm64 internal] load metadata for docker.io/library/alpine:latest                                                                                21.8s
 => [linux/amd64  1/11] FROM docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                     13.2s
 => => resolve docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                                    0.0s
 => => sha256:a24bb4013296f61e89ba57005a7b3e52274d8edd3ae2077d04395f806b63d83e 1.51kB / 1.51kB                                                                                0.0s
 => => sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321 1.64kB / 1.64kB                                                                                0.0s
 => => sha256:a15790640a6690aa1730c38cf0a440e2aa44aaca9b0e8931a9f2b0d7cc90fd65 528B / 528B                                                                                0.0s
 => => sha256:df20fa9351a15782c64e6dddb2d4a6f50bf6d3688060a34c4014b0d9a752eb4c 2.80MB / 2.80MB                                                                                6.4s
 => => unpacking docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                                  0.1s
 => [linux/arm64  1/11] FROM docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                     11.8s
 => => resolve docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                                    0.0s
 => => sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321 1.64kB / 1.64kB                                                                                0.0s
 => => sha256:3b3f647d2d99cac772ed64c4791e5d9b750dd5fe0b25db653ec4976f7b72837c 528B / 528B                                                                                0.0s
 => => sha256:b538f80385f9b48122e3da068c932a96ea5018afa3c7be79da00437414bd18cd 2.71MB / 2.71MB                                                                                6.9s
 => => sha256:62ee0e9f84408099149bdf3873554feebd1ee199daa1e0e80b840414cd5c4c9b 1.51kB / 1.51kB                                                                                0.0s
 => => unpacking docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                                  0.1s
 => [linux/arm/v7  1/11] FROM docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                    13.6s
 => => resolve docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                                    0.0s
 => => sha256:52278dd8e57993669c5b72a9620e89bebdc098f2af2379caaa8945f7403f77a2 2.41MB / 2.41MB                                                                                8.2s
 => => sha256:7e4bece93b3e57b41f44ed293874207984d801979836c7aa4f8e9ef079f5283c 1.51kB / 1.51kB                                                                                0.0s
 => => sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321 1.64kB / 1.64kB                                                                                0.0s
 => => sha256:c929c5ca1d3f793bfdd2c6d6d9210e2530f1184c0f488f514f1bb8080bb1e82b 528B / 528B                                                                                0.0s
 => => unpacking docker.io/library/alpine@sha256:185518070891758909c9f839cf4ca393ee977ac378609f700f60a771a2dfe321                                                                  0.1s
 => [linux/arm64  2/11] RUN echo "Image target platform details :: "                                                                                0.2s
 => [linux/arm64  3/11] RUN echo "TARGETPLATFORM    : linux/arm64"                                                                                0.2s
 => [linux/arm64  4/11] RUN echo "TARGETOS          : linux"                                                                                0.2s
 => [linux/arm64  5/11] RUN echo "TARGETARCH        : arm64"                                                                                0.1s
 => [linux/arm64  6/11] RUN echo "TARGETVARIANT     : "                                                                                0.1s
 => [linux/arm64  7/11] RUN echo "Image build platform details :: "                                                                                0.2s
 => [linux/arm64  8/11] RUN echo "BUILDPLATFORM     : linux/amd64"                                                                                0.1s
 => [linux/arm64  9/11] RUN echo "BUILDOS           : linux"                                                                                0.2s
 => [linux/arm64 10/11] RUN echo "BUILDARCH         : amd64"                                                                                0.2s
 => [linux/arm64 11/11] RUN echo "BUILDVARIANT      : "                                                                                0.2s
 => [linux/amd64  2/11] RUN echo "Image target platform details :: "                                                                                0.1s
 => [linux/amd64  3/11] RUN echo "TARGETPLATFORM    : linux/amd64"                                                                                0.2s
 => [linux/amd64  4/11] RUN echo "TARGETOS          : linux"                                                                                0.2s
 => [linux/arm/v7  2/11] RUN echo "Image target platform details :: "                                                                                0.2s
 => [linux/amd64  5/11] RUN echo "TARGETARCH        : amd64"                                                                                0.2s
 => [linux/arm/v7  3/11] RUN echo "TARGETPLATFORM    : linux/arm/v7"                                                                                0.2s
 => [linux/amd64  6/11] RUN echo "TARGETVARIANT     : "                                                                                0.1s
 => [linux/arm/v7  4/11] RUN echo "TARGETOS          : linux"                                                                                0.1s
 => [linux/amd64  7/11] RUN echo "Image build platform details :: "                                                                                0.2s
 => [linux/arm/v7  5/11] RUN echo "TARGETARCH        : arm"                                                                                0.2s
 => [linux/amd64  8/11] RUN echo "BUILDPLATFORM     : linux/amd64"                                                                                0.2s
 => [linux/arm/v7  6/11] RUN echo "TARGETVARIANT     : v7"                                                                                0.1s
 => [linux/amd64  9/11] RUN echo "BUILDOS           : linux"                                                                                0.1s
 => [linux/arm/v7  7/11] RUN echo "Image build platform details :: "                                                                                0.2s
 => [linux/amd64 10/11] RUN echo "BUILDARCH         : amd64"                                                                                0.1s
 => [linux/arm/v7  8/11] RUN echo "BUILDPLATFORM     : linux/amd64"                                                                                0.2s
 => [linux/amd64 11/11] RUN echo "BUILDVARIANT      : "                                                                                0.1s
 => [linux/arm/v7  9/11] RUN echo "BUILDOS           : linux"                                                                                0.1s
 => [linux/arm/v7 10/11] RUN echo "BUILDARCH         : amd64"                                                                                0.1s
 => [linux/arm/v7 11/11] RUN echo "BUILDVARIANT      : "                                                                                0.1s
 => exporting to image                                                                                20.3s
 => => exporting layers                                                                                0.6s
 => => exporting manifest sha256:df3e6c4fbf6641d1ecf860e05f7a796c44a0e2ada4f329a5d010ca57fd3e1c7a                                                                                0.0s
 => => exporting config sha256:2fa9e2f9dd38e963f3c62c529169029407436c2a33b438b1e5c9f40a93987100                                                                                0.0s
 => => exporting manifest sha256:b98e4b137e0966c9b67545facdc0ed481490e611faea202678274ad20f5e7b33                                                                                0.0s
 => => exporting config sha256:b90679defbecf0b6e3335bf84928bf71b7cd3a161db67aa2f68e0101a752ca5a                                                                                0.0s
 => => exporting manifest sha256:226daa79f5944d1df4a5265f56fd84f59fa53a4c7add722c9572d9abbb6c21db                                                                                0.0s
 => => exporting config sha256:61bf5fa0b01de86509cb10eaa833c9ec9231f9983e0abae99e9d0912580e951e                                                                                0.0s
 => => exporting manifest list sha256:995c492146ccd338fee877395543b4e756a583d670b9721d53724eb5f093d54f                                                                             0.0s
 => => pushing layers                                                                                8.2s
 => => pushing manifest for docker.io/sujaypillai/multiarc:latest                                                                                11.4s

Here is the result for docker manifest command -
docker manifest inspect docker.io/sujaypillai/multiarc:latest   | jq .manifests[].platform
{
  "architecture": "amd64",
  "os": "linux"
}
{
  "architecture": "arm64",
  "os": "linux"
}
{
  "architecture": "arm",
  "os": "linux",
  "variant": "v7"
}


text:
Q: Hide Inner Div Using jQuery      Link1

                    Here is the Child One

                    Here is the Child Two

How can i hide child1 div using jquery ?
UPDATE
I want to hide child1 on click of Link1

A: why use jQuery?
CSS
 #child1{
   display: none;
 }

or if you really want to use jQuery
$("#child1").hide();
If you want to hide on click:
Because you are using IDs in your markup, this is really simple
$("#parent").click(function() {
   $("#child1").hide();
});

A: $('div#parent > div#child1').hide();

Above for hiding direct child of #parent.
For Click
$('YOURLINK').on('click',function()
{
    $('div#parent > div#child1').hide();
});

A: Try with
$("#child1").hide();

or you can try like
$("#child1").css('display','none');

based on your edited question it should be like
$("#link1").click(function(e){
     e.preventDefault();
     $("#child1").hide();
});

and see jquery functionalities in http://jquery.com/
and see jquery selectors in http://api.jquery.com/selector/

A: If you want to hide the first Inner child inside the div:-
$('#link1ID').click(function(){
    $('div#parent div:first').hide();
});

If you want to hide using child ID:-
 $('#link1ID').click(function(){
        $('div#parent div#child1').hide();
 });

A: $(document).ready(function(){
     $("#link1").on('click',function(){
         $("#child1").hide();
     });
});

Same for child2 .

A: this will hide child1 onclick link1 and child2 onclick link2
DEMO
$('a').click(function(e){
    e.preventDefault()
    $(this).closest('div').hide();
});

if you want to hide child1 onclick of any link under parent div
$('a').click(function(e){
    e.preventDefault()
    $(this).parentsUntil('parent').find('#child1').hide();
});

HTML

         link1

         link2

A: Just select and hide the children, like this:
$("#parent").children().hide();

Then, select and show/hide/whatever the children whenever you want.


text:
Q: How to call block content from HTML I have this piece of code inside a .rb file:
main_content_blocks do
  5.times.map do |position|
    {
      id:                     rand(10..100),
      position:               position,
      block_type:             'text',
      text_markdown:          "**This is the Markdown number #{position}**",
      library_image_id:       nil,
      library_image_alt_text: nil,
      library_image_title:    nil,
      library_image_caption:  nil,
    }
  end
end

From HTML, for example within a Paragraph, I need to call the different options of the  main_content_blocks ... for example ID, text_markdown etc ...
How do I write the HTML with ruby <% %> ?

A: To elaborate a little more on bkunzi01's response - To get access to the main_content_blocks variable in your view after you make it in your controller simply add an @ to the beginning of the variable needed,  this will make it an instance variable. for example if you were hitting your ExampleController#index route.
controllers/example_controller.rb
class ExampleController < ApplicationController
  def index
    @view_data =
       main_content_blocks do
         5.times.map do |position|
           {
            id:                     rand(10..100),
            position:               position,
            block_type:             'text',
            text_markdown:          "**This is the Markdown number #{position}**",
            library_image_id:       nil,
            library_image_alt_text: nil,
            library_image_title:    nil,
            library_image_caption:  nil,
           }
          end
       end
   end
end

then in the view (using html and erb)
views/example/index.html.erb

   <% @view_data.each do |data| %>

<%= data[:id] %>

   <% end %>

would render some thing like the following:

1

2

3

4

5


text:
Q: Sorting list of dicts in order of values How can i do this:

In:

a = [{'10100': u'Z'}, {u'00101': u'C'}, {u'01100': u'B'}, {u'00111': u'T'}]

Out:

a = [{u'01100': u'B'}, {u'00101': u'C'}, {u'00111': u'T'}, {'10100': u'Z'}]

I mean in order to value

A: You can use dict.values() in the sorting key:
a = [{'10100': u'Z'}, {u'00101': u'C'}, {u'01100': u'B'}, {u'00111': u'T'}]
new_a = sorted(a, key=lambda x:x.values()[0])

Output:
[{u'01100': u'B'}, {u'00101': u'C'}, {u'00111': u'T'}, {'10100': u'Z'}]


text:
Q: Efficiently serialize/deserialize a SparseDataFrame Has anyone ever efficiently serialized/deserialized a pandas SparseDataFrame?
import pandas as pd
import scipy
from scipy import sparse
dfs = pd.SparseDataFrame(scipy.sparse.random(1000, 1000).toarray())
# just for testing

pickle is not an answer
It's outrageously slow.
import pickle, time
start = time.time()
# serialization
msg = list(pickle.dumps(dfs, protocol=pickle.HIGHEST_PROTOCOL))
# deserialization
dfs = pickle.loads(bytes(msg))
stop = time.time()
stop - start
# 0.4420337677001953
# This is with Python 3.5 so it's using cPickle

As a comparison msgpack is faster on the dense version
df = dfs.to_dense()
start = time.time()
# serialization
msg = list(df.to_msgpack(compress='zlib'))
# deserialization
df = pd.read_msgpack(bytes(msg))
stop = time.time()
stop - start
# 0.09514737129211426

msgpack
Msgpack would be the answer but I can't find an implementation for SparseDataFrame (related)
# serialization
dfs.to_msgpack(compress='zlib')
# Returns: NotImplementedError: msgpack sparse frame is not implemented

coordinate format
msgpack on a coordinate format via scipy.sparse.coo_matrix seems to be worth considering but conversion to python.sparse.coo_matrix is slow
from scipy.sparse import coo_matrix
start = time.time()

# serialization
columns = dfs.columns
shape = dfs.shape
start_to_coo = time.time()
dfc = dfs.to_coo()
stop_to_coo = time.time()
start_comprehension = time.time()
row = [x.item() for x in df.row]
col = [x.item() for x in df.col]
data = [x.item() for x in df.data]
stop_comprehension = time.time()
start_packing = time.time()
msg = list(msgpack.packb({'columns':list(columns), 'shape':shape, 'row':row, 'col':col, 'data':data}))
stop_packing = time.time()

# deserialization
start_unpacking = time.time()
dict = msgpack.unpackb(bytes(msg))
stop_unpacking = time.time()
columns=dict[b'columns']
index=range(dict[b'shape'][0])
dfc = coo_matrix((dict[b'data'], (dict[b'row'], dict[b'col'])), shape=dict[b'shape'])

stop = time.time()
print('total: ' + str(stop - start))
print('  to_coo: ' + str(stop_to_coo - start_to_coo))
print('  comprehension: ' + str(stop_comprehension - start_comprehension))
print('  packing: ' + str(stop_packing - start_packing))
print('  unpacking: ' + str(stop_unpacking - start_unpacking))

#total: 0.2799222469329834
#  to_coo:               0.22925591468811035
#  comprehension & cast: 0.02356100082397461 (msgpack does not support all numpy formats)
#  packing:              0.004893064498901367
#  unpacking:            0.001984834671020508

From there it seems one needs to go through a dense format.
start = time.time()
dfs = pd.SparseDataFrame(dfc.toarray())
stop = time.time()
stop - start
# 2.8947737216949463

A: The overhead in time stems from the string handling in dumps and loads.
Using dumps/loads:
def pickle_dumps():
    msg = list(pickle.dumps(dfs, protocol=pickle.HIGHEST_PROTOCOL))
    pickle.loads(bytes(msg))

%timeit pickle_dumps()
# 212 ms ± 2.19 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

Using dump/load:
def pickle_file():
    with open('dump.pickle', 'wb') as f:
        pickle.dump(dfs, f, protocol=pickle.HIGHEST_PROTOCOL)

    with open('dump.pickle', 'rb') as f:
        return pickle.load(f)

%timeit pickle_file()
# 82.7 ms ± 1.25 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Or even shorter using pandas builtins:
def to_pickle():
    dfs.to_pickle('./dump.pickle')
    pd.read_pickle('./dump.pickle')

%timeit to_pickle()
# 86.8 ms ± 1.54 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

A: There were problems with my tests
dfs = pd.SparseDataFrame(scipy.sparse.random(1000, 1000).toarray())

doesn't really store a sparse representation. Instead
dfs = pd.DataFrame(scipy.sparse.random(1000, 1000).toarray()).to_sparse(fill_value=0)

does.
After this, pickle on the sparse representation performs better than msgpack on the dense representation.
In addition, I used df.row instead of dfc.row. df pointed to a different dataframe. msgpack probably had the result in cache and didn't do anything.
After correcting this error, msgpack on the coo_matrix-based representation doesn't improve over pickle on the dataframe.


text:
Q: How to open hyperlinks in a new tab/window The default behaviour of PDF.js is to open hyperlinks in the existing window. However, this may not be the desired outcome at all times. How can we open hyperlinks in a new window/tab and override the default behaviour?

A: There's a property called PDFJS.externalLinkTarget. This is set to NONE by default. Set this to BLANK and target='_blank' attributes are added to all anchors. That will open your hyperlinks in a new tab/window.
Possible values:

*

*NONE [default]

*SELF

*BLANK

*PARENT

*TOP

Docs

A: In build/pdf.js, replace the line below:
target: data.newWindow ? _display_utils.LinkTarget.BLANK : linkService.externalLinkTarget,

With this one:
target: _display_utils.LinkTarget.BLANK,

And then all links will always open in a new tab. I suppose you could pass it as a parameter. I never looked into how, because I wanted it to be permanent anyway, so hard-coded it.


text:
Q: onUpgrade() sqlite database in Android I created an Android application which, check at startup if there is a new version of application. If yes, the application download the new apk file and over-install new apk.
My application use the sqlite db. But this db, from one version to other can change.
I think I have to use the method:
 onUpgrade()

but I don't know exactly how to use it.
When I start the application I use this code for crete database(if not exists):
DbHelper mDHelper = new DbHelper(context, DB_NAME, null, DB_VERSION)

What should I change if I want use onUpgrade() method?
And when do I have to call it?

A: if your are using the SQLiteOpenHelper the onUpgrade will be called whenever you change the DB version.
There is an additional requirement for this to work. The db name has to remain the same.
Old Version:
dbName = "mydb.db"
dbVersion = 1

New Version:
dbName = "mydb.db"
dbVersion = 2

in the onCreate of the content provider you create an instance of the SQLiteOpenHelper that takes these params. Your SQLiteOpenHelper implementation would look like this:
public static final class MySQLiteOpenHelper extends SQLiteOpenHelper {

        public MySQLiteOpenHelper(Context context, int dbVersion, String dbName) {
            super(context, dbName, null, dbVersion);
        }

        @Override
        public void onCreate(SQLiteDatabase db) {
            //Code to create your db here
        }

        @Override
        public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
            // Code to upgrade your db here
        }

}

it will be also called when you alter you table or add more tables in your database

A: I found this very helpful
https://thebhwgroup.com/blog/how-android-sqlite-onupgrade
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
    if (oldVersion < 2) {
         db.execSQL(DATABASE_ALTER_TEAM_1);
    }
    if (oldVersion < 3) {
         db.execSQL(DATABASE_ALTER_TEAM_2);
    }
}

A: onUpgrade() is called (you do not call it yourself) when version of your DB changed which means underlying table structure changed etc.
In general it means that OS is telling you "hey, you asked for database structure version 10 but I found we got something older here, so this is you chance to fix that before you start using database (and potentially crash due to structure mismatch)".
In that method you should do all that is necessary to, well.. upgrade structure of your old database to structure matching current version requirements like adding/droping columns, converting row contents or even dropping old db completely and create it from scratch - for Android it does not matter what you do here - it's just a sort of emergency callback for your code to do the necessary job (if any). You need to be aware that users may not update frequently so you have to always handle upgrade from version X to Y knowing that X may not be equal to i.e. (Y-1).


text:
Q: What can be said about a class of incidence structures closed under duals and complements? Note that I do not work in combinatorics, and so this question might be a bit naive. The question is inspired by some structures that arise in my research within representation theory.
Recall that an incidence structure consists of a triple $(P,L,I)$ where $P$ is a set of points, $L$ is a set of lines and $I$ is a relation between them.
The dual of an incidence structure $(P,L,I)$ is $(L,P,I)$, i.e. we interchange the roles of points and lines but keep the same incidence relation.
From an incidence structure $(P,L,I)$ we can get a bipartite graph, its incidence graph, by setting $G = (P \cup L, E)$ with $(p,l) \in E$ whenever $p$ is incident with $l$ for $p \in P$ and $l \in L$.
Similarly, any bipartite graph $G$ yields an incidence structure. The complement of an incidence structure is that corresponding to the bipartite complement of its incidence graph (i.e. the complement of the incidence graph in the appropriate complete bipartite graph).
Finally, call an incidence structure connected if its incidence graph is connected.
I am interested in a class of incidences structures that is closed under duals and complements, is connected and satisfies that each point is incident with at least two lines, and that for the set of lines incident with a point, there is some point $p$ such that some subset of those lines are not incident with $p$.
Moreover, for every point $p$ there is no other point incident with all the lines $p$ is incident with.
Of course, since such a class is closed under duals, the latter conditions must hold with "point" and "line" interchanged everywhere, too. Similarly, because of the closure under complements, there are more conditions that need to be satisfied derived from the ones already given.
There may be more conditions that we have not yet been able to determine, and here are some examples of structures that work and don't work.
The class should include as examples the following:

*

*the Fano plane;

*the generalized quadrangles corresponding to the 2x2 and 3x3 grids, i.e. GQ(1,1) and GQ(2,1);

*the smallest Benz plane (i.e. the trivial 3-(5,3,1) design given by all subsets of cardinality 3 of a 5 element set); and

*all of their complements and duals.

Non-examples should include:

*

*the projective plane over GF(3);

*the affine plane over GF(2);

*the generalized hexagon GH(1,2); and

*the Doily GQ(2,2).

I was wondering if incidence structures satisfying these or similar properties were studied in some context, and if the examples and non-examples that I give are consistent with some already known class of structures. I should add that closure under complements is observed in examples, but we have not been able to show that it must hold.


text:
Q: Full calendar fit to container and hide scroll I cannot figure out how to scale fullcalendar to fit to it's parent container. I want to display week view on a single page for users without need to scroll (So they quickly review items for a week).
I'm ok if I need to make text small, slots height smaller, etc, but I just not sure how to do this dynamically based on the size of the browser window.
(In my calendar I'm using slotMinutes:10 and times from 8am to 10pm)
jsfiddle with fullcalendar: http://jsfiddle.net/bQXYp/27/

A: There are several factors to be considered.
If you want to stick to having slotMinutes set to 10, then it is going to be quite difficult to fit time ranges from 8 AM to 10 PM on to the page without manually hacking the font size to be almost illegible.
If you are okay with increasing the slotMinutes attribute to something like 30 or even 60, you have a pretty good chance of getting your weekly view showing up without the need to scroll.
Apart from that, there are two properties you could use to influence the dimensions of the calendar. The first one is height. However this sets a pixel value which does not scale dynamically. The second one is aspectRatio which allows to the define the ratio of width to height. In other words, aspectRatio value of 2 means that it will try and stretch the height to be double that of the width (if at all that amount of height is needed).
I have set up an example here that shows you the effect of having a reasonable slotMinutes value. In my opinion, this is what will be most important to be able to achieve what you need.

A: I use it in list view to show all upcoming events. I added to my own CSS-
.fc-scroller {
height: auto!important;
overflow-y: auto;

A: i just solved my problem with below code
.fc-day-grid-container.fc-scroller {
    height: auto!important;
    overflow-y: auto;
}

A: Hi i am using two views ( month and agendaDay ) and when i switch to day view i change contentHeight like so:
viewDisplay: function(view) {
       //alert(view.name)
            if(view.name == 'agendaDay')
            {
                $('#calendar').fullCalendar('option', 'contentHeight', 700);
            }else{
                $('#calendar').fullCalendar('option', 'contentHeight', 200);
   }
 }

Maybe it can give some direction for what you want to do ;)

A: Try the contentHeight property:
http://arshaw.com/fullcalendar/docs/display/contentHeight/
With your desired minTime and maxTime this removes the vertical scroll bar on the content area of the FullCalendar in that jsfiddle example:
contentHeight: 1850,
minTime: '8',
maxTime: '22',

(But be sure not to set aspectRatio as that seems to over-ride the contentHeight)
Although as Karancan mentions to fit to one screen without scrolling you'll need to reduce the font size to an almost unreadable size.
(and if you're using IE8 then you may have other issues with the height..)

A: This worked for me too.
I opened the fullcalendar.css and scrolled to fc-scroller.
Added the height and changed the overflow-y option as was suggested.
And the calendar month view worked 100%


text:
Q: Is it mandatory to install WALinuxAgent? I'm creating a custom vhd image to make it available in azure market place. Its an inbuild centos 7 machine and I want to load it as an image. Is it mandatory to have WALinuxAgent agent to be installed as part of the image? Here is the documentation which says to install it https://learn.microsoft.com/en-us/azure/virtual-machines/linux/create-upload-centos#centos-70. I want to exclude that package from the image. Is that okay to do that ?

A: You do need it, otherwise the VM may not boot. This agent communicates with the Azure fabric to provide VM status amongst other things. You can find more information about it here: https://github.com/Azure/WALinuxAgent


text:
Q: Visual Basic Read from Keyboard I am trying to implement a simple calculation to output Total Price using Visual Basic.NET
I want to read Original Price and Shipping Weight then use it in the calculation. The problem is,
When I enter any values, both variables will return only first digit
For example, if enter 23 it will return 2
    Dim originalPrice As Double
    Dim commissionPrice As Double
    Dim shippingWeight As Double
    Dim totalPrice As Double

    Console.Write("Enter Original Price: ")
    originalPrice = Double.Parse(Console.ReadLine(originalPrice))

    Console.Write("Enter Shipping Weight: ")
    shippingWeight = Double.Parse(Console.ReadLine(shippingWeight))
    shippingWeight = shippingWeight * 7

    If (originalPrice + shippingWeight >= 200) Then
        commissionPrice = (originalPrice + shippingWeight) * 0.03
    Else
        commissionPrice = 5
    End If

    totalPrice = commissionPrice + originalPrice + shippingWeight

    Console.WriteLine(originalPrice)
    Console.WriteLine(commissionPrice)
    Console.WriteLine(shippingWeight)
    Console.WriteLine(totalPrice)

A: I think that your problem is that you are passing the variable to the Console.read()
In this way should work.
    Dim originalPrice As Double
    Dim commissionPrice As Double
    Dim shippingWeight As Double
    Dim totalPrice As Double

    Console.Write("Enter Original Price: ")
    originalPrice = Double.Parse(Console.ReadLine())

    Console.Write("Enter Shipping Weight: ")
    shippingWeight = Double.Parse(Console.ReadLine())
    shippingWeight = shippingWeight * 7

    If (originalPrice + shippingWeight >= 200) Then
        commissionPrice = (originalPrice + shippingWeight) * 0.03
    Else
        commissionPrice = 5
    End If

    totalPrice = commissionPrice + originalPrice + shippingWeight

    Console.WriteLine(originalPrice)
    Console.WriteLine(commissionPrice)
    Console.WriteLine(shippingWeight)
    Console.WriteLine(totalPrice)

    Console.Read()


text:
Q: create and display a powershell object with 2 columns with 15 lines from a file .txt I want to create and display a powershell object with two columns (two properties: np and date) with 15 lines from a file "test.txt".

1   21/05/20
2   21/05/20
3   21/05/20
4   21/05/20
5   21/05/20
6   21/05/20
7   21/05/20
8   21/05/20
9   21/05/20
10  21/05/20
11  21/05/20
12  21/05/20
13  21/05/20
14  21/05/20
15  21/05/20

Here is my code:
$path1="C:\content1\test.txt"
$tableau = Get-Content $path1

Foreach($valeur in $tableau) {
    # trim spaces at beginning and end

    $valeur = $valeur.trim()

    # insert , at specific places for ConvertFrom-CSV command

    $valeur = $valeur.insert(2,",")

    $valeur = $valeur -replace "\s+",""
    $Object = $valeur | ConvertFrom-Csv -Header 'np', 'date'
}

$Object

The output of my code is:

np date
-- ----
15 21/05/20

I have only the last line in my object $Object whereas I want the 15 lines of my .txt file.

A: In each turn of the foreach-loop you set $Object, thus overwriting the previous value.
Move the last line inside the loop and you will get the values.
$path1="C:\content1\test.txt"
$tableau =Get-Content $path1

Foreach($valeur in $tableau){ # trim spaces at beginning and end

$valeur= $valeur.trim()

# insert , at specific places for ConvertFrom-CSV command

$valeur=$valeur.insert(2,",")

  $valeur=$valeur -replace "\s+",""
  $Object =$valeur | ConvertFrom-Csv -Header 'np', 'date'
$Object
}

A: You can directly assign the output of foreach to variable $object like this:
$path1="C:\content1\test.txt"
$tableau = Get-Content $path1

$object = Foreach($valeur in $tableau) {
    # trim spaces at beginning and end

    $valeur = $valeur.trim()

    # insert , at specific places for ConvertFrom-CSV command

    $valeur = $valeur.insert(2,",")

    $valeur = $valeur -replace "\s+",""
    $valeur | ConvertFrom-Csv -Header 'np', 'date'
}

Looks strange, but it is a common pattern in PowerShell (e. g. you can also assign from output of other control blocks like if and switch).
This works similar to assigning output of a pipeline to a variable. The output of ConvertFrom-Csv gets captured automatically and added to the array that PowerShell builds up and finally assigns to $object.

A: How about just this...
$RecordList = (Get-Content 'D:\Temp\TestFile.txt'|
Select-Object -First 16) -replace "\s+","," |
ConvertFrom-Csv -Header np, date
# Results
<#
np date
-- ----
1  21/05/20
2  21/05/20
3  21/05/20
...
#>

 $RecordList.np
# Results
<#
1
2
3
...
#>

 $RecordList.date
 # Results
<#
21/05/20
21/05/20
21/05/20
...
#>

Or

(Get-Content 'D:\Temp\TestFile.txt'|
Select-Object -First 16) -replace "\s+","," |
ForEach {
    [pscustomobject]@{
        np   = ($PSItem -split ',')[0]
        date = ($PSItem -split ',')[1]
    }

}
# Results
<#
np date
-- ----
1  21/05/20
2  21/05/20
3  21/05/20
...
#>


text:
Q: Recursive aggregate type configured using many template parameters using std::index_sequence There is a class template:
template<std::size_t ID, std::size_t T1, std::size_t T2, std::size_t T3>
class Feature { /* Implementation goes here */ };

All the instantiations of Feature<...> are 'collected' here:
template<typename FEATURE, typename... OTHERS>
class Features<FEATURE, OTHERS...> : public Features<OTHERS...> {
public:
    /* Operations defined here */
private:
    FEATURE m_feature;
};

All the features are created as follows:
using FeatureConfig = Features<Feature<0, 1, 2, 3>, Feature<1, 4, 5, 6>>;
FeatureConfig m_features;

So far so good. My task is to get rid of those hard coded values in there 1..3, 4..6 etc. The way to do so is to have generated header file which contains the configuration for all the features. Something like:
template<std::size_t> struct Config;

template<>
struct Config<0> {
    static constexpr std::size_t t1 { 1 };
    static constexpr std::size_t t2 { 2 };
    static constexpr std::size_t t3 { 3 };
};

template<>
struct Config<1> {
    static constexpr std::size_t t1 { 4 };
    static constexpr std::size_t t2 { 5 };
    static constexpr std::size_t t3 { 6 };
};

Then I need to change type definition of FeatureConfig somehow to use the specializations of FeatureConfig based on an index (0, 1, ...). My unsuccessfull try is:
template<std::size_t... INDEX_SEQUENCE>
using FeatureConfig = Features<Feature<INDEX_SEQUENCE, Config<INDEX_SEQUENCE>::t1, Config<INDEX_SEQUENCE>::t2, Config<INDEX_SEQUENCE>::t3>...>;

FeatureConfig<std::make_index_sequence<2>> m_features;

It seems I am somehow mixing type and value...
Many thanks in advance to anyone willing to help me fix the incorrect code in my last listing up there.
Cheers Martin

A: If I understand correctly what do you want...
I propose the declaration (no definition required because is used only inside a decltype()) of the following function
template <std::size_t ... Is>
auto getFeaturesType (std::index_sequence<Is...>)
   -> Features<Feature<Is, Config<Is>::t1, Config<Is>::t2, Config<Is>::t3>...>;

Now you can define FeatureConfig simply as follows
template <std::size_t N>
using FeatureConfig
   = decltype(getFeaturesType(std::make_index_sequence<N>{}));

The following is a full compiling (simplified) example
#include <type_traits>
#include <utility>

template <std::size_t, std::size_t, std::size_t, std::size_t>
struct Feature { };

template <typename...>
struct Features
 { };

template <typename F, typename... Os>
struct Features<F, Os...> : public Features<Os...>
 { F m_feature; };

template <std::size_t N>
struct Config
 {
   static constexpr std::size_t t1 { N*3u };
   static constexpr std::size_t t2 { 1u + N*3u };
   static constexpr std::size_t t3 { 2u + N*3u };
 };

template <std::size_t ... Is>
auto getFeaturesType (std::index_sequence<Is...>)
   -> Features<Feature<Is, Config<Is>::t1, Config<Is>::t2, Config<Is>::t3>...>;

template <std::size_t N>
using FeatureConfig
   = decltype(getFeaturesType(std::make_index_sequence<N>{}));

int main ()
 {
   using T1 = FeatureConfig<2u>;
   using T2 = Features<Feature<0u, 0u, 1u, 2u>, Feature<1u, 3u, 4u, 5u>>;

   static_assert( std::is_same<T1, T2>::value, "!" );
 }

If I understand correctly how do you use Config (if t1 is ever N*3u, if if t2 is ever 1u+N*3u and if t3 is ever 2u+N*3u), you can avoid Config at all and write getFeaturesType as follows
template <std::size_t ... Is>
auto getFeaturesType (std::index_sequence<Is...>)
   -> Features<Feature<Is, Is*3u, Is*3u+1u, Is*3u+2u>...>;


text:
Q: Python Script Working in Jupyter But Not Command Line, listdir error I have a Python script where if the hash is available (checks against a csv full of hashes and file paths, then adds columns to the data frame), then I want to move a file to a new location.
I'm getting an issue in my script where my path is coming out as a float, when it should be a string. In my jupyter notebook, when I do print(type(path)) the output is <class 'str'> but when I do print(type(path)) in my script when I run it on the command line, it returns <class 'float'>.
When I run the full script, I get the error below:
Error
Traceback (most recent call last):
  File "compare_hashes_to_image_hashes.py", line 82, in <module>
    for source_filename in os.listdir(path):
TypeError: listdir: path should be string, bytes, os.PathLike, integer or None, not float

Why is it working in my jupyter notebook, but not in my script?
Script (sections relevant to issue)
#!/usr/bin/python36

import os
import shutil

# make columns into lists
users = list(master_df['USER_JID'])
avails = list(master_df['HASH_AVAILABLE'])
paths = list(df_merged['FILE_PATH'])
hashes = list(df_merged['SHA1_BASE16'])

# define source location and destination location
destination = "/opt/PhotoTips/input/"
source_img = "/opt/PhotoTips/hash_images/"

"""
Move images to appropriate user img folders
"""

# for every value in available list
for i in range(len(avails)):
    # each value in user list is a user
    user = users[i]
    # each value in path list is a path
    path = paths[i]
    # each value in hash value list is a hash
    hash_val = hashes[i]
    # build full location
    location = destination + user + '/img'
    # if hash image is available
    if 'Available' in avails[i]:
        # debug purposes
        # print(type(path)) # returns <class 'float'>
        # suggested by marklap
        # if isinstance(path, float):
            # print(path)
            # returns nan
        for source_filename in os.listdir(path):   <---- line with the issue
            # confirm text file for match
            if source_filename.startswith(hash_val):
                # build full path
                source_file_path = os.path.join(path, source_filename)
                # copy image to appropriate user location
                shutil.copy(source_file_path, location)
    # if hash image is NOT available
    else:
        # do nothing
        pass


text:
Q: How to use local.xml to insert a block in Magento 1.8? How can I use loca.xml to insert a block?
I want to insert the static block (identifier: footer_links) from the cms into this footer block inside my page.xml, but before footer_links,
<block type="core/template" name="bottom.footer" as="bottom.footer" template="page/html/footer-bottom.phtml">
   <block type="page/switch" name="store_switcher" as="store_switcher" template="page/switch/stores.phtml"/>
   <block type="page/template_links" name="footer_links" as="footer_links" template="page/template/links.phtml"/>
</block>

this is the config in my local.xml,
<block type="cms/block" name="cms_footer_links" before="footer_links">
 <!--
                The content of this block is taken from the database by its block_id.
                You can manage it in admin CMS -> Static Blocks
            -->
<action method="setBlockId"><block_id>footer_links</block_id></action>
</block>

is it possible?

A: answer,
<reference name="footer">
        <block type="cms/block" name="cms_footer_links" before="footer_links">
            <action method="setBlockId">
                <block_id>footer_links</block_id>
            </action>
        </block>
    </reference>


text:
Q: Multiple VideoCapture on one camera I might have more than one VideoCapture for a Camera. Unfortunately sometimes the connection to the camera seems to get terminated.
Example:
Mat img;
VideoCapture v1(0);
v1.read(img);      //img is a valid picture
VideoCapture v2(0);
v1.read(img);      //img is a valid picture
v2.read(img);      //img is a valid picture
v2 = v1;
v2.read(img);      //img is not a valid picture. Connection seems to be closed

Is this correct behaviour, or is it a bug in OpenCV?
Is there a way to check if a particular devicenumber is already open and get the responsible class?
Pseudocode:
Mat img;
VideoCapture v1(0);
VideoCapture v2 = alreadyOpen(0);

alreadyOpen(0){
    if(VideoCapture(0).isOpen()){ //how do i check that
        return "v1"               //how do i know where v1 is
    }else{
        return VideoCapture(0);
    }
}

A: See Comments:
It's not possible, it might be a bug/not clear if the behavior of OpenCV is intentional.


text:
Q: Evaluating laplace transform of {x} I came upon a question on Laplace transforms in my exams.
$${\scr L}[\{x\}]$$
where $\{x\}=x - [x]$ denotes the fractional part of $x$.
This is how I approached the problem.
$$f(x)=\{x\}=\sum_{n=-\infty}^\infty{(x-n)(u_n(x)-u_{n+1}(x))}$$
where $u_a(x)$ denotes the Heaviside function shifted to $x=a$.
$$\implies \scr L[f(x)]=\sum_{n=-\infty}^\infty{e^{-ns}\scr L[x-n]} - e^{-(n+1)s}\scr L[x-n]$$
$$=\sum_{n=-\infty}^\infty{\frac{e^{-ns}-e^{-(n+1)s}}{s^2}-\frac{n(e^{-ns}-e^{-(n+1)s})}{s}}$$
$$=\sum_{n=-\infty}^\infty{\frac{e^{-ns}-e^{-(n+1)s}}{s}\left(\frac{1}{s}-n\right)}$$
Is the way I approached the problem correct? I noticed that the last summation is a telescopic series which results in a $e^{\infty s}$ term which is making me doubtful. I've checked the procedure multiple times, and the vanishing property seems to hold too, but still, I'm not sure what to make of the telescopic series term.
So, in short, I need an experienced look on my method and tell me if I went wrong somewhere. Thanks in advance.

A:
You almost have it correct, but it appears that you are trying to take the bilateral Laplace Transform of $\{x\}$, which doesn't exist.
If you take the unilateral Laplace Transform, then the summation extends form $n=0$ to $\infty$.
Also, note that for $f_n(x)=(x-\lfloor x\rfloor)(u_n(x)-u_{n+1}(x))=(x-n)(u_n(x)-u_{n+1}(x))$, we have
$$\begin{align}
\sum_{n=0}^\infty\mathscr{L}\{ f_n\}(s)&=\sum_{n=0}^\infty \left(e^{-ns}\mathscr{L}\{x\}(s)-e^{-(n+1)s}\mathscr{L}\{x+1\}(s)\right)\\\\
&=\sum_{n=0}^\infty\left(e^{-ns}\mathscr{L}\{x\}(s)-e^{-(n+1)s}\mathscr{L}\{x+1\}(s) \right)\\\\
&=\sum_{n=0}^\infty\left(\frac{e^{-ns}-e^{-(n+1)s}}{s^2}-\frac{e^{-(n+1)s}}{s}\right)
\end{align}$$
which is not quite what you have.

Here is how I would suggest to proceed.  Let $f(x)=\{x\}$.  Then, the Laplace Transform of $f$ is given by
$$\begin{align}
\mathscr{L}\{f\}(s)&=\int_0^\infty \{x\}e^{-sx}\,dx\\\\
&=\int_0^\infty \left(x-\lfloor x\rfloor\right)e^{-sx}\,dx\\\\
&=\frac1{s^2}-\int_0^\infty \lfloor x\rfloor e^{-sx}\,dx\\\\
&=\frac1{s^2}-\sum_{n=0}^\infty \int_{n}^{n+1}\lfloor x\rfloor e^{-sx}\,dx\\\\
&=\frac1{s^2}-\sum_{n=0}^\infty ne^{-ns}\int_{0}^{1}  e^{-sx}\,dx\\\\
&=\frac1{s^2}-\left(\frac{1-e^{-s}}{s}\right)\sum_{n=0}^\infty ne^{-ns}\\\\
&=\frac1{s^2}-\left(\frac{1-e^{-s}}s\right)\frac{e^{-s}}{(1-e^{-s})^2}\\\\
&=\frac1{s^2}-\frac{e^{-s}}{s(1-e^{-s})}\\\\
&=\frac1{s^2}-\frac{e^{-s/2}}{s(e^{s/2}-e^{-s/2})}\\\\
&=\frac1{s^2}+\frac1{2s}-\frac{\coth(s/2)}{2s}
\end{align}$$

A: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
There is a serie representation of $\ds{\braces{x}}$. Namely,
$$
\braces{x} = {1 \over 2} - {1 \over \pi}\sum_{k = 1}^{\infty}
{\sin\pars{2\pi kx} \over k}
$$
Then,
\begin{align}
\int_{0}^{\infty}\braces{x}\expo{-xs}\,\dd x & =
{1 \over 2s} -
{1 \over \pi}\sum_{k = 1}^{\infty}{1 \over k}\
\overbrace{\int_{0}^{\infty}\sin\pars{2\pi k x}\expo{-sx}\,\dd x}
^{\ds{2\pi k \over 4\pi^{2}k^{2} + s^{2}}}
\\[5mm] & =
{1 \over 2s} - {1 \over 2\pi^{2}}\sum_{k = 1}^{\infty}
{1 \over k^{2} + \bracks{s/\pars{2\pi}}^{2}}
\\[5mm] & =
{1 \over 2s} - {1 \over 2\pi^{2}}\sum_{k = 0}^{\infty}
{1 \over
\bracks{k + 1 - \ic s/\pars{2\pi}}\bracks{k + 1 + \ic s/\pars{2\pi}}}
\\[5mm] & =
{1 \over 2s} - {1 \over 2\pi^{2}}
{\Psi\pars{1 + \ic s/\bracks{2\pi}} -
\Psi\pars{1 - \ic s/\bracks{2\pi}} \over \ic s/\pi}
\\[5mm] & =
{1 \over 2s} - {1 \over \pi s}\,\Im\,\Psi\pars{1 + \ic\,{s \over 2\pi}}
\\[5mm] & =
{1 \over 2s} - {1 \over \pi s}
\bracks{-\,{1 \over 2}\,{1 \over s/\pars{2\pi}} +
{1 \over 2}\,\pi\coth\pars{\pi\,{s \over 2\pi}}}
\\[5mm] & =
\bbox[15px,#ffd,border:1px solid navy]{{1 \over 2s} + {1 \over s^{2}} - {1 \over 2s}\coth\pars{s \over 2}}
\end{align}


text:
Q: Does Star-Lord ever go back to earth? In the Marvel Cinematic Universe, did Star-Lord ever go back to earth, following his capture by the Ravagers?
He had his own space ship, The Milano, so he is presumably capable of returning to earth.
If he doesn't go back, is there any reason why he's prevented from or chooses not to, even for a visit?
In the comics, everyone was prevented from interfering with earth, but I don't think there's any reference to this decree in the film.

A: This certainly is not canonical and certainly not definitive, but there are few clues as to why I think he has been back to earth.

*

*Has a wood paneled tape player that is not the one he was listeniing too when he was abducted.

*References Pulp Fiction and Jackson Pollack

*Peter's Ship has other earth things that are too many to keep in a backpack.

However, it certainly is not beyond the realm that Yondu collected those items with his trip to earth and gave them to Peter. Or that Peter could have picked up some sort of broad cast that showed him the culture over the last 20 years.


text:
Q: Filter out sub-array items that contain a specific key/value pair I want to use jq to filter out sub-array items that contain a specific key/value pair without filtering out the non-array data.
Input:
{
  "log": {
    "foo": {
      ...
    },
    "entries": [
      {
        "request": {
          "method": "OPTIONS",
          "url": "http://www.foobar.com"
        }
      },
      {
        "request": {
          "method": "GET",
          "url": "http://www.foobar.com"
        }
      }
    ]
  }
}

Desired output:
{
  "log": {
    "foo": {
      ...
    },
    "entries": [
      {
        "request": {
          "method": "GET",
          "url": "http://www.foobar.com"
        }
      }
    ]
  }
}

I have tried this:
jq '(.log.entries[] | select(.request.method != "OPTIONS"))'

But then I lose the all of the JSON data above entries.

A: Use |= assignment operator for modifying sub-elements in-place, e.g:
.log.entries |= map(select(.request.method != "OPTIONS"))

A: Directly use the del() operation on the object that matches your condition
del(.log.entries[] | select(.request.method == "OPTIONS"))


text:
Q: Query to find random 5 users that current_user isn't following I've done my due diligence and haven't been able to figure out this problem.
I'm trying to find a random set of 5 users, that (1) cannot be the current_user and (2) cannot already be followed by the current_user.
I'm trying to put this into the variable @users. My relationships are set up where Users have followed_users (which are the users they are following), and Users have followers.
User model
has_many :relationships, foreign_key: "follower_id", :dependent => :destroy
has_many :followed_users, through: :relationships, source: :followed
has_many :reverse_relationships, foreign_key: "followed_id",
                                  class_name: "Relationship",
                                   dependent: :destroy
has_many :followers, through: :reverse_relationships, source: :follower

Relationship model
belongs_to :follower, class_name: "User", touch: true
belongs_to :followed, class_name: "User", touch: true

Unfortunately, I'm terrible at queries so I'm not sure how to find this array of users. On top of a solution that one of you would implement, any resources where I can learn on my own how to do queries efficiently would be really appreciated.
If you  need any more code to help solve the problem, please let me know.
Thanks

A: This might work for you:
User.includes(:reverse_relationships)
    .where("#{Relationship.table_name}.follower_id <> :id", id: current_user.id)
    .where("users.id <> ?", current_user.id)
    .order("RAND()")
    .limit(5)

Not sure about the RAND() function, it depends on your DB.
Eventually replace the id <> :id with id NOT IN (?) to be able to pass more than just one id:
scope :some_other_users, lambda { |user_ids|
  user_ids = user_ids.kind_of?(Array) ? user_ids : [user_ids]
  includes(:reverse_relationships)
    .where("#{Relationship.table_name}.follower_id NOT IN (?)", user_ids)
    .where("users.id NOT IN (?)", user_ids)
    .order("RAND()")
    .limit(5)
}

query_getting_followed_user_ids = Relationship.where("follower_id IN (?)", [current_user.id]).select("relationships.followed_id").to_sql
User.where("id NOT IN (#{query_getting_followed_user_ids})")
    .where("id <> ?", current_user.id)
    .order("RAND()")
    .limit(5)

As you can see, I want to make a query on the result of an other query: Query-ception!


text:
Q: ARIMA model Prediction Vs Actual differences I have daily sales data for the year 2018 and have run through ARIMA modeling by applying grid search(for loops), got optimal values like (0,1,2) and RMSE value 61.562.
My Naive Forecast model RMSE value(126.39) is lesser than ARIMA RMSE(61.562), so I believe the ARIMA model is doing good?
Am having trouble in understanding the differences between predicted vs expected values of ARIMA and wanted to know whether a model performer well or not and differences are acceptable.
Have attached screenshot of ARIMA test & prediction plot.

Output of ARIMA
Train Set Lenght: 736
Test Set Lenght: 380
>Predicted=15.584, Expected= 20
>Predicted=18.602, Expected= 10
>Predicted=14.051, Expected= 30
>Predicted=22.576, Expected= 60
>Predicted=34.849, Expected= 10
>Predicted=16.423, Expected= 50
>Predicted=35.823, Expected= 54
>Predicted=36.277, Expected=  6
>Predicted=19.700, Expected= 35
>Predicted=32.607, Expected=  1
>Predicted=16.107, Expected= 36
>Predicted=31.214, Expected= 20
>Predicted=22.272, Expected=  4
>Predicted=17.035, Expected=  4
>Predicted=15.497, Expected=  8
>Predicted=15.150, Expected=  3
>Predicted=11.664, Expected=  3
>Predicted=10.629, Expected=  3
>Predicted=9.278, Expected=  3
>Predicted=8.268, Expected=  4
>Predicted=7.810, Expected=  4
>Predicted=7.114, Expected=  4
>Predicted=6.610, Expected=  4
>Predicted=6.168, Expected=  2
>Predicted=4.964, Expected= 12
>Predicted=8.790, Expected= 16

ARIMA Code snippet
train_series=north_top_painter_df["Volume"].values
train_size = int(len(train_series) * 0.66)
x_train, x_test = train_series[0:train_size], train_series[train_size:]
print('Train Set Lenght:',len(x_train))
print('Test Set Lenght:',len(x_test))
# walk-forward validation
history = [i for i in x_train]
predictions = list()

for i in range(len(x_test)):
  # predict
  model = ARIMA(history, order=(0,1,2))
  model_fit = model.fit(disp=0)
  #y_pred=model_fit.predict(start=len(train), end=len(train)+len(test)-1, dynamic=False)
  y_pred = model_fit.forecast()[0]
  predictions.append(y_pred)
  #observation
  test_obs = x_test[i]
  history.append(test_obs)
  print('>Predicted=%.3f, Expected=%3.f' % (y_pred, test_obs))
# report performance
rmse = sqrt(mean_squared_error(x_test, predictions))
print('RMSE: %.3f' % rmse)
plt.plot(x_test, label = "Test",color='blue')
#plt.plot(y_pred)
plt.plot(predictions, color = 'red', label = "Predict")
plt.legend(loc='best')
plt.show()


text:
Q: Wiring a UserServiceFactory of Google AppEngine using Spring I wanted to wire the Google App Engine user service in Spring by first creating a UserServiceFactory bean and then using that to get an instance of UserService.
<bean id="googleUserServiceFactory"
      class="com.google.appengine.api.users.UserServiceFactory"></bean>

<bean id="googleUserService"
      class="com.google.appengine.api.users.UserService"
      factory-bean="googleUserServiceFactory"
      factory-method="getUserService"></bean>

I am quite sure this is the right way to wire a bean which you get from a factory but I get this error:

Error creating bean with name 'googleUserService' defined in ServletContext resource [/WEB-INF/hardwire-service.xml]: No matching factory method found: factory bean 'googleUserServiceFactory'; factory method 'getUserService'

It says that the factory method cannot be found. Can it be that the factory method name has changed?

A: I got this to work by using a MethodInvokingFactoryBean instead. It still bugs me to think what's wrong with what I did earlier. Anyway:
<bean id="googleUserService"
      class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">

       <property name="staticMethod"
                 value="com.google.appengine.api.users.
                            UserServiceFactory.getUserService">
       </property>
</bean>

A: you can also do this:
@Configuration
public class AppConfig {

    @Bean
    public UserService userService() {
        return UserServiceFactory.getUserService();
    }


text:
Q: $\widetilde{H}^n(X,\Bbb Z_p)=0$ for all $n$, odd primes $p$ implies $\widetilde{ H}^n(X,\Bbb Z)$ consists entirely of elements of order a power of $2$ Let $X$ be a CW complex with finitely generated homology groups. We know that from the universal coefficient theorem(UCT) that $$H^n(X;G)\cong \textrm{Ext}(H_{n-1}(X),G)\oplus \textrm{Hom}(H_n(X),G)$$
for any abelian group $G$.
Suppose $\widetilde{H}^n(X,\Bbb Z_p)=0$ for all $n$ and for all odd primes $p$. Then how does the UCT imply that $\widetilde{ H}^n(X,\Bbb Z)$ consists entirely of elements of order a power of $2$?
(I was reading Hatcher's Example 3E.5.)

A: The assumption implies in particular that $\hom(H_n(X),\mathbb Z/p) = \mathrm{Ext}(H_n(X),\mathbb Z/p) = 0$ for all $n$ and odd primes $p$.
Using the long exact sequence associated to $0\to \mathbb Z\to \mathbb Z\to \mathbb Z/p\to 0$, we get that $\hom(H_n(X),\mathbb Z)$ is uniquely $p$-divisible (that is, multiplication by $p$ is an isomorphism), and same thing for $\mathrm{Ext}(H_n(X),\mathbb Z)$.
Now the first thing implies that $\hom(H_n(X),\mathbb Z) = 0$. Indeed, suppose $f$ is a nonzero morphism, then there are $x,k$ with $f(x) = k\neq 0$. Now if $f$ were $p$-divisible for all odd primes $p$, it would mean that $k$ is too, which is absurd. So $\hom(H_n(X),\mathbb Z) = 0$.
Since now $H_n(X)$ is finitely generated (you said so in the comments), this is enough to conclude : indeed by the structure theorem, $H_n(X) \cong \mathbb Z^r \oplus \bigoplus_p\bigoplus_i \mathbb Z/p^{\alpha_i}$ for some $r$ and $\alpha_i$'s, so that this equality to $0$ implies $r=0$, and the condition on the $\mathrm{Ext}$'s implies that all odd components are $0$.
So $H_n(X)$ is $2$-torsion, and therefore $H^n(X)\cong \mathrm{Ext}(H_n(X),\mathbb Z)$ is too
I'm not entirely sure what happens if you don't assume $H_n(X)$ to be finitely generated, but my guess is that the result doesn't hold.


text:
Q: make element visible for click in html css I have an element (the green color in image)

it has a property
top:-5vw;

Because of this it covers the link in text (1.5% /year) and makes it unclickable.
How do I make it clickable without replacing anything?
I tried using z-index, but that does not work.
Image is of inspect element, so blue colour is region of 2nd element

A: You can try to use pointer-events: none; on div or use negative z-index like z-index:-1.

A: z-index is what you are looking for. Z-index has certain things that stop it from acting the way you want it to. common mistakes are setting the position. make sure your positions are not set to static or absolute


text:
Q: Search value deeply nested within a Laravel Collection I have an Eloquent Collection just like this (dumped):
Collection {#788 ▼
  #items: array:3 [▼
    0 => Rating {#787 ▼
      #table: "ratings"
      +timestamps: false
      #connection: null
      #primaryKey: "id"
      #keyType: "int"
      #perPage: 15
      +incrementing: true
      #attributes: array:3 [▼
        "id" => 1
        "rating" => "50"
        "type" => "min"
      ]
      #original: array:3 [▶]
      #relations: []
      #hidden: []
      #visible: []
      #appends: []
      #fillable: []
      #guarded: array:1 [▶]
      #dates: []
      #dateFormat: null
      #casts: []
      #touches: []
      #observables: []
      #with: []
      #morphClass: null
      +exists: true
      +wasRecentlyCreated: false
    }
    1 => Rating {#786 ▶}
    2 => Rating {#785 ▶}
  ]
}

In one of my views, I need to show only the Ratings with 'max' type and I am trying to filter the collection without success until now.
My tries so far:
if ($ratings && $ratings -> search('max') != false)
OR
if ($ratings && $ratings -> contains('max'))
So... What is the smart and eloquent way of achieving this?
Thanks in advance.

A: You can use the where method: https://laravel.com/docs/5.4/collections#method-where
$filtered_ratings = $ratings->where('type', 'max');

A: You could also use the filter() method on the collection.
return $collection->filter(function ($value, $key) {
    if($value->type == 'max'){
      return $value;
    }
});


text:
Q: Want web page (js) file upload without form submission with servlet I am attempting to write a web page that allows an upload of one or more files to a servlet without making a form submission.
I'm willing to use jQuery and/or Ajax; I do not want to use other third-party libraries.
I have a servlet that works WITH a form submission; I can make alterations to that if necessary to make it work without a form submission:
package ajaxdemo;

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
/* The Java file upload Servlet example */

@WebServlet(name = "FileUploadServlet", urlPatterns = { "/fileuploadservlet" })
@MultipartConfig
(
  fileSizeThreshold = 1024 * 1024 * 1, // 1 MB
  maxFileSize = 1024 * 1024 * 10,      // 10 MB
  maxRequestSize = 1024 * 1024 * 100   // 100 MB
)
public class FileUploadServlet extends HttpServlet
{
  private static final long serialVersionUID = 1L;

  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  {
    response.setHeader("Access-Control-Allow-Origin", "*");
    response.setHeader("Access-Control-Request-Method", "POST");

    /* Receive file uploaded to the Servlet from the HTML5 form */
    System.out.println("FileUploadServlet.doPost() invoked");
    Part filePart = request.getPart("file");
    String fileName = filePart.getSubmittedFileName();
    for (Part part : request.getParts())
    {
      part.write("C:\\tmp\\" + fileName);
    }
    response.getWriter().print("The file uploaded sucessfully.");
    response.getWriter().print("Filename: " + fileName + " saved in //tmp");
  }

}

This works with the following input form:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>

        <meta charset="ISO-8859-1">
        <title>File Upload Form</title>

File Upload:

        Select a file to upload:

        <form action = "UploadFile.jsp" method = "post"
                enctype = "multipart/form-data">
                <input type = "file" name = "file" size = "50" />

                <input type = "submit" value = "Upload File" />
        </form>

In trying to make it work without the form submission, I have the following page:

        ×

Select a file, then upload it to be read

<input type="file" id="fileUploadChooserButton">

<button id="fileUploadButton">Upload</button>

<button id='openButton'>Open File</button>

<button id='closeButton'>Close</button>

xxx

This produces an error message from the server (in the eclipse console) saying that no multipart boundary is found.
If I comment out the JavaScript line setting the request header, the error message is that filePart is null, so getSubmittedFileName() can't be called on it.
I found another explanation of doing it that involved await fetch(...) instead of xmlRequest.send(...); I have it commented out above. I couldn't make it work either.
Eventually, I want to allow the user to upload multiple files, and return a JSON structure with which I'll display a table. But I haven't figured out how to get the first file uploaded yet.

A:
xmlRequest.setRequestHeader("Content-type", "multipart/form-data");

The multipart/form-data has a mandatory parameter describing the boundary that appears between each of the multiple parts.
Under normal circumstances, xhr or fetch will generate the whole Content-Type header, including the boundary parameter from the FormData object.
Here, you've overridden the Content-type and set it to multipart/form-data without a boundary.
Just don't do that.


text:
Q: helmfile: run prepare/cleanup scripts before/after release install/uninstall I am using a helmfile to deploy a release, with postsync hook.
ex:
  hooks:
  - events: ["postsync"]
    showlogs: true
    command: "./create_namespace.sh"
    args: ['{{`{{.Release.Namespace}}`}}', '{{`{{ .Values.kubeContext}}`}}']

but the issue I am having now is that this hook executes after install and also after uninstall, what I want to achieve is this:

*

*after install run a script ex: post_install.sh

*after uninstall run a script ex: cleanup.sh


text:
Q: Relationship between row and column range of a matrix Given matrix $A \in \Bbb R^{n \times m}$ with $\frac{n}{m} = O(n^{\delta})$, where $0 < \delta < 1$, and "nearly orthonormal" rows, i.e., for any $a_i, a_j$ rows of $A$ with $i \neq j$:
$$\|a_i\| = 1, \quad |a_i^\top a_j| \leq \epsilon \tag{condition (1)}$$
where $\epsilon > 0$ is fixed. Define the column range of $A$ as:
$$\text{range}(A) = \{Ax: x \in \mathbb{R}^m\}.$$
Can we find matrix $B \in \Bbb R^{n \times m}$ such that $\text{range}(A) = \text{range}(B)$ but $\|b_i\| = 1, |b_i^\top b_j| > \epsilon$ for all $i \neq j$?


text:
Q: Run-time error -2146234341 (8013101b) Automation error from VB.NET to VB6, using manifest? I am trying to access a VB.NET DLL (.NET FX 4.0) from a VB6 client in a reg-free scenario.
I tried to follow the example from http://msdn.microsoft.com/en-us/library/ms973915.aspx, but with no success. I downloaded (link in the article) the sources and compiled, no success (error message: Run-time error '-2146234341 (8013101b)': Automation error"). Running from VB6 IDE using registered VB.NET DLL works.
I tried other examples where the .NET DLL is created as a COM Class (using "COM Class" template from VS2010), with manifest for referenced DLL embedded or not, but nothing worked for me.
Can somebody provide some simple source code with manifests example of VB.NET DLL (.NET FX v4) used in VB6 client in reg-free scenario?
Thanks much in advance.

A:
Run-time error '-2146234341 (8013101b)': Automation error

Your problem doesn't have anything to do with a manifest, you'll need to fix this one first.  The error code is COR_E_NEWER_RUNTIME.  In other words, your [ComVisible] class cannot be loaded because it depends on CLR version 4.  And the program has already loaded the CLR, version 2 most likely, because another [ComVisible] class asked first.  And it asked for version 2.
You'll need an app.exe.config file that forces CLR version 4 to get loaded, even when somebody asks for version 2.  It should look like this:
<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
  </startup>
</configuration>

Give it the same name as the vb6 exe (like "foo.exe.config" to match "foo.exe") and put it in the same directory as the .exe.  If you want to use the VB6 IDE to debug your vb6 code that uses this library then you also need vb6.exe.config in c:\program files\microsoft visual studio\vb98


text:
Q: Error:'no variables defined' in stata when using monte carlo simulation I have written the program below and keep getting the error message that my variables are not defined.
Can somebody plese see where the error is and how I should adapt the code? Really nothing seems to work.
program define myreg, rclass
drop all

set obs 200
gen x= 2*uniform()
gen  z  = rnormal(0,1)
gen e = (invnorm(uniform()))^2
e=e-r(mean)
replace e=e-r(mean)
more
gen y = 1 + 1*x +1*z + 1*e
reg y  x z
e=e-r(mean)
replace e=e-r(mean)
more
gen y = 1 + 1*x +1*z + 1*e
reg y x z
more
return scalar b0 =_[_cons]
return scalar b1=_[x]
return scalar b2 =_[z]
more
end

simulate b_0 = r(b0) b_1 = r(b1) b_2 = r(b2), rep(1000): myreg

A: *A possible solution with eclass

capture program drop myreg
program define myreg, eclass
 * create an empty data by dropping all variables
 drop _all

set obs 200
gen x= 2*uniform()
gen z  = rnormal(0,1)
gen e = (invnorm(uniform()))^2
qui sum e  /*to get r(mean) you need to run sum first*/
replace e=e-r(mean)
gen y = 1 + 1*x +1*z + 1*e
reg y  x z
end
*gather the coefficients (_b) and standard errors (_se) from the *regression each time
simulate _b _se, reps(1000) seed (123): myreg
* show the final result
mat list  r(table)

* A possible solution with rclass
* To understand the difference between rclass and eclass, see the Stata manual(http://www.stata.com/manuals13/rstoredresults.pdf)

capture program drop myreg
program define myreg, rclass
drop _all

set obs 200
gen x= 2*uniform()
gen z  = rnormal(0,1)
gen e = (invnorm(uniform()))^2
qui sum e
replace e=e-r(mean)
gen y = 1 + 1*x +1*z + 1*e
reg y  x z

mat output=e(b)
return scalar b0=output[1,3]
return scalar b1=output[1,1]
return scalar b2=output[1,2]
end
simulate b_0=r(b0) b_1=r(b1) b_2=r(b2), rep(1000) seed (123): myreg
return list

*P.S. You should read all the comments as suggested by @Nick to fully understand what I did here. .


text:
Q: Problem with multiprocessing in selenium for loop Original question
I'm trying to scrap data from a table (1000rows). Here is my code:
@func_timer
def get_data():
    form = driver.find_elements(By.TAG_NAME, "tr")

    form_data = []
    for row in form[1:-1]:
        row_text = row.text
        link, *_, expire, price, _, _ = row_text.split(" ")
        href = row.find_element(By.CLASS_NAME, "a_ym").get_attribute('href')
        form_data.append((link, expire, price, href))
    return form_data

My code is working properly, but this for loop is very slow (it takes 60~70 seconds). How can I make this for loop faster?
First update
I think my problem could be solved with multiprocessing, and here is some of my new code and research I did.
def get_row_data(row):
    row_text = row.text
    link, *_, expire, price, _, _ = row_text.split(" ")
    href = row.find_element(By.CLASS_NAME,"a_ym").get_attribute('href')
    return link, expire, price, href

def get_data():
    form = driver.find_elements(By.TAG_NAME, "tr")
    with multiprocessing.Pool() as pool:
        form_data = pool.map(get_row_data, form[1:-1])
    return form_data

But I got the following error:
AttributeError: Can't pickle local object '_createenviron.<locals>.encode'


text:
Q: How to read netstat ports? I did the netstat -tulpn | grep listen and had the next results:
tcp        0      0 0.0.0.0:22              0.0.0.0:*               LISTEN      14901/sshd
tcp        0      0 127.0.0.1:25            0.0.0.0:*               LISTEN      1011/exim4
tcp        0      0 127.0.0.1:5000          0.0.0.0:*               LISTEN      826/ang
tcp6       0      0 :::80                   :::*                    LISTEN      655/apache2
tcp6       0      0 :::22                   :::*                    LISTEN      14901/sshd
tcp6       0      0 ::1:25                  :::*                    LISTEN      1011/exim4
tcp6       0      0 :::443                  :::*                    LISTEN      655/apache2

How can you close a port?
Does this configuration have any security issue?

A: The 1st part of the question - How to close the port ?

You can stop the service listed in the last column, or kill it. Stopping the service makes sure it wont start again on its own. Killing the service means some other process like upstart might start it up again.

The 2nd part of the question - Does this have a security issue ?

I would say yes, unless you have some firewall and access control mechanism in place. The reason is that the ssh service is listening for connections from any source. Ideally, you would restrict this on the firewall (or in the ssh config) and only allow known sources to connect. If you want to go one step further, make ssh listen on another port than the default port (22) so that you can avoid being seen by the most basic/common scanners. I only mention ssh as an example. You will need to review this periodically for any more software/services you deploy on that machine.


text:
Q: Force expression in certain form Is there a function in Mathematica to force an expression to be transformed into a given form. For example f[x] is a function of x with known symbolic expression, and the goal is to find constants A and B  such that f[x] = A*x + B.
Is yes, is this also possible in Wolfram Alpha?


text:
Q: how to delete account information
please let me know how to delete my account information from Magento online shopping website

A: You cannot unless you create this function or you delete the customer from backend.
If you need a simple code to make it via PHP look at the following:
$customer = Mage::getModel('customer/customer');
$customer
  ->setWebsiteId($websiteId)
  ->loadByEmail($customerEmail)
  ->delete();