text:
Q: Difficulty in extending the third party class I have the following classes
         class A{
          private String name;
          private int value;

           public A(String n, int v){
           name = n;
           value = v;
           }

           public void print(){
           System.out.println(name + " " + value);
           }
          }

           class B extends A{
            public B(String n, int v){
              super(n,v);
            }
           }

When i say B b = new B("new object", 1);
it created an object of type B with name = new object and value = 1. and printed the same on calling print() method. But though it has those values in it, i cant access them through B's methods. Is it the limitation of encapsulation or inheritance.
Because the same situation is there in front of me where i need to extend a third party class and the properties in this class which are private but are needed in the extending class, and there are no setters and getters for the private members.
So what do i have to do?

A: If the variables are private, they are meant to be so - the designer of the class has decided they are not needed.
However, the designer of that class may have been wrong. That's not a good thing to assume in the first place, but if you really need them, you can call:
Field field = getClass().getSuperclass().getDeclaredField("privateFieldName");
field.setAccessible(true);
Object value = field.get(this);

A: If the variables are private, then you can't access them outside of the class where they are defined.
You could shadow those fields in A by assigning them to fields in class B's constructor.  However, if the values are changed in A you will not know about those changes in class B and vice versa.

A: I assume you need to extend A because there are other things that expect an A and you want to be able to substitute a subtype?
I also assume you have the source code of A, as you're showing it above?
A solution (not a great solution, because you'll run into issues in dealing with upgrades to the third party class, but possibly workable one) is:
Copy the entire source of A to a new file B.
Change the class definition and constructor to:
public class B extends A {
  private String name;
  private int value;

  public B(String n, int v){
    name = n;
    value = v;
  }

Now you have a subclass that overrides every method of the parent class (with exactly the same code).
Modify B as required.
Or, better yet, make the instance variables in B protected, and then create a third subclass C extending B, and put your changes in that:
    public class B extends A {
      protected String name;
      protected int value;

      public B(String n, int v){
        name = n;
        value = v;
      }

      ...
    }

    public class C extends B {

      public C ( String n, int v) {
        super(n, v);
      }

Now your subclass can access the parent's instance variables directly, while the grandparent's (A) are completely hidden and irrelevant.  You've also kept your code separate from the third party code, meaning you'll have an easier time handling updates and upgrades from the third party.

A: If the private members are truly needed in the subclass, then your problem indicates poor design of the superclass.  Classes that are inheritable (as "A" is because it has no "final" qualifier) must be carefully designed to avoid problems such as the one you've encountered.  The best solution would be to rework class A to better support inheritance.
Failing that, the other answers are appropriate.

A: May be the third party class didn't provide any getters/setters by design. Reexamine your need for extending the class. Instead of extending the class can you achieve what you want by using composition instead of inheritance ?
Is there a interface which the third party class implements, check if your requirements can be achieved by using the Decorator pattern.


text:
Q: Javascript window.open not firing on Mobile I've been looking everywhere for an answer all over but I can't find anything that works.
It works fine on all of my browsers but doesn't work on mobile devices. I'd like to have the links open in a new tab if possible.
Does anyone have any suggestions?
Here's what I have:
<form name="dropdownForm" method="POST" action="" >
<select name="dropdown" id="myform" onchange="document.getElementById('form').setAttribute('action', this.value); document.dropdownForm.submit(); if (this.value);">
<option value="">Choose</option>
<option value="http://www.mywebsite2.com" name="My Website 1">1</option>
<option value="http://www.mywebsite2.com" name="My Website 2">2</option>
<option value="http://www.mywebsite3.com" name="My Website 3">3</option>
<option value="http://www.mywebsite4.com" name="My Website 4">4</option>
</select>

<script type="text/javascript">
document.getElementById("myform").onchange = function() {

var openNewTab = this.options[this.selectedIndex].value;

    if (this.selectedIndex!==0 && openNewTab.substring(0,4) == "http") {
        ga('send', 'event', 'Home', 'Clicks', this.value);
        window.open(this.value, '_blank');
    }
};
</script>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What does '%8.1fC\n' mean? I wanted to know the purpose of a percent inside a string with 8.1. Your help will be appreciated thanks.

A: %8.1f is a format specifier.  This should point you in the right direction for figuring out what all the parts mean.  It specifies the format in which a variable will be printed.  In this specific case, it is a place-holder for a floating point variable.  It reserves a width of at least 8 characters and a precision of 1.
For more information, do some research on format specifiers.  It's an extremely well documented and widely available topic for virtually every programming language.


text:
Q: Problems with Ubuntu MATE 16.04.01 LTS and Acer Aspire ONE D150-1 Bk I installed Ubuntu MATE 16.04.01 LTS on a netbook, Acer Aspire ONE D150-1 Bk and I have two issues:
1) When I turn off my netbook, the netbook doesn't turn off, but it goes to standby mode. I need to press the ON button, the PC restarts and again click on the icon to turn off the PC, and my netbook goes OFF. Same thing when I turn it ON, I press the ON button, and after the bios message, the PC goes to standby mode, I need to press again the ON button and only after this procedure, the PC turns ON, so what's the problem?
I also noticed that when I turn off my PC, the screen goes all black and it appears only a line that says something like dev/sda1 clean, xxxxxx bytes, xxxx bytes something like this. Is this a result of a fsck?, Can it be connected to my problem?
For this problem I try this "fix":

*

*I try with a shutdown -h now command and the PC turns OFF normally;

*Also checked my power management settings in System -> Preferences -> Hardware -> Power Management and set all the options to Never or Do Nothing, but I have the same problem;

*In System -> Preferences -> Hardware -> Power Management -> General I set When press the ON button -> Turn OFF the PC. When I press the ON button, my PC goes OFF normally but why the PC behaves this way? What's the problem?

2) Sometimes when I turn on my PC the Wi-Fi card doesn't show any wireless network, so I need to open a terminal and issue the following command: sudo service network-manager restart. After this command, the Wi-Fi starts to work well, why I need to do this, why the Wi-Fi card sometimes doesn't show any wireless network?
For this Problem I try this "fix":

*

*Here is the output of the command sudo systemctl status network-manager, performed after switching on the PC and before restarting the service network-manager: https://thepb.in/p/76hErQzXPk1HV

A: I solved these problems by updating the BIOS of my netbook to the latest version.


text:
Q: Outlook accepting meetings on behalf of? A couple of my users are having a problem where they will accept a meeting request, but the accept notice sent to the meeting coordinator says, "Accepted on behalf of X user by Y user." I have triple checked the settings for the permissions, and none of the people accepting on behalf of have access. (Not that they are actually doing the accepting anyways.)
We are currently using an Exchage2003 server with Office 2007. OS wise it's XP pro SP3.

A: I don't suppose those two users are using any similar odd Outlook add-ins?  I know that SP3 fixed some odd Outlook invite bugs, makes me wonder if a wire got crossed with previously written addins.

A: Are the people accepting direct recipients of the original invite?  This will happen if someone is forwarded a meeting request by someone who was directly invited.

A: check the delegate tab (tools --> options --> delegates).  I have had users with the same problem and I removed anyone that showed as a delegate and that resolved the issue


text:
Q: How to can I login root and password with telnet on Docker compose memcached Without username & password is working but I'm trying "memcached sasl authentication" but doesn't work. Because How can I login with telnet?
docker-compose.yml:
memcached:
restart: always
container_name: app-memcached
build:
  context: ./docker/images/memcached
  dockerfile: Dockerfile
ports:
  - "11211:11211"
environment:
  MEMCACHED_USERNAME: ${MEMCACHED_USERNAME:-root}
  MEMCACHED_PASSWORD: ${MEMCACHED_PASSWORD:-123456}
  MEMCACHED_CACHE_SIZE: ${MEMCACHED_CACHE_SIZE:-128}
  MEMCACHED_MAX_CONNECTIONS: ${MEMCACHED_MAX_CONNECTIONS:-2000}
  MEMCACHED_THREADS: ${MEMCACHED_THREADS:-4}
  MEMCACHED_MAX_ITEM_SIZE: ${MEMCACHED_MAX_ITEM_SIZE:-1048576}
networks:
  default:
    ipv4_address: 172.20.0.50

Dockerfile:
FROM bitnami/memcached:1.6.15-debian-11-r20

Terminal:
telnet 127.0.0.1 11211
Trying 127.0.0.1...
Connected to 127.0.0.1.
Escape character is '^]'.
set abc 123
get abc
get abc
Connection closed by foreign host.


text:
Q: change password code error I've created a code to change a password. Now it seem contain an error. When I fill in the form to change password, and click save the error message:

Warning: mysql_real_escape_string() expects parameter 2 to be resource, null given in C:\Program Files\xampp\htdocs\e-Complaint(FYP)\userChangePass.php on line 103
Warning: mysql_real_escape_string() expects parameter 2 to be resource, null given in C:\Program Files\xampp\htdocs\e-Complaint(FYP)\userChangePass.php on line 103

I really don't know what the error message means. Please guys. Help me fix it.
Here's is the code:
<?php session_start(); ?>
<?php # change password.php

//set the page title and include the html header.
$page_title = 'Change Your Password';
//include('templates/header.inc');

if(isset($_POST['submit'])){//handle the form
    require_once('connectioncomplaint.php');//connect to the db.
    //include "connectioncomplaint.php";

    //create a function for escaping the data.
    function escape_data($data){
        global $dbc;//need the connection.
        if(ini_get('magic_quotes_gpc')){
            $data=stripslashes($data);
        }
        return mysql_real_escape_string($data, $dbc);
    }//end function

    $message=NULL;//create the empty new variable.

    //check for a username
    if(empty($_POST['userid'])){
        $u=FALSE;
        $message .='
 You forgot enter your userid!
';
    }else{
        $u=escape_data($_POST['userid']);
    }

    //check for existing password
    if(empty($_POST['password'])){
        $p=FALSE;
        $message .='
You forgot to enter your existing password!
';
    }else{
        $p=escape_data($_POST['password']);
    }

    //check for a password and match againts the comfirmed password.
    if(empty($_POST['password1'])) {
        $np=FALSE;
        $message .='
 you forgot to enter your new password!
';
    }else{
        if($_POST['password1'] == $_POST['password2']){
        $np=escape_data($_POST['password1']);
    }else{
        $np=FALSE;
        $message .='
 your new password did not match the confirmed new password!
';
    }
}

if($u && $p && $np){//if everything's ok.

    $query="SELECT userid FROM access WHERE (userid='$u' AND password=PASSWORD('$p'))";
    $result=@mysql_query($query);
    $num=mysql_num_rows($result);
    if($num == 1){
        $row=mysql_fetch_array($result, MYSQL_NUM);

        //make the query
        $query="UPDATE access SET password=PASSWORD('$np') WHERE userid=$row[0]";
        $result=@mysql_query($query);//run the query.
        if(mysql_affected_rows() == 1) {//if it run ok.

            //send an email,if desired.
            echo '
your password has been changed.
';
            include('templates/footer.inc');//include the HTML footer.
            exit();//quit the script.

        }else{//if it did not run OK.
            $message= '
Your password could not be change due to a system error.We apolpgize for any inconvenience.

' .mysql_error() .'
';
            }
        }else{
            $message= '
 Your username and password do not match our records.
';
        }
        mysql_close();//close the database connection.

    }else{
        $message .='
Please try again.
';
    }
}//end oh=f the submit conditional.

//print the error message if there is one.
if(isset($message)){
    echo'' , $message, '';
}
?>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

    <?php include "header.php"; ?>

<fieldset><legend> Enter your information in the form below:</legend>

User ID: <input type="text" name="username" size="10" maxlength="20" value="<?php if(isset($_POST['userid'])) echo $_POST['userid']; ?>" />

Current Password: <input type="password" name="password" size="20" maxlength="20" />

New Password: <input type="password" name="password1" size="20" maxlength="20" />

Confirm New Password: <input type="password" name="password2" size="20" maxlength="20" />

</fieldset>

 <input type="submit" name="submit" value="Change My Password" />

</form>

A: Change
return mysql_real_escape_string($data, $dbc);

to
return mysql_real_escape_string($data);

Your $dbc is not a resource, it was null.

A: Since there is only one occurrence of mysql_real_escape_string() and it relies on the global variable $dbc to be set to the mysql connection resource try.
function escape_data($data){
  global $dbc;//need the connection.
  if ( !is_resource($dbc) ) {
    die('database connection resource not initialized');
  }

  if(ini_get('magic_quotes_gpc')){
    $data=stripslashes($data);
  }

  return mysql_real_escape_string($data, $dbc);
}


text:
Q: Open group in environment beginning and close it at its end I'm trying to call a program from within LaTeX via the \input command. The call itself works just fine however I want to pack everything inside an environment in order to make the call more readable.
The problem is that I need to be able to still give some arguments every time. I know that I could do it with a macro with multiple arguments, but it seemed to be cleaner to use an environment for this.
\begin{regression}{pathToFile}
    -param1=x
    -param2=y
\end{regression}

My goal is to expand the above code to
\input{|"java -jar pathToProgram -path=pathtoFile-param1=x -param2=y"}

My current approach is this one here:
\newenvironment{regression}[1]{\input{|"java -jar pathToProgram -path='#1'}{"}}

So the idea was that I'd open the \input command at the beginning of the environment and close it at it's ending.
However the problem is that Latex interprets the whole thing as one big argument for the \newenvironment command as if there was no after-definition.
How can I get LaTeX to just copy the curly braces in the argument for the \newenvironment command and only treat them as group-delimiters once the environment has been expanded?

A: You might do it with environ:
\usepackage{environ}

\NewEnviron{regression}[1]{%
  \input{|"java -jar pathToProgram -path=#1 \BODY"}%
}

but I see no advantage in doing
\begin{regression}{pathtoFile}
-param1=x
-param2=y
\end{regression}

over
\newcommand{\regression}[2]{%
  \input{|"java -jar pathToProgram -path=#1 #2"}%
}

with the call
\regression{pathtoFile}{
  -param1=x
  -param2=y
}


text:
Q: Javascript SpiderMonkey SyntaxError: missing : after property id: I'm using Spider Monkey to make a simple console chess game.
However I keep getting the error SyntaxError: missing : after property id: in my enum declaration.
SyntaxError: missing : after property id:
ChessPiece.js:4:5      var Color = {
ChessPiece.js:4:5 ............^

Heres the full code
class ChessPiece
{
    var Color = {
        WHITE : 'W',
        BLACK : 'B'
    };

    var Piece = {
        PAWN : 'P',
        ROOK : 'R',
        KNIGHT : 'N',
        BISHOP : 'B',
        QUEEN : 'Q',
        KING : 'K'
    };

    constructor(color, piece)
    {
        this.color = color;
        this.piece = piece;
    }

    toString()
    {
        return this.color + this.piece;
    }
}

Edit: Updated enum syntax as var declaration.

A: I guess enums can't be defined inside the class body. I was able to add them after the class definition.
class ChessPiece
{
    constructor(color, piece)
    {
        this.color = color;
        this.piece = piece;
    }

    toString()
    {
        return this.color + this.piece;
    }
}

ChessPiece.Color = {
    WHITE : 'W',
    BLACK : 'B'
};

ChessPiece.Piece = {
    PAWN : 'P',
    ROOK : 'R',
    KNIGHT : 'N',
    BISHOP : 'B',
    QUEEN : 'Q',
    KING : 'K'
};

A: The correct answer is here:
js classes instance properties

Static class-side properties and prototype data properties must be
  defined outside of the ClassBody declaration

Instance vars must be declared in the constructor with "this".


text:
Q: Is it possible to display output of /data from a command block? I'm playing 1.14 and wanted to test some villager mechanics in a creative world. To help debugging I thought it'd be a good idea to constantly print the home/workplace information of the closest  villager, which is found in the Brain tag of the NBT data. So I wrote the following command:
/data get entity @e[type=minecraft:villager,limit=1,sort=nearest] Brain

And it works great:

So now I thought I could just put this in a command block and trigger it every second to have easy debugging. So I put this in a command block:
/execute as orlp at orlp run data get entity @e[type=minecraft:villager,limit=1,sort=nearest] Brain

However I don't get any output on triggering the command block. Even /gamerule commandBlockOutput true doesn't make it output anything.
How do I output the result of a data command ran in a command block to chat (or otherwise)?

A: Yes! 1.14 added NBT as a JSON component. So you can now print NBT like this:
/tellraw @s {"nbt":"Brain","entity":"@e[type=villager]"}

This even works for multiple entities (unlike /data get), which puts "," between the NBT outputs (which usually leads to the second and further tags appearing in a new line, because Minecraft only wraps lines on spaces, which aren't normally in NBT).
You can also output all NBT of an entity like this:
/tellraw @s {"nbt":"","entity":"@e[type=villager]"}

It also works for blocks:
/tellraw @s {"nbt":"","block":"12 -34 56"}

And you can combine "block" and "entity", then "entity" just gets ignored.
And as a special treat, you can even interpret that NBT as a JSON component, for example if you give a villager a formatted name like this:
/summon minecraft:villager ~ ~ ~ {CustomName:"{\"text\":\"Horst\",\"bold\":true}"}

…, then you can either output that JSON as text:
/tellraw @s {"nbt":"CustomName","entity":"@e[type=villager]"}

Output: {"bold":true,"text":"Horst"}
… or you can output it how it appears on top of its head:
/tellraw @s {"nbt":"CustomName","entity":"@e[type=villager]","interpret":true}

Output: Horst
And finally you can get really crazy and recursive:
/give @s written_book{author:"",title:"",pages:["{\"nbt\":\"CustomName\",\"entity\":\"@e[type=villager]\",\"interpret\":true}"]}
/tellraw @s {"nbt":"Inventory[0].tag.pages[0]","entity":"@s"}

Output: {"nbt":"CustomName","entity":"@e[type=villager]","interpret":true}
And interpreted:
/tellraw @s {"nbt":"Inventory[0].tag.pages[0]","entity":"@s","interpret":true}

Output: Horst
Note that this changes when you open the book, because then the JSON gets interpreted and the book page changes from {"nbt":"CustomName","entity":"@e[type=villager]","interpret":true} to Horst.


text:
Q: Is it safe to remove all user passwords except root? Is it safe to remove all passwords (passwd -d) from users, including service users like apache, bind, and others, and keep only the root password? I suspect that a malicious user may have set a password on one of these users pass later access.

A: safe is somewhat subjective.  I would say no, a better approach would be

*

*passwd -l <account_name> to lock the account,

*verify all service accounts, like apache, bind, are also locked and that they have a non-login or non-interactive shell such /bin/false or bin/true, [ or /bin/nologin if available on your system ] ... sorry, I forget exactly what the current shell types are but basic point is for service type accounts that do not need an interactive/login shell make sure they do not have one; they should not have /bin/bash

*monitor your log files and audit logs and watch for any kind of red flag

passwd -Sa is quite useful showing all accounts, if they are locked

A: Much safer to just delete the users altogether. If you want them to be there but inaccessible, just set their home directory to /dev/null, and they will log in and automatically be logged out


text:
Q: Collapse groups according to a list of codes I have a table of comma separated codes that should be collapsed
group_codes <-
 tibble::tribble(
    ~group_codes,
  "AAA11, AAA1Z",
  "ZZZ21, ZZZ2Z"
  )

And a table on which the collapsing and summing should be run:
tibble::tribble(
   ~codes, ~values,
  "AAA11",     10,
  "AAA1Z",     20,
   "CCC3",     34,
  "ZZZ21",     10,
  "ZZZ2Z",     30
  )

The third row will stay intact, it is not in the list of codes to be collapsed.
The expected result is the collapse of codes in a list and sum their values.
tibble::tribble(
          ~codes, ~values,
   "AAA11,AAA1Z",     30L,
          "CCC3",     34L,
  "ZZZ21, ZZZ2Z",     40L
  )

I am expecting to run the collapse after a group-by. The codes will not repeat. They may in most cases follow each other but the order is unknown (data comes from a manual entry form. What would be best tidyverse approach?

A: We may split the column in group_codes, do a join and summarise
library(dplyr)
library(tidyr)
group_codes %>%
   mutate(codes = group_codes) %>%
   separate_rows(codes) %>%
   left_join(df1, ., by = "codes") %>%
   transmute(codes = coalesce(group_codes, codes), values) %>%
   group_by(codes) %>%
   summarise(values = sum(values, na.rm = TRUE), .groups = 'drop')

-output
# A tibble: 3 × 2
  codes        values
  <chr>         <dbl>
1 AAA11, AAA1Z     30
2 CCC3             34
3 ZZZ21, ZZZ2Z     40


text:
Q: How better perform Pearson R from 2 arrays of dimensions (m, n) and (n), returning an array of (m) size? [Python, NumPy, SciPy] I'm trying to improve a simple algorithm to obtaining the Pearson correlation coefficient from two arrays, X(m, n) and Y(n), returning me another array R of dimension (m).
In the case, I want to know the behavior each row of X regarding the values of Y. A sample (working) code is presented below:
import numpy as np
from scipy.stats import pearsonr

np.random.seed(1)
m, n = 10, 5

x = 100*np.random.rand(m, n)
y = 2 + 2*x.mean(0)
r = np.empty(m)

for i in range(m):
    r[i] = pearsonr(x[i], y)[0]

For this particular case, I get: r = array([0.95272843, -0.69134753, 0.36419159, 0.27467137, 0.76887201, 0.08823868, -0.72608421, -0.01224453, 0.58375626, 0.87442889])
For small values of m (near 10k) this runs pretty fast, but I'm starting to work with m ~ 30k, and so this is taking much longer than I expected. I'm aware I could implement multiprocessing/multi-threading but I believe there's a (better) pythonic way of doing this.
I tried to use use pearsonr(x, np.ones((m, n))*y), but it returns only (nan, nan).

A: pearsonr only supports 1D array internally. Moreover, it computes the p-values which is not used here. Thus, it would be more efficient not to compute it if possible. Additionally, the code also recompute the y vector every time and it does not efficiently make use of vectorized Numpy operations. This is why the computation is a bit slow. You can check this in the code here.
One way to compute this is by writing your own custom implementation based on the one of Scipy:
def multi_pearsonr(x, y):
    xmean = x.mean(axis=1)
    ymean = y.mean()
    xm = x - xmean[:,None]
    ym = y - ymean
    normxm = np.linalg.norm(xm, axis=1)
    normym = np.linalg.norm(ym)
    return np.clip(np.dot(xm/normxm[:,None], ym/normym), -1.0, 1.0)

It is 450 times faster on my machine for m = 10_000.
Note that I did not keep the checks of the Scipy code, but it may be a good idea to keep them if your input is not guaranteed to be statistically safe (ie. well formatted for the computation of the Pearson test).


text:
Q: Unknown component in a shaded pole motor coil I dismantled a shaded pole motor and just found a component under the tape of the coil. It is placed in series with the copper wire. It is marked L120 Y068A3 (see picture). It comes from a breast pump made in Korea in the late 2000's. Any idea what is this component and what's its purpose?

A:
Any idea what is this component and what's its purpose?

It's a thermal cut-out, to cut power to the motor in the event of the motor getting too hot.
From its markings "L120 Y068A3" I expect it is designed to open at around 120 degrees C.
Some of these are effectively a thermal fuse and do not reset when the motor's temperature drops again; others contain a bi-metallic strip and those do reset as they cool.


text:
Q: Check conflict after git pull in script I've the following script in a git repository, that allows me to add a subtree and performing push and pull in automatic way.
#!/bin/bash

# The script will update subtrees of the repository. Subtrees are stored in
# thirdparty folder.
#
# Since in a fresh clone subtrees are missing, the script at first will check if
# corresponding remotes are present. If they are missing then remotes will be
# created. Then, it starts the synchronization. Subtree repositories will be
# pulled, synchronized, with the current conflict resolution, and then pushed.

# Remotes
SUBTREELIB_REMOTE=name-of-subtree-remote
SUBTREELIB_URL=git@remote-git-address.git
SUBTREELIB_BRANCH=branch-that-must-be-checked-out
SUBTREELIB_PATH=path/where/subtree/is/stored

###############################################################################
# FUNCTIONS SECTION                                                           #
###############################################################################

# Exit if the tree is not clean.
RequireCleanWorkingTree () {
    # Update the index
    git update-index -q --ignore-submodules --refresh
    err=0

    # Disallow unstaged changes in the working tree
    if ! git diff-files --quiet --ignore-submodules --
    then
        echo >&2 "cannot $1: you have unstaged changes."
        git diff-files --name-status -r --ignore-submodules -- >&2
        err=1
    fi

    # Disallow uncommitted changes in the index
    if ! git diff-index --cached --quiet HEAD --ignore-submodules --
    then
        echo >&2 "cannot $1: your index contains uncommitted changes."
        git diff-index --cached --name-status -r --ignore-submodules HEAD -- >&2
        err=1
    fi

    if [ $err = 1 ]
    then
        echo >&2 "You need to commit or stash changes before updating subtrees."
        exit 1
    fi
}

# Function for syncronyzing a remote
#
# It needs 4 arguments:
#
# - The name of the remote that will be used in the repository
# - The url of the remote where it can be fetched
# - The branch of the remote that must be syncronized
# - The path where it must be stored in the repository.
function SyncronizeRemote {
  # Check if remote is present and add it if missing.
  echo "Testing if $1 is present"
  git ls-remote --exit-code $1
    if test $? != 0; then
      echo "Adding missing remote $1"
      git remote add -f $1 $2
      echo "Adding subtree for $1"
      git subtree add --prefix $4 $1 master --squash
  fi

  # Fetching remotes
  echo "Fetching remotes for $1"
  git fetch $1 $3

  # Pull remotes
  echo "Pulling remotes for $1"
  git subtree pull --prefix $4 $1 $3 --squash

  # Push remotes
echo "Updating remotes for $1"
git subtree push --prefix=$4 $1 $3
}

###############################################################################
# EXECUTION SECTION                                                           #
###############################################################################

# Ask ssh key password only once.
eval `ssh-agent -s`
ssh-add ~/.ssh/*_rsa

RequireCleanWorkingTree
SyncronizeRemote $SUBTREEIB_REMOTE $SUBTRELIB_URL $SUBTREELIB_BRANCH $SUBTREELIB_PATH

It works, but it has the problem than if I've a merge conflict after the pull, it doesn't stop and it does the push. For example if I have a conflic the output is:
Agent pid 1825
Enter passphrase for /c/Users/myuser/.ssh/id_rsa:
Identity added: /c/Users/myuser/.ssh/id_rsa (/c/Users/myuser/.ssh/id_rsa)
Testing if name-of-subtree-remote is present
a38faec39bf7f5515f570eb2835dfa80555e9be1        HEAD
8aa678cdca32b2fe6d91edb8d0097a6e0b6eeea9        refs/heads/develop
a38faec39bf7f5515f570eb2835dfa80555e9be1        refs/heads/master
Fetching remotes for name-of-subtree-remote
remote: Enumerating objects: 19, done.
remote: Counting objects: 100% (19/19), done.
remote: Compressing objects: 100% (10/10), done.
remote: Total 10 (delta 7), reused 0 (delta 0)
Unpacking objects: 100% (10/10), 3.58 KiB | 85.00 KiB/s, done.
From 192.168.100.236:loginlib
 * branch            develop    -> FETCH_HEAD
   00d5585..8aa678c  develop    -> name-of-subtree-remote/develop
Pulling remotes for name-of-subtree-remote
From 192.168.100.236:name-of-subtree-remote
 * branch            develop    -> FETCH_HEAD
CONFLICT (add/add): Merge conflict in path/where/subtree/is/stored/src/File1.hpp
Auto-merging path/where/subtree/is/stored/src/File1.hpp
CONFLICT (add/add): Merge conflict in path/where/subtree/is/stored/src/File2.hpp
Auto-merging path/where/subtree/is/stored/src/File2.hpp
CONFLICT (add/add): Merge conflict in path/where/subtree/is/stored/src/File3.hpp
Auto-merging path/where/subtree/is/stored/src/File3.hpp
Automatic merge failed; fix conflicts and then commit the result.
Updating remotes for name-of-subtree-remote
git push using:  name-of-subtree-remotedevelop
219/475 (212) [13]

I want that the script stops if I've a merge conflict with the pull, so I can solve the merge conflict and re-run the script in order to avoid problems.
How can I modify the script in order to check if there's a merge conflict and exit if there is?


text:
Q: Exception using System.Net.Mqtt pre-release version I am trying to use Nuget package System.Net.Mqtt: a lightweight C#... 0.3.6-pre for my sample Mqtt app. However, I am not able to connect to my client. Code is below
namespace TestMqtt
{
    class MqttHelper
    {
        public IMqttClient client;

        public async Task CreateClient()
        {
            MqttConfiguration configuration = new MqttConfiguration();
            configuration.Port = 8883;
            configuration.AllowWildcardsInTopicFilters = false;
            configuration.KeepAliveSecs = 180;

            string address = Dns.GetHostAddresses("hostname")[0].ToString();
            client = await System.Net.Mqtt.MqttClient.CreateAsync(address, configuration);
        }

        public async Task Connect(MqttClientCredentials credentials)
        {
            await client.ConnectAsync(credentials);
        }

        public bool IsConnected
        {
            get
            {
                return client.IsConnected;
            }
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                MqttHelper mqttHelper = new MqttHelper();

                Task.Run(() => mqttHelper.CreateClient()).Wait();

                MqttClientCredentials credentials = new MqttClientCredentials("clientId", "username", "password");

                Task.Run(() => mqttHelper.Connect(credentials)).Wait();

                bool connected = mqttHelper.IsConnected;
            }
            catch (Exception ex)
            {
                Console.WriteLine("exception occurred {0}, press key to exit", ex.InnerException);
            }

            Console.ReadLine();
        }
    }
}

I can connect with same credentials and host address by using another client M2Mqtt, so I am not sure what's wrong here. I am new to async stuff so there may something I am doing it wrong, but I tried all I can with no success. I get an exception - An existing connection was forcibly closed by the remote host in Connect method.
Any help will be appreciated, or if anyone has used the lib to connect please share the code. Nuget package documentation doesn't have any details on how to use the library. Any other suggestions for C# Mqtt client are welcome too, so far I have shortlisted M2Mqtt and Net.Mqtt for my use.
Thanks.


text:
Q: What is the difference between a linear mapping and a bilinear mapping? Especially, what's the difference between their matrixes.
I think the main difference is that in linear you cannot multiply two vectors but in bilinear mapping you can. But I'm not sure if I understand it correctly. Thank you for your explainations :)

A: The difference is that while

a linear map $L:V\to W$ is a function that take a vector and gives a vector :$L(\vec v)=\vec  w$

(and is linear: $L(a\vec x+b\vec y)=aL(\vec x) +b L(\vec y)$)

a bilinear map $B:V_1\times V_2 \to W$ take two vectors ( a couple in the cartesian product) and gives a vector: $B(\vec v_1,\vec v_2)=\vec w$

(and it is linear in the two arguments)
I'm not sure to understand what you say for ''in linear you cannot multiply two vectors but in bilinear mapping you can'' but also in a bilinear map we cannot ''multiply the arguments'', in the sense we cannot have something as $B(xy,z)=B(x,z)B(y,z)$.
As an example of bilinear form, that I suppose you  know, you can think at the cross product of two vectors in $\mathbb{R}^3$ that take two vectors $\vec v, \vec u$ and gives the  vector $\vec v \times \vec u$.

A: I find the simple example of multiplying a matrix $A$ with a column vector $x$ useful in thinking about linear and bilinear forms.
Viewing $A$ as a linear transformation, $Ax$ is the weighted sum of columns of $A$ with column $i$ weighted by $x_i$. This is the linear column space perspective.
A bilinear transformation is the dot product, which as the OP says, takes two vectors to a number.
From a dot product perspective, $A$ is simply a collection of rows, each of we dot product with $x$. The resulting list of numbers is $Ax$. If $Ax=0$, we have found a vector perpendicular to the row space of $A$. The focus is thus on the row space.
Strang calls the two perspectives outer vs. inner products.
The difference can also be seen in how you undo the effects of $A$ on $x$. In the linear case, if you know $Ax-b=0$, your best bet (not always exactly correct) is $x-A^+b = 0$, where $A^+$ is the pseudoinverse.
In the dot product bilinear case $(Ax,b) = 0$ becomes $(x,A^Tb)=0$ where $A^T$ is the transpose.
In a linear vector space, you can't ask for an angle between the two vectors; you can only ask for a matrix that moves one vector to the other. Multiplying and inverting these matrices is composition and inversion of the transformation.
But once you have a dot product, you can immediately get the angle.
You can see all of this in action together in the OLS regression of $y$ on $X$. The first step minimizes the dot product of $y-Xb$ with itself. That gives $X'y = X'Xb$. So only transposes ('). Next we take a linear perspective and pseudoinvert to $b = (X'X)^+X'y$.


text:
Q: The Average Number of Rides Completed in 4 Hours I have a dataset with each ride having its own ride_id and its completion time. I want to know how many rides happen every 4 hours, on average.
Sample Dataset:
dropoff_datetime    ride_id
2022-08-27 11:42:02 1715
2022-08-24 05:59:26 1713
2022-08-23 17:40:05 1716
2022-08-28 23:06:01 1715
2022-08-27 03:21:29 1714

For example, I would like to find out between 2022-8-27 12 PM to 2022-8-27 4 PM how many rides happened that time? And then again from 2022-8-27 4 PM to 2022-8-27 8 PM how many rides happened in that 4 hour period?
What I've tried:

*

*I first truncate my dropoff_datetime into the hour. (DATE_TRUNC)

*I then group by that hour to get the count of rides per hour.

Example Query:
Note: calling the above table - final.
SELECT  DATE_TRUNC('hour', dropoff_datetime) as by_hour
,count(ride_id) as total_rides
FROM final
WHERE 1=1
GROUP BY 1

Result:
by_hour total_rides
2022-08-27 4:00:00  3756
2022-08-27 5:00:00  6710

My question is:
How can I make it so it's grouping every 4 hours instead?

A: The question actually consists of two parts - how to generate date range and how to calculate the data. One possible approach is to use minimum and maximum dates in the data to generate range and then join with data again:
-- sample data
with dataset (dropoff_datetime, ride_id) AS
         (VALUES (timestamp  '2022-08-24 11:42:02', 1715),
                 (timestamp  '2022-08-24 05:59:26', 1713),
                 (timestamp  '2022-08-24 05:29:26', 1712),
                 (timestamp  '2022-08-23 17:40:05', 1716)),
-- query part
min_max as (
    select min(date_trunc('hour', dropoff_datetime)) d_min, max(date_trunc('hour', dropoff_datetime)) d_max
    from dataset
),
date_ranges as (
    select h
    from min_max,
     unnest (sequence(d_min, d_max, interval '4' hour)) t(h)
)

select h, count_if(ride_id is not null)
from date_ranges
left join dataset on dropoff_datetime between h and h + interval '4' hour
group by h
order by h;

Which will produce the next output:

h
_col1

2022-08-23 17:00:00
1

2022-08-23 21:00:00
0

2022-08-24 01:00:00
0

2022-08-24 05:00:00
2

2022-08-24 09:00:00
1

Note that this can be quite performance intensive for big amount of data.
Another approach is to get some "reference point" and start counting from it. For example using minimum data in the dataset:
-- sample data
with dataset (dropoff_datetime, ride_id) AS
         (VALUES (timestamp '2022-08-27 11:42:02', 1715),
                 (timestamp '2022-08-24 05:59:26', 1713),
                 (timestamp '2022-08-24 05:29:26', 1712),
                 (timestamp '2022-08-23 17:40:05', 1716),
                 (timestamp '2022-08-28 23:06:01', 1715),
                 (timestamp '2022-08-27 03:21:29', 1714)),
-- query part
base_with_curr AS (
    select (select min(date_trunc('hour', dropoff_datetime)) from dataset) base,
        date_trunc('hour', dropoff_datetime) dropoff_datetime
    from dataset)

select date_add('hour', (date_diff('hour', base, dropoff_datetime) / 4)*4, base) as four_hour,
       count(*)
from base_with_curr
group by 1;

Output:

four_hour
_col1

2022-08-23 17:00:00
1

2022-08-28 21:00:00
1

2022-08-24 05:00:00
2

2022-08-27 09:00:00
1

2022-08-27 01:00:00
1

Then you can use sequence approach to generate missing dates if needed.


text:
Q: Regular Level Set Theorem Application in Proofs I'm working through Lee's Differential Geometry textbook and have run into the regular level set theorem:
Theorem: Every regular level set of a smooth map between smooth manifolds is a properly embedded submanifold whose codimension is equal to the dimension of the codomain.
What I understand this to mean is that given two smooth manifold $U, V$, and a smooth mapping between them (call it $\phi:U\rightarrow V$), then for all $c \in V$ such that $d\phi${$\phi^{-1}(c)$} is surjective (note {$\phi^{-1}(c)$} is most likely a set of points, not a singleton), that that level set {$\phi^{-1}(c)$} is a properly embedded submanifold.
I'm just wondering how to use this. For example, One problem I was looking at was to show that a set $\tilde{G}(n,k)$ described to be the set of $n\times n$ matrices $M$ that are idempotent, symmetric, and have trace$(M)=k$, is a smooth manifold using the level set theorem. I know that this set is bijective to the Grassmannian of $\mathbb{R}^n$ of dimension $k$ (linear subspaces of dimension $k$ of $\mathbb{R}^n$) but I have no clue how to proceed from here.
When and how is the level set theorem useful in situations like these?


text:
Q: Surface of earth seen is 1/4 At what height from the ground can one see exactly 1/4 th of the Earth's surface ?
Take earth to be sphere of radius r.

A: $\newcommand{\+}{^{\dagger}}
 \newcommand{\angles}[1]{\left\langle #1 \right\rangle}
 \newcommand{\braces}[1]{\left\lbrace #1 \right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack #1 \right\rbrack}
 \newcommand{\ceil}[1]{\,\left\lceil #1 \right\rceil\,}
 \newcommand{\dd}{{\rm d}}
 \newcommand{\down}{\downarrow}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\equalby}[1]{{#1 \atop {= \atop \vphantom{\huge A}}}}
 \newcommand{\expo}[1]{\,{\rm e}^{#1}\,}
 \newcommand{\fermi}{\,{\rm f}}
 \newcommand{\floor}[1]{\,\left\lfloor #1 \right\rfloor\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{{\rm i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\isdiv}{\,\left.\right\vert\,}
 \newcommand{\ket}[1]{\left\vert #1\right\rangle}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left( #1 \right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\pp}{{\cal P}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,#2\,}\,}
 \newcommand{\sech}{\,{\rm sech}}
 \newcommand{\sgn}{\,{\rm sgn}}
 \newcommand{\totald}[3][]{\frac{{\rm d}^{#1} #2}{{\rm d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\, #1 \,\right\vert}$
$$
{1 \over 4}\,\pars{4\pi r^{2}} = 2\pi r^{2}\int_{0}^{\alpha}\sin\pars{\theta}\,\dd\theta =
4\pi r^{2}\sin^{2}\pars{\alpha \over 2}\quad\imp\quad
\sin^{2}\pars{\alpha \over 2} = {1 \over 4}
$$

$$
\cos\pars{\alpha} = 1 - 2\sin^{2}\pars{\alpha \over 2} = \half ={r \over r + h}\quad\imp\quad \color{#00f}{\large h = r}
$$

A: Let Earth's radius be $R$, and the height above it be $r$. Moreover, denote the radius of the spherical cap visible as $a$.
Form the right triangle with side $R$ and hypotenuse $R+r$, whose second side has length $\sqrt{(R+r)^2-R^2}$. By triangle similarity you have:
$$\frac{a}{\sqrt{(R+r)^2-R^2}}=\frac{R}{R+r}$$
Solve for $a$ and use the fact that the area of a spherical cap is:
$$A=\pi(a^2+(R-\sqrt{R^2-a^2})^2)=\pi (a^2+(R-\sqrt{R^2-a^2})^2)$$
And find for what $r$, $A= \pi R^2$ as requested.


text:
Q: Using moment.js to calculate elapsed time?   var currentTimeArray = [];
  function currentTime(){
    var time = moment();
    return currentTimeArray.push(time);
  }

  $('.next-fieldgroup').on('click', function(e){
    e.preventDefault();
    currentTime();

    var endTime = $(currentTimeArray).last();
    var startTime = currentTimeArray[0];
    var duration = moment.duration(endTime.diff(startTime));
    var elapsedTime = duration().asMinutes();

    $('#timer-counter').text( elapsedTime );
  });

What it is supposed to do...

*

*on click store NOW time in to ARRAY

*on click compare arr[0] with arr.last() to get time elapsed time

*update div with elapsed time in minutes

I expect the output to like:
"Time elapsed: 12 minutes"
I get the following error:

Uncaught TypeError: undefined is not a function

A: jQuery methods return objects wrapped in jQuery, so your endTime is a jQuery wrapped moment object. And jQuery does not have a .diff method so hence the error. Use .get(0) or [0] to get the actual moment object
var endTime = $(currentTimeArray).last().get(0);


text:
Q: How to tackle atomic transaction in mongodb I have a store where item price is determined based on the quantity available, so whenever user request items, I have to calculate price based on the requested quantity
I have to implement price calculation in an atomic way so that if a transaction occurs during calculation of an ongoing transaction and the price or availableQuantity changes, it should not affect both transactions.
Initial Database
{
   "_id": "1",
   "availableQuantity": 10,
   "pricePerItem": 15
},
{
   "_id": "2",
   "availableQuantity": 5,
   "pricePerItem": 10
},
{
   "_id": "3",
   "availableQuantity": 6,
   "pricePerItem": 20
}

It means that
I can sell 5 items with price 10 / item
next 10 items with price 15 / item
next 6 items with price 20 / item
senario:
User "A" wants to buy 8 items, price will be calculated like this
First, the minimum price object will be selected in our case it is _Id: "2"
5 items will be taken from this object then price = 10*5 = 50
updated database
{
   "_id": "1",
   "availableQuantity": 10,
   "pricePerItem": 15
},
{
   "_id": "3",
   "availableQuantity": 6,
   "pricePerItem": 20
}

Remaining 3 items will be taken from minimum price object which is _id: "1"
Price for 3 items will be price = 3*15 = 45
Total price for user "A" 8 items will be total price = 50 + 45 = 95
Final Database
{
   "_id": "1",
   "availableQuantity": 7,
   "pricePerItem": 15
},
{
   "_id": "3",
   "availableQuantity": 6,
   "pricePerItem": 20
}

Problem
During user "A" transaction if user "B" is requesting 4 items then how should we determine the correct prices.
Note: Many transactions are expected to happen simultaneously

A: Mongodb does not have support for transactions. There are not-so-popular npm packages which imitate transactional behaviour on the application level but that's it :(


text:
Q: How to disable windows snap target In a fresh install of Windows 10 Pro. When I drag a window a snap target position image is displayed. See image.

This is very frustrating as the image is often displayed under the place where I want to place the window. The affect being that the window is therefore snapped and not placed where I intended it to be.
How do I disable this?
To be clear I don't want to disable snapping altogether just the annoying destination image underlay
UPDATE
I do not have the option to "Allow the system to suggest companion windows when using Snap"

A: As @Wessel mentioned this is caused by Dell PremierColor. To disable it, open PremierColor, switch to advanced mode, and disable "Display Splitter".

A: This is caused by 3rd party software - For Dell Check - Dell PremierColor.
Windows
Under Settings > System > Multitasking,
This will allow you to disable the overlay.


text:
Q: Computing the gradient of the loss using Tensorflow.js I am trying to compute the gradient of a loss, with relation to a network's trainable weights using Tensorflow.js in order to apply these gradients to my network's weight. In python, this is easily done using the tf.gradients() functions, which takes two minimum inputs representing dx and dy.
However, I am not able to reproduce the behavior in Tensorflow.js. I am not sure wether my understanding of the gradient of the loss w.r.t the weights is wrong, or if my code contains mistakes.
I have spent some time analysing the core code of the tfjs-node package to understand how it is done when we call the function tf.model.fit(), but with little success so far.
let model = build_model(); //Two stacked dense layers followed by two parallel dense layers for the output
let loss = compute_loss(...); //This function returns a tf.Tensor of shape [1] containing the mean loss for the batch.
const f = () => loss;
const grad = tf.variableGrads(f);
grad(model.getWeights());

The model.getWeights() function returns an array of tf.variable(), so I assumed the function would compute dL/dW for each layer, which I could apply later to my network's weights, however, that's not quite the case as I get this error :
Error: Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.

I don't quite understand what does this error means.
How am I supposed to compute the gradient (analog to tf.gradients() in Python) of the loss using Tensorflow.js then ?
Edit :
 This is the function computing the loss :
function compute_loss(done, new_state, memory, agent, gamma=0.99) {
    let reward_sum = 0.;
    if(done) {
        reward_sum = 0.;
    } else {
        reward_sum = agent.call(tf.oneHot(new_state, 12).reshape([1, 9, 12]))
                    .values.flatten().get(0);
    }

    let discounted_rewards = [];
    let memory_reward_rev = memory.rewards;
    for(let reward of memory_reward_rev.reverse()) {
        reward_sum = reward + gamma * reward_sum;
        discounted_rewards.push(reward_sum);
    }
    discounted_rewards.reverse();

    let onehot_states = [];
    for(let state of memory.states) {
        onehot_states.push(tf.oneHot(state, 12));
    }
    let init_onehot = onehot_states[0];

    for(let i=1; i<onehot_states.length;i++) {
        init_onehot = init_onehot.concat(onehot_states[i]);
    }

    let log_val = agent.call(
        init_onehot.reshape([memory.states.length, 9, 12])
    );

    let disc_reward_tensor = tf.tensor(discounted_rewards);
    let advantage = disc_reward_tensor.reshapeAs(log_val.values).sub(log_val.values);
    let value_loss = advantage.square();
    log_val.values.print();

    let policy = tf.softmax(log_val.logits);
    let logits_cpy = log_val.logits.clone();

    let entropy = policy.mul(logits_cpy.mul(tf.scalar(-1)));
    entropy = entropy.sum();

    let memory_actions = [];
    for(let i=0; i< memory.actions.length; i++) {
        memory_actions.push(new Array(2000).fill(0));
        memory_actions[i][memory.actions[i]] = 1;
    }
    memory_actions = tf.tensor(memory_actions);
    let policy_loss = tf.losses.softmaxCrossEntropy(memory_actions.reshape([memory.actions.length, 2000]), log_val.logits);

    let value_loss_copy = value_loss.clone();
    let entropy_mul = (entropy.mul(tf.scalar(0.01))).mul(tf.scalar(-1));
    let total_loss_1 = value_loss_copy.mul(tf.scalar(0.5, dtype='float32'));

    let total_loss_2 = total_loss_1.add(policy_loss);
    let total_loss = total_loss_2.add(entropy_mul);
    total_loss.print();
    return total_loss.mean();

}

EDIT 2:
I managed to use the compute_loss as the loss function specified on model.compile(). But then, it is required that it takes only two inputs (predictions, labels), so it's not working out for me, as I want to input multiple parameters.
I am trully lost on the matter.

A: The error says it all.
Your issue has to do with tf.variableGrads. loss should be a scalar computed using all available tf tensors operators. loss should not return a tensor as indicated in your question.
Here is an example of what loss should be:
const a = tf.variable(tf.tensor1d([3, 4]));
const b = tf.variable(tf.tensor1d([5, 6]));
const x = tf.tensor1d([1, 2]);

const f = () => a.mul(x.square()).add(b.mul(x)).sum(); // f is a function
// df/da = x ^ 2, df/db = x
const {value, grads} = tf.variableGrads(f); // gradient of f as respect of each variable

Object.keys(grads).forEach(varName => grads[varName].print());

/!\ Notice that the gradient is calculated as respect of variables created using tf.variable
Update:
You're not computing the gradients as it should be. Here is the fix.
function compute_loss(done, new_state, memory, agent, gamma=0.99) {
    const f = () => { let reward_sum = 0.;
    if(done) {
        reward_sum = 0.;
    } else {
        reward_sum = agent.call(tf.oneHot(new_state, 12).reshape([1, 9, 12]))
                    .values.flatten().get(0);
    }

    let discounted_rewards = [];
    let memory_reward_rev = memory.rewards;
    for(let reward of memory_reward_rev.reverse()) {
        reward_sum = reward + gamma * reward_sum;
        discounted_rewards.push(reward_sum);
    }
    discounted_rewards.reverse();

    let onehot_states = [];
    for(let state of memory.states) {
        onehot_states.push(tf.oneHot(state, 12));
    }
    let init_onehot = onehot_states[0];

    for(let i=1; i<onehot_states.length;i++) {
        init_onehot = init_onehot.concat(onehot_states[i]);
    }

    let log_val = agent.call(
        init_onehot.reshape([memory.states.length, 9, 12])
    );

    let disc_reward_tensor = tf.tensor(discounted_rewards);
    let advantage = disc_reward_tensor.reshapeAs(log_val.values).sub(log_val.values);
    let value_loss = advantage.square();
    log_val.values.print();

    let policy = tf.softmax(log_val.logits);
    let logits_cpy = log_val.logits.clone();

    let entropy = policy.mul(logits_cpy.mul(tf.scalar(-1)));
    entropy = entropy.sum();

    let memory_actions = [];
    for(let i=0; i< memory.actions.length; i++) {
        memory_actions.push(new Array(2000).fill(0));
        memory_actions[i][memory.actions[i]] = 1;
    }
    memory_actions = tf.tensor(memory_actions);
    let policy_loss = tf.losses.softmaxCrossEntropy(memory_actions.reshape([memory.actions.length, 2000]), log_val.logits);

    let value_loss_copy = value_loss.clone();
    let entropy_mul = (entropy.mul(tf.scalar(0.01))).mul(tf.scalar(-1));
    let total_loss_1 = value_loss_copy.mul(tf.scalar(0.5, dtype='float32'));

    let total_loss_2 = total_loss_1.add(policy_loss);
    let total_loss = total_loss_2.add(entropy_mul);
    total_loss.print();
    return total_loss.mean().asScalar();
}

return tf.variableGrads(f);
}

Notice that you can quickly run into a memory consumption issue. It will advisable to surround the function differentiated with tf.tidy to dispose of the tensors.


text:
Q: Чем кроме WM_SIZE обработать изменение размера окна? Мне нужно, чтобы когда я "растягиваю" окно, оно постоянно перерисовывалось, а не когда я мышку отпускаю.
A: Изменение размеров окна ничем, кроме WM_SIZE обрабатывать просто не нужно. Это сообщение специально сделано для уведомления вашей оконной процедуры об изменении размеров окна.
А описанная вами проблема действительно устраняется настройками операционной системы. Кстати, не помешало бы и её уточнить в вопросе. Настройка "Отображать содержимое окна при перетаскивании". Для Windows 7: Мой компьютер -> Свойства -> Дополнительные параметры системы -> Визуальные эффекты -> Отображать содержимое окна при перетаскивании.
Также включить эту настрйку можно программно функцией SystemParametersInfo. Но не советовал бы её использовать. Вряд ли кому-то понравится программа, котоая меняет системные настройки для своей работы.
A: А когда вы "растягиваете" окно, перерисовывается только его рамка или все окно, но "мусором"?
Если первое, то смотрите настройки винды (флаг называется как-то так: "перерисовывать окно при перемещении").
Если второе, то в событии WM_MOUSEMOVE можно проверять, нажата ли левая кн. мыши и делать вызовы invalidate()\update().
A: Для этого логично использовать "кэтчер" событий в APIENTRY-функции WinMain() :
while (GetMessage(&msg, NULL, 0, 0))
    {
        if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg))
        {
            TranslateMessage(&msg);
            DispatchMessage(&msg);
        }
    }

A: Очевидно, вам нужно WM_SIZING. Это сообщение посылается время от времени, когда окно находится в процессе изменения размера.


text:
Q: How to make window size responsive in Electron. (On the opening of the app) I recently started making an app on Electron, I wanted to make the window responsive, for example, if I open app on different screens it should open in full-size according to the screen size.
my code:
  app.on('ready', () => {
      const htmlPath = path.join('src', 'html/login.html')
      mainWindow1 = new BrowserWindow({ width: 1000 , height: 1000})
      mainWindow1.loadFile(htmlPath)

    })

Please help me with this.

A: After creating your BrowserWindow you should call maximize()
mainWindow1 = new BrowserWindow();
mainWindow1.loadFile(htmlPath);
mainWindow1.maximize();

https://electronjs.org/docs/api/browser-window#winmaximize


text:
Q: Calculate vertical acceleration from sensor data I'm using Sensor.TYPE_LINEAR_ACCELERATION and Sensor.TYPE_ROTATION_VECTOR to read the rotation vector and accelerometer values from the device's sensors.
I want to use this data to calculate the vertical acceleration of the phone - i.e. regardless of how the phone is rotated, I want to be able to read the acceleration in the up/down direction relative to the ground.
How can I accomplish this?
UPDATE
Right now I have this code:
private double getVerticalAcceleration(){
    // Based on http://stackoverflow.com/questions/31268852/measuring-vertical-movement-of-non-fixed-android-device
    float[] rotationMatrix = new float[9]; // Both 9 and 16 works, depending on what you're doing with it
    SensorManager.getRotationMatrixFromVector(rotationMatrix, rotationVector);

    float[] accelerationInWorldFrame = matrixMult3x9(
            accelerometerValues,
            rotationMatrixTranspose(rotationMatrix)
    );

    return accelerationInWorldFrame[2];
}

private float[] matrixMult3x9(float[] a, float[] b){
    float[] result = new float[3];
    result[0] = a[0]*b[0] + a[1]*b[3] + a[2]*b[6];
    result[1] = a[0]*b[1] + a[1]*b[4] + a[2]*b[7];
    result[2] = a[0]*b[2] + a[1]*b[5] + a[2]*b[8];
    return result;
}

private float[] rotationMatrixTranspose(float[] rotationMatrix){
    float[] result = new float[9];
    result[0] = rotationMatrix[0];
    result[1] = rotationMatrix[3];
    result[2] = rotationMatrix[6];
    result[3] = rotationMatrix[1];
    result[4] = rotationMatrix[4];
    result[5] = rotationMatrix[7];
    result[6] = rotationMatrix[2];
    result[7] = rotationMatrix[5];
    result[8] = rotationMatrix[8];
    return result;
}

But it doesn't seem to be working very well, because if I hold the phone upright for example, the difference between the raw Y-accelerometer value and the value returned from getVerticalAcceleration() should be 0 (or very close to 0), but I'm seeing all sorts of values.


text:
Q: How to make this slider automatic I've created a manual slider, but i want to make the sliders autoplay. I use the data position to make each slide come to the front when you press the slider / buttons. How can i do that without modify all the js? Or if you can help me with a same slider, but just to be automatic? Any solution is welcome.
Here is my code

jQuery(document).ready(function () {

    function detect_active() {
        // get active
        var get_active = $("#dp-slider .dp_item:first-child").data("class");
        $("#dp-dots li").removeClass("active");
        $("#dp-dots li[data-class=" + get_active + "]").addClass("active");
    }

    $("#dp-dots li").click(function () {
        $("#dp-dots li").removeClass("active");
        $(this).addClass("active");
        var get_slide = $(this).attr('data-class');
        $("#dp-slider .dp_item[data-class=" + get_slide + "]").hide().prependTo("#dp-slider").fadeIn();
        $.each($('#slider .dp_item'), function (index, dp_item) {
            $(dp_item).attr('data-position', index + 1);
        });
    });

    $("body").on("click", "#dp-slider .dp_item:not(:first-child)", function () {
        var get_slide = $(this).attr('data-class');
        $("#dp-slider .dp_item[data-class=" + get_slide + "]").hide().prependTo("#dp-slider").fadeIn();
        $.each($('#slider .dp_item'), function (index, dp_item) {
            $(dp_item).attr('data-position', index + 1);
        });

        detect_active();
    });
    $("#dp-dots .first,#dp-slider .item-1").click(function () {
        $(".div-1").addClass('is-active');
        $(".item-1 .dp-content").addClass('opacity');
        $(".item-1 .dp-content img").addClass('fade-up');
        $(".item-2 .dp-content").removeClass('opacity');
        $(".item-2 .dp-content img").removeClass('fade-up');
        $(".item-3 .dp-content").removeClass('opacity');
        $(".item-3 .dp-content img").removeClass('fade-up');
        $(".div-2").removeClass('is-active');
        $(".div-3").removeClass('is-active');
    });

    $("#dp-dots .second, .item-2").click(function () {
        $(".div-1").removeClass('is-active');
        $(".item-1 .dp-content").removeClass('opacity');
        $(".item-1 .dp-content img").removeClass('fade-up');
        $(".item-2 .dp-content").addClass('opacity');
        $(".item-2 .dp-content img").addClass('fade-up');
        $(".item-3 .dp-content").removeClass('opacity');
        $(".item-3 .dp-content img").removeClass('fade-up');
        $(".div-3").removeClass('is-active');
        $(".div-2").addClass('is-active');
    });

    $("#dp-dots .third, .item-3").click(function () {
        $(".div-1").removeClass('is-active');
        $(".item-1 .dp-content").removeClass('opacity');
        $(".item-1 .dp-content img").removeClass('fade-up');
        $(".item-2 .dp-content").removeClass('opacity');
        $(".item-2 .dp-content img").removeClass('fade-up');
        $(".item-3 .dp-content").addClass('opacity');
        $(".item-3 .dp-content img").addClass('fade-up');
        $(".div-2").removeClass('is-active');
        $(".div-3").addClass('is-active');
    });

});
#home .content-slider {
    height: 600px;
    display: flex;
    justify-content: flex-end;
    position: relative;
    align-items: center;
    margin-top: -100px;
}

#home .text {
    margin-right: 50px;
    margin-top: -150px;
}

#home .div-1, #home .div-2, #home .div-3 {
    opacity: 0;
    left: -1000px;
    position: absolute;
    width: 320px;
    transition: 1s ease-in-out;
}

#home .is-active {
    opacity: 1;
    left: 160px;
}

#home .div-1, #home .div-2, #home .div-3 {
    text-align: right;
}

#home .div-1 h1, #home .div-2 h1, #home .div-3 h1 {
    font-family: Raleway-black;
    color: #000;
    text-transform: uppercase;
}

#home .div-1 p, #home .div-2 p, #home .div-3 p {
    font-family: Raleway-semi-bold;
    color: #333333;
}

#home .extra-bold {
    font-family: Raleway-extra-bold;
}

#home #slider {
    margin-right: 200px;
    margin-top: -150px;
}

#home .dp-wrap {
    margin: 0 auto;
    position: relative;
    height: 100%;
    width: 750px;
}

#home #dp-slider {
    width: 100%;
    height: 100% !important;
}

#home #slider .dp_item {
    display: block;
    position: absolute;
    color: #FFF;
    border-radius: 10px;
    transition: transform 1.2s;

}

#home #slider .dp-content {
    transition: 0.5s;
    opacity: 0;
}

#home #slider .item-1 {
    background-color: #cf132a;
}

#home .opacity {
    opacity: 1 !important;
}

#home #slider .item-1 img, #home #slider .item-2 img, #home #slider .item-3 img {
    width: 300px;
    filter: drop-shadow(0px 20px 10px rgba(0, 0, 0, 0.3));
    margin-left: 50px;
    top: 50px;
    position: relative;
    z-index: 1;
    transition: 1s ease-in-out;

}

#home .fade-up {
    top: 5px !important;
}

#home #slider .item-1 .absolute, #home #slider .item-2 .absolute, #home #slider .item-3 .absolute {
    font-family: Raleway-black;
    color: #a2a2a2;
    opacity: 0.33;
    position: absolute;
    letter-spacing: 15px;
    font-size: 1.8rem;
}

#home #slider .item-1 .line-1 {
    bottom: -60px;
    right: 30px;
}

#home #slider .item-1 .line-2 {
    bottom: -100px;
    right: -10px;
}

#home #slider .item-2 .line-1 {
    bottom: -60px;
    right: 20px;
}

#home #slider .item-2 .line-2 {
    bottom: -100px;
    right: 0;
}

#home #slider .item-3 .line-1 {
    bottom: -60px;
    right: 50px;
}

#home #slider .item-3 .line-2 {
    bottom: -100px;
    right: 0;
}

#home #slider .item-2 {
    background-color: #e3e3e3;
}

#home #slider .item-3 {
    background-color: #ffffff;
}

#home #dp-slider .dp_item:first-child {
    z-index: 10 !important;
    transform: rotateY(0deg) translateX(0px) !important;
}

#home #slider .dp_item[data-position="2"] {
    z-index: 9;
    transform: rotateY(0deg) translateX(10%) translateY(-15%) scale(0.9);
}

#home .transform {
    transform: rotateY(0deg) translateX(10%) translateY(-15%) scale(0.9) !important;
}

#home #slider .dp_item[data-position="3"] {
    z-index: 8;
    transform: rotateY(0deg) translateX(20%) translateY(-25%) scale(0.8);
}

#home #dp-dots {
    display: flex;
    position: absolute;
    top: -20px;
    z-index: 12;
    right: 30px;
    cursor: default;
    padding: 0;
}

#home #dp-dots li {
    list-style: none;
    width: 9px;
    background: #fff;
    border-radius: 10px;
    margin: 0 3px;
    filter: drop-shadow(0px 2px 1px rgba(0, 0, 0, 0.6));
    cursor: pointer;
}

#home #dp-dots .first {
    height: 55px;
}

#home #dp-dots .second {
    height: 45px;
}

#home #dp-dots .third {
    height: 35px;
}

#home #dp-dots li.active {
    background: #cf132a;
}

#home #slider .dp_item {
    box-shadow: 1px 2px 0 rgba(0, 0, 0, 0.2);
    width: 750px;
    height: 280px;
}

#home #dp-slider .dp_item:hover:not(:first-child) {
    cursor: pointer;
}

The New Hydra.VOX

With state-of-the-art tech the VOX is the newest generation of Audiobyte D/A Converters, the
                            result of years of research.

The New Hydra.HUB

The next step towards the ultimate Audio Stack – the hub packs enhanced audio transport
                            capability with a set of digital tools for even the most demanding user.

The Hydra.ZAP Power Supply

The ZAP is the dedicated, low-noise ultra-capacitor based power supply for the VOX HUB stack.
                            Attain supreme control over your digital equipment.

SUPREME IMMERSION

CONTEMPORARY DESIGN

VERSATILITY

DIGITAL MASTERY

HIGH PERFORMANCE

NO COMPROMISE

A: You should use the setInterval method to automate your slideshow.
For example, if you click a button and change the slide with event firing, call that method from setInterval starting from first index. And keep changing the value to make the slide show happen. I've created an example for you. (3 slides only)

jQuery(document).ready(function () {
  var ch = 1;
    function detect_active() {
        // get active
        var get_active = $("#dp-slider .dp_item:first-child").data("class");
        $("#dp-dots li").removeClass("active");
        $("#dp-dots li[data-class=" + get_active + "]").addClass("active");
    }
  function callClickEvent(){
    $("#dp-dots li").removeClass("active");
    var curCh = "ul li:nth-child("+ch+")";
        $(curCh).addClass("active");
        var get_slide = $(curCh).attr('data-class');
        $("#dp-slider .dp_item[data-class=" + get_slide + "]").hide().prependTo("#dp-slider").fadeIn();

        $('#slider .dp_item:nth-child('+ch+')').attr('data-position', ch);
    $(".div-"+ch+"").addClass('is-active');
        $(".item-"+ch+" .dp-content").addClass('opacity');
        $(".item-"+ch+" .dp-content img").addClass('fade-up');
    var r1 = r2 =0;
    if(ch == 1) {r1 = 2; r2 = 3;}
    if(ch == 2) {r1 = 1; r2 = 3;}
    if(ch == 3) {r1 = 1; r2 = 2;}
        $(".item-"+r1+" .dp-content").removeClass('opacity');
        $(".item-"+r1+" .dp-content img").removeClass('fade-up');
        $(".item-"+r2+" .dp-content").removeClass('opacity');
        $(".item-"+r2+" .dp-content img").removeClass('fade-up');
        $(".div-"+r1+"").removeClass('is-active');
        $(".div-"+r2+"").removeClass('is-active');
    ch++;
    if(ch>3) ch = 1;
  }
  setInterval(callClickEvent,2000);

    $("body").on("click", "#dp-slider .dp_item:not(:first-child)", function () {
        var get_slide = $(this).attr('data-class');
        $("#dp-slider .dp_item[data-class=" + get_slide + "]").hide().prependTo("#dp-slider").fadeIn();
        $.each($('#slider .dp_item'), function (index, dp_item) {
            $(dp_item).attr('data-position', index + 1);
        });

        detect_active();
    });
});
#home .content-slider {
    height: 600px;
    display: flex;
    justify-content: flex-end;
    position: relative;
    align-items: center;
    margin-top: -100px;
}

#home .text {
    margin-right: 50px;
    margin-top: -150px;
}

#home .div-1, #home .div-2, #home .div-3 {
    opacity: 0;
    left: -1000px;
    position: absolute;
    width: 320px;
    transition: 1s ease-in-out;
}

#home .is-active {
    opacity: 1;
    left: 160px;
}

#home .div-1, #home .div-2, #home .div-3 {
    text-align: right;
}

#home .div-1 h1, #home .div-2 h1, #home .div-3 h1 {
    font-family: Raleway-black;
    color: #000;
    text-transform: uppercase;
}

#home .div-1 p, #home .div-2 p, #home .div-3 p {
    font-family: Raleway-semi-bold;
    color: #333333;
}

#home .extra-bold {
    font-family: Raleway-extra-bold;
}

#home #slider {
    margin-right: 200px;
    margin-top: -150px;
}

#home .dp-wrap {
    margin: 0 auto;
    position: relative;
    height: 100%;
    width: 750px;
}

#home #dp-slider {
    width: 100%;
    height: 100% !important;
}

#home #slider .dp_item {
    display: block;
    position: absolute;
    color: #FFF;
    border-radius: 10px;
    transition: transform 1.2s;

}

#home #slider .dp-content {
    transition: 0.5s;
    opacity: 0;
}

#home #slider .item-1 {
    background-color: #cf132a;
}

#home .opacity {
    opacity: 1 !important;
}

#home #slider .item-1 img, #home #slider .item-2 img, #home #slider .item-3 img {
    width: 300px;
    filter: drop-shadow(0px 20px 10px rgba(0, 0, 0, 0.3));
    margin-left: 50px;
    top: 50px;
    position: relative;
    z-index: 1;
    transition: 1s ease-in-out;

}

#home .fade-up {
    top: 5px !important;
}

#home #slider .item-1 .absolute, #home #slider .item-2 .absolute, #home #slider .item-3 .absolute {
    font-family: Raleway-black;
    color: #a2a2a2;
    opacity: 0.33;
    position: absolute;
    letter-spacing: 15px;
    font-size: 1.8rem;
}

#home #slider .item-1 .line-1 {
    bottom: -60px;
    right: 30px;
}

#home #slider .item-1 .line-2 {
    bottom: -100px;
    right: -10px;
}

#home #slider .item-2 .line-1 {
    bottom: -60px;
    right: 20px;
}

#home #slider .item-2 .line-2 {
    bottom: -100px;
    right: 0;
}

#home #slider .item-3 .line-1 {
    bottom: -60px;
    right: 50px;
}

#home #slider .item-3 .line-2 {
    bottom: -100px;
    right: 0;
}

#home #slider .item-2 {
    background-color: #e3e3e3;
}

#home #slider .item-3 {
    background-color: #ffffff;
}

#home #dp-slider .dp_item:first-child {
    z-index: 10 !important;
    transform: rotateY(0deg) translateX(0px) !important;
}

#home #slider .dp_item[data-position="2"] {
    z-index: 9;
    transform: rotateY(0deg) translateX(10%) translateY(-15%) scale(0.9);
}

#home .transform {
    transform: rotateY(0deg) translateX(10%) translateY(-15%) scale(0.9) !important;
}

#home #slider .dp_item[data-position="3"] {
    z-index: 8;
    transform: rotateY(0deg) translateX(20%) translateY(-25%) scale(0.8);
}

#home #dp-dots {
    display: flex;
    position: absolute;
    top: -20px;
    z-index: 12;
    right: 30px;
    cursor: default;
    padding: 0;
}

#home #dp-dots li {
    list-style: none;
    width: 9px;
    background: #fff;
    border-radius: 10px;
    margin: 0 3px;
    filter: drop-shadow(0px 2px 1px rgba(0, 0, 0, 0.6));
    cursor: pointer;
}

#home #dp-dots .first {
    height: 55px;
}

#home #dp-dots .second {
    height: 45px;
}

#home #dp-dots .third {
    height: 35px;
}

#home #dp-dots li.active {
    background: #cf132a;
}

#home #slider .dp_item {
    box-shadow: 1px 2px 0 rgba(0, 0, 0, 0.2);
    width: 750px;
    height: 280px;
}

#home #dp-slider .dp_item:hover:not(:first-child) {
    cursor: pointer;
}

The New Hydra.VOX

With state-of-the-art tech the VOX is the newest generation of Audiobyte D/A Converters, the
                            result of years of research.

The New Hydra.HUB

The next step towards the ultimate Audio Stack – the hub packs enhanced audio transport
                            capability with a set of digital tools for even the most demanding user.

The Hydra.ZAP Power Supply

The ZAP is the dedicated, low-noise ultra-capacitor based power supply for the VOX HUB stack.
                            Attain supreme control over your digital equipment.

SUPREME IMMERSION

CONTEMPORARY DESIGN

VERSATILITY

DIGITAL MASTERY

HIGH PERFORMANCE

NO COMPROMISE

A: Another solution is to create a general function for both clicks and autoplay (that I created using a setInterval).
I decided to use your get_slide variable to switch to active li or slide.
These are my changes:
var num = 1; // a variable to set the actual active slider

$("#dp-dots li, #dp-slider .dp_item").click(function() {
    var get_slide = $(this).attr('data-class');
    num = get_slide
    generalClick(get_slide);
});

function generalClick(number) {
    $("#dp-dots li").removeClass("active");
    $("#dp-dots li:nth-child(" + number + ")").addClass("active");
    $("#dp-slider .dp_item[data-class=" + number + "]").hide().prependTo("#dp-slider").fadeIn();
    $.each($('#slider .dp_item'), function(index, dp_item) {
        $(dp_item).attr('data-position', index + 1);
    });

    $(".text .div").removeClass('is-active');
    $(".div-" + number).addClass('is-active');

    $(".dp_item .dp-content").removeClass('opacity');
    $(".dp_item .dp-content img").removeClass('fade-up');

    $(".item-" + number + " .dp-content").addClass('opacity');
    $(".item-" + number + " .dp-content img").addClass('fade-up');
}

setInterval(function() {
    num++
    if (num > $("#dp-dots li").length) {
        num = 1;
    }
    generalClick(num);
}, 5000);

The code at work (I commented on yours that I didn't use):

jQuery(document).ready(function () {

    function detect_active() {
        // get active
        var get_active = $("#dp-slider .dp_item:first-child").data("class");
        $("#dp-dots li").removeClass("active");
        $("#dp-dots li[data-class=" + get_active + "]").addClass("active");
    }

    var num=1;

    $("#dp-dots li, #dp-slider .dp_item").click(function () {
        /*$("#dp-dots li").removeClass("active");
        $(this).addClass("active");*/

        /*$("#dp-slider .dp_item[data-class=" + get_slide + "]").hide().prependTo("#dp-slider").fadeIn();*/
        var get_slide = $(this).attr('data-class');
        num=get_slide
        generalClick(get_slide);

    });

    function generalClick(number){
        $("#dp-dots li").removeClass("active");
        $("#dp-dots li:nth-child("+number+")").addClass("active");
        $("#dp-slider .dp_item[data-class=" + number + "]").hide().prependTo("#dp-slider").fadeIn();
        $.each($('#slider .dp_item'), function (index, dp_item) {
            $(dp_item).attr('data-position', index + 1);
        });

        $(".text .div").removeClass('is-active');
        $(".div-"+ number).addClass('is-active');

        $(".dp_item .dp-content").removeClass('opacity');
        $(".dp_item .dp-content img").removeClass('fade-up');

        $(".item-"+ number +" .dp-content").addClass('opacity');
        $(".item-"+ number +" .dp-content img").addClass('fade-up');
    }

    setInterval( function() {
        num ++
        if(num > $("#dp-dots li").length){
            num=1;
        }
        generalClick(num);
    }, 5000 );

    $("body").on("click", "#dp-slider .dp_item:not(:first-child)", function () {
        var get_slide = $(this).attr('data-class');
        $("#dp-slider .dp_item[data-class=" + get_slide + "]").hide().prependTo("#dp-slider").fadeIn();
        $.each($('#slider .dp_item'), function (index, dp_item) {
            $(dp_item).attr('data-position', index + 1);
        });

        detect_active();
    });

    /*$("#dp-dots .first,#dp-slider .item-1").click(function () {
        $(".div-1").addClass('is-active');
        $(".item-1 .dp-content").addClass('opacity');
        $(".item-1 .dp-content img").addClass('fade-up');
        $(".item-2 .dp-content").removeClass('opacity');
        $(".item-2 .dp-content img").removeClass('fade-up');
        $(".item-3 .dp-content").removeClass('opacity');
        $(".item-3 .dp-content img").removeClass('fade-up');
        $(".div-2").removeClass('is-active');
        $(".div-3").removeClass('is-active');
    });

    $("#dp-dots .second, .item-2").click(function () {
        $(".div-1").removeClass('is-active');
        $(".item-1 .dp-content").removeClass('opacity');
        $(".item-1 .dp-content img").removeClass('fade-up');
        $(".item-2 .dp-content").addClass('opacity');
        $(".item-2 .dp-content img").addClass('fade-up');
        $(".item-3 .dp-content").removeClass('opacity');
        $(".item-3 .dp-content img").removeClass('fade-up');
        $(".div-3").removeClass('is-active');
        $(".div-2").addClass('is-active');
    });

    $("#dp-dots .third, .item-3").click(function () {
        $(".div-1").removeClass('is-active');
        $(".item-1 .dp-content").removeClass('opacity');
        $(".item-1 .dp-content img").removeClass('fade-up');
        $(".item-2 .dp-content").removeClass('opacity');
        $(".item-2 .dp-content img").removeClass('fade-up');
        $(".item-3 .dp-content").addClass('opacity');
        $(".item-3 .dp-content img").addClass('fade-up');
        $(".div-2").removeClass('is-active');
        $(".div-3").addClass('is-active');
    });*/
});
#home .content-slider {
    height: 600px;
    display: flex;
    justify-content: flex-end;
    position: relative;
    align-items: center;
    margin-top: -100px;
}

