text:
Q: Remove appended elements in mouseleave (Jquery) I want an image to pop up (a larger version of it is displayed) when the mouse is hovered over the image and remove the appended elements when mouse leaves the image. Here's the relevant code:
var imgs;
$(document).on('mouseenter', '.gallery li', function() {
    $(this).find('img').addClass("gray");
    imgs = `
 `;
    var info = `

                'Title': ${$(this).find('img').attr('alt')}
                'City': ${$(this).find('img').attr('city')}
                'Date Taken': ${$(this).find('img').attr('taken')}

`;
    imgs += info;
    $("body").append($(imgs));
    // console.log(imgs);
})

$(document).on("mousemove", function( event ) {
    $("#preview").css("left", event.pageX);
    $("#preview").css("top", event.pageY);
});

$(document).on("mouseleave", '.gallery li', function() {
    // $("body").remove();
    // $("body").find('img').removeClass("gray");
    // $("body").remove($(imgs));
    alert('hello');
})

#preview {
    position: absolute;
    padding: 10px 10px 0 10px;
    /* display: none; */
    background-color: #424242;
}
.gray {
     filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
}

Mousleave is not working as I'd expect. Instead divs are appended to body. While debugging I found that mouseleave gets executed when mouse moves (alert message pops up on every mouse move). Also, the popped up image under the mouse cursor doesn't change. It stays the same.
What I want to to pop the appended elements during mouseenter, such that every time mouse is hovered over image, append and pop happens on mouseenter and mouseleave.
The output shows up like this. div is for some reason not obeying event coordinates. Images show up at the bottom.

A: Your div has id="preview" so you need id selector # to get element.
Use $('#preview').remove() it will work.
Or you can add class="preview" in then $(".preview").remove(); will work.
Edit added offset to top & left so when mouse moves it won't flicker.
Try it below. Added class="preview" and used class selector . as $('.preview').

var xOffset = 3;
var yOffset = 3;

$(document).on('mouseenter', '.gallery li', function() {
  $(this).find('img').addClass("gray");
  imgs = `
 `;
  var info = `

                'Title': ${$(this).find('img').attr('alt')}
                'City': ${$(this).find('img').attr('alt')}
                'Date Taken': ${$(this).find('img').attr('alt')}

`;
  imgs += info;
  $("body").append($(imgs));
  // console.log(imgs);
})

$(document).on("mousemove", function(event) {
 $("#preview")
            .css("top",(event.pageY + xOffset) + "px")
            .css("left",(event.pageX + yOffset) + "px");
});

$(document).on("mouseleave", '.gallery li', function() {
  $(".preview").remove();
})
#preview {
  position: absolute;
  padding: 10px 10px 0 10px;
  /* display: none; */
  background-color: #424242;
}

.gray {
  filter: grayscale(100%);
  -webkit-filter: grayscale(100%);
}

A: You should pass the index() of the li element that the image exists in, to the id of the .preview element. In addition you could use jQuery Deffered and .when() (this is optional). Below is an example.
var df = $.Deferred();
var xOffset = 3;
var yOffset = 3;

$(document).on('mouseenter', '.gallery li', function() {
  $(this).find('img').addClass("gray");
  let imgs = `
 `;
  var info = `

                'Title': ${$(this).find('img').attr('alt')}
                'City': ${$(this).find('img').attr('alt')}
                'Date Taken': ${$(this).find('img').attr('alt')}

`;
  imgs += info;
  let imgObj = $(imgs);
  imgObj.attr("id", "preview-"+$(this).index());
  $("body").append(imgObj );
  df.resolve( true );
});

$.when( df ).done(function ( v ) {
  if(v) {
      $(document).on("mousemove", '.gallery li', function(event) {
          $("#preview-"+$(this).index())
            .css("top",(event.pageY + xOffset) + "px")
            .css("left",(event.pageX + yOffset) + "px");
      });

      $(document).on("mouseleave", '.gallery li', function() {
          $("#preview-"+$(this).index()).remove();
      });
  }
});

Here is an example.

var df = $.Deferred();
const xOffset = 3;
const yOffset = 3;

$(document).on('mouseenter', '.gallery li img', function(event) {
  $(event.target).addClass("gray");
  let alttext = $(event.target).attr('alt');
  let imgs = `
 `;
  var info = `

                'Title': ${alttext}
                'City': ${alttext}
                'Date Taken': ${alttext}

`;
  imgs += info;
  let imgObj = $(imgs);
  imgObj.attr("id", "preview-"+$(event.target).parent().index());
  $("body").append(imgObj );
  df.resolve( true );
});

$.when( df ).done(function( v ) {
  if(v) {
      $(document).on("mousemove", '.gallery li img', function(event) {
          event.stopPropagation();
          $("#preview-"+$(event.target).parent().index())
            .css("top",(event.pageY + xOffset) + "px")
            .css("left",(event.pageX + yOffset) + "px")
            .css("display","block");
      });

      $(document).on("mouseleave", '.gallery li img', function(event) {
          $("#preview-"+$(event.target).parent().index()).remove();
      });
  }
});
[id^="preview-"] {
  position: absolute;
  z-index: 9999;
  padding: 10px;
  display: none;
  background-color: #424242;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  align-content: center;
  width: 11rem; // you may use percentage e.g. 20% or viewport units here e.g. 10vw
}
[id^="preview-"] img {
  width: 100%;
  height: auto;
}

.gray {
  filter: grayscale(100%);
  -webkit-filter: grayscale(100%);
}


text:
Q: concatenate characters in new string then convert them in integers number="0123,456,789,"
cleanedNumber=''

for i in range(0,len(number)):
    if number[i] in '0123456789':
        cleanedNumber = cleanedNumber + number[i]

newNumber = int(cleanedNumber)
print("The number is {}".format(newNumber))

I don't understand why do we use variable cleanedNumber=''?

A: In a for loop, the original string stored in number is looped character by character.
cleanedNumber string is used to store digits only. Everything that is not a digit (i.e. a character from 0 to 9) will not be added to the cleanedNumber string. At the end of the for loop, only characters that are digits are kept in this new variable.
Finally, it is converted to an integer and displayed.

A: It can be a lot easier than that. Just do:
newNumber = int(filter(str.isdigit, number))

Or, alternatively:
newNumber = int(number.replace(",", ""))

A: The original code simply creates a new string variable to store the "sanitized" or "cleaned" version of the original input.
We start off with a string:
number="0123,456,789,"

Then the originator decided to copy the "numbers" into another string variable:
cleanedNumber=''

To achieve this, a for loop was written just to read every string member:
  for i in range(0,len(number)):
    if number[i] in '0123456789':
        cleanedNumber = cleanedNumber + number[i]

The translation of this would be that for each "i" in the range from 0 to the length of the original string, we check if the value of "i" from the "number" string variable is present in '0123456789'. If it is present, then we copy it in the "cleanedNumber" variable.
In the end, the code converts it to an int and prints it:
newNumber = int(cleanedNumber)
print("The number is {}".format(newNumber))

There are simpler ways of writing this code though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: javascript not loading on page I have created a very simple page at this point and am adding a menu that using javascript to display a submenu.  I can't get the javascript to load and I am not getting any errors using Firebug. I have stripped my page down to pretty much bare content except for the javascript, but it still won't load.  The CSS associated with the menu does load. I didn't write the javascript, but have a basic concept of how it works.
Here is the page:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

    <title>The Journal</title>
    <meta http-equiv="Content-Type" content="text/html;charset=ISO-8859-1">
    <link href="http://celt.miamioh.edu/ject/images/favicon.png" rel="shortcut icon">

    <link rel="stylesheet" type="text/css" href="menustyle.css" media="screen, print" />

Test page for javascript functionality.

and here is he js:
subInfo[2] = new Array();
subInfo[3] = new Array();

//*** SET SUB MENUS TEXT LINKS AND TARGETS HERE ***//
subInfo[1][1] = new Array("Overview","http://celt.miamioh.edu/newject/about.php","");
subInfo[1][2] = new Array("Free Sample Issue","http://celt.miamioh.edu/newject/issue.php?v=19&n=1","");
subInfo[1][3] = new Array("Editorial Board/Staff","http://celt.miamioh.edu/newject/staff.php","");
subInfo[1][4] = new Array("Manuscript Submission","http://celt.miamioh.edu/newject/submission.php","");

subInfo[2][1] = new Array("Current Issue","http://celt.miamioh.edu/newject/issue.php?v=25&n=2","");
subInfo[2][2] = new Array("Issue Archive","http://celt.miamioh.edu/newject/archive.php","");
subInfo[2][3] = new Array("Special Issue Archive","http://celt.miamioh.edu/newject/special.php","");
subInfo[2][4] = new Array("Search Archive","http://celt.miamioh.edu/newject/search.php","");

subInfo[3][1] = new Array("Journal Subscription","http://celt.miamioh.edu/journals/subscription/subscriptionpage.php","");
subInfo[3][2] = new Array("Order Back Issue","http://celt.miamioh.edu/newject/order_backissues.php","");
subInfo[3][3] = new Array("Order Individual Articles","http://celt.miamioh.edu/newject/order_articles.php","");

//*** SET SUB MENU POSITION ( RELATIVE TO BUTTON ) ***//
var xSubOffset = 9;
var ySubOffset = 34;

//*** NO MORE SETTINGS BEYOND THIS POINT ***//
var overSub = false;
var delay = 1000;
totalButtons = upSources.length;

