text:
Q: Make clickable link inside clickable box (ActionLink inside ) I am trying to make a whole table row clickable and have done so using javascript. However, this does not let you see the target link in the status bar and also prevents you from opening these links in new tabs.
Therefore, I have been trying the following:

  @Html.ActionLink(...)
  @Html.ActionLink(...)
  @Html.ActionLink(...)

Then using display:block; on the anchors to make the full row clickable.
tr:hover {
   background: red;
}

td a {
   display: block;
   border: 1px solid black;
   padding: 16px;
}

However, I can no longer click the action link, wherever I click on the table row, it takes me to whatever I have in the anchor.
That leads me to my question. How can I make it so that if I click anywhere in the row, it takes me to my anchor, but if I click precisely on the action link, it takes me to where that is set.
Any help is greatly appreciated.

A: Someone has written a plugin for Bootstrap 3 that makes this easy to do. Jasny Bootstrap has "Row Links" which allow you do to the following:

    First Link
    Some text	Action

where the entire row will link to #wholerow and the  tag will link to #


text:
Q: How to contol KeyEvent in Qt
With the window declared with CustomWidget as super class: class App(CustomWidget) hitting Alt+A properly prints 'keyPressEvent: Alt + a' message.
But the KeyEvent functionality is broken when the CustomWidget is assigned to window with setCentralWidget() or is set with layer.addWidget(widget). What is missing in a code?
from PyQt4 import QtCore, QtGui

class CustomWidget(QtGui.QWidget):
    def __init__(self, parent):
        QtGui.QWidget.__init__(self, parent=parent)

    def keyPressEvent(self, event):
        if event.modifiers() == QtCore.Qt.AltModifier:
            if event.key() == QtCore.Qt.Key_A:
                print 'keyPressEvent: Alt + a'
        # super(CustomWidget, self).keyPressEvent(event)

class App(QtGui.QMainWindow):
    def __init__(self, parent=None):
        QtGui.QMainWindow.__init__(self, parent=parent)
        centralWidget = CustomWidget(self)

        self.setCentralWidget(centralWidget)

        mainLayout=QtGui.QVBoxLayout()
        centralWidget.setLayout(mainLayout)

        widget = CustomWidget(self)
        mainLayout.addWidget(widget)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = App()
    w.show()
    sys.exit(app.exec_())

A: The widget must have focus to receive the event.  Make sure you call setFocusPolicy() to have the CustomWidget accept and maintain focus after creating the window.
QWidget, keyPressEvent
QWidget, setFocusPolicy

A: Working Solution:
Important: At the end of GroupBox' keyPressEvent() method we have to pass the Event up to the super. Or the Event will not get propagated to the parent widget: super(QtGui.QGroupBox, self).keyPressEvent(event)

import sys
from PyQt4 import QtCore, QtGui

class MainWindow(QtGui.QMainWindow):
    def __init__(self, parent):
        QtGui.QMainWindow.__init__(self, parent=parent)
        self.setFocusPolicy(QtCore.Qt.StrongFocus)

    def keyPressEvent(self, event):
        if event.modifiers() == QtCore.Qt.ControlModifier:
            if event.key() == QtCore.Qt.Key_T:
                print 'MainWindow: Control + t'
            if event.key() == QtCore.Qt.Key_M:
                print 'MainWindow: Control + m'

class GroupBox(QtGui.QGroupBox):
    def __init__(self, parent=None):
        QtGui.QGroupBox.__init__(self, parent=parent)
        self.setFocusPolicy(QtCore.Qt.StrongFocus)

    def keyPressEvent(self, event):
        if event.modifiers() == QtCore.Qt.ControlModifier:
            if event.key() == QtCore.Qt.Key_T:
                print 'GroupBox: Control + t'
            if event.key() == QtCore.Qt.Key_S:
                print 'GroupBox: Control + s'
        super(QtGui.QGroupBox, self).keyPressEvent(event)

class App(MainWindow):
    def __init__(self, parent=None):
        MainWindow.__init__(self, parent=parent)
        centralWidget = QtGui.QWidget(self)

        self.setCentralWidget(centralWidget)

        mainLayout=QtGui.QVBoxLayout()
        centralWidget.setLayout(mainLayout)

        groupBox = GroupBox(self)
        mainLayout.addWidget(groupBox)

if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    w = App()
    w.show()
    sys.exit(app.exec_())

redpajama_set_name: RedPajamaStackExchange