#home .text {
    margin-right: 50px;
    margin-top: -150px;
}

#home .div-1, #home .div-2, #home .div-3 {
    opacity: 0;
    left: -1000px;
    position: absolute;
    width: 320px;
    transition: 1s ease-in-out;
}

#home .is-active {
    opacity: 1;
    left: 160px;
}

#home .div-1, #home .div-2, #home .div-3 {
    text-align: right;
}

#home .div-1 h1, #home .div-2 h1, #home .div-3 h1 {
    font-family: Raleway-black;
    color: #000;
    text-transform: uppercase;
}

#home .div-1 p, #home .div-2 p, #home .div-3 p {
    font-family: Raleway-semi-bold;
    color: #333333;
}

#home .extra-bold {
    font-family: Raleway-extra-bold;
}

#home #slider {
    margin-right: 200px;
    margin-top: -150px;
}

#home .dp-wrap {
    margin: 0 auto;
    position: relative;
    height: 100%;
    width: 750px;
}

#home #dp-slider {
    width: 100%;
    height: 100% !important;
}

#home #slider .dp_item {
    display: block;
    position: absolute;
    color: #FFF;
    border-radius: 10px;
    transition: transform 1.2s;

}

#home #slider .dp-content {
    transition: 0.5s;
    opacity: 0;
}