// GENERATE SUB MENUS
for ( x=0; x<totalButtons; x++) {
    // SET EMPTY DIV FOR BUTTONS WITHOUT SUBMENU
    if ( subInfo[x+1].length < 1 ) {
        document.write('
');
    // SET DIV FOR BUTTONS WITH SUBMENU
    } else {
        document.write('
');

        document.write('
');
        for ( k=0; k<subInfo[x+1].length-1; k++ ) {
            document.write('
');
            document.write('');
            document.write( subInfo[x+1][k+1][0] + '');
            document.write('
');
        }
        document.write('
');
    }
    document.write('
');
}

//*** MAIN BUTTONS FUNCTIONS ***//
// PRELOAD MAIN MENU BUTTON IMAGES
function preload() {
    for ( x=0; x<totalButtons; x++ ) {
        buttonUp = new Image();
        buttonUp.src = buttonFolder + upSources[x];
        buttonOver = new Image();
        buttonOver.src = buttonFolder + overSources[x];
    }
}

// SET MOUSEOVER BUTTON
function setOverImg(But, ID) {
    document.getElementById('button' + But + ID).src = buttonFolder + overSources[But-1];
}

// SET MOUSEOUT BUTTON
function setOutImg(But, ID) {
    document.getElementById('button' + But + ID).src = buttonFolder + upSources[But-1];
}

//*** SUB MENU FUNCTIONS ***//
// GET ELEMENT ID MULTI BROWSER
function getElement(id) {
    return document.getElementById ? document.getElementById(id) : document.all ? document.all(id) : null;
}

// GET X COORDINATE
function getRealLeft(id) {
    var el = getElement(id);
    if (el) {
        xPos = el.offsetLeft;
        tempEl = el.offsetParent;
        while (tempEl != null) {
            xPos += tempEl.offsetLeft;
            tempEl = tempEl.offsetParent;
        }
        return xPos;
    }
}

// GET Y COORDINATE
function getRealTop(id) {
    var el = getElement(id);
    if (el) {
        yPos = el.offsetTop;
        tempEl = el.offsetParent;
        while (tempEl != null) {
            yPos += tempEl.offsetTop;
            tempEl = tempEl.offsetParent;
        }
        return yPos;
    }
}

// MOVE OBJECT TO COORDINATE
function moveObjectTo(objectID,x,y) {
    var el = getElement(objectID);
    el.style.left = x;
    el.style.top = y;
}

// MOVE SUBMENU TO CORRESPONDING BUTTON
function showSubMenu(subID, buttonID) {
    hideAllSubMenus();
    butX = getRealLeft(buttonID);
    butY = getRealTop(buttonID);
    moveObjectTo(subID,butX+xSubOffset, butY+ySubOffset);
}

// HIDE ALL SUB MENUS
function hideAllSubMenus() {
    for ( x=0; x<totalButtons; x++) {
        moveObjectTo("submenu" + (x+1) + "",-500, -500 );
    }
}

// HIDE ONE SUB MENU
function hideSubMenu(subID) {
    if ( overSub == false ) {
        moveObjectTo(subID,-500, -500);
    }
}

//preload();

Any help on what is wrong or even how I can further troubleshoot it myself to find out what is wrong would be appreciated.

A: I created a copy of your file at JSBin here and can verify that the javascript does indeed run.
I also noticed you have code commented out at the bottom //preload(); and perhaps this is what you are expecting to execute?
If you still are not getting the expected results try adding a debugger; statement and running in Firebug and the code should break on the line you added that code.

A: Your src link is incorrect, to match the URLs in the js file it should be
http://celt.miamioh.edu/newject/menuscript.js


text:
Q: Spark SQL working on very large data set fails with file not found exception after 30 mins We have a Spark SQL working on very large data set (50 GB) this SQL does many aggregations. it fails after 30 mins saying "file not found". Is there any way we can ensure that code can be optimized to help reduce the network and CPU overhead?
We are working on HD insight cluster and we have increased timeout as well to ensure that it's not a network issue. Sample code below. Table A is created in parquet mode.
Agg_data_op = '''
SELECT trans_cd
    Sum ( b ),
    Sum (case … c)
    <50 aggregated fields>
From A group by trans_cd"
df_trans_mart = spark.sql(Agg_data_op)
df_trans_mart.write.mode("overwrite").saveAsTable("df_core_mart")


text:
Q: Access local Kubernetes cluster running in Virtualbox I have configured a Kubernetes cluster using kubeadm, by creating 3 Virtualbox nodes, each node running CentOS (master, node1, node2). Each virtualbox virtual machine is configured using 'Bridge' networking.
As a result, I have the following setup:

*

*Master node 'master.k8s' running at 192.168.19.87 (virtualbox)

*Worker node 1 'node1.k8s' running at 192.168.19.88 (virtualbox)

*Worker node 2 'node2.k8s' running at 192.168.19.89 (virtualbox

Now I would like to access services running in the cluster from my local machine (the physical machine where the virtualbox nodes are running).
Running kubectl cluster-info I see the following output:
Kubernetes master is running at https://192.168.19.87:6443
KubeDNS is running at ...

As an example, let's say I deploy the dashboard inside my cluster, how do I open the dashboard UI using a browser running on my physical machine?

A: The traditional way is to use kubectl proxy or a Load Balancer, but since you are in a development machine a NodePort can be used to publish the applications, as a Load balancer is not available in VirtualBox.
The following example deploys 3 replicas of an echo server running nginx and publishes the http port using a NodePort:
apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
spec:
  selector:
    matchLabels:
      app: nginx
  replicas: 3
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
        - name: my-echo
          image: gcr.io/google_containers/echoserver:1.8
---

apiVersion: v1
kind: Service
metadata:
  name: nginx-service-np
  labels:
    name: nginx-service-np
spec:
  type: NodePort
  ports:
    - port: 8082        # Cluster IP http://10.109.199.234:8082
      targetPort: 8080  # Application port
      nodePort: 30000   # Example (EXTERNAL-IP VirtualBox IPs) http://192.168.50.11:30000/ http://192.168.50.12:30000/ http://192.168.50.13:30000/
      protocol: TCP
      name: http
  selector:
    app: nginx

You can access the servers using any of the VirtualBox IPs, like
 http://192.168.50.11:30000 or  http://192.168.50.12:30000 or  http://192.168.50.13:30000
See a full example at Building a Kubernetes Cluster with Vagrant and Ansible (without Minikube).

A: The traditional way of getting access to the kubernetes dashboard is documented in their readme and is to use kubectl proxy.
One should not have to ssh into the cluster to access any kubernetes service, since that would defeat the purpose of having a cluster, and would absolutely shoot a hole in the cluster's security model. Any ssh to Nodes should be reserved for "in case of emergency, break glass" situations.
More generally speaking, a well configured Ingress controller will surface services en-masse and also has the very pleasing side-effect of meaning your local cluster will operate exactly the same as your "for real" cluster, without any underhanded ssh-ery rules required


text:
Q: OPE coefficients of primaries in a 2D CFT I am trying to compute the OPE coefficients in a 2D CFT, and I am convincing myself of something that I know is not true but cant find my mistake.
Given primaries $V_{\Delta_1}$ and $V_{\Delta_2}$ I know that
$$V_{\Delta_1}(z_1)V_{\Delta_2}(z_2) = \displaystyle\sum_\Delta C_{12}^\Delta(z_1,z_2) V_{\Delta}(z_2)  $$
Where $\Delta$ runs over all fields in my algebra, primaries and descendants. This far I know, here begins my guesswork. Since this holds as an operator equation, it should hold for expectation values as well. So I know
$\langle V_{\Delta_1}(z_1)V_{\Delta_2}(z_2) \rangle = \displaystyle\sum_\Delta C_{12}^\Delta(z_1,z_2)\langle V_{\Delta}(z_2) \rangle $
Now I know from the global ward identities that
$\langle V_{\Delta_1}(z_1)V_{\Delta_2}(z_2) \rangle = \delta_{\Delta_1 \Delta_2 }|z_{12}|^{-2\Delta_1}$
Where I've normalized my fields so that the overall coefficient in the 2-point function is 1. All this combined tells me that
$\delta_{\Delta_1 \Delta_2 }|z_{12}|^{-2\Delta_1} = \displaystyle\sum_\Delta C_{12}^\Delta(z_1,z_2)\langle V_{\Delta}(z_2) \rangle$
So to compute $C_{12}^\Delta(z_1,z_2)$ I need to know what that $\langle V_{\Delta}(z) \rangle $ can be. Again using global ward identities I know that for primaries $\langle V_{\Delta}(z) \rangle = 0$ unless $\Delta = 0$ in which case it is a constant. So I already know that $C_{12}^\Delta(z_1,z_2) = 0$ for any primary $\Delta \neq 0$. Now we move on to the descendants. I know that
$ \langle L_{-n} V_{\Delta}(z) \rangle = \left[ \frac{\partial_z}{z^{n-1}} +\frac{(n-1\Delta)}{z^n} \right] \langle V_{\Delta}(z) \rangle $
If $\Delta = 0$ then $\langle V_{\Delta}(z) \rangle$ is a constant so $\partial \langle V_{\Delta}(z) \rangle = 0$ and since $\Delta = 0$  I also know that $\Delta \langle V_{\Delta}(z) \rangle = 0$. If $\Delta \neq 0$ then $\langle V_{\Delta}(z) \rangle = 0$, so I get no contributions.
It seems then that the only non zero $C_{12}^\Delta(z_1,z_2)$ is $C_{11}^0(z_1,z_2)$ which I can get by
$\delta_{\Delta_1 \Delta_2 }|z_{12}|^{-2\Delta_1} = C_{11}^0(z_1,z_2)\langle V_{0}(z_2) \rangle$
and so $C_{11}^0(z_1,z_2) = |z_{12}|^{-2\Delta_1}$ (up to a constnat), but this is incorrect, in fact I know that there are contributions from $ \langle L_{-1} V_{\Delta}(z) \rangle$, but where is my mistake?

A: You're almost there, but you are missing some important facts about the $\Delta = 0$ multiplet. You say "in fact I know that there are contributions from $L_{-1} V_\Delta(z)$". This is true in general, that is to say for $\Delta > 0$ (except for some special values of $\Delta$ that depend on $c$). However, in a unitary CFT there can only be one operator with $\Delta = 0$, the unit operator, and this operator obeys $L_{-1} V_{\Delta = 0} = 0$ as an operator equation. (To prove this, you can simply compute that the state $|L_{-1} V_{\Delta = 0} \rangle$ has zero norm, and since the theory is unitary it implies that the state vanishes.) Consequently, your conclusion that
$$C_{11}^0(z_1,z_2) = |z_{12}|^{-2\Delta_1}$$
is completely correct.


text:
Q: Procedimiento almacenado en mysql Hola muchachos buenos días nuevamente aquí con nuevas dudas.
Estoy haciendo un mantenerdor en java Desktop y en la parte de búsqueda tengo una campo de texto en donde ingresaría el valor a buscar, pero además tengo unos radiobuttons que me permitieran elegir el campo de mi tabla en qué buscar.
Me explico: Tengo una tabla de proveedores con 3 campos: nombre, pais, region. Entonces en mi aplicación tengo una caja de texto donde ingreso el valor a buscar, pero además los radiobuttons me permiten elegir entre si buscar en el campo nombre o en el campo pais o en el campo región.
Entonces mi SP en Mysql lo hice así:
DELIMITER $$
CREATE PROCEDURE listarProveedores(campo varchar(50), valor varchar(50))
BEGIN
  select * from suppliers where campo like concat('%',valor,'%');
END
$$
DELIMITER ;

Y cuando llamo al SP:
CALL listarProveedores('ContactName','ch');

no me muestra nada.
Favor de que alguien me dé una opción.
Gracias de antemano.

A: El problema es que las variables del procedimiento no las puedes incluir en la SQL como tal. La solución a tu problema es un prepared statement. Se podría hacer algo así:
DELIMITER $$
CREATE PROCEDURE listarProveedores(campo varchar(50), valor varchar(50))
BEGIN
    SET @buffer = CONCAT("SELECT * FROM suppliers WHERE ", campo, " LIKE %", valor, "%'");
    PREPARE stmt FROM @buffer;
    EXECUTE stmt;

    DEALLOCATE PREPARE stmt;
END
$$
DELIMITER ;

O lo podrias hacer a través de un CASE:
DELIMITER $$
CREATE PROCEDURE listarProveedores(campo varchar(50), valor varchar(50))
BEGIN
  CASE campo
     WHEN 'a' THEN SELECT * FROM suplliers WHERE a LIKE CONCAT('%',valor,'%');
     WHEN 'b' THEN SELECT * FROM suplliers WHERE b LIKE CONCAT('%',valor,'%');
     WHEN 'c' THEN SELECT * FROM suplliers WHERE c LIKE CONCAT('%',valor,'%');
  END CASE;
 END
 $$
 DELIMITER ;


text:
Q: Sorting Lines Based on words in them as keys  Odrer     ID    Descrption    Type

Envelope  K205    Green       Paper     >>>>String Line with space in between
Box       J556    Yellow      Thermocol >>>>String Line with space in between
Envelope  L142    White       Plastic   >>>>String Line with space in between

I have a table something like above and I have to provide options sort the
data based on the column name, like "sort by Order", "Sort By Type" something like that
plz suggest me the best ideas to achieve this in Java... The table rows are strings with
space separating each touple..

A: You have to develop your custom Comparator. For example something like the following.
class ColumnComparator implements Comparator<String> {
    private int column;
    ColumnComparator(int column) {
         this.column = column;
    }
    public int compare(String s1, String s2) {
        return getColumn(s1).compareTo(getColumn(s2));
    }
    private String getColumn(String line) {
        return line.split("\\s+")[column];
    }

Then you can use Arrays.sort() or Collections.sort() passing there array or collection of your lines and instance of this comparator. I leave it for you to implement logic that finds the column index by column name.
}

A: Represent each row in your table as an object with order, id, description and type attributes. Add each object to a collection such as a list. You can then create different comparators such as an OrderComparator and a TypeComparator to sort the collection based on order or type respectively.
For example, here is what your data class might look like:
public class Data{
    private final String order;
    private final String id;
    private final String description;
    private final String type;

    public Data(String order, String id, String description, String type) {
        this.order=order;
        this.id=id;
        this.description=description;
        this.type=type;
    }

    /** getter methods here **/
}

Now, you would add them to a list and use a specific comparator to sort it:
//add data to a list
List<Data> list = new ArrayList<Data>();
list.add(new Data("Envelope","K205","Green","Paper"));
list.add(new Data("Box","J556","Yellow","Thermocol"));
list.add(new Data("Envelope","L142","White","Plastic"));

//create a comparator to sort by type
Comparator<Data> typeComparator = new Comparator<Data>() {
    @Override
    public int compare(Data o1, Data o2) {
        return o1.getType().compareTo(o2.getType());
    }
};

//sort the list
Collections.sort(list, typeComparator);

A: Outline of a possible approach (assuming the data does not come from a database):

*

*Represent your data as a class with the appropriate fields:
class YourData {
    private final String Order;
    private final String Id;
    private final String Description;
    private final String Type;

    // add getters, setters and appropriate constructors
}

Use the appropriate data-types. You can use a Scanner to parse the data.

*Write a Comparator for each attribute you want to order by. If you want to reverse the ordering, you can use Collections.reverseOrder.

*Put your data into an ArrayList, and use Collections.sort with the appropriate Comparator to achieve the desired ordering.


text:
Q: Is "pain" a noun or a verb? For example, which of the following sentences is correct:

*

*My eyes are paining.

*There is a pain in my eyes.

A: Sentence 2 is correct: "there is a pain in my eyes".
Pain can be a noun or verb, for example:

The pain is terrible = noun
It pains me to see you this way = verb

For more details please see:
http://dictionary.reference.com/browse/pain


text:
Q: Android First App Error(Starting another activity) I have a problem with loading another activity.I followed Tutorial When I click the button "Send", the application stops. Can anyone determine my error?
here is my MainActivity.java
    package com.example.myfirstapp;

    import android.content.Intent;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.support.v7.app.ActionBarActivity;
    import android.view.LayoutInflater;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.EditText;

    public class MainActivity extends ActionBarActivity {
        public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            if (savedInstanceState == null) {
                getSupportFragmentManager().beginTransaction()
                        .add(R.id.container, new PlaceholderFragment()).commit();
            }
        }

        @Override
        public boolean onCreateOptionsMenu(Menu menu) {

            // Inflate the menu; this adds items to the action bar if it is present.
            getMenuInflater().inflate(R.menu.main, menu);
            return true;
        }

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
            // Handle action bar item clicks here. The action bar will
            // automatically handle clicks on the Home/Up button, so long
            // as you specify a parent activity in AndroidManifest.xml.
            int id = item.getItemId();
            if (id == R.id.action_settings) {
                return true;
            }
            return super.onOptionsItemSelected(item);
        }
        /** Called when the user clicks the Send button */
        public void sendMessage(View view) {
            Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);
            EditText editText = (EditText) findViewById(R.id.edit_message);
            String message = editText.getText().toString();
            intent.putExtra(EXTRA_MESSAGE, message);
            startActivity(intent);
        }

/**
 * A placeholder fragment containing a simple view.
 */
        public static class PlaceholderFragment extends Fragment {

            public PlaceholderFragment() {
            }

            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
                View rootView = inflater.inflate(R.layout.fragment_main, container,false);
                return rootView;
            }
        }

    }

here is my DisplayMeassageActivity.java:
    public class DisplayMessageActivity extends ActionBarActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new PlaceholderFragment()).commit();
    }
    Intent intent = getIntent();
    String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
    TextView textView = new TextView(this);
    textView.setTextSize(40);
    textView.setText(message);
    setContentView(textView);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {

    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.display_message, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

/**
 * A placeholder fragment containing a simple view.
 */
public static class PlaceholderFragment extends Fragment {

    public PlaceholderFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.fragment_display_message,
                container, false);
        return rootView;
    }
}

}
here is my fragment_main.xml
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal"
            tools:context="com.example.myfirstapp.MainActivity$PlaceholderFragment" >
        <EditText android:id="@+id/edit_message"
            android:layout_weight="1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:hint="@string/edit_message" />
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/button_send"
            android:onClick="sendMessage" />
    </LinearLayout>

and AndroidManifest.xml
    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.example.myfirstapp"
        android:versionCode="1"
        android:versionName="1.0" >

        <uses-sdk
            android:minSdkVersion="8"
            android:targetSdkVersion="19" />

       <application
            android:allowBackup="true"
            android:icon="@drawable/ic_launcher"
            android:label="@string/app_name"
            android:theme="@style/AppTheme" >
            <activity
                android:name="com.example.myfirstapp.MainActivity"
                android:label="@string/app_name" >
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />

                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
            <activity
                    android:name="com.example.myfirstapp.DisplayMessageActivity"
                    android:label="@string/title_activity_display_message"
                    android:parentActivityName="com.example.myfirstapp.MainActivity" >
                <meta-data
                    android:name="android.support.PARENT_ACTIVITY"
                    android:value="com.example.myfirstapp.MainActivity" />
            </activity>

        </application>

    </manifest>

A: Issue is with your DisplayMessageActivity onCreate.
You are trying to add the Fragment before the contentView is set.
Aslo your setContentView(textView) is setting only a TextView.
So, you need to remove the code adding a fragment or create a layout and set a ContentView before finding a View.


text:
Q: Delete kinks and smooth curves I have some data which when plotted looks like the one shown in left on the picture attached.
It has some kinks which I wish to delete and smooth-en to get a nice curve [shown on right].
Presently I manually delete the kinks and interpolate the deleted part by polynomial of high order [say 9]. Then I repopulate the deleted fragment and re-draw the curve.
This takes a long time and I have quite a number of files to process.
Could you folks suggest an efficient way to do this ?
[in MATLAB or some other way]
Thanks a lot !!
P.S.: Added one more plot for clarification above

A: I think this is a simple low pass filtering problem like @thewaywealk suggests. Removing the kinks corresponds removing certain high frequencies in your signal. This can be achieved in matlab by the filter operation. Demonstrations are shown here on denoising a sinusoidal wave here.


text:
Q: How can you get the String values from an array of objects? I have some code that basically checks the list of queues a current business object has been through. These queues are kept in an array aptly named _queueNames of type IKeyMap, a custom object my company uses.
I would like to get the textual names of the queues, as I need to check for the presence of a particular keyword and handle it separately if it's hit that particular queue.
I was hoping I could just do something like this;
 var queues = _queueNames.ToArray().ToString();
 if (queues.Contains("Condition"))
     DoSomethingElse();

but that just gives me the object type, rather than a collection of the values. Looking at the KeyMap object, looks like just a simple key/value pair, might there be another way to do this?
Edit: KeyMap class & interface:
public interface IKeyMap : IDisposable
{
    string Ley {get;}
    string Field {get;}
}

public class KeyMap : IKeyMap
{
    string _key, field;

    public KeyMap(string key, string field)
    {
        _key = key;
        _field = field;
    }

    public override string ToString()
    {
        return string.Format("{0}_{1}", Key, Field);
    }

    public string Key { get {return _key; } }
    public string Field { get {return _field; } }
}

I left out some overrides, such as hashing & the Dispose method since I've got to manually type this out, can't copy-paste from my remote session :(

A: Without knowing what the objects inside of _queueNames look like, there is no exact answer. One mistake being made here is that you are checking a single string representing an entire array. What you want to do is check every object in the array for some value, or convert it to a string and check that value.
Here is an example:
foreach (var item in array)
{
    if (item.ToString().Contains("Condition"))
    {
        DoSomethingElse();
        break;
    }
}

Or the LINQ way:
if (array.Any(item => item.ToString().Contains("Condition")))
    DoSomethingElse();

This specific example only works if the object can be converted into a string that is useful to parse. You could also be accessing a member or invoking a function on said object to get your string. We can't know without more information, but hopefully this points you in the right direction.

A: In your IKeyMap interface, let's add a Boolean.
public string IsSpecial { get; set; }

When you create the object, set the IsSpecial flag. Then read it later..
var queues = _queueNames.ToArray().ToString();
if (queues.IsSpecial)
    DoSomethingElse();

This avoids searching for strings, which is something you want to avoid. What if one of the other queues accidently end up with that string? Or what if you change the special string in one place but forget to change it in another? Or what if the capitalization is different? Or what if the string ends up with a special character that you can't see in it?
And even better way would be with an enum instead of Boolean.
public HandleType QueueHandleType {get;set;}

public enum HandleType {Normal, Special, SuperSpecial}

A: I might be misreading this, but is there any reason you can't just store the queues by name in array of Key/Value pairs, or even a Dictionary?  For example:
var queues = new Dictionary<string, object>();
// add your queues to the dictionary, with the key name being your queue name
queues.Add("Queue1", myQueue);
// etc.

At that point you have a couple of options.  First, you don't need to loop through the total set of queues you have -- you can simply do this:
var specialQueue = queues[mySpecialQueueString];
// do something with it

Or you can use LINQ to get any queues whose name contains your special string:
var results = queues.Where(keyValuePair => keyValuePair.Key.Contains(mySpecialString)).ToArray();

That said, Mason has a point in that you might need to worry about string matching and the like.  There are, of course, several ways to go about this.  If all queues have a fixed name then I like to make a NameConstants class with a bunch of static strings and refer to members of that class.  Or you can do things like making them all upper and comparing to that.


text:
Q: Minimum criteria for quantum state dissolution What are the minimum conditions required to cause the colapse of the quantum state ? Or, what forces/equations determine when an object (for instance an electron) is forced out of its quantum state in to a determined position ?

A: The minimum condition is interaction with another quantum system, leading to entanglement of the electron's position with the scattering angle of a photon bouncing off, for instance. When the other system goes far away, it cannot interact anymore, and the state of the electron is collapsed to one or another approximate position, depending on the photon state. The exact state of the electron depends on the measured outgoing direction of the photon.


text:
Q: Tensorflow estimator exporter when training data is from tfrecords and inference is from raw data Background
0) I'm working on an NLP model that I would like to export
1) I have training data in the form of tfRecords
2) I would like to export my model and host it on a flask app, so the data that comes in is raw text
3) I handle all my pre-processing (tokenization and such) as part of my tensorflow graph
Question
1) Given the fact that I do the data loading (tf.Dataset creation, and pre-processing) as part of tensorflow graph, would the raw text that comes in break the process? (specifically in the tf.Dataset creation step)
2) Would it make more sense to just load in raw text instead of tf.Dataset data?

A: NVM, I completely forgot that you want to have an input_function which you feed datasets through, and a serving_input_function which accepts raw data


text:
Q: C - Access a struct variable from different functions I'm trying to declare a variable (struct typed) in a function, and manipulate it (read/write) from other functions. However, when I try to use that variable in any function that is not where I declared it, it contains only garbage.
This is my code:
    #include <stdio.h>
    #include <stdlib.h>

    typedef struct
      char name[25];
      int roll;
      float marks;
    }Student;

    void getInfo(Student student);
    void display(Student student);

    int main(int argc, char *argv[]) {
      Student student;
      getInfo(student);
      display(student);
      return 0;
    }

    void getInfo(Student student){
      printf("Enter student's name: \n");
      scanf("%s", &student.name);
      printf("Enter student's roll: \n");
      scanf("%d", &student.roll);
      printf("Enter student's grade: \n");
      scanf("%f", &student.marks);
    }

    void display(Student student){
      printf("NAME: %s\n", student.name);
      printf("ROLL: %d\n", student.roll);
      printf("GRADE: %.2f\n", student.marks);
    }

A: You should pass your struct by reference ( & operator )
#include <stdio.h>
#include <stdlib.h>

typedef struct{
    char name[25];
    int roll;
    float marks;
} Student;

void getInfo(Student *student);
void display(Student *student);

int main(int argc, char *argv[]) {
    Student student;
    getInfo( &student );
    display( &student );
    return 0;
}

void getInfo(Student *student){
    printf("Enter student's name:");
    scanf("%s", student->name);
    printf("Enter student's roll:");
    scanf("%d", &student->roll);
    printf("Enter student's grade:");
    scanf("%f", &student->marks);
}

void display(Student *student){
    printf("NAME: %s\n", student->name);
    printf("ROLL: %d\n", student->roll);
    printf("GRADE: %.2f\n", student->marks);
}

Demo : https://repl.it/repls/LowNonstopWeb


text:
Q: C program weird behaviour - pointer and memory I spent a few hours yesterday to find a bug in my program. I could break it down to the following. The code doesn't make much sense. But the problem is, that if I leave out the line
BST root2 = (BST) malloc(sizeof(BST));

in the function fillTree() the program does what it is supposed to. But uncommenting the line leads to the effect, that the data field of the BST root3 in fillTree() changes from NULL to something different.
But I don't understand why this is happening.
So uncommented I get the following output:
root3->data is still null!

But it should be (line commented):
root3->data is still null!
root3->data is still null!
root3->data is still null!
root3->data is still null!

Please help me!
Thank you very much!
#include <stdio.h>
#include <stdlib.h>

typedef struct BSTTag{
  struct BSTTag* lNode;
  struct BSTTag* rNode;
  void *data;
  int (*compare)(void*, void*);
} *BST;

BST createTree(BST root) {
  if(root == NULL) {
    BST bst = (BST) malloc(sizeof(BST));
    bst->lNode = NULL;
    bst->rNode = NULL;
    bst->data = NULL;
    return bst;
  }
  return root;
}

BST fillTree(BST root, int n) {
  int i;
  BST root3 = NULL;
  // error occurrs if this line is not commented
  //BST root2 = (BST) malloc(sizeof(BST));
  for(i = n; i > 0; i--) {
    int *rd = (int *)malloc(sizeof(int));
    *rd = i;
    if(i == n) {
      root3 = createTree(NULL);
    }
    if(root3->data == NULL) {
      printf("root3->data is still null!\n");
    }
  }
  return root;
}

int main(void) {
  fillTree(NULL, 4);
}

A: You are allocating space only for a pointer,
BST bst = (BST) malloc(sizeof(BST));

but you use it as if you allocated space for the structure,
BST createTree(BST root) {
  if(root == NULL) {
    BST bst = (BST) malloc(sizeof(BST));
    bst->lNode = NULL;
    bst->rNode = NULL;
    bst->data = NULL;
    return bst;
  }
  return root;
}

and thus write past the allocated memory, invoking undefined behaviour.
You should allocate the proper size,
BST bst = (BST) malloc(sizeof(*bst));


text:
Q: Indexing logs with Elasticsearch Logstash (using preprocessing Python script) I have an issue with Elasticsearch Logstash.
My objective is to send automatically logs into elasticsearch with logstash.
My raw logs looks like that :
2016-09-01T10:58:41+02:00 INFO (6):     165.225.76.76   entreprise1 email1@gmail.com    POST    /application/controller/action Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko    {"getid":"1"}   86rkt2dqsdze5if1bqldfl1
2016-09-01T10:58:41+02:00 INFO (6):     165.225.76.76   entreprise2 email2@gmail.com    POST    /application/controller2/action2    Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko   {"getid":"2"}   86rkt2rgdgdfgdfgeqldfl1
2016-09-01T10:58:41+02:00 INFO (6):     165.225.76.76   entreprise3 email3@gmail.com    POST    /application/controller2/action2    Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko   {"getid":"2"}

The problem is that I don't want to insert my logs in this form. I want to use a preprocessing script in python, in order to transform my data before injecting into Elastic with logstash.
At start, I wanted to do logging into elasticsearch only using python script. But I have huge quantity of logs separated in a lot of folders and files, constantly updated so I think it is way more powerfull to use logstash or filebeat. I was trying with filebeat and gork filter (not enough for my case) but I think its impossible to use a preprocess script before logging.
Logs should look like that at the end of the python script:
{"page": "/application/controller/action", "ip": "165.225.76.76", "browser": "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko", "action": "action", "client": "entreprise1", "email": "email1@gmail.com", "feature": "application_controller_action", "time": "2016-09-01 10:58:41", "method": "POST", "controller": "controller", "application": "application"}
{"page": "/application/controller2/action2", "ip": "165.225.76.76", "browser": "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko", "action": "action2", "client": "entreprise2", "email": "email2@gmail.com", "feature": "application_controller2_action2", "time": "2016-09-01 10:58:41", "method": "POST", "controller": "controller2", "application": "application"}
{"page": "/application3/controller/action3", "ip": "165.225.76.76", "browser": "Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko", "action": "action3", "client": "entreprise3", "email": "email3@gmail.com", "feature": "application_controller3_action3", "time": "2016-09-01 10:58:41", "method": "POST", "controller": "controller3", "application": "application"}

I'm struggling with the implementation of python script in logstash filter. I know it's something that can be implemented, but basically it's done with ruby script (cf : https://www.elastic.co/guide/en/logstash/current/plugins-filters-ruby.html)
1) Do you think it is possible to solve my problem using logstash ?
2) If yes, my python script should take a raw log line as input and the json formatted line as output ?
3) When a line of log is added into a log file, the entire file is reinsert each time, how can I handle this ?
4) Do you think it's possible to do it with filebeat ? And according to you, what is be the best for my case ?
For now, my configuration logstash file looks like this:
input {
  file {
    path => "/logpath/logs/*/*.txt"
    start_position => "beginning"
  }
}

filter {
  # Here is where I should use my script to transform my logs into my json needed format
  date {
    match => ["time", "YYYY-MM-dd HH:mm:ss" ]
  }

  geoip {
    source => "ip"
    target => "geoip"
  }

}

output {
  stdout  {
    codec => dots {}
  }

  elasticsearch {
    index => "logs_index"
    document_type => "logs"
    template => "./logs_template.json"
    template_name => "logs_test"
    template_overwrite => true
  }

}

I really want to thanks in advance any people that will help me out and consider my request.
Dimitri
PS: Sorry for the syntax, english is not my main language.

A: The standard way to convert logs to json format is using grok,json filters in logstash configuration. and inorder to reduce load on Logstash to process logs filebeat can be used along with your configuration.
Hence, Best cofiguration which can solve this problem is
filebeat->logstash->Elasticsearch stack.
You do not need the python script, instead use filebeat to catch all the logs from specific place and forward it to logstash.
Install filebeat on server where all the logs are getting accumulated, it will be good if you direct all logs in a specific folder. Install filebeat first and then setup configuration to forward logs to logstash
Here is the filebeat configuration:
filebeat:
  prospectors:
    -
      paths:
        - "*log_path_of_all_your_log_files*"
      input_type: log
      json.message_key: statement
      json.keys_under_root: true

  idle_timeout: 1s
  registry_file: /var/lib/filebeat/registry
output:

  logstash:
    hosts: ["*logstash-host-ip:5044*"]
    worker: 4
    bulk_max_size: 1024
shipper:
logging:
  files:
    rotateeverybytes: 10485760 # = 10MB
    level: debug

Now here, along with your logstash configuration, you need to have GROK filter to convert your logs to json format (make changes in logstash configuration file) and then forward it to elasticsearch kibana or wherever you want.


text:
Q: Weird behavior if DataTextures are not square (1:1) I have a pair of shader programs where everything works great if my DataTextures are square (1:1), but if one or both are 2:1 (width:height) ratio the behavior gets messed up. I can extend each of the buffers with unused filler to make sure they are always square, but this seems unnecessarily costly (memory-wise) in the long run, as one of the two buffer sizes is quite large to start. Is there a way to handle a 2:1 buffer in this scenario?
I have a pair of shader programs:

*

*The first is a single frag shader used to calculate the physics for my program (it writes out a texture tPositions to be read by the second set of shaders). It is driven by Three.js's GPUComputeRenderer script (resolution set at the size of my largest buffer.)

*The second pair of shaders (vert and frag) use the data texture tPositions produced by the first shader program to then render out the visualization (resolution set at the window size).

The visualization is a grid of variously shaped particle clouds. In the shader programs, there are textures of two different sizes: The smaller sized textures contain information for each of the particle clouds (one texel per cloud), larger sized textures contain information for each particle in all of the clouds (one texel per particle). Both have a certain amount of unused filler tacked on the end to fill them out to a power of 2.
Texel-per-particle sized textures (large): tPositions, tOffsets
Texel-per-cloud sized textures (small): tGridPositionsAndSeeds, tSelectionFactors
As I said before, the problem is that when these two buffer sizes (the large and the small) are at a 1:1 (width: height) ratio, the programs work just fine; however, when one or both are at a 2:1 (width:height) ratio the behavior is a mess. What accounts for this, and how can I address it? Thanks in advance!
UPDATE: Could the problem be related to my housing the texel coords to read the tPosition texture in the shader's position attribute in the second shader program? If so, perhaps this Github issue regarding texel coords in the position attribute may be related, though I can't find a corresponding question/answer here on SO.
UPDATE 2:
I'm also looking into whether this could be an unpack alignment issue. Thoughts?
Here's the set up in Three.js for the first shader program:
function initComputeRenderer() {

    textureData = MotifGrid.getBufferData();

    gpuCompute = new GPUComputationRenderer( textureData.uPerParticleBufferWidth, textureData.uPerParticleBufferHeight, renderer );

    dtPositions = gpuCompute.createTexture();
    dtPositions.image.data = textureData.tPositions;

    offsetsTexture = new THREE.DataTexture( textureData.tOffsets, textureData.uPerParticleBufferWidth, textureData.uPerParticleBufferHeight, THREE.RGBAFormat, THREE.FloatType );
    offsetsTexture.needsUpdate = true;

    gridPositionsAndSeedsTexture = new THREE.DataTexture( textureData.tGridPositionsAndSeeds, textureData.uPerMotifBufferWidth, textureData.uPerMotifBufferHeight, THREE.RGBAFormat, THREE.FloatType );
    gridPositionsAndSeedsTexture.needsUpdate = true;

    selectionFactorsTexture = new THREE.DataTexture( textureData.tSelectionFactors, textureData.uPerMotifBufferWidth, textureData.uPerMotifBufferHeight, THREE.RGBAFormat, THREE.FloatType );
    selectionFactorsTexture.needsUpdate = true;

    positionVariable = gpuCompute.addVariable( "tPositions", document.getElementById( 'position_fragment_shader' ).textContent, dtPositions );
    positionVariable.wrapS = THREE.RepeatWrapping; // repeat wrapping for use only with bit powers: 8x8, 16x16, etc.
    positionVariable.wrapT = THREE.RepeatWrapping;

    gpuCompute.setVariableDependencies( positionVariable, [ positionVariable ] );

    positionUniforms = positionVariable.material.uniforms;
    positionUniforms.tOffsets = { type: "t", value: offsetsTexture };
    positionUniforms.tGridPositionsAndSeeds = { type: "t", value: gridPositionsAndSeedsTexture };
    positionUniforms.tSelectionFactors = { type: "t", value: selectionFactorsTexture };
    positionUniforms.uPerMotifBufferWidth = { type : "f", value : textureData.uPerMotifBufferWidth };
    positionUniforms.uPerMotifBufferHeight = { type : "f", value : textureData.uPerMotifBufferHeight };
    positionUniforms.uTime = { type: "f", value: 0.0 };
    positionUniforms.uXOffW = { type: "f", value: 0.5 };

}

Here is the first shader program (only a frag for physics calculations):
   // tPositions is handled by the GPUCompute script
    uniform sampler2D tOffsets;
    uniform sampler2D tGridPositionsAndSeeds;
    uniform sampler2D tSelectionFactors;
    uniform float uPerMotifBufferWidth;
    uniform float uPerMotifBufferHeight;
    uniform float uTime;
    uniform float uXOffW;

    [...skipping a noise function for brevity...]

    void main() {

        vec2 uv = gl_FragCoord.xy / resolution.xy;

        vec4 offsets = texture2D( tOffsets, uv ).xyzw;
        float alphaMass = offsets.z;
        float cellIndex = offsets.w;

        if (cellIndex >= 0.0) {

            float damping = 0.98;

            float texelSizeX = 1.0 / uPerMotifBufferWidth;
            float texelSizeY = 1.0 / uPerMotifBufferHeight;
            vec2 perMotifUV = vec2( mod(cellIndex, uPerMotifBufferWidth)*texelSizeX, floor(cellIndex / uPerMotifBufferHeight)*texelSizeY );
            perMotifUV += vec2(0.5*texelSizeX, 0.5*texelSizeY);

            vec4 selectionFactors = texture2D( tSelectionFactors, perMotifUV ).xyzw;
            float swapState = selectionFactors.x;
            vec4 gridPosition = texture2D( tGridPositionsAndSeeds, perMotifUV ).xyzw;
            vec2 noiseSeed = gridPosition.zw;
            vec4 nowPos;
            vec2 velocity;

            nowPos = texture2D( tPositions, uv ).xyzw;
            velocity = vec2(nowPos.z, nowPos.w);

            if ( swapState == 0.0 ) {
                nowPos = texture2D( tPositions, uv ).xyzw;
                velocity = vec2(nowPos.z, nowPos.w);
            } else { // if swapState == 1
                //nowPos = vec4( -(uTime) + gridPosition.x + offsets.x, gridPosition.y + offsets.y, 0.0, 0.0 );
                nowPos = vec4( -(uTime) + offsets.x, offsets.y, 0.0, 0.0 );
                velocity = vec2(0.0, 0.0);
            }

            [...skipping the physics for brevity...]

            vec2 newPosition = vec2(nowPos.x - velocity.x, nowPos.y - velocity.y);
            // Write new position out
            gl_FragColor = vec4(newPosition.x, newPosition.y, velocity.x, velocity.y);
   }

Here is the setup for the second shader program:
Note: The renderer for this section is a WebGLRenderer at window size
function makePerParticleReferencePositions() {

    var positions = new Float32Array( perParticleBufferSize * 3 );

    var texelSizeX = 1 / perParticleBufferDimensions.width;
    var texelSizeY = 1 / perParticleBufferDimensions.height;

    for ( var j = 0, j3 = 0; j < perParticleBufferSize; j ++, j3 += 3 ) {

        positions[ j3 + 0 ] = ( ( j % perParticleBufferDimensions.width ) / perParticleBufferDimensions.width ) + ( 0.5 * texelSizeX );
        positions[ j3 + 1 ] = ( Math.floor( j / perParticleBufferDimensions.height ) / perParticleBufferDimensions.height ) + ( 0.5 * texelSizeY );
        positions[ j3 + 2 ] = j * 0.0001; // this is the real z value for the particle display

    }

    return positions;
}

var positions = makePerParticleReferencePositions();

...

// Add attributes to the BufferGeometry:
gridOfMotifs.geometry.addAttribute( 'position', new THREE.BufferAttribute( positions, 3 ) );
gridOfMotifs.geometry.addAttribute( 'aTextureIndex', new THREE.BufferAttribute( motifGridAttributes.aTextureIndex, 1 ) );
gridOfMotifs.geometry.addAttribute( 'aAlpha', new THREE.BufferAttribute( motifGridAttributes.aAlpha, 1 ) );
gridOfMotifs.geometry.addAttribute( 'aCellIndex', new THREE.BufferAttribute(
        motifGridAttributes.aCellIndex, 1 ) );

uniformValues = {};
uniformValues.tSelectionFactors = motifGridAttributes.tSelectionFactors;
uniformValues.uPerMotifBufferWidth = motifGridAttributes.uPerMotifBufferWidth;
uniformValues.uPerMotifBufferHeight = motifGridAttributes.uPerMotifBufferHeight;

gridOfMotifs.geometry.computeBoundingSphere();

...

function makeCustomUniforms( uniformValues ) {

    selectionFactorsTexture = new THREE.DataTexture( uniformValues.tSelectionFactors, uniformValues.uPerMotifBufferWidth, uniformValues.uPerMotifBufferHeight, THREE.RGBAFormat, THREE.FloatType );
    selectionFactorsTexture.needsUpdate = true;

    var customUniforms = {
        tPositions : { type : "t", value : null },
        tSelectionFactors : { type : "t", value : selectionFactorsTexture },
        uPerMotifBufferWidth : { type : "f", value : uniformValues.uPerMotifBufferWidth },
        uPerMotifBufferHeight : { type : "f", value : uniformValues.uPerMotifBufferHeight },
        uTextureSheet : { type : "t", value : texture }, // this is a sprite sheet of all 10 strokes
        uPointSize : { type : "f", value : 18.0 }, // the radius of a point in WebGL units, e.g. 30.0
        // Coords for the hatch textures:
        uTextureCoordSizeX : { type : "f", value : 1.0 / numTexturesInSheet },
        uTextureCoordSizeY : { type : "f", value : 1.0 }, // the size of a texture in the texture map ( they're square, thus only one value )
    };
    return customUniforms;
}

And here is the corresponding shader program (vert & frag):
Vertex shader:
    uniform sampler2D tPositions;
    uniform sampler2D tSelectionFactors;
    uniform float uPerMotifBufferWidth;
    uniform float uPerMotifBufferHeight;
    uniform sampler2D uTextureSheet;
    uniform float uPointSize; // the radius size of the point in WebGL units, e.g. "30.0"
    uniform float uTextureCoordSizeX; // vertical dimension of each texture given the full side = 1
    uniform float uTextureCoordSizeY; // horizontal dimension of each texture given the full side = 1

    attribute float aTextureIndex;
    attribute float aAlpha;
    attribute float aCellIndex;

    varying float vCellIndex;
    varying vec2 vTextureCoords;
    varying vec2 vTextureSize;
    varying float vAlpha;
    varying vec3 vColor;
    varying float vDensity;

   [...skipping noise function for brevity...]

    void main() {

        vec4 tmpPos = texture2D( tPositions, position.xy );
        vec2 pos = tmpPos.xy;
        vec2 vel = tmpPos.zw;

        vCellIndex = aCellIndex;

        if (aCellIndex >= 0.0) { // buffer filler cell indexes are -1

            float texelSizeX = 1.0 / uPerMotifBufferWidth;
            float texelSizeY = 1.0 / uPerMotifBufferHeight;
            vec2 perMotifUV = vec2( mod(aCellIndex, uPerMotifBufferWidth)*texelSizeX, floor(aCellIndex / uPerMotifBufferHeight)*texelSizeY );
            perMotifUV += vec2(0.5*texelSizeX, 0.5*texelSizeY);

            vec4 selectionFactors = texture2D( tSelectionFactors, perMotifUV ).xyzw;
            float aSelectedMotif = selectionFactors.x;
            float aColor = selectionFactors.y;
            float fadeFactor = selectionFactors.z;

            vTextureCoords = vec2( aTextureIndex * uTextureCoordSizeX, 0 );
            vTextureSize = vec2( uTextureCoordSizeX, uTextureCoordSizeY );

            vAlpha = aAlpha * fadeFactor;
            vDensity = vel.x + vel.y;
            vAlpha *= abs( vDensity * 3.0 );

            vColor = vec3( 1.0, aColor, 1.0 ); // set RGB color associated to vertex; use later in fragment shader.

            gl_PointSize = uPointSize;

        } else { // if this is a filler cell index (-1)
            vAlpha = 0.0;
            vDensity = 0.0;
            vColor = vec3(0.0, 0.0, 0.0);
            gl_PointSize = 0.0;
        }
        gl_Position = projectionMatrix * modelViewMatrix * vec4( pos.x, pos.y, position.z, 1.0 ); // position holds the real z value. The z value of "color" is a component of velocity
    }

Fragment shader:
    uniform sampler2D tPositions;
    uniform sampler2D uTextureSheet;

    varying float vCellIndex;
    varying vec2 vTextureCoords;
    varying vec2 vTextureSize;
    varying float vAlpha;
    varying vec3 vColor;
    varying float vDensity;

    void main() {
        gl_FragColor = vec4( vColor, vAlpha );

        if (vCellIndex >= 0.0) { // only render out the texture if this point is not a buffer filler
            vec2 realTexCoord = vTextureCoords + ( gl_PointCoord * vTextureSize );
            gl_FragColor = gl_FragColor * texture2D( uTextureSheet, realTexCoord );
        }
    }

Expected Behavior: I can achieve this by forcing all the DataTextures to be 1:1

Weird Behavior: When the smaller DataTextures are 2:1 those perfectly horizontal clouds in the top right of the picture below form and have messed up physics. When the larger DataTextures are 2:1, the grid is skewed, and the clouds appear to be missing parts (as seen below). When both the small and large textures are 2:1, both odd behaviors happen (this is the case in the image below).

A: Thanks to an answer to my related question here, I now know what was going wrong. The problem was in the way I was using the arrays of indexes (1,2,3,4,5...) to access the DataTextures' texels in the shader.
In this function (and the one for the larger DataTextures)...
float texelSizeX = 1.0 / uPerMotifBufferWidth;
float texelSizeY = 1.0 / uPerMotifBufferHeight;
vec2 perMotifUV = vec2(
    mod(aCellIndex, uPerMotifBufferWidth)*texelSizeX,
    floor(aCellIndex / uPerMotifBufferHeight)*texelSizeY );
perMotifUV += vec2(0.5*texelSizeX, 0.5*texelSizeY);

...I assumed that in order to create the y value for my custom uv, perMotifUV, I would need to divide the aCellIndex by the height of the buffer, uPerMotifBufferHeight (it's "vertical" dimension). However, as explained in the SO Q&A here the indices should, of course, be divided by the buffer's width, which would then tell you how many rows down you are!
Thus, the function should be revised to...
float texelSizeX = 1.0 / uPerMotifBufferWidth;
float texelSizeY = 1.0 / uPerMotifBufferHeight;
vec2 perMotifUV = vec2(
    mod(aCellIndex, uPerMotifBufferWidth)*texelSizeX,
    floor(aCellIndex / uPerMotifBufferWidth)*texelSizeY ); **Note the change to uPerMotifBufferWidth here
perMotifUV += vec2(0.5*texelSizeX, 0.5*texelSizeY);

The reason my program worked on square DataTextures (1:1) is that in such cases the height and width were equal, so my function was effectively dividing by width in the incorrect line because height=width!


text:
Q: Should all these "in-place-editing" tags be merged as synonyms? When requesting the two tags "inplace" / "in-place" be merged I discovered this bunch of tags all with similar names that should be unified:

*

*edit-in-place × 55

*inplace-editing × 26

*in-place-editor × 10

*in-place-edit × 6


text:
Q: Timestamp is too far from current time, How to handle this type of error message and stuck in the loading page I am getting the error message as below:
Error Domain=com.google.HTTPStatus Code=400 "The operation couldn't be completed. (com.google.HTTPStatus error 400.)" UserInfo=0x5d229c0 {data=<54696d65 7374616d 70206973 20746f6f 20666172 2066726f 6d206375 7272656e 74207469 6d653a20 31323938 39383936 32330a0a>}
2011-03-01 20:01:49.770 Warrantify[802:207] Timestamp is too far from current time: 1298989623
I am unable to go further and application becomes hang.
How can I solve this issue, Please help me out of this.
Thank you,
Madan Mohan.

A: Check the clock on your hardware; it may be so far off that server security certificate checks are failing.


text:
Q: Nokogiri check if value exists I'm scraping some web stuff and I get the following error,
scrape.rb:27:in block in <main>': undefined methodtext' for nil:NilClass (NoMethodError)
when running my ruby task, due to the css not containing any content inside.
Is there a way to check if CSS is not undefined so it wont stop crawling? My code wont work :(
products.each do |product|

     web = Nokogiri::HTML(open(product))

      counter = products.index(product)

      if web.at_css('.entry-title').text != undefined
      puts "CSS content is not undefined"
      else
      puts "Error"
      end

A: You can just IF the object result before calling text
result = web.at_css('.entry-title')
if result
  puts "CSS content is not undefined"
  puts result.text
else
  puts "Error"
end

A: I agree at_css & IF is the best solution for testing a class existence. Here's an example I whipped up..
user_agents = ["Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (compatible; Konqueror/3; Linux)",
            "Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.4) Gecko/20030624",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (Macintosh; U; PPC Mac OS X Mach-O; en-US; rv:1.4a) Gecko/20030401",
            "Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_2; de-at) AppleWebKit/531.21.8 (KHTML, like Gecko) Version/4.0.4 Safari/531.21.10",
            "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_2) AppleWebKit/601.3.9 (KHTML, like Gecko) Version/9.0.2 Safari/601.3.9",
            "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/43.0.2357.125 Safari/537.36",
            "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)",
            "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/5.0 (compatible; MSIE 8.0; Windows NT 5.1; Trident/4.0; .NET CLR 1.1.4322; .NET CLR 2.0.50727)",
            "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)",
            "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)",
            "Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko",
            "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2486.0 Safari/537.36 Edge/13.10586",
            "Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.4b) Gecko/20030516 Mozilla Firebird/0.6",
            "Mozilla/5.0 (Windows NT 6.3; WOW64; rv:43.0) Gecko/20100101 Firefox/43.0",
            "Mozilla/5.0 (iPhone; CPU iPhone OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B5110e Safari/601.1",
            "Mozilla/5.0 (iPad; CPU OS 9_1 like Mac OS X) AppleWebKit/601.1.46 (KHTML, like Gecko) Version/9.0 Mobile/13B143 Safari/601.1",
            "Mozilla/5.0 (Linux; Android 5.1.1; Nexus 7 Build/LMY47V) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.76 Safari/537.36"]
user_agent = user_agents.sample

good_2_go = "https://gomovies.to/genre/action/1"
my_bad = "https://gomovies.to/genre/action/100"

crawls = []
crawls.push(good_2_go, my_bad)

crawls.each do |crawl|
  doc = Nokogiri::HTML(open(crawl, 'User-Agent' => user_agent).read, nil, 'utf-8')

  entries = doc.at_css('.ml-item')

  if entries
      puts crawl
      puts "Found entries class, proceeding with scrape.."
  else
      puts crawl
      puts "Could not find base class for entries"
  end
end

This will STDOUT ...
=> https://gomovies.to/genre/action/1
   Found entries class, proceeding with scrape..
   https://gomovies.to/genre/action/100
   Could not find base class for entries


text:
Q: How can I play transparent videos in GVRKit? I am creating a Virtual Reality app using Google's GVRKit for Google Cardboard.
I need to implement transparency in GVRVideoRenderer.
The use case for this is for playing a video over a 360° photo background to give a VR effect.
I have used Chroma Key blending with an input and mask image to implement the transparency in AVPlayerItem:
let filter = AlphaFrameFilter()
filter.inputImage = request.sourceImage.cropped(to: sourceRect)
filter.maskImage = request.sourceImage.cropped(to: alphaRect).transformed(by: transform)

Unfortunately, when passing this into GVRVideoRenderer, the view still has a black background.
How can I fix this?


text:
Q: Running ant script from within scala program I tried

val cmd = sys.process.Process(Seq("C:\apache-ant-1.9.3\bin\ant", "everythingNoJunit"),   new java.io.File(scriptDir))
cmd.lines

and got this error:

CreateProcess error=193, %1 is not a valid Win32 application

How do I run the ant script from within scala app?

A: The basic answer is that your should be using "ant.bat" instead of "ant" on a windows machine as in this answer
In addition to that, I would suggest using a non-windows styled path so you don't have to escape the backslashes:
val cmd = sys.process.Process(Seq("/apache-ant-1.9.3/bin/ant.bat", "everythingNoJunit"), new java.io.File(scriptDir))

Using this approach, I'm able to run an an ant target successfully when my scala application is also in "c:".


text:
Q: Do i need to add the constraint line I used in a strong entity when I'm making a create statement for a weak entity? So if i have a strong entity like:
Book (bid, price)
PK (bid)
Constraint chk_book_price check (price >= 0)

And weak entity like:
Store (bid, storename)
FK (bid)

Do i need to add the constraint line I used in the strong entity when I'm making a create statement for the weak entity?
So like
Create Table Store
(
    bid number (4),
    storename varchar2 (20),
    Foreign Key (bid) references Book (bid),
    Constraint chk_book_price check (price >= 0)
);

A: No, you don't have to.
you just need to have constraints for the STORE table in the definition.
Create Table Store
(
    bid number (4),
    storename varchar2 (20),
    Foreign Key (bid) references Book (bid),
);

So for table BOOK you only need to create constraints for itself like
CREATE TABLE BOOK (
BID NUMBER(5),
PRICE NUMBER(7, 2)
CONSTRAINT CHK_BOOK_PRICE CHECK (PRICE >= 0)
)

FOREIGN KEY CONSTRIANT refers to a unique or primary key of another table and before you can create FOREIGN KEY you must create a parent table first with PRIMARY OR UNIQUE KEY.
Either you create BOOK table first or use ALTER TABLE to create constraints when both tables are created.


text:
Q: Grouped Data Endless Scroll ListView Kendo Not working I can't get kendo listview to properly auto scroll when I have grouping.  Change autoscroll to true to see issue below.
I am also having a similar problem with angular.
JSFiddle below
https://jsfiddle.net/jcbowyer/ao0xzoaz/1/
<!DOCTYPE html>

        <meta charset="utf-8"/>
        <title>Kendo UI Snippet</title>
        <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.226/styles/kendo.common.min.css"/>
        <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.226/styles/kendo.rtl.min.css"/>
        <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.226/styles/kendo.silver.min.css"/>
        <link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.1.226/styles/kendo.mobile.all.min.css"/>

A: Per Telerik support this grouped data is not a supported configuration when virtual scrolling is enabled.


text:
Q: Не могу присвоить значение переменной по индексу, постоянно выдает ошибку. IndexError: list index out of range import csv

k = ['ВС','07.11.2021 14:00','Россия,Премьер-лига',',','Урал - Зенит Санкт-Петербург','12.75','5.95','1.285','2.30','1.69','2.15']

d = ['Урал - Зенит Санкт-Петербург''0:0','0:0']

print(d)
day = ''
date = ''
strana = ''
championat = ''
items = ''
items_1 = ''
comands = ''
p1 = ''
x = ''
p2 = ''
tm = ''
tb = ''
oz = ''
comands2 = ''
for i in k:
    day = i[0]
    date = i[1]
    strana = i[2]
    championat = i[3]
    comands = i[4]
    p1 = i[5]
    x = i[6]
    p2 = i[9]
    tm = i[10]
    tb = i[11]
    oz = i[11]
    intejea = []
    for i in d:
        comands2 = i[0]
        items = i[1]
        items_1 = i[2]
        if comands == comands2:
            intejea = [{
            'day': day,
            'date': date,
            'strana': strana,
            'championat': championat,
            'items': items,
            'items_1': items_1,
            'comands': comands,
            'p1': p1,
            'x': x,
            'p2': p2,
            'tm': tm,
            'tb': tb,
            'oz': oz,
            }]
            print(intejea)
            with open('готовый результат', 'a', newline='', encoding='utf-8')as file:
                writer = csv.writer(file, delimiter=';')
                for i in intejea:
                    writer.writerow(введите сюда код
                        [i['day'], i['date'], i['strana'],
                         i['championat'], i['items'], i['items_1'],
                         i['comands'], i['p1'], i['x'],
                         i['p2'], i['tm'], i['tb'], i['oz']])

A: Раз вы перебираете k в цикле, используйте не просто список, а список списков:
k = [['ВС','07.11.2021 14:00','Россия,Премьер-лига',',','Урал - Зенит Санкт-Петербург','12.75','5.95','1.285','2.30','1.69','2.15']]

Далее, в k всего 11 элементов, обращение к индексу [11] вызовет ошибку, поскольку нумерация идёт с нуля и допустимы индексы от 0 до 10, разберитесь с нумерацией полей:
    tb = i[11]
    oz = i[11]

Вообще лучше не присваивать переменные по индексу, а использовать распаковку переменных, тогда переменные сами заполнятся согласно позиции:
    day, date, strana, championat, comands, p1, x, _, _, p2, tm, tb, oz = i

Если какие-то поля нужно пропустить, используйте для этого переменную со специальным названием _.


text:
Q: Create a trigger Create a trigger called NewEntry, that will not allow a result to be inserted into the student exam table if it is less than zero. In your query display a suitable message if the result is less than zero and supply code to test the trigger.
This is what I have done, but I keep getting

warning : trrigger created with compilation errors.

This is my code, please help!
CREATE OR REPLACE TRIGGER NewEntry
AFTER INSERT OR UPDATE ON Assignment2.Student_Exam
FOR EACH ROW
DECLARE
Results NUMBER;
BEGIN
IF(:NEW.Results < '0')
THEN
RAISE_APPLICATION_ERROR
(-20700,'Student's result cannot be less-than ZERO..Enter valid Results':);
ENDIF;
END;
 /

A: END IF, not ENDIF. Also as Jeremy C mentions above you need to create the trigger as BEFORE INSERT OR UPDATE

A: There are two errors: Firstly it is 'END IF' not ENDIF, secondly you have apostrophe's in your message.
The correct code is:
CREATE OR REPLACE TRIGGER NewEntry
AFTER INSERT OR UPDATE ON Assignment2.Student_Exam
FOR EACH ROW
DECLARE
Results NUMBER;
BEGIN
IF(:NEW.Results < '0')
THEN
RAISE_APPLICATION_ERROR
(-20700, 'students result cannot be less-than ZERO..Enter valid Results:');
END IF;
END;
 /

As others have said you could have de-bugged this yourself by typing show errors;   This would have given you the answer e.g.
SQL> show errors;
Errors for TRIGGER NEWENTRY:

LINE/COL ERROR
-------------------------------------------------------------------------
7/18     PLS-00103: Encountered the symbol "S" when expecting one of the
following:
) , * & = - + < / > at in is mod remainder not rem =>
<an exponent (**)> <> or != or ~= >= <= <> and or like like2
like4 likec between || multiset member submultiset

edit: In reply to Ersin - If it was New.Results then you would get a bind error e.g.
SQL> show errors;
Errors for TRIGGER NEWENTRY:

LINE/COL ERROR
-------- -----------------------------------------------------------------
4/4      PLS-00049: bad bind variable 'NEW.RESULTS'
SQL>

This will be a result of 'RESULTS' not being a column in Student_Exam, which I presume does exist given the rest of the statement.

A: you listen the other answers but one more thing ,
you must focus on :NEW.Results  this is the thing.


text:
Q: How to run every 10 seconds in GCP Cloud Scheduler What would be a correct syntax for the Cloud Scheduler Frequency field to run it every 10 seconds?
I've been using https://crontab.guru/ but it seems to be missing the seconds and starts with minutes, hours and etc.

A: As John said, it's not possible. As alternative, you can call a function with a Cloud Scheduler that create an HTTP task in a Task Queue.
In this function, set the scheduledTime every 10s for XX tasks and the final HTTP request that you want to perform. Be careful to the timeout and the retry policy and apply them according to your use case

A: Google Cloud Scheduler does not support seconds. The smallest scheduling interval is one minute.


text:
Q: How to find the minimum distance in a Poisson Point Process? Let us consider a Poisson Point Process (PPP) $\Phi$ of density $\lambda$.
The region is a unit circle (radius=1).
If there is a point $o\notin\Phi$ (not belonging to the poison process) in the centre, how to find the minimum distance from the point $o$ to the closest point $z$ belonging to the PPP, i.e., $z\in\Phi$ for different $\lambda$?
Note: The distribution of the distance between the point $o$ and $z$, i.e.,$r=\|o-z\|$ is given by $$2\pi\lambda r\exp(-\pi\lambda r^2)$$
For example, I want $r_{\min}$ in terms of a numerical value or an expression. Lets say $r_{\min}=0.12$. Expectation will also be fine.

A: First I'll do this on the whole plane.  Let $R$ be the distance from the origin to the nearest point in the process.  Then
\begin{align}
& \Pr(R \ge r) \\[6pt]
= {} & \Pr(\text{the number of points in the process at distance $<r$ from the origin} = 0) \\[6pt]
= {} & \frac{(\lambda\cdot\text{area})^0 e^{-\lambda\cdot\text{area}}}{0!} = e^{-\lambda\pi r^2}. \tag 1
\end{align}
From this you can find the c.d.f. and the p.d.f.
Now let's assume the support is a disk. Here I'm tempted to say $R=\infty$ if the number of points or the process that are within the disk are $0$.  Alternatively, one could plausibly say it is the radius of the disk.  In that case $(1)$ would hold for $r\le\text{the radius}$ and you've have to work piecewise; you'd have a mixture of discrete and continuous distributions.


text:
Q: What is considered the best way to style components in React with Emotion in terms of readability and performance? I guess there are 3 main ways to style components in Emotion
<div
    className={
        css`
        height: 150px;
        display: flex;
        padding: ${theme.defaultUnit}px ${theme.defaultUnit * 4}px;
        border-top: 1px solid red;
        border-right: 1px solid yellow;
        background: #fff;
        align-items: center;
        `,
    }
/>

const styles =  css`
        height: 150px;
        display: flex;
        padding: ${theme.defaultUnit}px ${theme.defaultUnit * 4}px;
        border-top: 1px solid red;
        border-right: 1px solid yellow;
        background: #fff;
        align-items: center;
        `,
<div className={styles} />

const StyledContainer = styled.div`
     height: 150px;
     display: flex;
     padding: ${theme.defaultUnit}px ${theme.defaultUnit * 4}px;
     border-top: 1px solid red;
     border-right: 1px solid yellow;
     background: #fff;
     align-items: center;
`
<StyledContainer />

Out of those 3 is there one considered best? I don't like option 1 personally as it bloats components with css and makes them harder to read. But I was wondering if there was performance implications with option 2? and therefore does that make option 3 the best? wondering if anyone has insight on this

A: I have worked on projects where one or all the above are used. It really comes down to culture and need.
No one has a final answer and the community is still debating the subject.
Emotion best practices is evolving
Object styles are easier to use and in my opinion closer to the concept of good functional and object oriented programming used by react.
A good article on the subject talks more in detail about some of the pros and cons, but again it's mostly preference.
The best for a team is code that looks clean and is human readable that doesn't clutter the component.


text:
Q: SavedGameRequestStatus.InternalError google play services I have a problem with Google Play Save Games.
Authorization with Google Play Services is working fine. And I'm using EnableSavedGames(), DataSource.ReadCacheOrNetwork, ConflictResolutionStrategy.UseLongestPlaytime.
But when I'm trying to access saved sessions, I get InternalError message.
Screenshot with API Goodle Drive calls included:
GoogleDriveApiMethods
Any ideas how to fix this?

A: I'm a little late, but for me, the problem was in this bit of obscure documentation: https://github.com/playgameservices/play-games-plugin-for-unity#incremental-authorization

This will allow silent sign-in to succeed, because silent sign-in will always fail if you ask for more than GAMES_LITE and, if you use Saved Games, DRIVE.APP_DATA.

Specifically I needed to request permissions for Drive:
PlayGamesPlatform.Instance.RequestPermission("https://www.googleapis.com/auth/drive.appdata", permissionResult => {

        if (permissionResult == SignInStatus.Success)
        {
            ((PlayGamesPlatform)Social.Active).SavedGame.OpenWithAutomaticConflictResolution(GOOGLE_PLAY_FILENAME, DataSource.ReadCacheOrNetwork,
                ConflictResolutionStrategy.UseLongestPlaytime, OnSavedGameOpened);
        }
    });


text:
Q: difference between weak and strong actions on a category If a group acts on a category (in some sense), sometimes the phrases "weak action" and "strong action" come up. I don't know what these mean though. Could someone provide an appropriate definition? (Or is it really context dependent?)
Note if someone finds a link to the answer in the top ten results in a search engine... please tell me which phrase you typed... I couldn't seem to get anything.

A: The notion of weak vs strong categorical actions in the context you are interested in (i.e. Ben Webster's paper on knot homologies) is defined in this paper. A weak categorification of an irreducible $\mathfrak{sl}_2$ representation consists of the data of categories $V_\lambda$, $\lambda\in\mathbb{Z}$, together with functors
$$E:V_{\lambda}\to V_{\lambda+2},\;\;\;F:V_{\lambda}\to V_{\lambda-2}$$
which satisfy isomorphisms
$$EF\cong FE\oplus Id^{\oplus\lambda}$$
if $\lambda\geq 0$ and
$$FE\cong EF\oplus Id^{\oplus(-\lambda)}$$
if $\lambda<0$.
A weak categorification becomes a (strong) categorification if you additionally have the data of natural transformations
$$X:E\to E\;\;\;\mbox{and}\;\;\; T:E^2\to E^2$$
which satisfy Hecke algebra type relations $TX-XT=Id$ (though one can certainly generalize this using formal group laws). These allow you to obtain a categorification of the divided powers $E^{(n)}$ and $F^{(n)}$. All this can be generalized to categorifications of arbitrary Lie algebras (see here and here and here).
I recommend reading the following paper by Lauda before trying to tackle Ben's paper.

A: My impression, and I'm not sure about this at all, is that there are two things people mean by "weak action," one of which is bad. One is weak-as-opposed-to-strict, meaning that for every element of the group $g \in G$ you have a functor $F(g): C \to C$, and instead of requiring that $F(gh)$ is literally equal to $F(g) F(h)$ you require that there is a natural isomorphism between them, which is further subject to an associativity condition (see e.g. this blog post). This is the correct notion of a group action on a category.
The bad definition involves not requiring the associativity condition, as Tobias says in the comments. I think the only reason this definition appears in the literature is that it's the best people can do in some situations.
One reason the bad definition is bad is that typically in category theory the "weak" thing is the thing you actually want, but that's not the case here.


text:
Q: SqlServer Select Where In I'm thrown for a loop on this one, and wondering if I don't fully understand the select where in usage or if I've just made a boo boo in this code:
DECLARE @driver TABLE (ID INT)
INSERT INTO @driver select eventid from event where event_code_name IS NULL
select eventid from event where eventid in (select eventid from @driver)

There are 3137 records total in the event table.  There are 458 records who's event_code_name field is null.  In the select above I'm expecting 458, but I'm getting all event records back instead.
What did I miss?

A: I think (select eventid from @driver) should be (select id from @driver)

A: Since you are using 2 tables, one virtual and one physical, the solution is to use the INNER JOIN clause:

DECLARE @driver TABLE (ID INT)
INSERT INTO @driver SELECT eventid FROM event WHERE event_code_name IS NULL
SELECT eventid FROM event INNER JOIN @driver ON id = event.eventid

This way you only get the IDs that are present in both the event table and the @driver table.
INNER JOIN is also much more efficent than using an IN (SELECT ...)
Without the use of the @driver table you can just obtain the same result using the SELECT query you used in the INSERT statement:

SELECT eventid FROM event WHERE event_code_name IS NULL

A: Are you missing a DISTINCT?
select DISTINCT  eventid from event where eventid in (select eventid from @driver)

A: It might be worth performing an ISNULL on all columns that may contain a null value and filtering out the default value of the ISNULL.

A: Using IN operator can be less efficient sometimes, Specially if your column in sub query is Nullable IN operator can show some really unexpected results.
I would suggest using EXSITS, something like this...
select eventid
from [event]
where EXISTS (select 1
              from @driver
              WHERE id = [event].eventid)

For your this specific query you dont really need a table variable. you can simple do a select againt your table, something like this...
SELECT eventid
FROM [event]
WHERE event_code_name IS NULL


text:
Q: bcrypt next() is not defined var mongoose =  require('mongoose');
var bcrypt = require('bcrypt-nodejs');
var Schema =  mongoose.Schema;

var UserSchema = new Schema({
    username:{type: String,lowercase: true, required: true,unique:true},
    password:{type:String, required:true},
    email:{type:String,required:true,lowercase:true,unique:true},
});

// mongoose middleware
UserSchema.pre('save',(req,res,next)=>{
    var user = this;
    bcrypt.hash(user.password,null,null,(err,hash)=>{
        if(err) return next(err);
        user.password = hash;
        next();
    });
 });
 module.exports = mongoose.model('User',UserSchema);

below the error i can't find out the error
POST /users 200 58.468 ms - 14
    /var/www/html/meanstacktutorial/app/models/user.js:17
            next();
            ^
ReferenceError: next is not defined
    at bcrypt.hash (/var/www/html/meanstacktutorial/app/models/user.js:17:9)
    at /var/www/html/meanstacktutorial/node_modules/bcrypt-nodejs/bCrypt.js:631:3
    at _combinedTickCallback (internal/process/next_tick.js:131:7)
    at process._tickCallback (internal/process/next_tick.js:180:9)
[nodemon] app crashed - waiting for file changes before starting...

when i make password to encrypt then it gets some error like "next() is not defined " why i don't know exactly ..i have been trying to slove the problem but i couldn't please help me out thank you

A: The function passed to your pre-save hook should only take next as an argument.
You have also passed in req and res.
Try this instead:
UserSchema.pre('save', (next) => {
  var user = this;
  bcrypt.hash(user.password, null, null, (err, hash) => {
    if(err) return next(err);
    user.password = hash;
    next();
  });
});

I hope this helps.


text:
Q: Run iOS 6 device as a BLE peripheral As we know, iOS 6 support running devices (iPhone 4s and above, and new iPad) as a BLE peripheral. There is a demo in WWDC 2012 Session 705 called "advanced core bluetooth". I asked for the source code from Apple. They sent me a modified version of source code (BTLE_Transfer_Draft). Then I:

*

*Run the app in iPhone 5 (iOS 6) in "Peripheral Mode" and start "Advertising"

*Run the app in new iPad (iOS 5.1.1) in "Central Mode"

The problem is that the peripheral is never been discovered at all. So I use other testing applications including some downloaded from App Store. All failed to discover peripherals. I think the problem should be in BTLE_Transfer_Draft. Because I'm not sure whether I'm allowed to present the whole source code. So I just show the "peripheral mode" part here:
- (void)viewDidLoad {
    [super viewDidLoad];

    // Start up the CBPeripheralManager
    _peripheralManager = [[CBPeripheralManager alloc] initWithDelegate:self queue:nil];
}

- (void)peripheralManagerDidUpdateState:(CBPeripheralManager *)peripheral {
    // Opt out from any other state
    if (peripheral.state != CBPeripheralManagerStatePoweredOn) {
        return;
    }

    // We're in CBPeripheralManagerStatePoweredOn state...
    NSLog(@"self.peripheralManager powered on.");

    // ... so build our service.

    // Start with the CBMutableCharacteristic
    self.transferCharacteristic = [[CBMutableCharacteristic alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_CHARACTERISTIC_UUID]
                                                                  properties:CBCharacteristicPropertyNotify
                                                                       value:nil
                                                                 permissions:CBAttributePermissionsReadable];

    // Then the service
    CBMutableService *transferService = [[CBMutableService alloc] initWithType:[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]
                                                                    primary:YES];

    // Add the characteristic to the service
    transferService.characteristics = @[self.transferCharacteristic];

    // And add it to the peripheral manager
    [self.peripheralManager addService:transferService];
}

/** Start advertising
 */
- (IBAction)switchChanged:(id)sender
{
    if (self.advertisingSwitch.on) {
        // All we advertise is our service's UUID
        [self.peripheralManager startAdvertising:@{ CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:TRANSFER_SERVICE_UUID]] }];
    }
    else {
        [self.peripheralManager stopAdvertising];
    }
}

The BLE is in powered on status and the startAdvertising is called. But the BLE central can never discover it.
Post updated:
According to mttrb's suggestion I added "CBAdvertisementDataLocalNameKey" when I startAdvertising. But my service is still can't be discovered by most of the apps including some apps from app store. The only one app can discover my service is an app from app store called "BLE scanner".
My question is: does this mean my application is working as a peripheral? But why my own code can't discover the service? How am I supposed to debug it ?
My code in Central Mode is like this:
- (void)viewDidLoad
{
    [super viewDidLoad];

    // Start up the CBCentralManager
    _centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
}

- (void)centralManagerDidUpdateState:(CBCentralManager *)central
{
    if (central.state != CBCentralManagerStatePoweredOn) {
        return;
    }
    [self.centralManager scanForPeripheralsWithServices:nil options:nil];
}

- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
......
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverServices:(NSError *)error
{
    if (error) {
        NSLog(@"Error discovering services: %@", [error localizedDescription]);
        return;
    }
}

- (void)peripheral:(CBPeripheral *)peripheral didDiscoverCharacteristicsForService:(CBService *)service error:(NSError *)error
{
    // Deal with errors (if any)
    if (error) {
        NSLog(@"Error discovering characteristics: %@", [error localizedDescription]);
        return;
    }
}

- (void)centralManager:(CBCentralManager *)central didDisconnectPeripheral:(CBPeripheral *)peripheral error:(NSError *)error
{
    NSLog(@"Peripheral Disconnected");
    self.discoveredPeripheral = nil;
}

The didDiscoverPeripheral and didDiscoverServices are never called. What could be wrong? Any idea? Thanks

A: I would try moving the startAdvertising: method call up and into the end of your peripheralManagerDidUpdateState: delegate method and see if that helps.
I would also add a CBAdvertisementDataLocalNameKey key-value pair to your startAdvertising: method call.  I found things were unreliable when the advertisement didn't have a name.
Finally, I would invest in the BLExplr app available in the App Store to help with scanning for your peripheral.  It removes the assumption that your central is working correctly.

A: This Git hub project also throws some light on the CBPeripheralManager API. Called PeripheralModeTest.
This line is particularly useful for setting the advertising data
 NSDictionary *advertisingData = @{CBAdvertisementDataLocalNameKey : @"Device Name", CBAdvertisementDataServiceUUIDsKey : @[[CBUUID UUIDWithString:CBUUIDGenericAccessProfileString]]};

Though I can't see any official documentation in the Apple iOS Developer Library yet. More specifically anything about setting the repeat period for the advertising.

A: The BTLE Transfer example has this piece of (odd) code, which may cause some troubles:
- (void)centralManager:(CBCentralManager *)central didDiscoverPeripheral:(CBPeripheral *)peripheral advertisementData:(NSDictionary *)advertisementData RSSI:(NSNumber *)RSSI
{
    // Reject any where the value is above reasonable range
    if (RSSI.integerValue > -15) {
        return;
    }

    // Reject if the signal strength is too low to be close enough (Close is around -22dB)
    if (RSSI.integerValue < -35) {
        return;
    }

Just remove those two if-statements as it makes no sense!
I have made a simplified version available here that can be used to test high volumes of messages being sent from peripheral to central.
Please note that the CBPeripheralManager class was first introduced in iOS 6.0.

A: There is also a high quality free app called LightBlue that you can use to test your code with. It should be able to pick up all devices advertising in peripheral mode and it can even turn itself into an advertising peripheral if you want to make sure your device is working properly.

A: I do not know witch version of BTLE Central Peripheral Transfer you did actually test but current version has iOS 6 as requirement.
So I would suggest to test linkage against iOS 5.1 to see what compatibility issues it shows.


text:
Q: Proposition for software registration When a user buy a software and enter a serial number, it is registered to the user? right?
If yes, what is the proposition for the Register

This program is registered with/to/for XXX company.

A: Yes, we generally say that the product is registered to the user who bought it.  If you're talking about the company that sold the software, it would be more normal to say that the program is registered with the company.  For example, "Customers must have all Red Hat software registered with Red Hat to qualify for the warranty."
By the way, software is a mass noun or uncountable noun, so you can't say "a software".  Use "software" to speak of software in general, or "a program" if you need to talk about a specific example.

A: There can also be the use of "by" to denote who handles the registration process.

This program is registered by XXX company.


text:
Q: Paypal sdk for windows 10 app I am developing a Windows 10 app which needs to accept payments through Paypal. I googled for that Windows SDK but didn't find Paypal SDK or documentation related to that.
So if anyone implement that previously please help me out for this.

A:
I googled for that Windows SDK but didn't find Paypal SDK or documentation related to that.

There is no official SDK for integrating Paypal in an UWP app for now.
My suggestion is that you can try to use Rest API to implement Paypal in your app.