text:
Q: Publish NetCore 2.2 on IIS from Linux I know there is an open issue to make msdeploy cross-platform (https://github.com/aspnet/Tooling/issues/583). But I would like to know if there is any workaround deploy a NetCore application in a Windows IIS machine from Linux.
I have a CentOS jenkins-agent that does the dotnet build, dotnet test and then dotnet publish. In a Windows agent I would call MSDeploy, but I don't have one. How to approach this?

A: Use up to dotnet -publish and copy to the desired folder. Pre-copy the file appofline and delete it after.


text:
Q: Magento admin login not working in chrome but works fine for firefox I am just a newbie to the magento. I have installed magento on my localhost. After all the setup when I used the admin page to login I can't able to login in chrome browser even with my right username and password. But when I am trying to login in firefox there is no problem. So can some one really help me here to solve the problem?

A: I think there is the problem with session cookie with the chrome browser.
So just go through this directory
/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php file
and comment out the line from 85 to 92 in magento (1.7.2 for my case). Like this
    // session cookie params
   /* $cookieParams = array(
        'lifetime' => $cookie->getLifetime(),
        'path'     => $cookie->getPath(),
        'domain'   => $cookie->getConfigDomain(),
        'secure'   => $cookie->isSecure(),
        'httponly' => $cookie->getHttponly()
    );
  */

after that try to make login from your backend. Hopefully you can make login with chrome. This will definitely help you. If you are still facing the problem then just reply me.

A: From System -> Configuration -> General -> Web, set Unsecure and Secure Base URL with IP Address. And try to login again.

A: GO to File at this location :- app\code\core\Mage\Core\Model\Session\Abstract\Varien.php
And commenting out the following (it's lines 85 to 102);
// session cookie params
$cookieParams = array(
    'lifetime' => $cookie->getLifetime(),
    'path'     => $cookie->getPath()//,
    //'domain'   => $cookie->getConfigDomain(),
    //'secure'   => $cookie->isSecure(),
    //'httponly' => $cookie->getHttponly()
);

//if (!$cookieParams['httponly']) {
//    unset($cookieParams['httponly']);
//    if (!$cookieParams['secure']) {
//        unset($cookieParams['secure']);
//        if (!$cookieParams['domain']) {
//            unset($cookieParams['domain']);
//        }
//    }
//}

And use your credentials to logged in. Hope that should works for you!!!

A: try using 127.0.0.1 when you set up magento in localhost. I have also encounter same problem, that's the solution a have made and it works fine.

A: Magento sees cookie_domain on core_config_data table when you try to login. If it is diffrent from your domain, you can not enter your admin panel, just refreshing the page, no error comes up.
Open core_config_data table from your database and search or filter the path column for web/cookie/cookie_domain and change it to null or your domain.

A: When it happens with me, the problems was because I make a directory move but the .HTACCESS files of main content was not moved to new path.
Check if your .htaccess file is in main content.

A: just apply the comment here...
file location : \app\code\core\Mage\Core\Model\Session\Abstract\Varien.php
/*
// session cookie params
    $cookieParams = array(
        'lifetime' => $cookie->getLifetime(),
        'path'     => $cookie->getPath(),
        'domain'   => $cookie->getConfigDomain(),
        'secure'   => $cookie->isSecure(),
        'httponly' => $cookie->getHttponly()
    );
  */

A: login as admin with internet explorer or other broswer. flush all caches.. And you will be able to log in using chrome . You can login in without having to modify any code

A: If you are using Magento 1.9, the file must be slightly different:
/app/code/core/Mage/Core/Model/Session/Abstract/Varien.php
 $cookieParams = array(
        'lifetime' => $cookie->getLifetime(),
        'path'     => $cookie->getPath()/*,
        'domain'   => $cookie->getConfigDomain(),
        'secure'   => $cookie->isSecure(),
        'httponly' => $cookie->getHttponly()*/
    );

    /*if (!$cookieParams['httponly']) {
        unset($cookieParams['httponly']);
        if (!$cookieParams['secure']) {
            unset($cookieParams['secure']);
            if (!$cookieParams['domain']) {
                unset($cookieParams['domain']);
            }
        }
    }*/

A: It's also important that you have a form key present, otherwise your form won't get processed.
<?php echo $this->getBlockHtml('formkey'); ?>

A: This is my simple solution that helped me in the same situation. Try it for 60 seconds of your time.
In Google Chrome, in Developer Tools (right-click on any page element and select Inspect Element), go to the Resources -> Cookies tab. Delete the extra cookie for your original domain. Or set your base url domain to something else, or change the port.

A: As the accepted answer pointed out, the problem lies with chrome when accessing Magento on a localhost. Wrap the code in theapp/code/core/Mage/Core/Model/Session/Abstract/Varien.php with the following snippet, and the session parameter array will be only reset if you are on localhost (IP'127.0.0.1' or '::1').
// SNIPPET Part 1: add this before the original array definition
// -----------------------------------------------------------

if(in_array($_SERVER['REMOTE_ADDR'], array('127.0.0.1', '::1'))) {
    $cookieParams = array();
} else {

    // here comes the original code, thats what you should
    // look for but not touch
    // -------------------------------------------------------

    // session cookie params
    $cookieParams = array(
        'lifetime' => $cookie->getLifetime(),
        'path' => $cookie->getPath(),
        'domain' => $cookie->getConfigDomain(),
        'secure' => $cookie->isSecure(),
        'httponly' => $cookie->getHttponly()
    );

// SNIPPET Part 2: add the closing bracket
// ------------------------------------------

}

A: I have Magento ver. 1.14.2.1
changing varien.php did not solve my problem.
entering 127.0.0.1 instead of localhost in Dashboard configuration Web Base URL solved my problem.
I can still enter localhost in the url and it automatically redirects it to the ip format url.

A: For Magento 2
Instead of localhost on your WAMP please use http://127.0.0.1

{folder
  path}\magento2\vendor\magento\zendframework1\library\Zend\Session.php

Go to & Comment as mentioned
 public static function rememberUntil($seconds = 0)
    {
        if (self::$_unitTestEnabled) {
            self::regenerateId();
            return;
        }

        $cookieParams = session_get_cookie_params();

        session_set_cookie_params(
            $seconds,
            //$cookieParams['path'],
            //$cookieParams['domain'],
            //$cookieParams['secure']
            );

        // normally "rememberMe()" represents a security context change, so should use new session id
        self::regenerateId();
    }

A: Having session/cookie problems with webkit browsers (e.g. Chrome) in Magento? Go to System -> Configuration -> Web -> Session Cookie Management and set "Use HTTP Only" to no. Have fun.


text:
Q: What does use instances for synchronization mean? When I was reading the Integer class of Java Docs, I found this clause that This is a value-based class; programmers should treat instances that are equal as interchangeable and should not use instances for synchronization, or unpredictable behavior may occur.. What does this mean?
I didn't try anything.


text:
Q: Cómo seleccionar campos de una tabla MySQL con PHP Básicamente quiero seleccionar todos los campos que yo quiero (que no son todos) de una tabla MySQL con PHP. El código que tengo es:
 $query="SELECT Marketplace, IdPedido, fecha, nombre cliente as nombre, direccion, DNI, CP, poblacion, provincia
        from pedidos";

        $rs_pedidos_WS=mysqli_query($conWebService, $query);
        while($row=mysqli_fetch_array($rs_pedidos_WS)){
            echo $row['Marketplace'];

El caso es que me da el siguiente error: " mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given" y no comprendo por qué. ¿Alguna idea? Gracias.

A: Prueba de la siguiente manera:
 $user = "root";
    $pass = "mypass";
    $host = "localhost";
    $db = "mybd";
    $con = mysqli_connect($host, $user, $pass, $db);
$sql = "SELECT Marketplace, IdPedido, fecha, nombre cliente as nombre, direccion, DNI, CP, poblacion, provincia from pedidos";
$res = $con->query($sql);

    while($row = mysqli_fetch_assoc($res)){
      echo "<p>".$row["Marketplace"]."</p>";
    }

Utilizando  la función query de $con ejecuta la consulta.
Suerte.

A: Lo que te está diciendo es boolean given, esto quiere decir que se ha pasado un booleano en vez de un array que es lo que la función mysqli_fetch_array espera recibir.
Consejos:

*

*Controla y maneja los errores en un handler de errores como die() o mysqli_error()

*Aprende a utilizar la lógica a tu favor y revisa a ver si lo que estas solicitando realmente es un recurso alcanzable (a reachable resource)

*El flujo de aprendizaje y mejora de programación es el siguiente: Lee, Aprende, Practica, Busca y Mejora.

Ahora te escribiré un código de ejemplo con comentarios para que sepas cómo puede mejorar tu código si aplicas los consejos que te menciono más arriba:
<?php
    $user = "root";
    $password = "";
    $host = "localhost";
    $db = "";
    $conWebService = mysqli_connect($host, $user, $pass, $db);
    /* comprobamos si hay conexion */
    if($conWebService){
        $sql=mysqli_query($link,"SELECT Marketplace, IdPedido, fecha, nombre cliente
 As nombre, direccion, DNI, CP, poblacion, provincia FROM pedidos");
        /* ¿La consulta se ejecutó bien? */
        if($sql){

            $filaSql=mysqli_fetch_array($sql, MYSQLI_ASSOC);
            echo $filaSql["Marketplace"];

        }else{
            echo mysqli_error($conWebService);
        }

    }else{

        echo "Error: La conexión no existe";
    }

?>


text:
Q: Change seed for random numbers in Matlab when doing job array I am running a Matlab job array using HPC. Each job performs a loop involving random numbers. I get the same random number in each job. How can I solve this issue and get different random numbers per job?
I have found a similar question here but I think it is about a case more complicated than mine: instead of a parfor loop in each job, I have just a for loop.
Here a simplified version of my code
%%%% main.m %%%%%
clear all
n=5;
K=2;
H=5; %number of jobs per worker

%%%% f.m %%%%%
RVall=zeros(n,K,H);
for s=1:H
    RVall(:,:,s) = unifrnd(0,1,n,K);
end
filename = sprintf('RVall.%d.mat', ID);
save(filename, 'RVall')

The .sh file is
#Example

#$ -S /bin/bash
#$ -l h_vmem=4G
#$ -l tmem=4G
#$ -l h_rt=360:0:0
#$ -cwd
#$ -j y

#Run 200 tasks where each task has a different $SGE_TASK_ID ranging
from 1 to 200
#$ -t 1-200

#$ -N try
date
hostname

#Output the Task ID
echo "Task ID is $SGE_TASK_ID"

matlab -nodisplay -nodesktop -nojvm -nosplash -r "main; ID = $SGE_TASK_ID; f; exit"

In this example, you'll see that RVall.1=RVall.2=...=RVall.200

A: I think the answer you refer to still applies. A simple workaround to start with would be to seed the random number generation in each run with a different seed using rng(ID), e.g.:
%%%% main.m %%%%%
clear all
n=5;
K=2;
H=5; %number of jobs per worker

%%%% f.m %%%%%
rng(ID);
RVall=zeros(n,K,H);
for s=1:H
    RVall(:,:,s) = unifrnd(0,1,n,K);
end
filename = sprintf('RVall.%d.mat', ID);
save(filename, 'RVall')

Reason: MATLAB's random number generator is set to default values at startup, namely the Mersenne-Twister algorithm with seed 0. The sequence of random numbers will be the same for all your runs unless you set a different seed in each run.


text:
Q: Why the Haar measure on $F^\times$? Given a Haar measure $dx$ on a field $F$, we always take the Haar measure $d^\times x = dx/|x|$ on its multiplicative group $F^\times$. Is there a good reason to do so, and not for instance to conserve the measure $dx$?
Can you provide some references for me?

A: Simply because $dx$ is no more an invariant measure for the multiplication. Indeed, $d(nx)=|n|dx$ (this is the usual change of variables rules, where $|n|$ is the jacobian determinant of $x \mapsto nx$), so you want to get rid of this multiplicative factor to get the sought invariance.


text:
Q: Incomplete match with AND patterns I've defined an expression tree structure in F# as follows:
type Num = int
type Name = string
type Expr =
    | Con of Num
    | Var of Name
    | Add of Expr * Expr
    | Sub of Expr * Expr
    | Mult of Expr * Expr
    | Div of Expr * Expr
    | Pow of Expr * Expr
    | Neg of Expr

I wanted to be able to pretty-print the expression tree so I did the following:
let (|Unary|Binary|Terminal|) expr =
    match expr with
    | Add(x, y) -> Binary(x, y)
    | Sub(x, y) -> Binary(x, y)
    | Mult(x, y) -> Binary(x, y)
    | Div(x, y) -> Binary(x, y)
    | Pow(x, y) -> Binary(x, y)
    | Neg(x) -> Unary(x)
    | Con(x) -> Terminal(box x)
    | Var(x) -> Terminal(box x)

let operator expr =
    match expr with
    | Add(_) -> "+"
    | Sub(_) | Neg(_) -> "-"
    | Mult(_) -> "*"
    | Div(_) -> "/"
    | Pow(_) -> "**"
    | _ -> failwith "There is no operator for the given expression."

let rec format expr =
    match expr with
    | Unary(x) -> sprintf "%s(%s)" (operator expr) (format x)
    | Binary(x, y) -> sprintf "(%s %s %s)" (format x) (operator expr) (format y)
    | Terminal(x) -> string x

However, I don't really like the failwith approach for the operator function since it's not compile-time safe. So I rewrote it as an active pattern:
let (|Operator|_|) expr =
    match expr with
    | Add(_) -> Some "+"
    | Sub(_) | Neg(_) -> Some "-"
    | Mult(_) -> Some "*"
    | Div(_) -> Some "/"
    | Pow(_) -> Some "**"
    | _ -> None

Now I can rewrite my format function beautifully as follows:
let rec format expr =
    match expr with
    | Unary(x) & Operator(op) -> sprintf "%s(%s)" op (format x)
    | Binary(x, y) & Operator(op) -> sprintf "(%s %s %s)" (format x) op (format y)
    | Terminal(x) -> string x

I assumed, since F# is magic, that this would just work. Unfortunately, the compiler then warns me about incomplete pattern matches, because it can't see that anything that matches Unary(x) will also match Operator(op) and anything that matches Binary(x, y) will also match Operator(op). And I consider warnings like that to be as bad as compiler errors.
So my questions are: Is there a specific reason why this doesn't work (like have I left some magical annotation off somewhere or is there something that I'm just not seeing)? Is there a simple workaround I could use to get the type of safety I want? And is there an inherent problem with this type of compile-time checking, or is it something that F# might add in some future release?

A: If you code the destinction between ground terms and complex terms into the type system, you can avoid the runtime check and make them be complete pattern matches.
type Num = int
type Name = string

type GroundTerm =
    | Con of Num
    | Var of Name
type ComplexTerm =
    | Add of Term * Term
    | Sub of Term * Term
    | Mult of Term * Term
    | Div of Term * Term
    | Pow of Term * Term
    | Neg of Term
and Term =
    | GroundTerm of GroundTerm
    | ComplexTerm of ComplexTerm

let (|Operator|) ct =
    match ct with
    | Add(_) -> "+"
    | Sub(_) | Neg(_) -> "-"
    | Mult(_) -> "*"
    | Div(_) -> "/"
    | Pow(_) -> "**"

let (|Unary|Binary|) ct =
    match ct with
    | Add(x, y) -> Binary(x, y)
    | Sub(x, y) -> Binary(x, y)
    | Mult(x, y) -> Binary(x, y)
    | Div(x, y) -> Binary(x, y)
    | Pow(x, y) -> Binary(x, y)
    | Neg(x) -> Unary(x)

let (|Terminal|) gt =
    match gt with
    | Con x -> Terminal(string x)
    | Var x -> Terminal(string x)

let rec format expr =
    match expr with
    | ComplexTerm ct ->
        match ct with
        | Unary(x) & Operator(op) -> sprintf "%s(%s)" op (format x)
        | Binary(x, y) & Operator(op) -> sprintf "(%s %s %s)" (format x) op (format y)
    | GroundTerm gt ->
        match gt with
        | Terminal(x) -> x

also, imo, you should avoid boxing if you want to be type-safe. If you really want both cases, make two pattern. Or, as done here, just make a projection to the type you need later on. This way you avoid the boxing and instead you return what you need for printing.

A: I think you can make operator a normal function rather than an active pattern. Because  operator is just a function which gives you an operator string for an expr, where as unary, binary and terminal are expression types and hence it make sense to pattern match on them.
let operator expr =
    match expr with
    | Add(_) -> "+"
    | Sub(_) | Neg(_) -> "-"
    | Mult(_) -> "*"
    | Div(_) -> "/"
    | Pow(_) -> "**"
    | Var(_) | Con(_) -> ""

let rec format expr =
    match expr with
    | Unary(x) -> sprintf "%s(%s)" (operator expr) (format x)
    | Binary(x, y) -> sprintf "(%s %s %s)" (format x) (operator expr) (format y)
    | Terminal(x) -> string x

A: I find the best solution is to restructure your original type defintion:
type UnOp = Neg
type BinOp = Add | Sub | Mul | Div | Pow
type Expr =
  | Int of int
  | UnOp of UnOp * Expr
  | BinOp of BinOp * Expr * Expr

All sorts of functions can then be written over the UnOp and BinOp types including selecting operators. You may even want to split BinOp into arithmetic and comparison operators in the future.
For example, I used this approach in the (non-free) article "Language-oriented programming: The Term-level Interpreter
" (2008) in the F# Journal.


text:
Q: Merging items in a list - Python Say I have a list in python, like such:
list=[1,2,3,4,5]

How would I merge the list so that it becomes:
list= [12345]

If anyone has a way to do this, it would be greatly appreciated!!

A: This probably better:
"%s" * len(L) % tuple(L)

which can handle:
>>> L=[1, 2, 3, '456', '7', 8]
>>> "%s"*len(L) % tuple(L)
'12345678'

A: >>> list=[1,2,3,4,5]
>>> k = [str(x) for x in list]
>>> k
['1', '2', '3', '4', '5']
>>> "".join(k)
'12345'
>>> ["".join(k)]
['12345']
>>>
>>> [int("".join(k))]
[12345]
>>>

A: list=[int("".join(map(str,list)))]

A: a = [1,2,3,4,5]
result = [int("".join(str(x) for x in a))]

A: reduce(lambda x,y:10*x+y, [1,2,3,4,5])
# returns 12345

A: Is this really what you mean by "merge the list"? You understand that a Python list can contain things other than numbers, right? You understand that Python is strongly typed, and will not let you "add" strings to numbers or vice-versa, right? What should the result be of "merging" the list [1, 2, "hi mom"] ?

A: [int(reduce(lambda x,y: str(x) + str(y),range(1,6)))]


text:
Q: NSCoding, NSData, UIImages and performance I'm using NSCoding to manage a custom object with a few different fields, one of them images. I'm only targeting iOS 5.0+ and have switched to ARC. I have everything working but am focused on performance--I haven't seen a question like this asked, so here it goes:
I transform the UIImage into NSData and add it to the main NSCoding file (a plist, if it matters) for storage on the disk. If there is more than one image, the image names become sequential (e.g. image1, image2, image3.) I then use the image both in a UITableView (as a resized thumbnail) and in a detail view. The negative side to this is that the plist balloons in size, which means slow initial load times when I use it because it's loading all of the NSData at once.
What is the best way to eliminate this problem and only force the loading of one image at a time?
What I've thought of:
I write the NSData to the disk, add an array to the plist, and add only a reference to the filename of each image to the array. I suppose I'd then reference the image filename at specified position, find it on the disk, and use it?
Any and all thoughts would be most welcome. I'm more stuck on the conceptual implementation than anything else and, funnily enough, this is not an oft-discussed topic.
Thanks,
EDIT:
As requested below, here's an example of taking an image and turning it into NSData:
  UIImage *originalImage;

            NSData *imageData = UIImagePNGRepresentation(originalImage);
            //I save it all to the app's document directory
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];

    //I am using the images in a tableView and thus found it easiest to append the row number to each image filename.
//'y' below is just an integer that corresponds to the number of items in the master array

            NSString *fileName  = [NSString stringWithFormat:@"image%d.png",y];
            documentsDirectory = [documentsDirectory stringByAppendingPathComponent:fileName];
            [imageData writeToFile:documentsDirectory atomically:YES];

            //  NSLog(@"The filename is %@", fileName);

            //newObject is an instance of my NSCoding object
            [newObject setImageName: fileName];

A: Your suggestion is sound. Imagine a relational database. I would never save the images in one field as a blob. A filesystem is a very good place to save binary date in large amounts. It also gives you easy ways to duplicate files and so on.
So saving a reference in your plist will make parsing really fast and lazy loading an easy task to process images only when you need them.

A: iOS Programming: The Big Nerd Ranch Guide has a perfect example of this solution in chapter 14 of the 3rd Edition.  Just download the code that is accessible from their site for a completed solution.
iOS Programming 3rd edition
Download Solutions


text:
Q: Resize the .resize class dependant on screen size I have the code that works at current
jQuery.event.add(window, "load", resizeFrame);
jQuery.event.add(window, "resize", resizeFrame);

function resizeFrame()
{
var w = $(window).width();
$('.resize').css('width', (w <= 1680) ? 1680 : 1920);
}

but now i need to add in other screen sizes, such as:
$('.resize').css('width', (w <= 1280) ? 1280 : 1920);
$('.resize').css('width', (w <= 1024) ? 1024 : 1920);

but im unsure about how to chain these together, ive tried using || but this didn't work
help appreciated

A: function resizeFrame() {
  var height = $(window).height(),
      width  = $(window).width(),
      resizeWidth;

  if (width <= 1024) {
    resizeWidth = 1024;
  } else if (width <= 1280) {
    resizeWidth = 1280;
  } else if (width <= 1680) {
    resizeWidth = 1680;
  } else {
    resizeWidth = 1920;
  }

  $('.resize').css('width', resizeWidth);
}

A: $('.resize').css('width', function() {
  var width = 1920;
  if(w <= 1680 && w > 1280) {
    width = 1680;
  } else if(w <= 1280 && w > 1024) {
     width = 1280;
  } else if(w <= 1024) {
     width = 1024;
  }
  return width;
});

A: It's not as readable as an if/else, but you can stick one ternary inside another, and do this:
$(window).on('resize', function() {
    var w = $(this).width(),
        width = w <= 1024 ? 1024 : w <= 1280 ? 1280 : w <= 1680 ? 1680 : 1920;
    $('.resize').css('width', width);
}


text:
Q: How to demultiplex BCL data with two different barcoding systems? I was wondering if anyone has experience in demultiplexing BCL files from Illumina with two different barcoding systems in one go?
we would like to know whether it is possible to use different, barcoded Tn5 adaptors during tagmentation and then use those Barcodes in combination with the barcodes on the sequencing primers to demultiplex the samples.
Has anyone has experience with this kind of analysis?
Is it possible to only add the Tn5 sequence to the primer sequence before demultiplexing and use it in the BCL2fastq run?
thanks
Assa

A: I'm not very well aware of Tn5 adaptors library but I will give it a shot.
In theory, it should be possible. bcl2fastq can demultiplex anything as long as you give it a proper samplesheet and a correct --use-bases-mask argument.
If you need to demultiplex all samples with a combination of two barcode system, you will have to create a samplesheet with a line for each combination that can be found. You also need to know at which cycles the Tn5 adaptors are sequenced.
For example lets say my original samplesheet is like:
[Data]
Sample_ID,Sample_Name,Sample_Plate,Sample_Well,Index_Plate_Well,I7_Index_ID,index,I5_Index_ID,index2,Sample_Project,Description
ID-1,ID-1,,,A01,UDP0001,GAACTG,UDP0001,TCGTGG,project,
ID-2,ID-2,,,B01,UDP0002,AGGTCA,UDP0002,CTACAA,project,

i would use a --use-bases-mask argument like Y*,I6,I6,Y* to tell bcl2fastq that is needs to read 6 bases for the barcodes.
Now if your Tn5 adaptors are located just after your illumina barcodes, you will need a samplesheet like:
    [Data]
Sample_ID,Sample_Name,Sample_Plate,Sample_Well,Index_Plate_Well,I7_Index_ID,index,I5_Index_ID,index2,Sample_Project,Description
    ID-1-1,ID-1-1,,,A01,UDP0001,GAACTGATGC,UDP0001,TCGTGGATGC,project,
    ID-1-2,ID-1-2,,,A01,UDP0001,GAACTGCGAT,UDP0001,TCGTGGCGAT,project,
    ID-2-1,ID-2-1,,,B01,UDP0002,AGGTCAATGC,UDP0002,CTACAAATGC,project,
    ID-2-2,ID-2-2,,,B01,UDP0002,AGGTCACGAT,UDP0002,CTACAACGAT,project,

note the added 4 bases behind the (previously defined) illumina adaptors with different combinations. Here we would use a --use-bases-mask argument like Y*,I10,I10,Y*. This is a very dummy example to illustrate how bcl2fastq works.
Two major difficulties:

*

*You have to know all the possible combinations to put them in the samplesheet. If you have a kind of UMI barcoding (random bases), you cannot do it.

*You must know precisely at which cycles the barcodes are read to use a --use-bases-mask argument accordingly.

Maybe I could understand better what you're trying to achieve with an example of a samplesheet you're using and the bcl2fastq command you're running.


text:
Q: Не показывает Главное фото ( Featured Image ) Advanced Custom Fields Wordpress Используется  Wordpress  и плагин  Advanced Custom Fields. Через этот плагин сделаны поля , в том числе и для загрузки Featured Image. Но этого поля не видно ( как показано на скрине) должно быть "Выберите файл" или что-то там еще.
Через браузер видно, что стоит класс для этого поля .hide-if-js . Раньше такого не было. Может как-то по ключу задать чтобы он всегда был виден?

Если этот класс убрать (в браузере) , то появится поле:


text:
Q: Limit number of concurrent connections in Apache2 Is there a way I can limit the number of concurrent connections to the Web Application running on my Apache Server.
My server version is Apache 2.2.11

A: Have a look at limitipconn module.

A: I'm not sure if it will useful to you but definitely worth a chance.
Maybe you can use the directives
MaxClients and
ListenBackLog
Although they apply to the concurrent access to the entire server, not only your application, and on a resource base.

A: We completely built an application layer thing that stored, checked and restricted the limit on # of application users that could be logged on concurrently.
If it got exceeded, we sent them to a 'waiting room' - worked like a charm.
So it was all application managed - we had multiple apache servers in a cluster.
We were not using the Zend clustering stuff , IMO.

A: Sure thing:
http://apache.ivn.cl/#bandwidth
and you can find a debian package too
libapache2-mod-bw


text:
Q: Removing inner borders from multipolygons in ArcGIS? I have the following multipolygon, where each polygon is a different county:

What I'd like to do is get ONLY the outline of the whole polygon, so that when I give it an outline, it is just the outermost border. Unfortunately, removing the outline color is not an option, as I'd still like to have the outline of the whole polygon available. What I'd like would be something like this:

So, how do you remove those pesky inner lines?

A: As @Vince had suggested, the Dissolve tool was what I was looking for.


text:
Q: Differentiability of derivative
Let $f$ be continuous on $[-1,1]$ and twice differentiable on $(-1,1)$. Let $\varphi(x) = (f(x) - f(0))/x$ for $x\neq 0$ and $\varphi(0) = f'(0)$. Show that $\varphi$ is continuous on $[-1,1]$ and differentiable on $(-1,1)$. By using a second order mean value theorem for $f$ show that $\varphi'(x) = f''(\frac{\theta x}{2})$ for some $\theta \in (0,1)$. Hence prove there exists $c \in (-1,1)$ such that $f'(c) = f(-1) + f(1) - 2f(0)$.

So for $x\neq 0$ it's easy to see that $\varphi$ is continuous and differentiable. We have $\varphi(x) \to \varphi(0) = f'(0)$ as $x\to 0$ by differentiability of $f$. So $\phi$ is continuous at $0$.
We have $$\frac{\phi(h) - \phi(0)}{h} = \frac{1}{h}\left(\frac{f(h) - f(0)}{h} - f'(0)\right)$$
now I'd very much like to say that as $h\to 0$ we have the inside bracket going to $0$ as well so the entire thing goes to $0$, but that doesn't work since there's a $1/h$ to take into account as well. So this seems like a prime time to pull out L'Hopital (I'm not sure if this is rigorous or not) so we get $$\frac{\frac{hf'(h) - f(h) + f(0)}{h^2}}{1}$$ but this seems to make matters even worse.
As for the other parts, I'd appreciate any help.

A: Whe have
\begin{equation}
\frac {\phi(h)-\phi(0)} {h}  = \frac {1} {h} \left ( \frac {f(h) - f(0)} {h} - f'(0) \right ) = \frac {f(h) - f(0) - hf'(0)} {h^2}.
\end{equation}
If you apply L'Hopital rule on the last quotient (of the above equation), it is easy to see that you can, you find (where we used the differentiability of $f'$ for the very last step of the equation below)
\begin{equation}
\lim_{h\to 0}\frac {\phi(h)-\phi(0)} {h}  = \lim_{h\to 0} \frac {f(h) - f(0) - hf'(0)} {h^2} = \lim_{h\to 0} \frac {f'(h) - f'(0)} {2h} = \frac 12 f''(0).
\end{equation}
So $\phi$ is differentiable at $0$ and $\phi'(0) = \frac 12 f''(0)$.
(text) = edit.


text:
Q: *ngFor data not displaying I'm trying to display on a table some tracks with spotify api, and it's not displaying anything. Here's the code
This is the tracksArray from the console.
(4) [{…}, {…}, {…}, {…}]
0: {uri: ""}
1: {uri: "spotify:track:4JhloJcv1weqqs8RfBLWk0"}
2: {uri: "spotify:track:7rHJr8x10nTZYR4j2VYlXu"}
3: {uri: "spotify:track:60SdxE8apGAxMiRrpbmLY0"}
length: 4
__proto__: Array(0)

Here's the html
@Component({
    moduleId: module.id,
    selector: 'app-favtracks',
    template: `

            Vista Previa

    `,
    styleUrls: ['./favtracks.component.scss'],
    providers: [SpotifyService]
})

A: If you use a proper DomSanitizer pipe you should get the elements properly, however I believe you are trying to display the uri by itself. I don't know if there's a way for that to work on its own, but if you put https://embed.spotify.com/?uri= in front of each of your uri, it should work. You could either do that in your template like so:
Template

(Or save it as variable in your .ts then use that instead of writing the whole string in the template)

Or you can modify your array in your .ts, if you wanna keep the uri as they are for other things just add a property to your array:
Component
 ngOnInit() {
      this.tracksArray.forEach(e => {
        e["embeddedUri"] = "https://embed.spotify.com/?uri=" + e.uri;
      });
    }

Template


text:
Q: Prevent internal drive from mounting automatically I don't use the internal hard drive on my iMac any more, but for obvious reasons, it's awkward to remove it. I'd like to stop OS X from automatically mounting it when the iMac boots. Is this possible? I didn't see anything in Disk Utility that looked appropriate. I know I can unmount it myself, but I'd prefer if it were never mounted in the first place.
I found a previous answer that describes editing /etc/fstab. However on OS X 10.11 "El Capitan", this file contains only the following information:
IGNORE THIS FILE.
This file does nothing, contains no useful data, and might go away in
future releases.  Do not depend on this file or its contents.

...so that appears to be no longer relevant.

A: 1) Make sure the disk you want to prevent mounting at boot is mounted.
2) Launch Terminal.
3) Run the following command to print out information about the disk:
 diskutil info /Volumes/<volume that shouldn't be mounted>