#home #slider .item-1 {
    background-color: #cf132a;
}

#home .opacity {
    opacity: 1 !important;
}

#home #slider .item-1 img, #home #slider .item-2 img, #home #slider .item-3 img {
    width: 300px;
    filter: drop-shadow(0px 20px 10px rgba(0, 0, 0, 0.3));
    margin-left: 50px;
    top: 50px;
    position: relative;
    z-index: 1;
    transition: 1s ease-in-out;

}

#home .fade-up {
    top: 5px !important;
}

#home #slider .item-1 .absolute, #home #slider .item-2 .absolute, #home #slider .item-3 .absolute {
    font-family: Raleway-black;
    color: #a2a2a2;
    opacity: 0.33;
    position: absolute;
    letter-spacing: 15px;
    font-size: 1.8rem;
}

#home #slider .item-1 .line-1 {
    bottom: -60px;
    right: 30px;
}

#home #slider .item-1 .line-2 {
    bottom: -100px;
    right: -10px;
}

#home #slider .item-2 .line-1 {
    bottom: -60px;
    right: 20px;
}

#home #slider .item-2 .line-2 {
    bottom: -100px;
    right: 0;
}

#home #slider .item-3 .line-1 {
    bottom: -60px;
    right: 50px;
}

#home #slider .item-3 .line-2 {
    bottom: -100px;
    right: 0;
}