4) Locate the line that starts with: Volume UUID:. Select the UUID (Universal Unique Identifier) that follows on the rest of the line. It will be something that looks like FF9DBDC4-F77F-3F72-A6C2-26676F39B7CE. Your value will be different
5) Copy the UUID to the clipboard.
6) Navigate to /etc by typing the following and pressing enter:
 cd /etc

7) Edit (or create) an fstab file by typing the following and pressing enter:
 sudo vifs

8) Enter the following line, substituting the UUID you copied in step 5). (Note: vifs uses the value of the EDITOR environment variable to pick the text editor to use. This article assumes you are using the default value of vim. In vim, starts in command mode. To add a new line, move to the end of the document, and press the o key to append a new line and enter edit mode. Then type the following and press the return key.):
UUID=FF9DBDC4-F77F-3F72-A6C2-26676F39B7CE none hfs rw,noauto

9) Type escape to return to command mode and then type ZZ to save and exit vifs (or some other method to save and exit if you are using something other than vim.
10) Type the following and press enter to reset the auto mounter:
 sudo automount -vc

11) Quit Terminal
Now, the next time you restart, or unplug the drive in the case of an external drive, that volume will not be mounted. All you have to do is launch Disk Utility, select the grey, disabled volume, and click the Mount button.
Source


text:
Q: error: failed to push some refs to 'https://git.heroku.com/xxxxxxxxx.git' I got an error,error: failed to push some refs to 'https://git.heroku.com/xxxxxxxxx.git'.I want to upload my application which be made Django to heroku.I run heroku create xxxxxxxxx. And I run git push heroku ,so
Counting objects: 6951, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (5952/5952), done.
Writing objects: 100% (6951/6951), 11.21 MiB | 891.00 KiB/s, done.
Total 6951 (delta 2087), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote:
remote: -----> Python app detected
remote:  !     The latest version of Python 3 is python-3.6.5 (you are using python-3.6.4, which is unsupported).
remote:  !     We recommend upgrading by specifying the latest version (python-3.6.5).
remote:        Learn More: https://devcenter.heroku.com/articles/python-runtimes
remote: -----> Installing python-3.6.4
remote: -----> Installing pip
remote: -----> Installing requirements with pip
remote:        Collecting alabaster==0.7.10 (from -r /tmp/build_6adefb27873345001cb4512d3fd963e3/requirements.txt (line 1))
remote:          Downloading https://files.pythonhosted.org/packages/2e/c3/9b7dcd8548cf2c00531763ba154e524af575e8f36701bacfe5bcadc67440/alabaster-0.7.10-py2.py3-none-any.whl
remote:        Collecting anaconda-client==1.6.9 (from -r /tmp/build_6adefb27873345001cb4512d3fd963e3/requirements.txt (line 2))
remote:          Could not find a version that satisfies the requirement anaconda-client==1.6.9 (from -r /tmp/build_6adefb27873345001cb4512d3fd963e3/requirements.txt (line 2)) (from versions: 1.1.1, 1.2.2)
remote:        No matching distribution found for anaconda-client==1.6.9 (from -r /tmp/build_6adefb27873345001cb4512d3fd963e3/requirements.txt (line 2))
remote:  !     Push rejected, failed to compile Python app.
remote:
remote:  !     Push failed
remote: Verifying deploy...
remote:
remote: !   Push rejected to xxxxxxxxx.
remote:
To https://git.heroku.com/xxxxxxxxx.git
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'https://git.heroku.com/xxxxxxxxx.git'

I searched this error,maybe conda install pip command should be installed.So I run it and heroku create command run again, but same error happens.What is wrong?How should I fix this?

A: The error is telling you that it cannot install anaconda-client, because it can't find version 1.6.9 which you specified in the requirements.txt. The latest version of that library on PyPi is version 1.2.2. However, it appears to be abandoned - why have you specified it at all? What are you using it for?


text:
Q: How can I access application context of helper file in android I have main activity and onClick method I am executing JsonTask
 @Override
public void onClick(View v) {
  switch (v.getId()) {
        case R.id.blogin:
              new JsonTask().execute("https://www.aboutmyclinic.com/android/index.php","login" );
            break;
}

I have created a helper file called JsonTask to pass th post parameters to server and to get the json response from server
public class JsonTask extends AsyncTask<String, String, String> {

@Override
protected String doInBackground(String... params) {...
}

@Override
protected void onPostExecute(String result) {
    super.onPostExecute(result);

    JSONObject json = null;
    String sucessvalue = null;
    String errorvalue = null;
    String token = null;
    try {
        json = new JSONObject(result);
        sucessvalue = json.getString("Success");
    } catch (JSONException e) {
        e.printStackTrace();
    }
    if (sucessvalue != null) {
        new Preferences().PutExtra("Success",sucessvalue);
    } else {
        // Content.setText(result);
    }

}
}

I have another helper file called Preferences to get and set sharedPreferences. Here is the code
public class Preferences  extends AppCompatActivity {
SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;

public Preferences(){

    sharedpreferences =getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}

public void PutExtra(String key, String value)
{
    SharedPreferences.Editor editor = sharedpreferences.edit();
    editor.putString(key, value);
    editor.commit();

}
public String getExtra(String key, String defaultValue)
{

    return sharedpreferences.getString(key, defaultValue);
}
}

I am getting error
java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.SharedPreferences android.content.Context.getSharedPreferences(java.lang.String, int)' on a null object reference

I am not able to get a context from main activity in Preferences helper file.
Any help would be appreciated. Thank you.

A: You need to pass Context to Preferences Class
First change constructer
public Preferences(Context context){
  sharedpreferences = context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
}

then call function like this
new Preferences(context).PutExtra("Success",sucessvalue);

Where
context = CurrentActivity.this;

A: I have modified your code
Your Preference Helper class should not extend Appcompat activity
  public class PreferencesHelper {

        private static PreferencesHelper preferenceHelperInstance;

        private PreferencesHelper() {
        }

        public static PreferencesHelper getPrefernceHelperInstace() {

            if (null == preferenceHelperInstance) {
                preferenceHelperInstance = new PreferencesHelper();
            }

            return preferenceHelperInstance;
        }

        public static final String MyPREFERENCES = "MyPrefs";

        public void PutExtra(Context context, String key, String value) {

            context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE).edit().putString(key, value).commit();

        }

        public String getExtra(Context context, String key, String defaultValue) {

            return context.getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE).getString(key, defaultValue);
        }
    }

Pass context into your JSON executor with the help of Constructor
public class JsonTask extends AsyncTask<String, String, String> {

    private Context mContext;

    //Pass Context
    public JsonTask(Context context) {
        this.mContext = context;
    }

    @Override
    protected String doInBackground(String... params) {...
    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        JSONObject json = null;
        String sucessvalue = null;
        String errorvalue = null;
        String token = null;
        try {
            json = new JSONObject(result);
            sucessvalue = json.getString("Success");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        if (sucessvalue != null) {

            //Get Preferences
            PreferencesHelper.getPrefernceHelperInstace().PutExtra(mContext, "Success", sucessvalue);
        } else {
            // Content.setText(result);
        }

    }
}

Finally inject context for both Async task and PreferenceHelper like this

new
  JsonTask(getApplicationContext()).execute("https://www.aboutmyclinic.com/android/index.php",
  "login");


text:
Q: Bootstrap assign spans to custom CSS id/class? How would I create a CSS ID #sidebar that is equal to span4? I mean I could do <div id="sidebar" class="span4">, but I would prefer to abstract that into #sidebar  by not typing span4 and not have to specify width dimensions manually in #sidebar either.
Is that possible with just plain CSS?
Edit: Found a great article on this issue: Please stop embedding Bootstrap classes in your HTML

A: No it is not possible using only css.
Another solution is to make a custom build of bootstrap. You can add your a custom less style and build the bootstrap css from it.
ex
#sidebar {
    .span4;
}

What you need to do is to
1. Clone the bootstrap repository
2. Add a custom.less files under less directory
3. Add custom.less file at the bottom of bootstrap.less file
4. Compile the bootstrap.less file with a tool like Cruch!
5. Instead of the default bootstrap.css file use the custom file