#home #slider .item-2 {
    background-color: #e3e3e3;
}

#home #slider .item-3 {
    background-color: #ffffff;
}

#home #dp-slider .dp_item:first-child {
    z-index: 10 !important;
    transform: rotateY(0deg) translateX(0px) !important;
}

#home #slider .dp_item[data-position="2"] {
    z-index: 9;
    transform: rotateY(0deg) translateX(10%) translateY(-15%) scale(0.9);
}

#home .transform {
    transform: rotateY(0deg) translateX(10%) translateY(-15%) scale(0.9) !important;
}

#home #slider .dp_item[data-position="3"] {
    z-index: 8;
    transform: rotateY(0deg) translateX(20%) translateY(-25%) scale(0.8);
}

#home #dp-dots {
    display: flex;
    position: absolute;
    top: -20px;
    z-index: 12;
    right: 30px;
    cursor: default;
    padding: 0;
}

#home #dp-dots li {
    list-style: none;
    width: 9px;
    background: #fff;
    border-radius: 10px;
    margin: 0 3px;
    filter: drop-shadow(0px 2px 1px rgba(0, 0, 0, 0.6));
    cursor: pointer;
}

#home #dp-dots .first {
    height: 55px;
}

#home #dp-dots .second {
    height: 45px;
}

#home #dp-dots .third {
    height: 35px;
}