text:
Q: Specifying Javascript in a header template for a column on my Kendo MVC grid just renders the Javascript (Kendo UI MVC) When specifying Javascript in a header template for a column on my grid, the result renders the javascript itself and does not evoke the method and render the result of the method.
Specifying the exact same code in the ClientHeader does work.  Are we not able to process Javascript in HeaderTemplates?
Or is there a different syntax / mechanism?
Note, I'm trying to do this in ASP.NET MVC Kendo, not the JQuery Kendo (and I am a Kendo novice)
    c.Bound(b => b)
        .Title("Dates")
        .Filterable(false)
        .Sortable(false)
        .HeaderTemplate("<span> #= new Date().getFullYear() #</span>")

A: MVC Grid header templates are server templates. Currently you are trying to use a client-side Kendo UI template, which works in databound rows.
Consider using a server-side expression that will return the desired year as a string and it will be rendered as expected. No #= ... # expressions will be necessary.


text:
Q: Call order of constructors #include <iostream>
using namespace std;
struct A{
  A() {cout << "A" << endl;}
  A(int a) {cout << "A+" << endl;}
};

struct B : virtual A{
  B() : A(1) {cout << "B" << endl;}
};
struct C : virtual A{
  C() : A(1) {cout << "C" << endl;}
};
struct D : virtual A{
  D() : A() {cout << "D" << endl;}
};
struct E : B, virtual C, D{
  E(){cout << "E" << endl;}
};
struct F : D, virtual C{
  F(){cout << "F" << endl;}
};
struct G : E, F{
  G() {cout << "G" << endl;}
};

int main(){
  G g;
  return 0;
}

Program prints:
A
C
B
D
E
D
F
G

I would like to know what rules should I use to determine in what order constructors get called. Thanks.

A: You should follow the rules given in the C++ standard:

[C++11: 12.6.2/10]: In a non-delegating constructor, initialization proceeds in the following order:

*

*First, and only for the constructor of the most derived class (1.8), virtual base classes are initialized in the order they appear on a depth-first left-to-right traversal of the directed acyclic graph of base classes, where "left-to-right" is the order of appearance of the base classes in the derived class base-specifier-list.

*Then, direct base classes are initialized in declaration order as they appear in the base-specifier-list (regardless of the order of the mem-initializers).

*Then, non-static data members are initialized in the order they were declared in the class definition (again regardless of the order of the mem-initializers).

*Finally, the compound-statement of the constructor body is executed.

  [ Note: The declaration order is mandated to ensure that base and member subobjects are destroyed in the reverse order of initialization. —end note ]

A: Virtual base subobjects are constructed first, by the most-derived class, before any other bases. This is the only way that makes sense, since the relation of the virtual bases to tbe most-derived object is not known until object construction, at runtime (hence "virtual"). All intermediate initializers for virtual bases are ignored.
So, what are your virtual bases? G derives from E and F. E derives virtually from C, which in turn derives virtually from A, so A, C are first. Next, F doesn't add any further virtual bases. Next, E has non-virtual bases B and D, in that order, which are constructed next, and then E is complete. Then comes F's non-virtual base D, and F is complete. Finally, G is complete.
All in all, it's virtual bases A, C, then non-virtual bases B, D, E and D, F, and then G itself.

A: You can investigate the order of constructor calls from this quote of the C++ Standard and try to trap it yourself

10 In a non-delegating constructor, initialization proceeds in the
  following order: — First, and only for the constructor of the most
  derived class (1.8), virtual base classes are initialized in the order
  they appear on a depth-first left-to-right traversal of the directed
  acyclic graph of base classes, where "left-to-right" is the order of
  appearance of the base classes in the derived class
  base-specifier-list. — Then, direct base classes are initialized in
  declaration order as they appear in the base-specifier-list
  (regardless of the order of the mem-initializers). — Then, non-static
  data members are initialized in the order they were declared in the
  class definition (again regardless of the order of the
  mem-initializers). — Finally, the compound-statement of the
  constructor body is executed. [ Note: The declaration order is
  mandated to ensure that base and member subobjects are destroyed in
  the reverse order of initialization. —end note ]


text:
Q: Confusion about probability of finding a particle The wave representation of a particle is said to be $\psi(x,t)=A\exp\left[i(kx−\omega t)\right]$.
The probability of the particle to be found at position x at time t is calculated to be $\left|\psi\right|^2=\psi \psi^*$ which is $\sqrt{A^2(\cos^2+\sin^2)}$. And since $\cos^2+\sin^2=1$ regardless of position and time, does that means the probability is always $A$? I think I am doing something wrong but I know what!

A: *

*$\lvert \psi \rvert^2 (x,t)$ is not a probability, it is a probability density which you have to integrate over smoe region of space to get a probability. The probability to find the particle in an interval $[a,b]$ is $\int_a^b \lvert \psi(x)\rvert^2\mathrm{d}x$, which is zero for $a=b$, i.e. the probability to find a particle at a point is always zero.

*The plane wave $\psi(x,t) = A\mathrm{e}^{\mathrm{i}(kx-\omega t)}$ is only an admissible quantum state if the particle is confined to a region of space $S$ of finite volume, and then $A = 1/\sqrt{\mathrm{vol}(S)}$ because we want the probability density to be normalized as $\int_S \lvert \psi(x,t)\rvert^2\mathrm{d}x = 1$. If the particle is not confined, the function is not normalized and does not represent an actual quantum state.

A: It is not true that the probability of finding the particle at $x$ is $|\psi|^2$ (think of it as if you have a continuum of possible values, what is the probability of obtaining an specific value?). As it has been pointed out, $|\psi|^2$ can be interpreted as a probability density, so the probability of finding a particle between $x$ and $x + \mathrm dx$ is $|\psi(x)|^2\mathrm dx$. Integrating you can compute that probability for a specific interval.


text:
Q: How to define global constant when creating Web component? I am creating custom web component "upload-widget", and declaring three constants in constructor to be referenced in functions later:
const template = document.createElement('template');
template.innerHTML = `

    <input type="file" name="file_input" id="file_name">
    <button type="button" id="upload_btn">Upload</button>

  `;

class UploadWidget extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode: 'open'});
    this.shadowRoot.appendChild(template.content.cloneNode(true));

    const FILE_NAME = this.shadowRoot.getElementById("file_name");
    const UPLOAD_BUTTON = this.shadowRoot.getElementById("upload_btn");
    const UPLOAD_STATUS = this.shadowRoot.getElementById("upload_status");

  };

  upload_action() {
    if (!FILE_NAME.value) {
    console.log("File does not exists");
        return;
    UPLOAD_STATUS.innerHTML = 'File Uploaded';
  };

  connectedCallback() {
    UPLOAD_BUTTON.addEventListener("click", () => this.upload_action());
  }
}

customElements.define('upload-widget', UploadWidget);

This code fails since Javascript does not recognize the declared constants in the "connectedCallback()" nor in the function "upload_action()". Moving the declaration to either of the functions makes the constants valid only for the function scope, not beyond.
How do I declare constant/variable valid for the whole scope of the class including functions?

A: you need to declare them as class variables, so your constructor would look like:
constructor() {
    super();
    this.attachShadow({mode: 'open'});
    this.shadowRoot.appendChild(template.content.cloneNode(true));

    this.FILE_NAME = this.shadowRoot.getElementById("file_name");
    this.UPLOAD_BUTTON = this.shadowRoot.getElementById("upload_btn");
    this.UPLOAD_STATUS = this.shadowRoot.getElementById("upload_status");
  };

Later in the code you can access them as this.UPLOAD_BUTTON.
Advice: Try to use camelCase when naming variables, it looks more "javascripty". So instead of this.UPLOAD_BUTTON write this.uploadButton.

A: Note your template use is a bit bloated, you can do:
 constructor() {
    let html = `

           <input type="file" name="file_input" id="file_name">
           <button type="button" id="upload_btn">Upload</button>

`;
    super() // sets AND returns this scope
      .attachShadow({mode: 'open'}) // sets AND returns this.shadowRoot
      .innerHTML = html;
  }


text:
Q: Rails and MiniTest: add additional folder I use Ruby 2 and Rails 4. I have a folder test/lib, where a few tests are located.
But running rake test does not use them. Only the other tests (models, controllers, ...) are running.
Where do I have to add the lib folder?
I already tried MiniTest::Rails::Testing.default_tasks << 'lib', but I get NameError Exception: uninitialized constant MiniTest::Rails. I did not add the minitest gem to my Gemfile, because Ruby 2 uses it by default.

A: To use MiniTest::Rails::Testing.default_tasks << 'lib' you need to add the minitest-rails gem to your Gemfile. It is separate from Minitest and adds enables many Minitest features missing that are not enabled in Rails by default. And minitest-rails adds other features, such as creating rake tasks for all the directories that have tests. So without any changes to your Rakefile you can run things like this:
$ rake minitest:lib

Alternatively, to do this the old fashioned way, you can add the following to your Rakefile:
namespace :test do

  desc "Test lib source"
  Rake::TestTask.new(:lib) do |t|
    t.libs << "test"
    t.pattern = 'test/lib/**/*_test.rb'
    t.verbose = true
  end

end

Rake::Task[:test].enhance { Rake::Task["test:lib"].invoke }

This assumes you want to run your lib tests without using any database fixtures. If you want the fixtures and database transactions, then you should create the rake task with a dependency on "test:prepare".
namespace :test do

  desc "Test lib source"
  Rake::TestTask.new(:lib => "test:prepare") do |t|
    t.libs << "test"
    t.pattern = 'test/lib/**/*_test.rb'
    t.verbose = true
  end

end

Rake::Task[:test].enhance { Rake::Task["test:lib"].invoke }


text:
Q: get_template_part not working on wordpress I have been working on this for hours and don't know what I'm overlooking or not understanding. I'm trying to use get_template_part to call another php document. When I run the code below there is nothing in the div.content. I don't understand why my partial-banner.php is being called.
front-page.php
<?php get_header(); ?>

   <?php while ( have_posts() ) : the_post(); ?>
       <?php get_template_part( 'template-parts/partial', 'banner' ); ?>
   <?php endwhile; // end of the loop. ?>

<?php get_footer(); ?>

partial-banner.php

Does this work

and here's an image of my file structure.

A: You could just use a simple PHP include, instead of using WordPress logic
<?php include('template-parts/partial-banner.php'); ?>


text:
Q: Is it possible to sync custom fonts between macOS and iOS devices? I am curious as to whether it is possible to synchronise custom/downloaded fonts from macOS High Sierra to an iPhone?
From what I understand, if both devices meet the requirements for Continuity they are capable of implementing the Handoff feature. This means a document (containing the custom font) started on the mac will show the same custom font on the iPhone, correct?
Is it possible then, to reverse the logic such that custom fonts are always synced between both devices, without employing the use of the Handoff feature - making the fonts available in other iOS applications?
The Handoff feature is just an example of what looks like font synchronisation but what I am really interested in is a way to copy/sync a font from the macOS device to the iOS device if it does not exist there (e.g. downloaded fonts). Making it available on a system-wide level (not per application) to each application capable of creating/displaying rich text.
I am interested in this from a security point of view to learn whether file types like fonts can be just as easily synced as Contacts and similar cloud-based content.

A: No, you're not exactly correct.
Most app developers will make sure that both the macOS and iOS versions of their program display the custom font. This is done using either font embedding (i.e. the font is stored inside the document), or using streaming, which is a Handoff-feature that allows for the source program to transfer larger quantities of data to the destination program.
Some app developers have not invested the time necessary to do this, or are constrained in other ways. In those cases the document will show up with a wrong font on the destination device.
As such, there's no automatic, iOS/macOS handled synchronization of fonts taking place during Handoff.
In general, you can add fonts to the system font library using configuration profiles. This is intended for enterprise usage where iOS devices that are supervised or where it is otherwise accepted to install configuration profiles. This way they can have for example the company's own font installed. In the case of iOS devices managed by for example an MDM system, you could say that it is possible to "synchronise" fonts from a Mac.
These fonts are available to use in apps that support choosing from the system library. Not all apps do this! - However apps like Pages and Numbers do support it.
To create a correct configuration profile with a font payload, you'll need a code signing certificate - otherwise the user will get a lot of warnings when installing the configuration profile. The user must install the configuration themselves by agreeing to the installation in System Preferences (you can send them there by the way of a link or similar).
For home users the easiest way to install a font is probably using a third party app such as AnyFont! or similar.
If you're interested in specifically whether an ordinary user can select somewhere that all the fonts on their Mac must be available on their iOS device - then no, no such synchronisation method is available on standard iOS.


text:
Q: separating tables through css and html I am brand new to web development and coding and i was wondering what is the code to separating two of the tables? Which is a couple of lines down?

Future Car's

    Lincoln
    BMW
    Mercedes

Plan's for the future

    Web Development Job
    San Francisco
    Create web sites

Thanks

A: You need to create two separate tables. I'd advise you to do all your styling in a separate css file and include it in your html for a cleaner code.

Future Car's

 Lincoln
 BMW
 Mercedes

Plan's for the future

 Web Development Job
 San Francisco
 Create web sites

Future Car's

 Lincoln
 BMW
 Mercedes

Plan's for the future

 Web Development Job
 San Francisco
 Create web sites

This will give you a 20px distance between your tables. You can adjust it according to your need.

A: If I undestood well enough you want to separate the rows, a quick way to do it is making a empty column with colspan of 3 and height of your liking; you can fill it with
 too,  &nbsp is a non breaking space.

Future Car's

        Lincoln
        BMW
        Mercedes

        &nbsp

Plan's for the future

        Web Development Job
        San Francisco
        Create web sites


text:
Q: Несколько вопросов по ASP.NET Здравствуйте.
Вот решил самостоятельно немного освоить ASP.NET. Начал осваивать по одной там методичке, она писалась под более старую Visual Studio, поэтому, быть может, идут несовпадения...
Вот например там я дошел до пункта: "Выберите св-во Style", так у меня такого св-ва нету в чистом документе ни на одном элементе, поэтому пришлось что-то там искать в Format и этот далее упоминаемый Style Builder... В этом же Style Buildere там есть по методичке "Выберите слева Background, выберите опцию Transparent" - опции Transparent у меня нету...
Я уже не говорю о том, что там есть пункт: "Выберите все эти 4 элемента управления (там texboxы и т.п.) с помощью Shift и в св-вах в меню Layout выберите Position - Absolute". Ну во-первых: у меня оно выделилось с помощью CTRL только, ну и самое главное: никакого св-ва Position со значением Absolute я не нашёл.
Помогите, пожалуйста, разобраться и почему столько расхождений со старой Visual Studio?
Понимаю, что вопрос, наверное, очень простой для профессионалов, но я только этот ASP.NET начал осваивать сам, а там уже не успел и страницу текста прочитать такие расхождения... Вот и хотелось бы разобраться, а то сам не нашел.
A: Во-первых, надо изучать версию asp.net  хотя бы  2.х. Существенной разницы не будет между ней и последней версией.
Во-вторых, переходя с  2008 студии на 2010, никаких проблем не ощутил.
В-третьих, бросайте вы эти методички и читайте(если дружите с английским):

*

*ASP.NET 4 Unleashed

*Apress - Beginning ASP.NET 4 in C.Sharp 2010

Если не дружите:

*

*Мак-Дональд М., Шпушта М.  ASP.NET 3.5 с примерами на C#2008

*Дино Экспозито. ASP.NET 2.0 Базовый курс_(лично я учился по этой)

Ещё есть довольно неплохие курсы Гайдара Магданурова, очень доходчиво обьясняет, на интуите есть его видео.
A: Советую не заморачиваться с книгами, а изучать технологию по вебкастам. В частности, это можно делать на http://www.techdays.ru. Плюс, опять же, советую изучать ASP.NET MVC 3 и новый движок Razor.


text:
Q: What is the best way to align text at the center of the HTML What is the best way to align text at the center of the HTML (both horizontally and vertically aligned) to represent it in the WebBrowser control in Windows Forms? Is there any way to do it at all?
Thanks in advance.

A: .centered {
    width: 50px;
    height: 50px;
    top: 50%;
    left: 50%;
    position: absolute;
    margin-left: -(50/2)px;
    margin-top: -(50/2)px;
}

this 50px can be varied according to your choice


text:
Q: php multidimensional array search, sorting best match first I'm currently searching a multidimensional array for keyword matching.. the searching function works great, but I was wondering how I could go about showing the best match first.. basically if it finds an exact match, show that as first result in the array, then show any partial matches?
$results = array_multi_search($array, $keyword);

foreach($results as $row) {
  echo $row['name'];
}

function array_multi_search($array, $input){
  $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
  foreach($iterator as $id => $sub){
    $subArray = $iterator->getSubIterator();
    if(@strstr(strtolower($sub), strtolower($input))){
      $subArray = iterator_to_array($subArray);
      $outputArray[] = array_merge($subArray, array('Matched' => $id));
    }
  }
  return $outputArray;
}


text:
Q: how to stop audio playing in background in exoplayer **

Need to implement video stream within a fragment using exoplayer. Streaming works fine but when moved from the fragment activity to other activity or if the screen is rotated, multiple copys of same audio plays in background continuously until the app is killed.how to handle this please help. Thanks in advance.
**
    public class VideoFragment extends Fragment {
    private SimpleExoPlayerView simpleExoPlayerView;
    public SimpleExoPlayer player;
    Uri mp4VideoUri;
    String TAG ="LOGG";
    SharedPrefs sharedPrefs;
    TextView notavailable;
    String url;
    Connection connection;
    long media_length;

    public VideoFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater,ViewGroup container,Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.video_fragment,container,false);
        sharedPrefs = new SharedPrefs(getContext());
        connection = new Connection(getContext());
        notavailable= (TextView) rootView.findViewById(R.id.videonotavailable);
        BandwidthMeter bandwidthMeter = new DefaultBandwidthMeter();
        TrackSelection.Factory videoTrackSelectionFactory = new AdaptiveTrackSelection.Factory(bandwidthMeter);
        TrackSelector trackSelector = new DefaultTrackSelector(videoTrackSelectionFactory);
        LoadControl loadControl = new DefaultLoadControl();
        player = ExoPlayerFactory.newSimpleInstance(getContext(), trackSelector, loadControl);
        simpleExoPlayerView = new SimpleExoPlayerView(getContext());
        simpleExoPlayerView = (SimpleExoPlayerView) rootView.findViewById(R.id.player_view);
        simpleExoPlayerView.setUseController(true);
        simpleExoPlayerView.requestFocus();
        simpleExoPlayerView.setPlayer(player);
        DefaultBandwidthMeter bandwidthMeterA = new DefaultBandwidthMeter();
        DefaultDataSourceFactory dataSourceFactory = new DefaultDataSourceFactory(getContext(), Util.getUserAgent(getContext(), "exoplayer2example"), bandwidthMeterA);
        ExtractorsFactory extractorsFactory = new DefaultExtractorsFactory();
        url=sharedPrefs.getvideoUrl();
        if (url==null || url.equals("")){
            simpleExoPlayerView.setVisibility(View.GONE);
            notavailable.setVisibility(View.VISIBLE);
        }else if (connection.isInternet()){
            mp4VideoUri=Uri.parse(sharedPrefs.getvideoUrl());
            MediaSource videoSource = new ExtractorMediaSource(mp4VideoUri,dataSourceFactory,extractorsFactory,null,null);
            final LoopingMediaSource loopingSource = new LoopingMediaSource(videoSource);

            player.prepare(loopingSource);

            player.addListener(new ExoPlayer.EventListener() {
                @Override
                public void onLoadingChanged(boolean isLoading) {
                    Log.v(TAG,"Listener-onLoadingChanged...");
                }

                @Override
                public void onPlayerStateChanged(boolean playWhenReady, int playbackState) {
                    Log.v(TAG,"Listener-onPlayerStateChanged...");
                }

                @Override
                public void onTimelineChanged(Timeline timeline, Object manifest) {
                    Log.v(TAG,"Listener-onTimelineChanged...");

                }

                @Override
                public void onTracksChanged(TrackGroupArray trackGroups, TrackSelectionArray trackSelections) {

                }

                @Override
                public void onPlayerError(ExoPlaybackException error) {
                    Log.v(TAG,"Listener-onPlayerError...");
                    player.stop();
                }

                @Override
                public void onPositionDiscontinuity() {
                    Log.v("LOG","Listener-onPositionDiscontinuity...");

                }

                @Override
                public void onPlaybackParametersChanged(PlaybackParameters playbackParameters) {

                }
            });
            player.setPlayWhenReady(true);
        }else {
            simpleExoPlayerView.setVisibility(View.GONE);
            notavailable.setVisibility(View.VISIBLE);
            notavailable.setText(getString(R.string.nointernet));
        }
        return rootView;
    }

    @Override
    public void onPause() {
        super.onPause();
        if(player != null) {
            player.stop();
            player.release();
            media_length = player.getCurrentPosition();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if(player != null) {
            player.seekTo(media_length);
            player.setPlayWhenReady(true);
        }
    }
}

A: In your fragment-holding activity, you need to handle the situation in the onPause method:
@Override
protected void onPause() {
    super.onPause();
    mPlayerFragment.pause();
}

You can define a method in your fragment to pause playback by passing false to setPlayWhenReady().
public void pausePlayback() {
        mExoPlayer.setPlayWhenReady(false); //pauses the playback if it's playing
    }

A: I am facing same issue and problem resolved after implement below code in my existing code
First You need to create global variable
 boolean isActivityRunning = false;

Set this value in onCreate() and onResume() of activity to true.
You need to set Player if value isActivityRunning is true
After that you need to release player and set isActivityRunning = false in onPause(), onStop() and onDestroy() that look like
 @Override
    public void onPause() {
        super.onPause();
        isActivityRunning = false;
        releasePlayer();
    }

    @Override
    public void onStop() {
        super.onStop();
        isActivityRunning = false;
        releasePlayer();
    }

 @Override
    public void onBackPressed() {
        super.onBackPressed();
        releasePlayer();
    }

  @Override
    protected void onDestroy(){
        super.onDestroy();
        releasePlayer();
    }

and releasePlayer() implementation look like is
 SimpleExoPlayer player;
 PlayerView playerUI;

     private void releasePlayer(){
            if(player!=null){
                player.release();
                player.clearVideoSurface();
                playerUI.getPlayer().release();;

                player = null;
                playerUI =null;
            }
        }

Where player and player UI is Global variable that need to set null
This solution work well for me.