#home #dp-dots li.active {
    background: #cf132a;
}

#home #slider .dp_item {
    box-shadow: 1px 2px 0 rgba(0, 0, 0, 0.2);
    width: 750px;
    height: 280px;
}

#home #dp-slider .dp_item:hover:not(:first-child) {
    cursor: pointer;
}

The New Hydra.VOX

With state-of-the-art tech the VOX is the newest generation of Audiobyte D/A Converters, the
               result of years of research.

The New Hydra.HUB

The next step towards the ultimate Audio Stack – the hub packs enhanced audio transport
               capability with a set of digital tools for even the most demanding user.

The Hydra.ZAP Power Supply

The ZAP is the dedicated, low-noise ultra-capacitor based power supply for the VOX HUB stack.
               Attain supreme control over your digital equipment.

SUPREME IMMERSION

CONTEMPORARY DESIGN

VERSATILITY

DIGITAL MASTERY

HIGH PERFORMANCE

NO COMPROMISE

EDIT1
To stop the interval when you enter with mouse in slider stage I did these changes:
var myInterval = setInterval(myTimer, 5000);

function myTimer() {
  num ++
  if(num > $("#dp-dots li").length){
    num=1;
  }
  generalClick(num);
}

$(".content-slider").on("mouseenter", function() {
    clearInterval(myInterval);
}).on("mouseleave", function() {
    myInterval = setInterval(myTimer, 5000);
});