text:
Q: angularjs: ui-router (nested view) and bootstrap tabs not playing nice http://plnkr.co/edit/F5jojPEBVaAIyMa0CXDw
I am having issues getting the ui-router to load a fragment into a bootstrap tab body. I linked my code example above. Please let me know if I missed something. I have looked at 10 different stack overflow examples and non of them have helped solve my problem.
I have an outer ui-view that loads the initial page fragment fine.

Next I have the fragment that is loaded (This is where the tabs are set up)

{{tab.label}}

Following that I have a two fragment pages that for test only have some text in them (request-tab.html and approved-tab.html)
Finally, I have the js file that routes the views. I left off the controllers to shorten the post. They are on the plunker if needed but they shouldn't be the issue.
var app = angular.module("BRAVO", ['ui.router', 'ui.bootstrap', 'ui.bootstrap.tpls']);

app.config(function($stateProvider, $urlRouterProvider) {
    $urlRouterProvider.otherwise('/requestView/request');
    $stateProvider
    /* Main Views */
      .state('requestView', {
        url: '/requestView',
        templateUrl: 'bravo_home.html',
        controller: 'requestCtrl'
      })
      /*Other states here*/

    /* Tabs */
    .state('requestView.request', {
        url: '/request',
        view: {
          'tabs': {
            templateUrl: 'request-tab.html',
            controller: 'requestTabCtrl'
          }
        }
      })

      .state('requestView.approved', {
        url: '/approved',
        view: {
          'tabs': {
            templateUrl: 'approved-tab.html'
          }
        }
      });
  })

A: plunker

{{tab.label}}

A: You should set your states like this:
    $stateProvider
    /* Main Views */
      .state('requestView', {
        url: '/requestView',
        templateUrl: 'bravo_home.html',
        controller: 'requestCtrl'
      })
      /*Other states here*/

    /* Tabs */
    .state('requestView.request', {
        url: '/request',
        templateUrl: 'request-tab.html'
     })

    .state('requestView.approved', {
        url: '/approved',
        templateUrl: 'approved-tab.html'
     });

Then, in your bravo_home.html:

Note that I removed the ="tabs". You can add controllers to your nested tab states as needed, for example:
    // add "controller: 'requestTabCtrl'" to state
    .controller("requestTabCtrl", function($scope) {
        console.log('Hello Request Tab');
    })
    // add "controller: 'approvedTabCtrl''" to state
    .controller("approvedTabCtrl", function($scope) {
        console.log('Hello Approved Tab');
    });


text:
Q: Power BI and Python not aligned I'm new to power BI but not new to python / pandas. What about power BI changes the values passed to the python script editor and how do I account for it in my scripting / setup in Power BI?
If I have to manually grab excel files in power BI it somewhat defeats the purpose of using it at all.
Here is the scenario: I created a .groupby() pivot table and plotted it in python. I get the graph I expected. When I move the script over to the power BI python script editor I get a clearly incorrect graph. It only has 3 data points and it looks like it is doing a table sum rather than a group by average? The values go out to 1E6
To clarify the incorrect graph is generated when I use the dataframe created by Power BI after selecting the fields you want access to. The core data source is exactly the same. I am able to recreate the original correct graph if I grab the original CSV.
Here is a picture of the graph power BI creates.

Here is something close to what I expect

I am using the following code in both python and the Power BI python script editor. Th
#The following code to create a dataframe and remove duplicated rows is always executed and acts as a preamble for your script:

#dataset = pandas.DataFrame(Color, ValueB, Value_A, ID, StepTime, Bucket)
#dataset = dataset.drop_duplicates()

#Paste or type your script code here:
#assumptions: all returned email columns are named
import sys
import time

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap

df1 = dataset  # Power BI specific and returns the funky graph
df1 = pd.read_excel # Works in both power BI and Python

base = 100
print(df1.head())
df1['Value_A'] = df1['Value_A'].round(0).astype('Int64')
df1['Buckets'] = (df1['Value_A']/base).round(0)*base
df1['Buckets'] = df1['Buckets'].round(0).astype('Int64')

df2 = df1.groupby(['ID','Buckets'])['ValueB'].mean().reset_index()

df2 = df2.loc[df2['Buckets'] > 5]
group_19 = df2.loc[df2['ID'] == 19]
group_67 = df2.loc[df2['ID'] == 67]
group_69 = df2.loc[df2['ID'] == 69]

#Plotting
plt.scatter(group_19['Buckets'], group_19['ValueB'],c = 'blue')
plt.plot(group_19['Buckets'],group_19['ValueB'],ls='-',marker = 'o', c = 'blue')

plt.scatter(group_67['Buckets'], group_67['ValueB'],c = 'green')
plt.plot(group_67['Buckets'],group_67['ValueB'],ls='-',marker = 'o', c = 'green')

plt.scatter(group_69['Buckets'], group_69['ValueB'],c = 'red')
plt.plot(group_69['Buckets'],group_69['ValueB'],ls='-',marker = 'o', c = 'red')

plt.show()

A: The answer was simpler than i thought. Power BI automatically summarizes the data when you load it in. I have to manually choose "Do not Summarize" in order to get the correct raw data.


text:
Q: Multivariable equation for a hessian matrix I have those two equations and i should find the values to make them equal to 0
3x^2+1-4y=0
-4x-4y=0
I find the values x=-1 and y=1 but the book says there should be also another solution but i cannot find it after doing multiple tries.

A: $$3x^2+1-4y=0$$
$$-4x-4y=0$$
$$y=-x$$
$$3x^2+1+4x=0$$
$$(3x+1)(x+1)=0$$
Hopefully you can see the other solution.


text:
Q: Chrome extension background script sometimes does not run after install or update I have had recent reports of a chrome extension that I develop that stops working after an update or a fresh install. The background script seems to not start at all.

*

*There is no response to messages sent to it from the content scripts.

*There is no process for it in the task manager.

*Opening background page from chrome://extensions does not show any activity in the console, or show any source files.

*Profiling, memory snapshot buttons are disabled.

Once this issue appears, it persists for the chrome profile even after reloading or uninstalling/reinstalling the extension.
Restarting chrome resolves the problem.
The issue has been seen on chrome v79. But I cannot say for sure that it is exclusive to this version, as the issue is difficult to reproduce and seemingly random.
Has anyone seen such an issue, or has any ideas what to look for? I am happy to update my question with any new info I have or with any info you need.
Edit:
Here is my webNavigation listener, which is used to inject content scripts. This handler is wired up in the 'root' context of the background script (not asynchronously inside an event handler)
chrome.webNavigation.onCompleted.addListener((details) ⇒ {
   if(details.frameId === 0) {
     injectScript(
       'js/contentScript.js',
       details.tabId,
       details.frameId,
       details.url
     ).catch((e) ⇒ {});
   }
}

The injectScript function is as follows
export const injectScript = ƒ (scriptPath,tab,frame,tabUrl) {
  return new Promise((res,rej) ⇒ {
    let options = {
      file : scriptPath,
      allFrames : false,
      frameId : frame,
      matchAboutBlank: false,
      runAt : 'document_idle',
    };
    const cb = ƒ () {
      if (chrome.runtime.lastError) {
        let err = new Error('Could not inject script');
        capture(err,{
          ...options,
          tabUrl,
          lastError : chrome.runtime.lastError.message,
        });
        rej(err);
      }else{
        res();
      }
    };
    if (tabUrl.indexOf('.salesforce.com') !== -1) {
      window.setTimeout(() => {
        chrome.tabs.executeScript(tab,options,cb);
      },500);
    }else{
      chrome.tabs.executeScript(tab,options,cb);
    }
  });
};

Note above, the capture function reports the error to a backend and I cannot see it being reported there as well. Cannot add a breakpoint in code because no source appears in the background page, as noted above.

A:
A background service worker is loaded when it is needed, and unloaded when it goes idle.
https://developer.chrome.com/docs/extensions/mv3/service_workers/
You can use the following methods:
// Keep heartbeat
let heartTimer;
const keepAlive = () => {
    heartTimer && clearTimeout(heartTimer);
    heartTimer = setTimeout(() => {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
            console.info('[heartbeat]')
            tabs.length && chrome.tabs.sendMessage(
                tabs[0].id,
                { action: "heartbeat" }
            );
        });
        keepAlive();
    }, 10000);
};
keepAlive();


text:
Q: XML Schema Validation Error. It appears to be inline with the schema I am getting an error while validating my xml document against its schema. Please help.
Below is the XML document I am trying to validate.
<?xml version="1.0" encoding="utf-8"?>
<QuestionForm xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:xsd="http://www.w3.org/2001/XMLSchema"
  xmlns="http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd">
  <Overview>
    <Text>This is overview</Text>
  </Overview>
  <Question>
    <QuestionIdentifier>nextmove</QuestionIdentifier>
    <DisplayName>Display Name</DisplayName>
    <IsRequired>true</IsRequired>
    <QuestionContent>
      <Text>The Main Question will go here?</Text>
    </QuestionContent>
    <AnswerSpecification>
      <FreeTextAnswer>
        <Constraints>
          <IsNumeric minValue="0" maxValue="9999" />
          <Length minLength="0" maxLength="4" />
        </Constraints>
        <NumberOfLinesSuggestion>1</NumberOfLinesSuggestion>
      </FreeTextAnswer>
    </AnswerSpecification>
  </Question>
</QuestionForm>

Here is the link for XML Schema document.
Here is the error message

Unhandled Exception: Amazon.WebServices.MechanicalTurk.Exceptions.ParseErrorException: There was an error parsing the XML question or answer data in your request.  Pl
      ease make sure the data is well-formed and validates against the appropriate schema. Details: cvc-complex-type.2.4.a: Invalid content was found starting with element
      'QuestionContent'. One of '{"http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd":QuestionIdentifier}' is expected. (14084243
      91173 s)
         at Amazon.WebServices.MechanicalTurk.MTurkClient.ProcessErrors(ErrorsError[] errors, Object ret, OperationRequest opsReq)
         at Amazon.WebServices.MechanicalTurk.MTurkClient.SendRequest(Object req)
         at   Amazon.WebServices.MechanicalTurk.MTurkClient.CreateHIT(CreateHITRequest request)

  [1]: http://mechanicalturk.amazonaws.com/AWSMechanicalTurkDataSchemas/2005-10-01/QuestionForm.xsd

A: The input you show does not have the error indicated.  It's valid against the schema you point to.
Either you are submitting input to the validator which is not the input you show, or the validator is using some schema other than the one you point to.  Either way, the only solution to your problem is to make sure that the validator is actually using the inputs you want it to use, and not some other inputs.


text:
Q: Map Annotation Won't Show Custom UIButton for rightCalloutAccessoryView I have a map with dozens of annotations. The annotations correctly show title and subtitle and I would like to add a custom "Go" button to the right of them. The Go button will open Apple Maps and give users directions to the annotation they were looking at on the map.
I've copied the code I'm using below. In it's current form, no button will appear.
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if !(annotation is MKUserLocation) {
        let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: String(annotation.hash))

        let rightButton = UIButton(type: .custom)
        rightButton.setImage(UIImage(named: "Go"), for: .normal)
        rightButton.tag = annotation.hash

        pinView.canShowCallout = true
        pinView.rightCalloutAccessoryView = rightButton

        return pinView
    }
    else {
        return nil
    }
}