EDIT 2
To stop the click action on the active element you can work with a simple conditional statement:
$("#dp-dots li, #dp-slider .dp_item").click(function() {
     var get_slide = $(this).attr('data-class');
     num=get_slide
     if($(this).attr('data-position')!=1){
        generalClick(get_slide);
     }
});

jQuery(document).ready(function () {

    var num=1;

    $("#dp-dots li, #dp-slider .dp_item").click(function() {
        var get_slide = $(this).attr('data-class');
        num=get_slide
        if($(this).attr('data-position')!=1){
            generalClick(get_slide);
         }
    });

    function generalClick(number){
        $("#dp-dots li").removeClass("active");
        $("#dp-dots li:nth-child("+number+")").addClass("active");
        $("#dp-slider .dp_item[data-class=" + number + "]").hide().prependTo("#dp-slider").fadeIn();
        $.each($('#slider .dp_item'), function (index, dp_item) {
            $(dp_item).attr('data-position', index + 1);
        });

        $(".text .div").removeClass('is-active');
        $(".div-"+ number).addClass('is-active');

        $(".dp_item .dp-content").removeClass('opacity');
        $(".dp_item .dp-content img").removeClass('fade-up');

        $(".item-"+ number +" .dp-content").addClass('opacity');
        $(".item-"+ number +" .dp-content img").addClass('fade-up');
    }

    var myInterval = setInterval(myTimer, 5000);

    function myTimer() {
      num ++
      if(num > $("#dp-dots li").length){
        num=1;
      }
      generalClick(num);
    }

    $(".content-slider").on("mouseenter", function() {
        clearInterval(myInterval);
    }).on("mouseleave", function() {
        myInterval = setInterval(myTimer, 5000);
    });

});
#home .content-slider {
    height: 600px;
    display: flex;
    justify-content: flex-end;
    position: relative;
    align-items: center;
    margin-top: -100px;
}

#home .text {
    margin-right: 50px;
    margin-top: -150px;
}

#home .div-1, #home .div-2, #home .div-3 {
    opacity: 0;
    left: -1000px;
    position: absolute;
    width: 320px;
    transition: 1s ease-in-out;
}

#home .is-active {
    opacity: 1;
    left: 160px;
}

#home .div-1, #home .div-2, #home .div-3 {
    text-align: right;
}

#home .div-1 h1, #home .div-2 h1, #home .div-3 h1 {
    font-family: Raleway-black;
    color: #000;
    text-transform: uppercase;
}

#home .div-1 p, #home .div-2 p, #home .div-3 p {
    font-family: Raleway-semi-bold;
    color: #333333;
}

#home .extra-bold {
    font-family: Raleway-extra-bold;
}

#home #slider {
    margin-right: 200px;
    margin-top: -150px;
}

#home .dp-wrap {
    margin: 0 auto;
    position: relative;
    height: 100%;
    width: 750px;
}

#home #dp-slider {
    width: 100%;
    height: 100% !important;
}

#home #slider .dp_item {
    display: block;
    position: absolute;
    color: #FFF;
    border-radius: 10px;
    transition: transform 1.2s;

}

#home #slider .dp-content {
    transition: 0.5s;
    opacity: 0;
}

#home #slider .item-1 {
    background-color: #cf132a;
}

#home .opacity {
    opacity: 1 !important;
}

#home #slider .item-1 img, #home #slider .item-2 img, #home #slider .item-3 img {
    width: 300px;
    filter: drop-shadow(0px 20px 10px rgba(0, 0, 0, 0.3));
    margin-left: 50px;
    top: 50px;
    position: relative;
    z-index: 1;
    transition: 1s ease-in-out;

}

#home .fade-up {
    top: 5px !important;
}

#home #slider .item-1 .absolute, #home #slider .item-2 .absolute, #home #slider .item-3 .absolute {
    font-family: Raleway-black;
    color: #a2a2a2;
    opacity: 0.33;
    position: absolute;
    letter-spacing: 15px;
    font-size: 1.8rem;
}

#home #slider .item-1 .line-1 {
    bottom: -60px;
    right: 30px;
}

#home #slider .item-1 .line-2 {
    bottom: -100px;
    right: -10px;
}

#home #slider .item-2 .line-1 {
    bottom: -60px;
    right: 20px;
}

#home #slider .item-2 .line-2 {
    bottom: -100px;
    right: 0;
}

#home #slider .item-3 .line-1 {
    bottom: -60px;
    right: 50px;
}

#home #slider .item-3 .line-2 {
    bottom: -100px;
    right: 0;
}

#home #slider .item-2 {
    background-color: #e3e3e3;
}

#home #slider .item-3 {
    background-color: #ffffff;
}

#home #dp-slider .dp_item:first-child {
    z-index: 10 !important;
    transform: rotateY(0deg) translateX(0px) !important;
}

#home #slider .dp_item[data-position="2"] {
    z-index: 9;
    transform: rotateY(0deg) translateX(10%) translateY(-15%) scale(0.9);
}

#home .transform {
    transform: rotateY(0deg) translateX(10%) translateY(-15%) scale(0.9) !important;
}

#home #slider .dp_item[data-position="3"] {
    z-index: 8;
    transform: rotateY(0deg) translateX(20%) translateY(-25%) scale(0.8);
}

#home #dp-dots {
    display: flex;
    position: absolute;
    top: -20px;
    z-index: 12;
    right: 30px;
    cursor: default;
    padding: 0;
}