If I remove the following line:
rightButton.setImage(UIImage(named: "Go"), for: .normal)

and change the one above it to:
let rightButton = UIButton(type: .detailDisclosure)

The button does correctly display, which tells me that it's a problem with my attempt to use a custom image for the button.
Any ideas on what I'm missing?

A: I was able to correct it by changing the UIButton type to the following:
let rightButton = UIButton(type: .infoLight)

My code snippet now looks so:
func mapView(_ mapView: MKMapView, viewFor annotation: MKAnnotation) -> MKAnnotationView? {
    if !(annotation is MKUserLocation) {
        let pinView = MKPinAnnotationView(annotation: annotation, reuseIdentifier: String(annotation.hash))

        let rightButton = UIButton(type: .infoLight)
        rightButton.setImage(UIImage(named: "Go"), for: .normal)
        rightButton.tag = annotation.hash

        pinView.canShowCallout = true
        pinView.rightCalloutAccessoryView = rightButton

        return pinView
    }
    else {
        return nil
    }
}


text:
Q: Finding the value of a particular index in a Python list I have a simple python program.
from nltk.tokenize import word_tokenize

negation ='no','not','never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')
sentence = 'loss money'

if any(word in list2 for word in word_tokenize(sentence)) and (any(word in
list2 for word in word_tokenize(sentence))[-1:])not in negation :
  print 'sad'
else:
  print 'not sad'

This make error which is
TypeError: 'bool' object has no attribute '__getitem__'

What I need here, I want to check if any word in the sentence is in the list2. If yes, then want to check its before index value is in the negation list or not. if yes it should be "not sad".
For an example "I miss him" should sad, "I not miss him" should be not sad.
Can anyone help me !

A: You have a number of problems here, for starters:

*

*If you are going to be looking through sets of words, use sets, not lists. e.g. negations={'no','not','never'}

*'give up' will never be found as a token in a sentence.

*any() returns a boolean (see this question) for how it works.

*listobj[-1:] returns the slice of the list with only the last element

*you are not trying to extract items from a list or container, as any() returns a boolean, you are trying to treat a boolean as a container.  This is what is causing the error you can see.

I suggest you break down your problem into more logical steps rather than jumping straight into list comprehensions / generators.
Where you want to access items in a list based on the position of others, I recommend starting with a indexed for loop:
for index, value in enumerate(var):
    last_word=var[index-1] if index > 0 else None

And do operations like word tokenisation only once, no need to keep doing it over and over.
Example solution:
def sad_sentence(sentence):
    wordlist=sentence.split()
    negations={'no','not','never'}
    negphrases={'miss','loss','gone','give up','lost'}

    for index, word in enumerate(wordlist):
        last_word=wordlist[index-1] if index > 0 else None
        if word in negphrases:
            if last_word in negations:
                print 'not sad'
            else:
                print 'sad'
            break;
        print 'not sad'

This results in:
>>> sad_sentence("I am not gone")
not sad
>>> sad_sentence("I am not here I am gone")
sad
>>>

A: You didn't write the second part of your if well.
You first look at any(word in list2 for word in word_tokenize(sentence)) which returns a boolean. Then you try to extract the last element of this boolean ([-1]) which return an error.
No need to use nltk library here, you can do it with just .split():
negation ='no,not,never'.split(',')
list2 = 'miss,loss,gone,give up,lost'.split(',')

def f(sentence):
    if any(word in list2 for word in sentence.split()) and not any(word in negation for word in sentence.split()):
        print 'sad'
    else:
        print 'not sad'

l = ['loss money', 'I miss him', 'I not miss him']
for e in l:
    f(e)
# Outputs: sad / sad / not sad

edit New version to take into account @Baldrickk good remark.
I took two more cases into consideration. It prints 'happy' if no words belong to list2. If several words belongs to list2, it checks every previous words and not just the first one.
negation = {'no', 'not', 'never'}
list2 = {'miss', 'loss', 'gone', 'give up', 'lost'}

def f(sentence):
    s = sentence.split()
    l = [s.index(word) for word in s if word in list2]
    # Will returns list of indices (of sentence) where word is in list2
    if len(l) > 0:
        for e in l:
            # Check previous word
            if s[e-1] not in negation:
                print 'sad'
            else:
                print 'not sad'
    else:
        print 'happy'

l = ['loss money', 'I miss him', 'I not miss him', 'happy new year', 'I am not here I am gone']
for e in l:
    f(e)
# sad / sad / not sad / happy / sad


text:
Q: Shrinkage estimation for regression with ARMA errors I was wondering if someone knows a R-package or function library for the topic of shrinkage for regression with ARMA errors.
Please let me know if you came across something related.


text:
Q: Entity framework navigation properties not included in web api json content I how the two entities:
public partial class Item
{
    public FeedItem()
    {
        this.Votes = new List<Vote>();
    }

    public long ItemId { get; set; }
    public long UserId { get; set; }
    public string UserComment { get; set; }
    public System.DateTime CreationDate { get; set; }
    public virtual User User { get; set; }
    public virtual ICollection<Vote> Votes { get; set; }
}

public partial class User
    {
        public User()
        {
            this.FeedItems = new List<FeedItem>();
            this.Votes = new List<Vote>();
        }

        public long Id { get; set; }
        public virtual ICollection<Item> Items { get; set; }
        public virtual ICollection<Vote> Votes { get; set; }
    }

On the other side of the of the Http request I see nulls for the User property and Votes is always an empty collection. I have been playing around all day with Newtonsoft.Json attributes like JsonIgnore and such and I'm not getting anywhere.
Can this be done or to I need to make a change to my object model in order to transport it via web api?


text:
Q: Mac OSX, Bash, awk, and negative look behind I want to find a particular process using awk:
ps aux|awk '/plugin-container.*Flash.*/'

Now it finds the process, but it includes itself in the results, because ps results include them as well. To prevent that, I am trying to use negative look behind as follows:
ps aux|awk '/(\?<!awk).*plugin-container.*Flash.*/'

But it does not work. Does awk support look behind? What am I doing wrong? Thanks

A: The common trick is to use
ps aux | grep '[p]lugin-container.*Flash.*'

The character class [p] prevents grep itself from being matched.

A: I don't know whether awk supports lookbehind, but I usually solve this problem with grep -v:
aix@aix:~$ ps aux | awk '/plugin-container.*Flash/' | grep -v awk

(Also, I'd normally use grep for the awk command above.)

A: I don't know if awk supports lookbehinds, but if, then the question mark at the start should not be escaped, a negative lookbehind starts (?<!
A question mark right after the opening bracket is the sign, that this group is not a capturing group, i.e. it has some special meaning.


text:
Q: Path is wrong, what to do? I'd like to write something to my path.
My code is following
QString Log::logPacketsPath = QDir::currentPath() + "/logs/Packets/";
int userID = 1;
QString text = "test 1 2 3";

QFile logPacketFile(logPacketsPath + "UserID: " + userID + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");

if (logPacketFile.open(QFile::WriteOnly | QFile::Text | QFile::Append))
{
    QTextStream out(&logPacketFile);
    out << "[" << QDateTime::currentDateTime().toString("dd.MM.yy, hh:mm:ss") << "]: " << text << "\n";
    logPacketFile.close();
}

But it only creates the file named "UserID" with nothing in it.
Do you know where the mistake is?

A: I'm not sure which OS you're using, but ':' is invalid in a Windows filename.
Next, you should flush the QTextStream before closing the file:
out.flush();
logPacketFile.close();

or create additional scope:
{
    QTextStream out(&logPacketFile);
    out << "[" << QDateTime::currentDateTime().toString("dd.MM.yy, hh:mm:ss") << "]: " << text << "\n";
}
logPacketFile.close();

Also, as Chemobyl has pointed out, you can get into trouble by concatinating the int userID to your filepath. I'd suggest using string formatting to create the filename:
QString logPacketFile("%1UserID%2 - %3.log")
         .arg(logPacketsPath)
         .arg(userID)
         .arg(QDateTime::currentDateTime().toString("dd.MM.yy"));

A: Convert int to QString:
Use QString::number().
Output with your current code:
"C:/.../logs/Packets/UserID [bad symbols here] - 17.11.14.log"

Output with
QFile logPacketFile(logPacketsPath + "UserID " + QString::number(userID) + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");//removed colon

is:
"C:/.../logs/Packets/UserID 1 - 17.11.14.log"

It is source of big troubles. See next:
int userID = 70;
QString text = "test 1 2 3";
QFile logPacketFile(logPacketsPath + "UserID " + userID + " - " +  QDateTime::currentDateTime().toString("dd.MM.yy") + ".log");

Output:
.../UserID F - 17.11.14.log"

Note F, not a 70 because operator+ thought that you use simple char and 70 in char is F:
http://www.asciitable.com/
So I strongly suggest you to use QString::number to prevent errors.


text:
Q: WordPress filter APPEND nofollow to rel I am trying append nofollow to add external links. If a link does not have a rel attribute, rel="nofollow" will be added. If a link already has rel="nofollow" nothing will happen, and if a link has rel=something else the nofollow value should also be added.
function nofollow($content) {
  $content = preg_replace_callback('/]*href=["|\']([^"|\']*)["|\'][^>]*>([^<]*)<\/a>/i',
  function($m) {
    $parseUrl = parse_url(home_url());
    $mydomain = $parseUrl['host'];
    if (strpos($m[1], $mydomain) === false) {
      return ''.$m[2].'';
    } else {
      return ''.$m[2].'';
    }
  },
  $content);
  return $content;
}
add_filter('the_content', 'nofollow');

The code successfully adds rel=follow to external links but if for a example a link has rel="noopener" it will replace it willrel=follow. Why is it no appending like so?rel="noopener nofollow"`

A: Because you ignore all attributes of  tag except href. If you want to take existing rel value into account, you should read it also. And maybe it is easier to do with some html parser function, because regexp is a bit too low-level for your case.


text:
Q: Upload New Version (Files Tab) - trigger in Lightning In Lightning I am trying to write a trigger when user click "Upload New version" and try to upload. But i couldnt find tiggers to place some code before insert.
In Salesforce classic, i used triggers in content version. please refer the screen shot.

Any suggestion please how to fire triggers on "upload New Version" in Salesforce Lightning or how can we get the control to write some logic when user click on "Upload New version button"?
Thanks in Advance

A: The object underlying the lightning experience and the classic is same content version .
Looks like at this point the UI link to write triggers on content version is missing in lightning experience but that does not mean triggers wont work .
You can still code the triggers as needed using developer console or an IDE and everything should work in lightning experience .


text:
Q: Save a result of printSchema() function to variable in Pyspark? I'm using the printSchema function to infer schema of Json file. I want to save the result of this function call in a variable to parse it line by line so that I can  extract a structure of a schema and convert it in a DDL schema for creating a table in hive.
How can this be done?

A: If you inspect the source code for printSchema(), you will see that this function just does the following:
print(self._jdf.schema().treeString())

Therefore, you can save the output as follows:
printSchemaString = df._jdf.schema().treeString()

Other references:

*

*Saving result of DataFrame show() to string in pyspark

*Capturing the result of explain() in pyspark