#home #dp-dots li {
    list-style: none;
    width: 9px;
    background: #fff;
    border-radius: 10px;
    margin: 0 3px;
    filter: drop-shadow(0px 2px 1px rgba(0, 0, 0, 0.6));
    cursor: pointer;
}

#home #dp-dots .first {
    height: 55px;
}

#home #dp-dots .second {
    height: 45px;
}

#home #dp-dots .third {
    height: 35px;
}

#home #dp-dots li.active {
    background: #cf132a;
}

#home #slider .dp_item {
    box-shadow: 1px 2px 0 rgba(0, 0, 0, 0.2);
    width: 750px;
    height: 280px;
}

#home #dp-slider .dp_item:hover:not(:first-child) {
    cursor: pointer;
}

The New Hydra.VOX

With state-of-the-art tech the VOX is the newest generation of Audiobyte D/A Converters, the
               result of years of research.

The New Hydra.HUB

The next step towards the ultimate Audio Stack – the hub packs enhanced audio transport
               capability with a set of digital tools for even the most demanding user.

The Hydra.ZAP Power Supply

The ZAP is the dedicated, low-noise ultra-capacitor based power supply for the VOX HUB stack.
               Attain supreme control over your digital equipment.

SUPREME IMMERSION

CONTEMPORARY DESIGN

VERSATILITY

DIGITAL MASTERY

HIGH PERFORMANCE

NO COMPROMISE


text:
Q: UITextView appears scrolled halfway down I have a view that entirely contains a UITextView. Using scrollRangeToVisible or scrollRectToVisible worked in Xcode 6, but no longer works in Xcode 7. Here is my code:
@IBOutlet weak var textView: UITextView!

override func viewDidLoad() {
    super.viewDidLoad()

    textView.text = "super long text...."
    self.navigationController!.navigationBar.translucent = false
    self.textView.scrollRangeToVisible(NSMakeRange(0, 1))
    self.textView.scrollRectToVisible(CGRectMake(0, 0, 1, 1), animated: true)
}

I've tried putting scrollRangeToVisible and scrollRectToVisible in viewDidAppear and viewWillAppear, tried changing their range/rect values, and nothing seems to work.
Again, this did work pre-Swift 2. Has anything about scrolling text views changed with the upgrade?


text:
Q: What behaviors might attract the ghost to you? When a hunt starts, the ghost goes out looking for a victim. What I heard when a hunt happens is go into a room, close the door, close your flashlights and shut up. But that is only hearsay, I never saw really what you need to do to dodge a hunt.
So what comportments really make a ghost know where you are?

A: The biggest thing that attracts a ghost to you in line of sight and sound. Having low sanity will make hunts more frequent, but as far as I know, it doesn't affect who gets targeted during a hunt.
However, a ghost having line of sight to your character means that you're likely to be targeted. Ghosts seem to have a perception based on a cone coming from their character, meaning they may not spot you if you're behind them or far enough to their peripheral. If you're in front of them, directly in their sight then they'll likely target you.
Next is sound. Ghosts investigate the locations players spoke at. During a hunt once line of sight is broken (or never established) it is important to keep quiet as to not attract a ghost to your location. Ghosts can hear sounds in their proximity meaning they may hunt you down even in an enclosed room if the players don't stop talking. It is crucial to note that ghosts can hear all voices, even if push-to-talk isn't pressed. If you're muttering to yourself even without speaking to other players the ghost can still locate you.
Now, what happens if the ghost spots two players at the same time? It's still unclear but it seems to be random, or close to random on who gets targeted. Sanity does not seem to correlate with who is targeted, there are a few videos of players standing close to the ghost while it runs past them to target other players, so it may be determined by who is unlucky enough to be seen first by the ghost. This is still unconfirmed and the ghost is known to switch targets during a hunt, especially if other players come closer to the ghost.
Lastly, while it doesn't attract the ghost to you, hiding in the ghost's room is dangerous during a hunt because the ghost spawns in or adjacent to the room and roams the immediate area. This when attempting to hide you may still be spotted as the ghost patrols more thoroughly in this zone than elsewhere.


text:
Q: css: expand div on hover without displacing other divs I have the following code :

text 1
text 1
text 1

text 2
text 2
text 2

text 3
text 3
text 3

text 4
text 4
text 4

text 5
text 5
text 5

text 6
text 6
text 6

text 7
text 7
text 7

text 8
text 8
text 8

text 9
text 9
text 9

text 10
text 10
text 10

see it in action :
http://jsfiddle.net/6K7t4/
when a div id hovered, it should expand without displacing other divs as shown at :
http://shopping.kelkoo.co.uk/ss-shirt.html
Also, please suggest how to achieve a cross-browser solution.
If it can be done using pure css, I prefer that solution.
If not, can it be done using jquery in an easy way without plugins?

A: You can use the child selector element by adding another div with the class you would like to select. Here is your code updated below using it. Hope this helps!

 1
text 1
text 1

 2
text 2
text 2

 3
text 3
text 3

 4
text 4
text 4

 5
text 5
text 5

 6
text 6
text 6

 7
text 7
text 7

 8
text 8
text 8

 9
text 9
text 9

 10
text 10
text 10

 #items {width:300px;}
.item {width:100px;border:solid 1px #ccc;float:left;height:20px;overflow:hidden;}
.item:hover >.item-extend {position:absolute;width:100px;background:#fff;}

You can demo the updated code here : http://jsfiddle.net/6K7t4/35/
UPDATE: you dont even have to use the child selector element, instead you can just change it on :hover by switching out .item:hover >.item-extend with .item-extend:hover. Works the exact same way.

A: You need an extra div in order to hold an absolute-positioned one inside.
HTML

text 1
text 1
text 1

item is absolute, and itemHolder floats.
CSS
#items {width:300px; padding:30px;}

// Floats and hides content with height and overflow
.itemHolder {float:left; width:100px; border:solid 1px #ccc; height:20px; overflow:hidden; position:relative;}

// Absolute
.item {position:absolute; top:0; left:0; z-index:1; width:100%; background:#FFF; border:1px solid #999; border-top:0;}

// On hover we make the overflow visible and give the div to show a higher z index
.itemHolder:hover {overflow:visible;}
.itemHolder:hover .item {z-index:2;}

Live solution here: http://jsfiddle.net/vWGCc/
:)

A: You can achieve it with little javascript. See below,
$('.item').hover(function () {
    var pos = $(this).position();
    var $clone = $(this).clone();
    $clone.appendTo(this).addClass('item_clone').css({
        left: pos.left,
        top: pos.top
    });
}, function () {
    $('.item_clone', this).remove();
});

DEMO: http://jsfiddle.net/6K7t4/32/
Note: Check other CSS based answers which is always better than achieving it via scripts.

A: See this demo: http://jsfiddle.net/6K7t4/24/
HTML:

text 1
text 1
text 1

text 2
text 2
text 2

text 3
text 3
text 3

text 4
text 4
text 4

text 5
text 5
text 5

text 6
text 6
text 6

text 7
text 7
text 7

text 8
text 8
text 8

text 9
text 9
text 9

text 10
text 10
text 10

CSS:
#items {
     width:300px;
}

.item {
    width:100px;
    border:solid 1px #ccc;
    float:left;
    height:20px;
    z-index:0;
    overflow:hidden;
    position:relative;
}

.item:hover {
    overflow:visible;
    z-index:100;
}

.item:hover .inner {
    z-index: 100;
}

.inner {
    position: absolute;
    background: white;
    width: 100%;
}

Each .item is now positioned relatively and has new child which wraps all content inside it. Once div is hovered, .item's overflow:hidden is changed to overflow:visible and z-index of .inner is set to 100 (in order to show it above other divs).
UPD: New demo and updated code. For IE7 (z-index is changed for .item:hover, otherwise inner div is hidden below other .items in IE7)


text:
Q: Parsing webserver JSON Values to data property I am trying to use the JSON values from a file on a hosted webserver and believe I am parsing the values correctly and using them within my Chartjs arrays, but for some reason I am getting error messages that I can't quite debug.
error 1: Uncaught SyntaxError: Unexpected token h
code reference: var gaValues = JSON.parse(url);
error 2: Uncaught SyntaxError: Unexpected token :
code reference: labels: [ga:dayOfWeekName],
JSON:
{"kind": "analytics#gaData", "rows": [["Friday", "2"], ["Monday", "3"], ["Saturday", "0"], ["Sunday", "1"], ["Thursday", "4"], ["Tuesday", "4"], ["Wednesday", "4"]], "containsSampledData": false, "profileInfo": {"webPropertyId": "UA-22222-1", "internalWebPropertyId": "222222", "tableId": "ga:22222", "profileId": "2222", "profileName": "All Web Site Data", "accountId": "222222"}, "itemsPerPage": 50, "id": "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:222222&dimensions=ga:dayOfWeekName&metrics=ga:sessions&start-date=7daysAgo&end-date=yesterday&max-results=50", "totalResults": 7, "query": {"max-results": 50, "dimensions": "ga:dayOfWeekName", "start-date": "7daysAgo", "start-index": 1, "ids": "ga:22222", "metrics": ["ga:sessions"], "end-date": "yesterday"}, "totalsForAllResults": {"ga:sessions": "18"}, "columnHeaders": [{"dataType": "STRING", "columnType": "DIMENSION", "name": "ga:dayOfWeekName"}, {"dataType": "INTEGER", "columnType": "METRIC", "name": "ga:sessions"}], "selfLink": "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:22222&dimensions=ga:dayOfWeekName&metrics=ga:sessions&start-date=7daysAgo&end-date=yesterday&max-results=50"}

charts-options.js:
    var url = 'https://test.appspot.com/query?id=ahJzfmNvbm5vcnBoaWxsaXBzMjtetssesestestststRyFQsSCEFwaVF1ZXJ5GICAgICAgIAKDA';

    var gaValues = JSON.parse(url);

    var barChartdata = {
        labels: [ga:dayOfWeekName],
        datasets: [
            {
                label: "My First dataset",
                fillColor: "rgba(220,220,220,0.5)",
                strokeColor: "rgba(220,220,220,0.8)",
                highlightFill: "rgba(220,220,220,0.75)",
                highlightStroke: "rgba(220,220,220,1)",
                data: [gaValues.ga:sessions]
            }
        ]
    };

    var options = {

        //Boolean - Whether the scale should start at zero, or an order of magnitude down from the lowest value
        scaleBeginAtZero : true,

        //Boolean - Whether grid lines are shown across the chart
        scaleShowGridLines : true,

        //String - Colour of the grid lines
        scaleGridLineColor : "rgba(0,0,0,.05)",

        //Number - Width of the grid lines
        scaleGridLineWidth : 1,

        //Boolean - If there is a stroke on each bar
        barShowStroke : true,

        //Number - Pixel width of the bar stroke
        barStrokeWidth : 2,

        //Number - Spacing between each of the X value sets
        barValueSpacing : 5,

        //Number - Spacing between data sets within X values
        barDatasetSpacing : 1,

        //Boolean - Set if responsive or not
        responsive : true

    }

window.onload = function(){

    // Get the context of the canvas element
    var ctx = document.getElementById("sessions-graph").getContext("2d");
    var sessionsGraph = new Chart(ctx).Bar(barChartdata, options); //Create a chart with "data" array

};

index.html:
<!doctype html>
<html>

    <head>
        <title>Google Super Proxy Test</title>

        <script src="chart-options.js"></script>
         <script src="Chart.min.js"></script>
         <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    </head>

<body>

    <div style="width: 50%">
        <canvas id="sessions-graph" height="450" width="600"></canvas>
    </div>

</body>

</html>

A: JSON.parse expects a json string, not an URL you need to load the data yourself i.e. using XMLHTTPRequest. Despite the fact that gaValues is undefined, you also need to access object keys containing special characters using the following notation:
gaValues["ga:sessions"]

A: You are trying to parse URL in your code at line var gaValues = JSON.parse(url);
The JSON.parse() method parses a string as JSON. You need to pass your response as parameter not URL.


text:
Q: Administer AppFabric cache remotely I have written a website which administers my company's appfabric cache. I would like to deploy that website to a server other than the any within the cache cluster.
I have copied the powershell modules from my development machine to the web server, but when I fire up my website it says it's missing the Microsoft.ApplicationServer.StoreManagement assembly.
Now I could probably hack things by creating a zip file with all the assemblies it needs and install those manually into the GAC. But I would rather do things properly. So, is there a correct/supported way of installing the administration part of appfabric without installing the cache services?