text:
Q: Continuous variables and marginal function Lets say we have random variables $X,Y$.
Density function
$f_{X,Y}(x,y) = 1/2ye^{(-x-y^{2})/2}$  for $x>0$ and $y>0$.
Now our task is to find if random variables are indenpendant and find $E(X+Y)$.
We know that if $f_{X,Y}(x,y) = f_{X}(x) * f_{Y}(y)$ random variables X and Y are indenpendant. To find $f_{X}(x)$ and $f_{Y}(y)$ we need to integrate our density function.
However, we also know, that if we can transform $f_{X,Y}(x,y) = g(x) * h(y)$. Random variable X and Y are independant.
We see that
a ) $1/2ye^{(-x-y^{2})/2} = 1/2e^{-x/2} * ye^{-y^{2}/2}$ or
b ) $1/2ye^{(-x-y^{2})/2} = e^{-x/2} * 1/2ye^{-y^{2}/2}$
Which means random variables X and Y are indenpendant. However, in order to calculate $E(X+Y)$ we need to know $f_{X}(x)$ and $ f_{Y}(y)$ So we still have to integrate.
Is there a way how to decide $f_{X}(x)$ and $ f_{Y}(y)$ when we can transform function into $f_{X,Y}(x,y) = g(x) * h(y)$.? By definition they can differ by multiplicative constant.

A: Recall that a probability density function must integrate to $1$. Since
$$
\int_0^\infty \frac12 e^{-\frac12 x}\ \mathsf dx = \int_0^\infty ye^{-\frac12 y^2}\ \mathsf dy = 1,
$$
we see that $f_X(x) = \frac12 e^{-\frac12 x}\mathsf 1_{(0,\infty)}(x)$, $f_Y(y)=ye^{-\frac12 y^2}\mathsf 1_{(0,\infty)}(y)$ is the correct choice of density functions. We compute
$$
\mathbb E[X] = \int_0^\infty x\frac12 e^{-\frac12 x}\ \mathsf dx = 2
$$
and
$$
\mathbb E[Y] = \int_0^\infty y^2e^{-\frac12 y^2}\ \mathsf dy = \sqrt{\frac\pi 2},
$$
and hence
$$\mathbb E[X+Y] = \mathbb E[X] + \mathbb E[Y] = 2+\sqrt{\frac\pi2}.$$


text:
Q: Whats the meaning of Left of '-> NewGlobalRef' must point to struct/union? To implement a C callback to java code using JNI, I followed the advice from here and here and adapted my native method implementation to store a reference to the objects I need for the callbacks later:
JavaVM * g_vm;
jobject g_obj;
jmethodID g_mid;

//More code here

JNIEXPORT jboolean JNICALL
Java_a_B_initialize(JNIEnv * env, jobject obj)
{
    g_obj = env->NewGlobalRef(obj);
    jclass g_clazz = env->GetObjectClass(g_obj);
    if (g_clazz == NULL) {
        printf("Failed to find class");
    }

    g_mid = env->GetMethodID(g_clazz, "callback", "(I)V");
    if (g_mid == NULL) {
        printf("Unable to get method ref");
    }

However, this does not compile and I get the error messages:
Left of '-> NewGlobalRef' must point to struct/union
Left of '-> GetObjectClass' must point to struct/union
Left of '-> GtMethodID' must point to struct/union

I do not understand these error message. What's wrong with my code?

A: You are attempting to use the C++ interface. You've tagged the question [C] so I assume you are using C.
In C, do it this way:
(*env)->NewGlobalRef(env, obj)

A: You are missing the JNI include:
#include <jni.h>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where are secant, cosecant, and cotangent applied? The textbook we use says:

The cosecant function and the secant function are the reciprocal
  functions of the sine function and the cosine function, respectively,
  and thus are also periodic functions. Their graphs are not as useful
  and are seldom encountered because the cosecant is undefined at values
  of theta where the sine has a value of zero and the secant is
  undefined where the cosine has a value of zero.

I don't know of any applications for these functions outside pure mathematics. Where are they applied outside pure mathematics (if they are applied)?

A: Their graphs are often useful... though maybe not in rectangular coordinates.  Plot $r=\sec(\theta) $ or $ r=\csc(\theta)$ in polar coordinates - you get a straight line a distance $1$ from the origin.  Consequently, they are useful when you want to solve "straight line" problems in polar coordinates.
In general, polar equations are nice in physics problems because macroscopic force laws often are dependent only on the distance between two particles.  You might end up using secant if you are calculating electrical interactions between a point charge (the origin) and an infinite straight charged wire at a distance $d$, parametrized by $r=d\sec(\theta)$.  The contribution of any point on the wire to the electric field will depend on its distance $d\sec(\theta)$ from the origin.
Another example: if you are standing a distance $d$ from a long straight road watching a car go along, and you want to find the rate $d\theta/dt$ you have to turn your head to watch the car at a certain point, I believe you will find yourself differentiating $\sec$ or $\csc$ if you solve it as a related rates problem.

A: Using sec and csc is an anglo saxon tradition: In France for instance, we use ONLY cos and sin (cot occasionaly appears). I got an engineering degree in France without seeing sec and csc ever but they are averywhere in American and Australian textbooks.
I wonder what they do in other countries?
Laure


text:
Q: How do i handle HOC from it's wrapped component? I have a HOC to handling loading using axios,
here's a code of withAxiosHOC:
export default (url, WrapComponent) => {
  return class extends React.Component {
    constructor(props) {
      super(props);
      this.state = {
        data: null,
        isLoading:false,
        isFailed:false,
        isError:false,
        message:null,
      };
    }

    componentDidMount(){
      this.callAPI()
    }

    async callAPI(){
      //show loading
      // handle API and pass to wrapped component
      // hide loading
    }

    render() {
      if (this.state.isLoading) {
        return (
          //show loading UI
        )
      } else if(this.state.isFailed){
        return(
          //show Failed UI
        )
      } else if(this.state.isError){
        return(
          //show Error UI
        )
      }

      return (
        <WrapComponent data={this.state.data} {...this.props} />
      )
    }
  }
}

and usually i'm used HOC like this, let say Home.js:
export default withAxiosHttp(
  'https://reactnative.dev/movies.json',
  class Home extends React.Component{
    constructor(props) {
      super(props);
      this.state = {
        data:props.data
      }
    }

    render() {
      return(
        <View style={{flex:1, backgroundColor:Color.black}}>
          <MyText>{JSON.stringify(this.state.data, null, 2)}</MyText>
        </View>
      )
    }
  }
)

but sometimes i need to call the URL depend on state of my wrapped component,
something like this Suggestion.js:
export default withAxiosHttp(
  'https://exampleAPIneedDynamicValue.com/suggestion?lat='+this.state.position.lat+'&long='+this.state.position.long,
  class Suggestion extends React.Component{
    constructor(props) {
      super(props);
      this.state = {
        data:props.data,
        position:{lat:null, long:null}
      }
    }

    componentDidMount(){
      let tempPosition = this.state.position
      tempPosition.lat = MyLatitude
      tempPosition.long = MyLongitude
      this.setState({position:tempPosition})
    }

    render() {
      return(
        <View style={{flex:1, backgroundColor:Color.black}}>
          <MyText>{JSON.stringify(this.state.data, null, 2)}</MyText>
        </View>
      )
    }
  }
)

as you see in Suggestion.js, i need to call a URL depending on lat and long of position state,
and lat long state only available in wrappedComponent of HOC,
My Question:

*

*How do i handle HOC to run when lat long state is available in wrappedComponent?

*does my HOC can be used to POST method also?

Please give me a suggestion/answer in React Native scope

A: You can modify the url parameter is a function instead of a string.
In withAxiosHOC
async callAPI(){
   axios.get(url(this.state)).then(data => {
       //logic here
   })
}

Your Suggestion.js will be
export default withAxiosHttp(
  (state) => {
      return 'https://exampleAPIneedDynamicValue.com/suggestion?lat='+state.position.lat+'&long='+state.position.long
  },
  class Suggestion extends React.Component{
    constructor(props) {
      super(props);
      this.state = {
        data:props.data,
        position:{lat:null, long:null}
      }
    }

    componentDidMount(){
      let tempPosition = this.state.position
      tempPosition.lat = MyLatitude
      tempPosition.long = MyLongitude
      this.setState({position:tempPosition})
    }

    render() {
      return(
        <View style={{flex:1, backgroundColor:Color.black}}>
          <MyText>{JSON.stringify(this.state.data, null, 2)}</MyText>
        </View>
      )
    }
  }
)


text:
Q: When should one event listener be used and when should multiple ones be used? I'm kind of confused as to what is the best option, performance-wise, when using event listeners (using jQuery for that), in these kind of cases.
Case 1:
Say you have a div that contains two inputs, and you want to "listen" to both, for a keyUp event. (this div is the only thing in the document, and its height and width is also that of the full document)

            <input type="text" id="a">
            <input type="text" id="b">

What would be better? : Attaching a 'delegated event listener'  to formContainer or attaching an event listener to each input?
Case 2:
Now, say you have an html structure like this (again, chatContainer is full height and width of document, and it, and its children, are only thing in it)

 //Has to listen to clicks for interactivity

 //Has to listen to clicks on every message appended
     <input type="text" id="inputSomething"> //Has to listen to keyUp events

In this case, is it better to attach an event listener to every div/input or to attach all needed event listeners to chatContainer (keyUp, click)?
I have read up on delegated events, but I don't know if I got it right. I would just like to do what's better, even if the performance difference is small.
Thank you very much.

A: I also didn't know which is faster(even if the difference is small).So I wrote the test code
code written by coffeescript
they are compiled code though you can see javascript code at jsfiddle.
case 1 http://jsfiddle.net/5mnroam3/
(your question case)

    <input type="text" id="a">
    <input type="text" id="b">

counterA = counterB = 0
$("#formContainer").click( (e) ->
  switch $(e.target).attr("id")
    when "a"
      counterA++
    when "b"
      counterB++
)
startTime = new Date()
for i in [0...10000]
  $("#a").trigger("click")
  $("#b").trigger("click")
endTime = new Date() - startTime
console.log("listen to container : #{endTime} ms","counterA is #{counterA}","counterB is #{counterB}")

counterA = counterB = 0
$("#formContainer").off("click")
$("#a").click((e) ->
  counterA++
)
$("#b").click((e) ->
  counterB++
)
startTime = new Date()
for i in [0...10000]
  $("#a").trigger("click")
  $("#b").trigger("click")
endTime = new Date() - startTime
console.log("listen to each elem : #{endTime} ms","counterA is #{counterA}","counterB is #{counterB}")

code above is doing 10000times click on both "#a" and "#b" and doing "counter++" everytime the event's occurred.
in my macbook(MBP2013mid chrome latest), the result was
listen to container : 2224 ms counterA is 10000 counterB is 10000

listen to each elem : 1952 ms counterA is 10000 counterB is 10000

listening each elem is bit faster.
case 2 http://jsfiddle.net/fbjyp5yL/
(Case target element has an child element which means when you listen to outer element,you have to check if the clicked element has the target elements as its parent or not because e.target or this in the event callback function is always most inner element you can click)

counterA = counterB = 0

$("#outer").click( (e) ->
  if $(e.target).closest("#element1").length
    counterA++
  else if $(e.target).closest("#element2").length
    counterB++
  else
    console.log("unexpected event")
)
startTime = new Date()
for i in [0...5000]
  $("#element1 .children1").trigger("click")
  $("#element1 .children2").trigger("click")
  $("#element2 .children1").trigger("click")
  $("#element2 .children2").trigger("click")
endTime = new Date() - startTime
console.log("listen to outer : #{endTime} ms",counterA,counterB)

$("#outer").off("click")
counterA = counterB = 0
$("#element1 .children1,#element1 .children2").click( (e) ->
  counterA++
)
$("#element2 .children1,#element2 .children2").click( (e) ->
  counterB++
)
startTime = new Date()
for i in [0...5000]
  $("#element1 .children1").trigger("click")
  $("#element1 .children2").trigger("click")
  $("#element2 .children1").trigger("click")
  $("#element2 .children2").trigger("click")
endTime = new Date() - startTime
console.log("listen to each elem : #{endTime} ms",counterA,counterB)

in this case, my result was
listen to outer : 2547 ms 10000 10000

listen to each elem : 2159 ms 10000 10000

So listening outer element is slower just like case 1 and the difference is bigger than case1 even though it's just 300-400ms through 20000times click.
conclusion
listening an event on each div/input is faster though the difference between using outer or each inner elems is small.and I'm sure if there are 10 or 20 inner elements,the difference is still small enough.so choose on your favor whichever you like.


text:
Q: Forzar la descarga de un fichero csv desde un servlet Estoy realizando una aplicación en java donde hay que descargar un fichero CSV.
Pero me está ocurriendo que el navegador no muestra el dialogo de descarga, sino que lo muestra incrustado en el propio navegador.
Este es el código de mi servlet:
        List<MisDatosBean> listaDatos = miDAL.obtenerDatos();
        if (listaDatos!= null) {
            PrintWriter writer;
            writer = response.getWriter();
            for (MisDatosBean d : listaDatos) {
                CSVUtils.writeLine(writer, generarLista(d));
            }
            response.setContentType("text/csv");
            response.setHeader("Content-Disposition", "attachment; filename=\"datos.csv\"");
            if (!request.isSecure()) {
                response.setHeader("Cache-Control", "no-cache");
                response.setHeader("Pragma", "no-cache");
                response.setHeader("Expires", "0");
            }
            writer.flush();
            writer.close();
        }

¿Qué más hay que indicar, para que me muestre el diálogo de descarga? Me ocurre en todos los navegadores que he probado, tanto IE11, firefox y chrome.

A: Al fin, mediante esta respuesta he podido solucionarlo.
El caso es que la descripción de la cabecera hay que hacerla antes de escribir el contenido del archivo en el flujo de salida.
Es decir, quedaría asi:
        List<MisDatosBean> listaDatos = miDAL.obtenerDatos();
    if (listaDatos!= null) {
        response.setContentType("text/csv");
        response.setHeader("Content-Disposition", "attachment; filename=\"datos.csv\"");
        if (!request.isSecure()) {
            response.setHeader("Cache-Control", "no-cache");
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Expires", "0");
        }
        PrintWriter writer;
        writer = response.getWriter();
        for (MisDatosBean d : listaDatos) {
            CSVUtils.writeLine(writer, generarLista(d));
        }
        writer.flush();
        writer.close();
    }

Al hacerlo así, el navegador ya da la opción de descargarlo en lugar de mostrarlo.


text:
Q: What controller is called when category is clicked from top menu in Magento 2 I want to know which controller is called when I click on category from the top menu bar.
For eg : When I click on Men it opens page with url http://127.0.0.1/Magento21/men.html. But I don't see any controller name in the url.
What controller is called in here?

A: There are some tricly,you can find a  url's route name, controller name,Action name from Html content body.
In magento, whenever page is render html content  and have html body<body> tag then this html's have  some few classes.
Those classes must indicate current page  url's route name, controller name,Action name
like frontendofModule-ControllerName-ActionName
For http://127.0.0.1/Magento21/men.html body may look that

class="page-products categorypath-men category-men
  catalog-category-view page-layout-2columns-left"

Here catalog-category-view this indicate that url

*

*frontend Route name catalog

*Controller is  Category

*Action name is View
That means your  current page action file is
Magento\Catalog\Controller\Category\View

A: When you click on any category, following controller is called.
Magento\Catalog\Controller\Category\View


text:
Q: Blur the background of Layout I made a Style/Theme which fully transparents my layout.Now I want to Blur the background.The most solutions I founded are for two Views.So the second layout blurs the first out.But thats NOT what I want.I just want to blur the background which is seeable (For example android luncher menu or homescreen etc.).
My Style:
<style name="Theme.Transparent" parent="@android:style/Theme.Dialog">
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowBackground">@android:color/transparent</item>
<item name="android:windowContentOverlay">@null</item>
<item name="android:windowNoTitle">true</item>
<item name="android:backgroundDimEnabled">false</item>

I used this on my application in manifest.
Some one got an idea ?
EDIT:
Now I wanted to take a screenshot so I can blur the image after that.this should propably screen the android luncher, homescreen whatever
.I used this code and it is throwsing a null object
public Bitmap screenshot_menu()
            {
                RelativeLayout r1;

                r1 = (RelativeLayout)findViewById(R.id.relativeLayout_MAIN);
                View v1 = r1.getRootView();
                v1.setDrawingCacheEnabled(true);
                Bitmap bm = v1.getDrawingCache();

                return bm;
            }

Is it because of my theme ? Or what could be wrong here ?

A: I don't know wheather it will match your needs but you can also use FrameLayout and set a semi transparent image at the top other components so that if you make it visible the whole layout seems blured below it:
    <FrameLayout
     android:layout_width="match_parent"
    android:layout_height="match_parent"
     >
    <ImageView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
     android:src="@drawable/some_semi_tansparentimage"
    >
    <\ImageView>
    <OtherElements1>
    <OtherElements2>
    <OtherElements3>

    <\FrameLayout>

just alter the visibility of ImageView to add ro remove blured ness


text:
Q: importing a module in Idle shell I'm trying to learn python and I'm having trouble importing a module.
I have a .pyc file that I'm trying to import into idle shell called dfa.pyc
I have the file in a folder called xyz.
I navigate to this folder using:
    os.chdir('/Users/xxx/Desktop/xyz')

So now, if I try to run the command:
    from dfa import *

i get the error:
    ImportError: No module named dfa

If i run the command:
    os.path.isfile('dfa.pyc')

it returns true.
Can someone explain how i can get the dfa.pyc file imported?
Thanks

A: you can add to the PYTHONPATH in code by doing
sys.path.append('<newpath'>)
from dfa import *

I don't believe changing your current directory has any impact on the import process and even if it did, I'm not sure that's how you would want to do it.

A: I don't think python modules are loaded I based on what you do with chdir. Modules are loaded from the folder you started the python shell and folders in PYTHONPATH.
If you want dynamically load modules maybe you can check imp.loadmodule (sample in the bottom of the page).

A: from  Brian Fitzgerald in Loading (and unloading) Python modules
"
... and this to "un-import"
del sys.modules["package"]
del package

"


text:
Q: php performance issue in while loop I use PHP to proceed latitude/longitude points in order to generate JS and displays points on an OSM Map. I would like to make a new track on the map when I have a pause au 10 minutes or more on the recording.
My dataset as currently about 30000 records on about 10 differents tracks (some tracks have about 300 points, others have thousands).
I encounter a performance issue with PHP. When the loop agregate some hundreds of points, datas are processed with good speed, but if the track has thousands of points, performances drop dramatically.
Here is the time needed to proceed each point for each track
+-----------------+------------------------------+
| Points On Track | Time To Proceed 10000 Points |
+-----------------+------------------------------+
|              21 | 0.75                         |
|           18865 | 14.52                        |
|             539 | 0.79                         |
|             395 | 0.71                         |
|             827 | 0.79                         |
|             400 | 0.74                         |
|             674 | 0.78                         |
|            2060 | 1.01                         |
|            2056 | 0.99                         |
|             477 | 0.73                         |
|             628 | 0.77                         |
|             472 | 0.73                         |
+-----------------+------------------------------+

We can see that when I have a lot of points on a track, performances drop dramaticaly. In this particular case, processing all points require about 30 secondes. If I limit number of points for each track to 500 points, performances are pretty good (about 2,5 seconds to proceed my data set).
I use my Synology DS415play as webserver.
Here is my code :
$dataTab = array();
if ($result = $mysqli->query($sql))
    {
        $count = 0;

        $row = $result->fetch_array();
        $data = $dataTab[$tabPrt] . "[" . $row['latitude'] . "," . $row['longitude'] . "]," ;
        $date = new DateTime($row['time']);

        while($row = $result->fetch_array())
        {
            $count++;

            $newDate = new DateTime($row['time']);
            if(($newDate->getTimestamp() - $date->getTimestamp()) > 600)
            {
                array_push($dataTab, $data);
                $data= "";
                $count = 0;
            }

            $data = $data . "[" . $row['latitude'] . "," . $row['longitude'] . "]," ;
            $date = $newDate;
        }
        array_push($dataTab, $data);
    }

If I limit each track to 500 points like that, performance is pretty good
$dataTab = array();
    if ($result = $mysqli->query($sql))
        {
            $count = 0;

            $row = $result->fetch_array();
            $data = $dataTab[$tabPrt] . "[" . $row['latitude'] . "," . $row['longitude'] . "]," ;
            $date = new DateTime($row['time']);

            while($row = $result->fetch_array())
            {
                $count++;

                $newDate = new DateTime($row['time']);
                if(($newDate->getTimestamp() - $date->getTimestamp()) > 600
                    || $count > 500)
                {
                    array_push($dataTab, $data);
                    $data= "";
                    $count = 0;
                }

                $data = $data . "[" . $row['latitude'] . "," . $row['longitude'] . "]," ;
                $date = $newDate;
            }
            array_push($dataTab, $data);
        }

Thanks
EDIT : I provide a sample of data here : http://109.190.92.126/tracker/gpsData.sql
Slow script : http://109.190.92.126/tracker/map.php
Normal execution speed by spliting each track (500 pts max) : http://109.190.92.126/tracker/map_split.php
Thanks

A: If you are getting 18000 records from a database in your worst case scenario, you could move the timestamp check to the query to drop it considerably, it looks like all you are doing is seeing if theres a ten minute gap then pushing to an array which could be done at the mysql level, this way you wouldn't be fetching 18000 rows from the database every time, just the ones you need.
If you post your mysql queries, we can take a look at putting that in there.
Edit: try changing the query to this:
SELECT time, latitude, longitude
FROM gpsData
WHERE  time >= '2015-09-01'
AND provider = 'gps'
ORDER BY time DESC

A: Here's the final product (its on Heroku so wait until dyno starts up)
http://sove.herokuapp.com/gps/
The idea behind the solution is to calculate diff in timestamps on the server side, and manipulate data in the arrays.
The script finishes in 0.278s on my MBP, takes 15.75MB of memory and final output of $ts is an array of routes (I got 7 in total).
There are quite a few optimizations, including skipping same coordinate points. Zoom bounds is not correct on the map but you'll figure it out.
I should have really asked a bounty for this job ...
If you like the outcome then let me know, I can share the codebase.
Source: https://gist.github.com/jpaljasma/04f54e0d2fa3a632071e


text:
Q: Remove element from a set only if element is in it A list of players is defined as a set:
(def players (atom #{}))

Function that removes player should return different HTTP codes based on whether element was in the set or not:
(defn remove-player [player-name]
  (if (contains? @players player-name)
    (do (swap! players disj player-name)
        (status (response "") 200))
    (status (response "") 404)))

The problem with this code is that it might return multiple 200 to concurrent requests, even if only one request actually removed the element.
I guess I need to execute both contains? and disj atomically. Do I need to do explicit locking or is there a better way to do it?

A: the swap! itself is atomic operation, so inside the swap's calculating function you can be sure that the first parameter (atom's current value) is consistent. Personally i would make a helper function for that like this:
(defn remove-existent [value set-a]
  (let [existed (atom false)]
    (swap! set-a
           #(if (contains? % value)
              (do (reset! existed true)
                  (disj % value))
              (do (reset! existed false)
                  %))
    @existed))

as you can see, lambda expression contains both existency check and removal.
user> (def players (atom #{:user1 :user2}))
#'user/players

user> (remove-existent :user100 players)
false

user> (remove-existent :user1 players)
true

user> @players
#{:user2}

update
Inspired by @clojuremostly's excellent metadata approach, you can make it much better:
(defn remove-existent [value set-a]
  (-> (swap! set-a #(with-meta (disj % value)
                      {:existed (contains? % value)}))
      meta
      :existed))

A: You can just add some more logic to your swapping function:
(for [el-rem [:valid-el :not-there]]
  (let [a (atom #{:valid-el :another-one})
        disj-res
        (swap! a
               (fn [a]
                 (with-meta (disj a el-rem)
                            {:before-count (count a)})))]
    [disj-res
     "removed:"
     el-rem
     (not (== (:before-count (meta disj-res))
              (count disj-res)))]))

You then compare the count of the return value disj-res and the count in the meta data. If it differs, then disj did remove an element. If not, the element was not present.


text:
Q: creating an http request in android it get stopped and the application force close I am trying to use HTTP request on android with JSON and php/mysql to display some data from the mysql database .
the application is simply push a button and it will display in the log cat the selected data from the database and it display the second page on the emulator using intent..
the problem is that when i try to run the application the system crush before it send the request to the http and i use a localhost server (wamp) so the URL i used is: http://10.0.2.2/studentservice/StudentService/getStudentByID.php
after i push the button this is the
logCat
10-15 14:07:28.160: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:28.320: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:07:28.630: D/gralloc_goldfish(854): Emulator without GPU emulation detected.
10-15 14:07:28.660: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:28.670: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:07:35.800: E/Error befor http(854): Error before the http request
10-15 14:07:36.210: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:36.230: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:07:36.730: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:36.750: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:07:37.250: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:37.270: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:07:37.770: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:37.780: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:07:38.281: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:38.300: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:07:38.800: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:38.821: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:07:48.400: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:07:48.460: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'
10-15 14:10:25.630: I/dalvikvm(854): threadid=3: reacting to signal 3
10-15 14:10:25.650: I/dalvikvm(854): Wrote stack traces to '/data/anr/traces.txt'

after it crush the log cat display
10-15 14:35:13.781: E/AndroidRuntime(906): FATAL EXCEPTION: main
10-15 14:35:13.781: E/AndroidRuntime(906): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.lebdev.fitguide.activities/com.lebdev.fitguide.activities.SecondaryActivity}: java.lang.NullPointerException: println needs a message
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.app.ActivityThread.access$600(ActivityThread.java:123)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.os.Handler.dispatchMessage(Handler.java:99)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.os.Looper.loop(Looper.java:137)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.app.ActivityThread.main(ActivityThread.java:4424)
10-15 14:35:13.781: E/AndroidRuntime(906):  at java.lang.reflect.Method.invokeNative(Native Method)
10-15 14:35:13.781: E/AndroidRuntime(906):  at java.lang.reflect.Method.invoke(Method.java:511)
10-15 14:35:13.781: E/AndroidRuntime(906):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
10-15 14:35:13.781: E/AndroidRuntime(906):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
10-15 14:35:13.781: E/AndroidRuntime(906):  at dalvik.system.NativeStart.main(Native Method)
10-15 14:35:13.781: E/AndroidRuntime(906): Caused by: java.lang.NullPointerException: println needs a message
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.util.Log.println_native(Native Method)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.util.Log.e(Log.java:231)
10-15 14:35:13.781: E/AndroidRuntime(906):  at com.lebdev.fitguide.controller.HttpManager.getResponseFromURL(HttpManager.java:70)
10-15 14:35:13.781: E/AndroidRuntime(906):  at com.lebdev.fitguide.activities.SecondaryActivity.onCreate(SecondaryActivity.java:54)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.app.Activity.performCreate(Activity.java:4465)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
10-15 14:35:13.781: E/AndroidRuntime(906):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
10-15 14:35:13.781: E/AndroidRuntime(906):  ... 11 more
10-15 14:35:14.341: I/dalvikvm(906): threadid=3: reacting to signal 3
10-15 14:35:14.370: I/dalvikvm(906): Wrote stack traces to '/data/anr/traces.txt'

MainActivity
package com.lebdev.fitguide.activities;

import com.lebdev.fitguide.businessModel.Student;
import com.lebdev.fitguide.businessModel.Subject;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    EditText txtMessage;
    TextView lblMessage;

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

        txtMessage = (EditText) findViewById(R.id.txtMessage);
        lblMessage = (TextView) findViewById(R.id.lblMessage);
    }

    @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;
    }

    public void Onclick_btnSend(View v) {

         Intent intent  = new Intent(this, SecondaryActivity.class);
         //intent.putExtra("message", txtMessage.getText().toString());
         Student std = new Student(txtMessage.getText().toString(),1234, 1);
         std.getSubjects().add(new Subject("itc", 5));
         intent.putExtra("Student", std);
         startActivity(intent);

         Toast.makeText(this, "i am sending a message here", Toast.LENGTH_SHORT).show();

    }
}

JsonObjectMapper
package com.lebdev.fitguide.om;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONObject;

import android.util.Log;

import com.lebdev.fitguide.businessModel.Student;

public class JsonObjectMapper {

    public static Student jsonToStudent(JSONObject jsonObject) {

        Student std = null;

        try {

            std = new Student(jsonObject.getJSONArray("Student")
                    .getJSONObject(0).getString("Name"),
                    Integer.parseInt(jsonObject.getJSONArray("Student")
                            .getJSONObject(0).getString("index")),
                    Integer.parseInt(jsonObject.getJSONArray("Student")
                            .getJSONObject(0).getString("ID")));
        } catch (Exception ex) {
            Log.e("Error Json Converter", ex.getMessage());
        }

        return std;
    }

    public static List<Student> jsonToStudentList(JSONObject jsonObject) {

        List<Student> stdList = new ArrayList<Student>();
        try {

            for (int i = 0; i < jsonObject.getJSONArray("Student").length(); i++) {

                stdList.add(new Student(jsonObject.getJSONArray("Student")
                        .getJSONObject(i).getString("Name"), Integer
                        .parseInt(jsonObject.getJSONArray("Student")
                                .getJSONObject(i).getString("index")), Integer
                        .parseInt(jsonObject.getJSONArray("Student")
                                .getJSONObject(i).getString("ID"))));
            }
        } catch (Exception ex) {

            Log.e("Error Json Converter", ex.getMessage());
        }

        return stdList;
    }
}

SecondaryObject
package com.lebdev.fitguide.activities;

import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;

import com.lebdev.fitguide.businessModel.Student;
import com.lebdev.fitguide.controller.HttpManager;
import com.lebdev.fitguide.controller.JSONParser;
import com.lebdev.fitguide.om.JsonObjectMapper;

import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.widget.TextView;
import android.widget.Toast;

public class SecondaryActivity extends Activity {

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

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
                .permitAll().build();
        StrictMode.setThreadPolicy(policy);

        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("sid", "2"));

        Log.e("Error befor http", "Error before the http request");
        JSONObject jsonObj = JSONParser
                .parseJSONFromString(new HttpManager()
                        .getResponseFromURL(
                                "http://10.0.2.2/studentservice/StudentService/getStudentByID.php",
                                params));

        Log.e("Error after http", "Error after the http request");

        Student std = JsonObjectMapper.jsonToStudent(jsonObj);

        Log.e("STUDENT DATA", "ID:" + std.getID() +     "Name:" + std.getName()
                + "Index: " + std.getIndex());
/*
        Bundle bundle = getIntent().getExtras();
        if (bundle != null) {
            TextView lblMessage = (TextView) findViewById(R.id.lblSentMessage);
            Student student = bundle.getParcelable("Student");

            lblMessage.setText("I 've recieved a student with a name "
                    + student.getName() + " and has a Subject "
                    + student.getSubjects().get(0).getName() + " with a grade "
                    + student.getSubjects().get(0).getGrade());
        }
*/
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.secondary, menu);
        return true;
    }

}

A: 10-15 14:35:13.781: E/AndroidRuntime(906):  at com.lebdev.fitguide.controller.HttpManager.getResponseFromURL(HttpManager.java:70)
That's a pointer to your code, line number and all, about where the null pointer (null message to Log.e() ) is coming from and causing the crash.
That's obvious from your logcat, so you're doing something in
JSONObject jsonObj = JSONParser
                .parseJSONFromString(new HttpManager()
                        .getResponseFromURL(
                                "http://10.0.2.2/studentservice/StudentService/getStudentByID.php",
                                params));
That's causing a null msg written to Log.e().


text:
Q: How to get a data API from another function in python django I am doing an project that pulling user API from github and I successfully done that but I'm working on how to show that data on a chart. I'm using Chart.js
Here is my views.py:
def user(req, username):
    username = str.lower(username)

    # Get User Repo Info
    with urlopen(f'https://api.github.com/users/{username}/repos') as response:
        source = response.read()
    sorted_by_stars = json.loads(source)

    def sort_user_repo_by_stars(sorted_by_stars):
        return sorted_by_stars['stargazers_count']

    sorted_by_stars.sort(key=sort_user_repo_by_stars, reverse=True)

    context = {
        'username': username,
        'sorted_by_stars': sorted_by_stars[:8],
    }
    return render(req, 'user.html', context)

class ChartData(APIView):
    authentication_classes = []
    permission_classes = []

    def get(self, request, format=None):
        labels = ["Blue", "Yellow", "Green", "Purple", "Orange"]
        default_items = [ DATA ]
        data = {
            "labels": labels,
            "default": default_items,
        }
        return Response(data)

I want to get data that I pulled from github which is sorted_by_stars = json.loads(source) and it put in ChartData. How can I do that?

A: You can put that part of code in a method and use it any function. For example:
def get_stars(username):
    with urlopen(f'https://api.github.com/users/{username}/repos') as response:
        source = response.read()
    return json.loads(source)

def user(req, username):
    username = str.lower(username)
    sorted_by_stars=get_stars(username)
    ...

class ChartData(APIView):
    ...

    def get(self, request, username=None, format=None):
        labels = ["Blue", "Yellow", "Green", "Purple", "Orange"]
        stars = get_stars(username)  # or use request.user.username if the use is authenticated with github username
        # rest of the code

You can also store this information in request.session and use it different views. For example:
def user(req, username):
    username = str.lower(username)
    sorted_by_stars=get_stars(username)
    req.session['stars']=sorted_by_stars
    # rest of the code

class ChartData(APIView):
        ...
        def get(self, request, format=None):
           stars = request.session.get('stars', None)
           # rest of the code


text:
Q: Full Calendar IO implementing columns into a single day view Good morning, i've been struggling with fullCalendar.io for a few days trying to implement custom views and i've gone too far with code that is incorrect so i've rolled back and I have the calendar working correctly and it's purely a visual issue i'm trying to resolve.
For a single day I am showing events from multiple staff and would like to split the single day into columns. Where might you tackle something like that in fullCalendar without going down the custom view route?
The calendar is already displaying the events but they look like https://trello-attachments.s3.amazonaws.com/5b0d30e471191c2f25ff2049/5ddbdf0f8d817e8937371471/07bfbc1c1593c6a019bdca59827b4bc3/image.png and it would be clearer if I could get a heading on each column and display them appropriately. The problem is some staff may have gaps in their day but the calendar fills those gaps.

A: You mentioned:

For a single day I am showing events from multiple staff...

This is a perfect use case for resource-aware view such as the vertical resource view which will create exactly the kind of display you're describing.
Be aware that this is a premium product though so depending on how you are going to use it in your live environment, you may need to pay fullCalendar a license fee. See https://fullcalendar.io/license and https://fullcalendar.io/license/premium for further details of the circumstances when you need to get a paid license, and what the costs are.


text:
Q: how to get info on failed authentication to domain - security audit? Setup:
1 Windows Server 2012 box as Domain Controller, named DC1.
2 Windows Server 2012 R2 boxes, S1 and S2, on the same network, same config, joined to the domain.
Issue:
At random times, S1, S2 or both will not allow me to RDP on the boxes with a domain user, with the message "The trust relationship between this workstation and the primary domain failed". RDP with a Local admin works. This is usually solved with a restart of S2.
Question:
How do I check the logs on DC1, to see these failed authentication events ? Do I have to enable some kind of security audits and download some applications/SDK with extra management tools ?


text:
Q: Why does Viterbi algorithm (POS tagging) always predict one tag? Here is my HMM model class:
class HiddenMarkovModel:
    def __init__(self):

        pass

    def fit(self, train_tokens_tags_list):
        """
        train_tokens_tags_list: array of sentences of pairs word-tag (for train)
        """
        tags = [tag for sent in train_tokens_tags_list
                for (word, tag) in sent]
        words = [word for sent in train_tokens_tags_list
                 for (word, tag) in sent]

        tag_num = pd.Series(data = nltk.FreqDist(tags)).sort_index()
        word_num = pd.Series(data = nltk.FreqDist(words)).sort_values(ascending=False)

        self.tags = tag_num.index
        self.words = word_num.index

        A = pd.DataFrame({'{}'.format(tag) : [0] * len(tag_num) for tag in tag_num.index}, index=tag_num.index)
        B = pd.DataFrame({'{}'.format(tag) : [0] * len(word_num) for tag in tag_num.index}, index=word_num.index)

        # Compure matrixes A and B from count of words and tags

        # sent - sentence
        # sent[i][0] - i word in this sentence, sent[i][1] - i tag in this sentence
        for sent in train_tokens_tags_list:
            for i in range(len(sent)):
                B.loc[sent[i][0], sent[i][1]] += 1 # current i-pair word-tag
                if len(sent) - 1 != i: # for last tag there is no next tag
                    A.loc[sent[i][1], sent[i + 1][1]] += 1 # pair tag-tag

        # now to probabilities

        # normalize along the row, i.e along all possible next tags
        A = A.divide(A.sum(axis=1), axis=0)

        # normalize along column, i.e along all possible current words
        B = B / np.sum(B, axis=0)

        self.A = A
        self.B = B

        return self

    def predict(self, test_tokens_list):
        """
        test_tokens_list : array of sentences of pairs word-tag (for test)
        """
        predict_tags = OrderedDict({i : np.array([]) for i in range(len(test_tokens_list))})

        for i_sent in range(len(test_tokens_list)):

            current_sent = test_tokens_list[i_sent] # current sentence
            len_sent = len(current_sent) # lenght of sentence

            q = np.zeros(shape=(len_sent + 1, len(self.tags)))
            q[0] = 1 # zero state (equal distribution for all s)
            back_point = np.zeros(shape=(len_sent + 1, len(self.tags))) # # argmax

            for t in range(len_sent):

                # if we haven't met this word during training,
                # we'll use the most popular word with most popular tag instead
                if current_sent[t] not in self.words:
                  # print('this word not in dictionary', current_sent[t])
                  tagdict = findtags('NOUN', brown_tagged_words)
                  current_sent[t] = tagdict['NOUN'][0][0]

                # using max we choose next tag
                for i_s in range(len(self.tags)):
                    # i_s - index for tag
                    s = self.tags[i_s] # tag

                    # formula (1)
                    probability = np.max(q[t][i_s] * self.A.loc[:, s] * self.B.loc[current_sent[t], s])

                    q[t + 1][i_s] = np.max(probability)

                    # argmax formula(1)

                    # argmax for recreating the sequence of tags
                    back_point[t + 1][i_s] = (probability).reset_index()[s].idxmax() # index

            back_point = back_point.astype('int')

            # saving tags and changing their order for real one
            back_tag = deque()
            current_tag = np.argmax(q[len_sent])

            for t in range(len_sent, 0, -1):
                back_tag.appendleft(self.tags[current_tag])
                current_tag = back_point[t, current_tag]

            predict_tags[i_sent] = np.array(back_tag)

        return predict_tags

It was actually almost completely written before me. I was to fill in some gaps (above all in the Viterbi algorithm where we compute q and back_point matrices). But I think I did something wrong as my model always predicts something like that:
OrderedDict([(0, array(['.', '.', '.'], dtype='<U1'))])

In the example above I gave it this sentence:  [['he', 'can', 'stay']]
I've checked : all these words are in the train data.
I've printed out matrices A and B. Here they are:
A:

B:

This shows that the first part of model is working fine.
These are folmulas I had for help:

This is the data:
brown_tagged_sents = brown.tagged_sents(tagset="universal", categories='humor')

my_brown_tagged_sents = []
for sent in brown_tagged_sents:
    my_brown_tagged_sents.append(list(map(lambda x: (x[0].lower(), x[1]), sent)))
my_brown_tagged_sents = np.array(my_brown_tagged_sents)

from sklearn.model_selection import train_test_split
train_sents, test_sents = train_test_split(my_brown_tagged_sents, random_state=0, test_size=0.1)

What could be wrong with my model?

A: Probability should look like that:
probability = q[t, :] * self.A.loc[:, s] * self.B.loc[current_sent[t], s]

instead of this:
probability = q[t][i_s] * self.A.loc[:, s] * self.B.loc[current_sent[t], s]


text:
Q: Python turtle.onkey doesn't run function This is my code:
import turtle

# window
wn = turtle.Screen()
wn.setup(width=800, height=600)
wn.tracer(0)

def hi():
    print("hi")

def bye():
    print("bye")

wn.listen()
wn.onkey(hi, "a")
wn.onkeyrelease(bye, "a")

while True:
    wn.update()

When I press the key, it doesn't print "hi", but when I release the key it prints "bye" just fine. What am I doing wrong?

A: onkey is just alias for onkeyrelease
Use onkeypress instead
wn.onkeypress(hi, "a")
wn.onkeyrelease(bye, "a")


text:
Q: How to make function2 run after function1 has already finished? I am working on a sidebar navigation: And the sidebar opens when we click on the toggle button and it stays open until we click again on the toggle button.
For the same sidebar I have a hover function : on mouseEnter sidebar opens and onMouseLeave sidebar closes.
The problem I have is with the closing the sidebar onClick. When I click close on the toggle button the sidebar stays open because the mouseEnter function is triggered.
I want the mouseEnter to be ready after the navbar close animation is finished.
Here is my code for the click event:
$('body').on('click', '.sidebar-toggler', function (e) {
            var sidebar = $('.page-sidebar');
            var sidebarMenu = $('.page-sidebar-menu');
        if (body.hasClass("page-sidebar-closed")) {
                    body.removeClass("page-sidebar-closed");
                    sidebarMenu.removeClass("page-sidebar-menu-closed");
                } else {
                    body.addClass("page-sidebar-closed");
                    sidebarMenu.addClass("page-sidebar-menu-closed");
                    if (body.hasClass("page-sidebar-fixed")) {
                        sidebarMenu.trigger("mouseleave");
                    }
    }

and here is the code for the hover event:
 if (body.hasClass('page-sidebar-fixed')) {
            $('.page-sidebar').on('mouseenter', function () {
                if (body.hasClass('page-sidebar-closed')) {
                    $(this).find('.page-sidebar-menu').removeClass('page-sidebar-menu-closed');
                }
            }).on('mouseleave', function () {
                if (body.hasClass('page-sidebar-closed')) {
                    $(this).find('.page-sidebar-menu').addClass('page-sidebar-menu-closed');
                }
            });
        }

A: Try to .off() the mouseenter event when the sidebar is opened with the toggle button.
http://api.jquery.com/off/


text:
Q: How to "pin" html elements to parent, but prevent rotation inheritance? I am trying to build a certain UI element based around spinning the control object with various indicators on it. The control is an Object element containing SVG and within the SVG there are image tags embedded that are the icons users interact with. When the user spins the element such that the icon is within a "target zone", some function is triggered.
A very very simplified example here: http://jsfiddle.net/megakoresh/pp7mt1nm/2/
The element is build using CSS transform: rotate() property set via javascript and as you can see from the example, all of it's children rotate with it. What I would like to do is to keep them upright, but still change position, as if they were "hanging" from the parent element.
If you go to the fiddle and uncomment the JS code, you can see one solution with requestAnimationFrame, but it's really heavy and messy and I really don't like it. Is there any better way to keep elements upright when the parent rotates, but still have them move with it?
Important:
Ok I think I wasn't clear enough: it's a rotatable UI element I am building. The 130deg there is just an example - the user can rotate the element to any degree they wish. I can not simply hardcode those degrees, I have to prevent the children from inheriting rotation.
Like Mr. Polywhirl has pointed out, it is something like this:
http://codepen.io/mr_alien/pen/Alzqe
except the user can grab the wheel and rotate it in any direction themseleves.

A: a {
    transition: transform 1s ease;
}
.block:hover a {
    transform: rotate(-130deg);
}

A: With Javascript, the answer is to dynamically add negative rotation to the child to compensate the parent.
Without Javascript, use a common container, but don't actually put the sticky element into the rotating one. The fiddle has been updated with this example.

  ( ͡° ͜ʖ ͡°)

  Click this!
  No, click this!


text:
Q: Work with Firebase Realtime Database, create entries in triggers Hello stackoverflow and Peoples that have been helping me for years, here is my first question!
I have been programming in Android for some time, I like to test new ways to optimize apps.
Now I came across Firebase Relatime Database and the possibility to trigger the entries on the server side with "function".I watched dozens of Firebase videos, rolled through the Firebase pages, and tried the whole thing with Typescript
Unfortunately my English is very, very bad and I can't find any examples of how I can get a simple code to work. I created a code with Node.js, tested it with firebase emulators: start, and it worked, but not on the Google server after "Firebase deploy".
The goal is to make an entry in another path, after triggering an entry:
I still don't understand the principle. that gives me the most difficulty, can someone explain what it could be and what it should look like?
import * as functions from 'firebase-functions';
import * as admin from 'firebase-admin'
const serviceAccount = require('../serviceAccount.json')

let userId = "";

admin.initializeApp({
    credential: admin.credential.applicationDefault() ,
    databaseURL:`https://${serviceAccount.project_id}.firebasio.com`
});

// const db = admin.database();

// // Start writing Firebase Functions
// // https://firebase.google.com/docs/functions/typescript
//
 export const helloWorld = functions.https.onRequest((request, response) => {
     console.log("hallo world");
  response.send("Hello from Firebase!");
 });

 export const setPlayerInTeam = functions.database.ref('{userId}/team/{teamId}/allPlayer/{spielerId}/')
 .onCreate( (snapshot,context)=>{
    const original = snapshot.val();
    userId = context.params.userId;
    console.log('userId',userId);
    console.log('teamId',context.params.teamId);
    console.log('spielerId',context.params.spielerId);
    console.log('original.name',original.name);
    console.log('Updates',context.params.spielerId," "+context.params.teamId);

    const adaNameRef = admin.database().ref();
       adaNameRef.child('test').push({ first: 'Ada', last: 'Lovelace' }).then(function() {
        console.log('Synchronization succeeded');
      })
      .catch(function(error) {
        console.log('Synchronization failed');
      });

      return adaNameRef;

 });

I also tried async, the result according to Console was the same
 .onCreate(async (snapshot,context)=>{
 ......
await  adaNameRef.child('test')

my Powershell Console says:
  userId TZBAxFGSgZPZBoYZz7F4MVm5MAP2
>  teamId -M797y0K4BBCEOa_nVoB
>  spielerId -M7skpftMOOF4QlEW2kv
>  original.name luigi
>  Updates -M7skpftMOOF4QlEW2kv  -M797y0K4BBCEOa_nVoB
i  functions: Finished "setPlayerInTeam" in ~1s
>  Synchronization succeeded

My Firebase Console Log says:
Function execution started
Billing account not configured. External network is not accessible and quotas are severely limited. Configure billing account to remove these restrictions
userId TZBAxFGSgZPZBoYZz7F4MVm5MAP2
teamId -M8e9ro1Dlb7VA9Pab4t
spielerId -M8e9ozdo0uU6NCXfG2z
original.name Ayla
Updates -M8e9ozdo0uU6NCXfG2z -M8e9ro1Dlb7VA9Pab4t
Function execution took 1151 ms, finished with status: 'ok'

no succes, no error?
Sorry, for the Bad English, everything is translated with google translated, I thank you already

A: I've created a sample code for you hopping this can help you to start with.
const functions = require('firebase-functions');
const admin = require('firebase-admin');

//Initialize the App
admin.initializeApp(functions.config().firebase);

//When an userID is created, the function will be triggered
exports.makeUppercase = functions.database.ref('/pamyu/{userID}')
    .onCreate((snapshot, context) => {

      //Then I'll create an entry in this other path
      //You can change the path according to your DB
      admin.database().ref("/kyary").update({
        userid: "1234567890"
      });
    });

Good luck! :D


text:
Q: change input value with change in select menu options This is javacript for getting same category_name in input box as in select box
but i dont know the code for getting my category_id and category_desc for the same

This is the jsp page's code with which i set the default values but i want these values to change a s the select option value changes, if u need any other information please let me know.
                <%! Connection con = null;%>
                <%! Statement st = null;%>
                <%! ResultSet rs = null;%>
                <%
                    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
                    con = DriverManager.getConnection("jdbc:derby://localhost:1527/mydb1", "mydb", "mydb");
                    st = con.createStatement();
                    rs = st.executeQuery("SELECT category_id, category_name FROM Category");
                    con.setAutoCommit(false);
                %>

                        CATEGORY NAME

                        <%-- using select tag  --%>
                        <select id="sel" onchange="filltxtbox()">
                            <%
                                String catname = null;
                                int catid = 0;
                                while (rs.next()) {
                                    catname = rs.getString(2);
                                    catid = rs.getInt(1);
                                    out.println("<option value=" + catid + ">" + catname + "</option>");
                                }
                            %>
                        </select>

                    <jsp:setProperty name="category" property="*"/>
                    <%--// category_id input  --%>

                        CATEGORY ID

                        <%  rs = st.executeQuery("SELECT category_id FROM Category");
                            if (rs.next()) {
                                int defcatid = rs.getInt(1);
                                out.print("<input  type = 'text' name = 'category_id' id='txtselid' value ='" + defcatid + "' size = '30'/>  ");
                            }
                        %>

                <%--// category_name input  --%>

                        CATEGORY NAME

                        <%  rs = st.executeQuery("SELECT category_name FROM Category");
                            if (rs.next()) {
                                String defcatname = rs.getString(1);
                                out.print("<input  type = 'text' name = 'category_name' id='txtselname' value ='" + defcatname + "' size = '30'/>  ");
                            }
                        %>

                <%--// category_desc input  --%>

                        CATEGORY DESCRIPTION

                    <%
                        rs = st.executeQuery("SELECT category_desc FROM category");
                        if (rs.next()) {
                   String defcatdesc = rs.getString(1);
                   out.print("<textarea name='category_desc' rows='10' cols='50' >" +defcatdesc + "</textarea>");

}%>`

A: call this method using onChange() for select box.
function filltxtbox(){
   document.getElementById("textBoxId").value =
   document.getElementById("selectBoxId").options[e.selectedIndex].value;
  }

document.getElementById("selectBoxId").options[e.selectedIndex].text  this will give the selected test(i.e category_desc)


text:
Q: Inserting year with zero Is it possible to enter a date with a zero year?
What would the insert clause look like?
I ask, as an application is doing this, see the dump of the date:
dt_data: 05/01/00
dump(dt_data): Typ=12 Len=7: 100,100,5,1,1,1,1
to_char(dt_data, 'dd/MM/yyyy'): 00/00/0000

Oracle Database 11g Enterprise Edition Release 11.2.0.3.0

A: SQL> create table t1 (c1 date);

Table created.

SQL> insert into t1 values (date'0000-01-05');

1 row created.

SQL> commit;

Commit complete.

SQL> select c1, to_char(c1, 'dd/MM/yyyy'), dump(c1) from t1;

C1                  TO_CHAR(C1
------------------- ----------
DUMP(C1)
--------------------------------------------------------------------------------
0000-01-05 00:00:00 00/00/0000
Typ=12 Len=7: 100,100,1,5,1,1,1


text:
Q: How to access an instance variable from a separate controller(amount variable in checkout) I am working on the checkout process of my tool rental app project using Stripe checkout. I am running into a problem when I want to dynamically change the rent-price dependent on what the person who posts the tool wants to rent it at.
I have my charges nested within my tools like so:
Rails.application.routes.draw do
  devise_for :users

  root 'pages#home'

  resources :tools do
    resources :charges
    get :manage, :on => :collection
  end

When I navigate to /tools/1/charges/new I am getting the following error:
Couldn't find Tool with 'id'=

This is my charges controller:
class ChargesController < ApplicationController

    def new
      @tool = Tool.find(params[:id])
      @amount = @tool.rent_price * 100
    end

    def create
      @tool = Tool.find(params[:id])
      @amount = @tool.rent_price * 100

      customer = Stripe::Customer.create(
        :email => 'example@stripe.com',
        :card  => params[:stripeToken]
      )

      charge = Stripe::Charge.create(
        :customer    => customer.id,
        :amount      => @amount,
        :description => 'Rails Stripe customer',
        :currency    => 'usd'
      )

    rescue Stripe::CardError => e
      flash[:error] = e.message
      redirect_to charges_path
    end

    private

    def tool_params
        params.require(:tool).permit(:name, :description, :user_id, :tool_image, :rent_price)
    end

end

This is my tools controller:
class ToolsController < ApplicationController
before_action :set_tool, only:[:show, :edit, :update, :destroy]
before_action :authenticate_user!, only:[:new, :destroy, :edit, :manage], notice: 'you must be logged in to proceed'

    def index
        @tools = Tool.all
    end

    def manage
        @user = current_user
        @tools = @user.tools
    end

    def show
    end

    def new
        @tool = Tool.new
    end

    def create
        @tool = Tool.new(tool_params)
        if @tool.save
            redirect_to @tool
        else
            redirect_to :action => "new"
            flash[:notice] = "You did not fill out all the fields"
        end
    end

    def edit
    end

    def update
        @tool.update(tool_params)
        redirect_to @tool
    end

    def destroy
        @tool.destroy
        redirect_to tools_path
    end

    private

    def set_tool
        @tool = Tool.find(params[:id])
    end

    def tool_params
        params.require(:tool).permit(:name, :description, :user_id, :tool_image, :rent_price)
    end

end

Take a look at my charges controller. The Stripe checkout documentation usually has the amount value hardcoded into the @amount instance variable. However I want it to be set by the tool creator. I have a rent_price column on my tool table and want to pass this value to the amount instance variable.
I attempt to do it by finding the tool under which the charge is being created. However there is no Charge Model and hence no association between the Tool and Charge. Stripe checkout works without the model. I am not sure how to access the amount set by the tool creator(Tool.rent_price) in the charges controller in this case. It appears there is no Tool.id being passed to the param. Any ideas on how to fix this?
I am thinking i will create a charges model even though stripe doesnt say to and use an association to chain call the amount. But not sure if there is a better way without having to create the charges model.

A: To me it looks like problem with using wrong parameters or problem with routes.
Did you try using Tool.find(params[:tool_id]) instead of Tool.find(params[:id])?
According to documentation about nested resources http://guides.rubyonrails.org/routing.html#nested-resources, in your example, params[:id] should be related to charge resource and params[:tool_id] to tool resource.


text:
Q: Start Ubuntu GUI from CLI I am having trouble starting the Ubuntu GUI from CLI. I currently have a fresh install of Ubuntu 20.04 desktop. I ran the following command to disable the GUI to start on boot (this is a headless server).
systemctl set-default multi-user

I started an instance of Xvfb as follows:
Xvfb :1 -screen 0 1920x1080x24*32 -nocursor -fbdir /var/tmp &

Now I read online that I could run this command to start the UI:
DISPLAY=:1 gnome-session --session=ubuntu &

However the UI looks slightly odd and is definitely not the default 20.04 Ubuntu UI. For example the side doc is missing, icons are missing. My desktop is empty etc.
Commands I have tried:
startx
systemctl start gdm3.service
systemctl isolate graphical

Any help would be greatly appreciated.


text:
Q: TypeScript: How to dynamically set properties on objects? I want to convert a Typescript Map to an object. The following code shows a compiler error:
const sourceMap = new Map<string, string>();
sourceMap.set('foo', 'bar');

const jsonObject = {};
sourceMap.forEach((value, key) => {
    jsonObject[key] = value;
});
console.log(JSON.stringify(jsonObject));

Playground Link
The compiler doesn't like the line jsonObject[key] = value; saying:

Element implicitly has an 'any' type because expression of type 'string' can't be used to index type '{}'. No index signature with a parameter of type 'string' was found on type '{}'.(7053)

How can I fix that or what am I doing wrong here?

A: You can add an explicit type annotation to jsonObject to allow indexing with any string. The predefined type Record should work fine:
const sourceMap = new Map<string, string>();
sourceMap.set('foo', 'bar');

const jsonObject: Record<string, string> = {};
sourceMap.forEach((value, key) => {
    jsonObject[key] = value;
});
console.log(JSON.stringify(jsonObject));

Playground Link


text:
Q: Hiding library project implementation from client app I'm building an android library project, which will act like an SDK. Other apps will include the project, and call methods from it as normal.
I'm providing the functionality to the client app by means of a singleton, i.e. MySdk.getInstance().doSomethingGreat(). However, I only want the desired SDK behaviour to be available. My library has has many classes organised into several packages, which naturally contain many public variables and methods. Currently the client app can access lots of stuff which I don't want it to. How can I hide all this stuff from the client app?
The only way I can think of is to organise all my classes into one package, so that I can keep all my methods and variables private, protected, or default visibility. But that's really poor organisation to work with, surely there is another way?


text:
Q: Is there a way to instrument CSS file? I have a CSS file on a webpage. I have a bunch of selenium tests that validates the styles for a component. I want to instrument this CSS file to generate the code coverage for it? Is this possible?
Any help on this is highly appreciative.

A: Why do you want to generate code coverage for CSS? This seems rather odd as you cannot be sure that the CSS written will be displayed in the browser due to specificity etc.
You can use the Galen test framework to test the styling of UI components: http://galenframework.com/

A: "Instrumenting" a CSS file, no, that doesn't really make sense since CSS stylesheets do not contain executable code in the way that Java or JavaScript source/class files do.
What you can do to detect unused styles, rules, etc., is to use a static analysis tool that understands CSS. Certain Java IDEs (IntelliJ IDEA, at least) do have this ability. There are also dedicated tools for CSS analysis and optimization as well, as mentioned in this other answer.


text:
Q: Basis for a plane If I have a given plane, and I choose two linearly independent vectors within the plane, why must they be a basis for the plane? I'm having trouble conceptualizing this.

A: A plane is fundamentally built out of two directions. They are ideally orthogonal but this is not necessary. Any pair of different directions within that plane are sufficient to form all of it (i.e. the vectors representing those directions form a basis).
Two vectors that are linearly independent are by definition different directions, and if both come from the plane of interest, they are enough to build exactly that plane, no more and no less.
Hence, any LI pair of vectors are a basis for a plane, and any LI pair of vectors from a specific plane are a basis for that plane (and no other).

A: Take a flat sheet of paper. Take any point as the origin. Draw any 2 non-collinear vectors starting at the origin. Draw a third vector. Is it possible that this vector is not the sum of the two other vectors eventually multiplied by scalars (positive or negative)?

A: A plane , if it passes through the origin, has dimension 2. So any two linearly independent vectors in the plane must be a basis.

A: Define the plane as $2$ linearly independent vectors such that
$$v = \begin{bmatrix}a\\0\end{bmatrix}, u = \begin{bmatrix}0\\b\end{bmatrix}$$
and $a, b \in \mathbb{R}$
$$v + u = \begin{bmatrix}a\\b\end{bmatrix}$$
Now that we have added the vectors, can you see how we can get to every point on the plane now by scaling $a$ and $b$?


text:
Q: I want to hide a specific legend entry, while keeping the main aesthetic in ggplot. How would yo go about it? I dont want the CRF part to show up in my legend. I tried to use a scale_color_manual but could not figure out how to get rid of that entry.
    fr30_clean <- ex37_fr30 %>%
  select(1,3) %>%
  rowid_to_column() %>%
  rename(response = rowid,
         time = Time,
         schedule = Schedule) %>%
  mutate(schedule = as.factor(schedule))

vi5_clean <- ex37_vi5 %>%
  select (1,3) %>%
  rowid_to_column() %>%
  rename(response = rowid,
         time = Time,
         schedule = Schedule) %>%
  mutate(schedule = as.factor(schedule))

plot01 <- ggplot(data = fr30_clean, aes(x = time, y = response)) +
  geom_point(aes(color = schedule), size = 3) +
  xlim (217860,230135) +
  ylim (98,431) +
  xlab("Time [ms]") +
  ylab ("Cumulative Responses") +
  labs(color = "Schedule") +
  ggtitle(label = "Figure 1",
          subtitle = "Extinction under FR30") +
  theme_apa() +
  geom_line(linetype = "dashed")

plot01

Any help would be greatly appreciated :)
Thank you.


text:
Q: How to make sublist uses the same enumeration style
*

*I need to make the sublist uses the same enumeration style.

What I get is:
1)
    a)
    b)
2)

I need:
1)
    1.1)
    1.2)
2)

*In another case, how can I change the enumeration of the main list from numbers to letters?

This is the script:
\documentclass[journal,comsoc]{IEEEtran}
\begin{document}
\title{Test}
\maketitle
\section{Listing}
\subsection{Sub Section}
\begin{enumerate}
    \item First
        \begin{enumerate}
            \item First First
            \item First Second
        \end{enumerate}
    \item Second
\end{enumerate}
\end{document}

A: Very simple with enumitem: using the label* key prepends the parent counter to the sublist counter.
\documentclass{article}
\usepackage{enumitem}

\begin{document}

\section{Listing}
\subsection{Sub Section}
\begin{enumerate}
    \item First
        \begin{enumerate}[label*=\arabic*)]
            \item First First
            \item First Second
        \end{enumerate}
    \item Second
\end{enumerate}

\end{document}

A: Similar to @Bernard answer (+1), but use of enumi counter:
\documentclass[journal,comsoc]{IEEEtran}
\usepackage{enumitem}

\begin{document}

\section{Listing}
\subsection{Sub Section}
\begin{enumerate}
    \item First
        \begin{enumerate}[label=\theenumi.\arabic*),leftmargin=*]
            \item First First
            \item First Second
        \end{enumerate}
    \item Second
        \begin{enumerate}[label=\theenumi.\arabic*),leftmargin=*]
            \item First First
            \item First Second
        \end{enumerate}
\end{enumerate}
\end{document}


text:
Q: Post Pagination Customization (wp_link_pages) Editing Navigation I want to create a post pagination where there is only ONE 'nextpagelink' button per page.
However, I want the text inside the the first 'nextpagelink'  to say "WELCOME".
And I want the text inside every 'nextpagelink' after that to say "NEXT PAGE".
Quick Schematic

I figured out the "NEXT PAGE" part:
The following is inside single.php
wp_link_pages( array(
'before' => '
',
'after' => '
',
'next_or_number' => 'next',
'previouspagelink' => ' PREVIOUS SLIDE ',
'nextpagelink' => ' NEXT PAGE '
)); ?>

The problem is that it makes ALL 'nextpagelink' "NEXT PAGE"
I am trying the following but its not really working:
The following is inside post-template.php
            if ( $next = 1 ) {
            $link = _wp_link_page( $next ) . $r['link_before'] . $r['nextpagelink_first'] . $r['link_after'] . '';

Where "nextpagelink_first" = 'WELCOME'
All that does is display 'WELCOME' next to 'NEXT PAGE', and 'WELCOME' always points to first slide, not good.
Please help!

A: It makes all pages show "NEXT PAGE", because you don't tell it that it should be any different.
What you need is to set that link conditionally based on which page is currently displayed:
wp_link_pages( array(
    'before' => '
',
    'after' => '
',
    'next_or_number' => 'next',
    'previouspagelink' => ' PREVIOUS SLIDE ',
    'nextpagelink' => ( get_query_var('page') < 2 ) ? ' WELCOME ' : ' NEXT PAGE '
) );

This uses a conditional statement:
( get_query_var('page') < 2 ) ? ' WELCOME ' : ' NEXT PAGE '

which checks the current page (you can get it by checking page query var) and returning one of the strings based on the condition (here we check if it's the first page or any other).
You can read more on page query var here: What is the difference between $paged and $page?


text:
Q: Cakephp 2.x remove automatic created select tags from form helper I am working on a form and i can't figure out how to disable the select tags that get created automatically.
I am creating an input field that has the name campaign_id. It looks to me that whenever an inputname has something with _id, CakePHP creates selectboxes around the input field.
     echo $this->Form->input('campaign_id', array(
                                'label' => __('Campaign ID')
                            ));

I tried to chang the name and then it's working. But for the application the name needs to be campaign_id.
is there an option or a way to disable the select tags, so that i can use the input field manually instead of needing to select from a list?
UPDATE:
Thx to Arilia for pointing this out.
Forgot about the option: type => 'text'


text:
Q: I have a click button that sets the wallpaper from URL both for lock and home screen but it does not work for lockScreen in API level 28 or lower I am tring to set an image from URL as wallaper for both home screen and lock screen.it is not working for lock screen for API level 28 or lower but works for home screen.
val policy = StrictMode.ThreadPolicy.Builder().permitAll().build()
                    StrictMode.setThreadPolicy(policy)
                    var input: InputStream? = null
                    try {
                        input = URL(intent).openStream()
                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                            val wallpaperManager = WallpaperManager.getInstance(applicationContext)
                            wallpaperManager.setStream(
                                input, null, true,
                                WallpaperManager.FLAG_LOCK or WallpaperManager.FLAG_SYSTEM
                            )
                            Toast.makeText(this, "Wallpaper set successfully!", Toast.LENGTH_SHORT)
                                .show()
                        }
                    } catch (e: Exception) {
                        e.printStackTrace()
                    }


text:
Q: INSERTs and UPDATEs in ruby/rails using PostgreSQL functions I'm using activerecord-postgis-adapter and squeel in a geo oriented application. Fetching data using various queries based on find and where is working fine and squeel allows me to use PostgreSQL/PostGIS functions to query based on spatial functions and datatypes.
However, I can't figure out how to access similar functions when performing INSERTs and UPDATEs. Say I want to do something in the line of:
UPDATE object SET raster = ST_AsRaster(ST_Buffer(ST_Point(1,5),10),150, 150, '2BUI')
where id = 12345;

How could I perform such a query? Squeel doesn't even seem to have support for other queries than SELECTs.
In a perfect world I would even want to have Rgeo's datatypes automatically converted when used in UPDATE queries, just like with where queries.
I am aware that I can fall back to

ActiveRecord::Base.connection.execute

, but would rather avoid that unless someone tells me it's the only way.
-ra

A: you could create a connection to the database per model you're working with. one method you can run is the select_value method, there are others:
sql = "UPDATE object SET raster = ST_AsRaster(ST_Buffer(ST_Point(1,5),10),150, 150, '2BUI') where id = 12345;"
conn = ModelName.connection
conn.select_value(sql)

should run your command
see this post by Daniel Azuma for more about this one: http://blog.daniel-azuma.com/archives/216
you could conceivably put this type of code in migrations. In fact its probably a best practice.

A: update_all accepts an array param, so that you could e.g. do:
SomeClass
  .where(id: 123)
  .limit(1)
  .update_all(
    ["some_field = some_pg_func(?, ?)", "some", "values"]
  )

https://api.rubyonrails.org/v7.0.4/classes/ActiveRecord/Relation.html#method-i-update_all


text:
Q: Approximating the identity function by a sequence of smooth functions satisfying some properties I am reading a paper that claims the following without proof:

Let $\mathbf{1}$ denote the identity function on $\mathbb{R}^d$.  Then there exists a sequence of $C^{\infty}_c$ functions $\varphi_n =(\varphi^{(1)}_n , \varphi^{(2)}_n , \ldots, \varphi^{(d)}_n )  : \mathbb{R}^d \to \mathbb{R}^d$ such that on compact sets,
  $$
\left\{
                \begin{array}{ll}
                  \varphi_n \to \mathbf{1}, \\
                  \frac{\partial}{\partial x_j} \varphi^{(i)}_n \to \delta_{i,j}, \quad \quad i,j \in \{1, \ldots, d\},\\
                  \frac{\partial^2 }{\partial x_i \partial x_j} \varphi^{(k)} _n          \to 0,    \quad \quad i,j,k \in \{1, \ldots, d\},   \end{array}
              \right.
$$
  uniformly.

Strangely, it further claims that the choice of $\varphi_n$ can be made such that the following conditions are also satisfied:

Without loss of generality, we can assume that there exists a constant $C$ such that for any $n \in \mathbb{N}$ and $v \in \mathbb{R}^d$,
  $$
\left\{
                \begin{array}{ll}
                  \| \varphi_n (v) \| \leq C \| v \|, \\
                  \big| \frac{\partial}{\partial x_j} \varphi^{(i)}_n (v) \big|  \leq C, \quad \quad i,j \in \{1, \ldots, d\},\\
                  \big| \frac{\partial^2 }{\partial x_i \partial x_j} \varphi^{(k)} _n \big| \leq C,     \quad \quad i,j,k \in \{1, \ldots, d\},   \end{array}
              \right.
$$
  and that $\varphi_n(v) =v$, for any $n \in \mathbb{N}$ and any $v \in \mathbb{R}^d$ with $\|v \| \leq n$.

The only relevant result that I can recall is the fact that the set $C^{\infty}_c$ is dense in $L^p$. However, this doesn't give any information about the derivatives of $\varphi_n$, nor boundedness of the derivatives.  Does this involve any theorem in Sobolev spaces? I have absolutely no idea at the moment.


text:
Q: Function parameters out of nowhere? I've just begun to work with NodeJS and I find myself puzzled on code such as
app.get('/home', function(req, res) {
    // req and res are objects
})

I often see these kinds of function calls where the parameters in the anonymous function seem to come out of nowhere, yet contain various attributes and/or methods within?

A: You are passing a function to another function, this
function(req, res) {
}

is a function. Assuming you gave it a local variable name like b in the called method, the function could then be invoked. As an example, -
app.get = function(a, b) { // <-- assign a function to app.get
  b("one", "two"); // <-- and then req would be one, and res would be two.
}

A: This is actually found here:
app.listen = function(){
  var server = http.createServer(this);
  return server.listen.apply(server, arguments);
};

As you can see, express() is this and it is being used as a parameter to createServer.
You can find the documentation of createServer here:

The requestListener is a function which is automatically added to the 'request' event.

Then when you check the request event here:
Event: 'request'
function (request, response) { }

Emitted each time there is a request. Note that there may be multiple
  requests per connection (in the case of keep-alive connections).
  request is an instance of http.IncomingMessage and response is an
  instance of http.ServerResponse.

Technically this event gets emitted every time a new request from a browser is received.
And this code
app.get('/home', function(req, res) {
    // req and res are objects
})

Is somewhat a listener for a request to this route (check expressjs source code).
So req and res are short-hand of request and response and are passed from the request event.
Then express added some more methods/properties found here and here.

If you want to see the code for .get(), see here.


text:
Q: counting after and before change in value, within groups, generating new variables for each unique shift I am working to count occurrences of unique values within my groups, id. I'm looking at TF. When TF changes I want to count both forward and backwards from that point. This counting should be stored in a new variable PM#, so that PM# holds both plus and minus to each unique shift in  TF. From what I've gathered I need to use rle, but I am kinda stuck.
I made this working example to illustrate my issue.
I have this data
df <- structure(list(id = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L), TF = c(NA, 0L, NA, 0L, 0L, 1L, 1L, 1L, NA, 0L,
0L, NA, 0L, 0L, 0L, 1L, 1L, 1L, NA, NA, 0L, 0L, 1L, 0L, 0L, 1L,
0L, 1L, 1L, 1L)), .Names = c("id", "TF"), class = "data.frame", row.names = c(NA,
-30L))

This is the kinda data I am seeing
df[c(1:12,19:30),]
#>    id TF
#> 1   0 NA
#> 2   0  0
#> 3   0 NA
#> 4   0  0
#> 5   0  0
#> 6   0  1
#> 7   0  1
#> 8   0  1
#> 9   0 NA
#> 10  0  0
#> 11  0  0
#> 12  1 NA
#> 19  1 NA
#> 20  7 NA
#> 21  7  0
#> 22  7  0
#> 23  7  1
#> 24  7  0
#> 25  7  0
#> 26  7  1
#> 27  7  0
#> 28  7  1
#> 29  7  1
#> 30  7  1

I've started meddling with ave, cumsum and with rle, but haven't solved it this way yet.
df$PM01 <- with(df, ifelse(is.na(TF), NA, 1))
df$PM01 <- with(df, ave(PM01, TF, id, FUN=cumsum))

with(df, tapply(TF, rep(rle(id)[[2]], rle(id)[[1]]), count))

This is what I am trying to obtain,
dfa <- structure(list(id = c(0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 7L, 7L, 7L, 7L, 7L, 7L, 7L,
7L, 7L, 7L, 7L), TF = c(NA, 0L, NA, 0L, 0L, 1L, 1L, 1L, NA, 0L,
0L, NA, 0L, 0L, 0L, 1L, 1L, 1L, NA, NA, 0L, 0L, 1L, 0L, 0L, 1L,
0L, 1L, 1L, 1L), PM1 = c(NA, -3L, NA, -2L, -1L, 1L, 2L, 3L, NA,
NA, NA, NA, -3L, -2L, -1L, 1L, 2L, 3L, NA, NA, -2L, -1L, 1L,
NA, NA, NA, NA, NA, NA, NA), PM2 = c(NA, NA, NA, NA, NA, -3L,
-2L, -1L, NA, 1L, 2L, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, -1L, 1L, 2L, NA, NA, NA, NA, NA), PM3 = c(NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, -2L, -1L, 1L, NA, NA, NA, NA), PM4 = c(NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, -1L, 1L, NA, NA, NA), PM5 = c(NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA,
NA, NA, NA, NA, NA, NA, NA, NA, -1L, 1L, 2L, 3L)), .Names = c("id",
"TF", "PM1", "PM2", "PM3", "PM4", "PM5"), class = "data.frame", row.names = c(NA,
-30L))

dfa[c(1:12,19:30),]
#>    id TF PM1 PM2 PM3 PM4 PM5
#> 1   0 NA  NA  NA  NA  NA  NA
#> 2   0  0  -3  NA  NA  NA  NA
#> 3   0 NA  NA  NA  NA  NA  NA
#> 4   0  0  -2  NA  NA  NA  NA
#> 5   0  0  -1  NA  NA  NA  NA
#> 6   0  1   1  -3  NA  NA  NA
#> 7   0  1   2  -2  NA  NA  NA
#> 8   0  1   3  -1  NA  NA  NA
#> 9   0 NA  NA  NA  NA  NA  NA
#> 10  0  0  NA   1  NA  NA  NA
#> 11  0  0  NA   2  NA  NA  NA
#> 12  1 NA  NA  NA  NA  NA  NA
#> 19  1 NA  NA  NA  NA  NA  NA
#> 20  7 NA  NA  NA  NA  NA  NA
#> 21  7  0  -2  NA  NA  NA  NA
#> 22  7  0  -1  NA  NA  NA  NA
#> 23  7  1   1  -1  NA  NA  NA
#> 24  7  0  NA   1  -2  NA  NA
#> 25  7  0  NA   2  -1  NA  NA
#> 26  7  1  NA  NA   1  -1  NA
#> 27  7  0  NA  NA  NA   1  -1
#> 28  7  1  NA  NA  NA  NA   1
#> 29  7  1  NA  NA  NA  NA   2
#> 30  7  1  NA  NA  NA  NA   3

A: This was really a tricky one, and I'm sure the code can be further improved. However, I was able to reproduce your expected result.  Please, try this approach with your production data. If OK, I will add an explanation later.
library(data.table)

tmp <- setDT(df)[, rn := .I][!is.na(TF)][, rl := rleid(TF), by = id][
  , c("up", "dn") := .(seq_len(.N), -rev(seq_len(.N))), by = .(id, rl)][]

res <- tmp[tmp[, seq_len(max(rl) - 1L), by = .(id)], on = .(id), allow.cartesian = TRUE][
  rl == V1, PM := dn][rl == V1 + 1L, PM := up][
    , dcast(.SD, id + TF + rn ~ paste0("PM", V1), value.var = "PM")][
      df, on = .(rn, id, TF)][, -"rn"]
res

    id TF PM1 PM2 PM3 PM4 PM5
 1:  0 NA  NA  NA  NA  NA  NA
 2:  0  0  -3  NA  NA  NA  NA
 3:  0 NA  NA  NA  NA  NA  NA
 4:  0  0  -2  NA  NA  NA  NA
 5:  0  0  -1  NA  NA  NA  NA
 6:  0  1   1  -3  NA  NA  NA
 7:  0  1   2  -2  NA  NA  NA
 8:  0  1   3  -1  NA  NA  NA
 9:  0 NA  NA  NA  NA  NA  NA
10:  0  0  NA   1  NA  NA  NA
11:  0  0  NA   2  NA  NA  NA
12:  1 NA  NA  NA  NA  NA  NA
13:  1  0  -3  NA  NA  NA  NA
14:  1  0  -2  NA  NA  NA  NA
15:  1  0  -1  NA  NA  NA  NA
16:  1  1   1  NA  NA  NA  NA
17:  1  1   2  NA  NA  NA  NA
18:  1  1   3  NA  NA  NA  NA
19:  1 NA  NA  NA  NA  NA  NA
20:  7 NA  NA  NA  NA  NA  NA
21:  7  0  -2  NA  NA  NA  NA
22:  7  0  -1  NA  NA  NA  NA
23:  7  1   1  -1  NA  NA  NA
24:  7  0  NA   1  -2  NA  NA
25:  7  0  NA   2  -1  NA  NA
26:  7  1  NA  NA   1  -1  NA
27:  7  0  NA  NA  NA   1  -1
28:  7  1  NA  NA  NA  NA   1
29:  7  1  NA  NA  NA  NA   2
30:  7  1  NA  NA  NA  NA   3
    id TF PM1 PM2 PM3 PM4 PM5

# verify results are identical
identical(res, dfa)

[1] TRUE

In case of more than 9 changes per group paste0("PM", V1) should be replaced by sprintf("PM%02d",V1) in the call to dcast() to ensure the PM columns are ordered properly.
Explanation
tmp <-
  # coerce to data.table
  setDT(df)[
    # create row id column (required for final join to get NA rows back in)
    , rn := .I][
      # ignore NA rows
      !is.na(TF)][
        # number streaks of unique values within each group
        , rl := rleid(TF), by = id][
          # create ascending and descending counts for each streak
          # this is done once to avoid repeatedly creation of counts for each PM
          # (slight performance gain)
          , c("up", "dn") := .(seq_len(.N), -rev(seq_len(.N))), by = .(id, rl)]

tmp[]

    id TF rn rl up dn
 1:  0  0  2  1  1 -3
 2:  0  0  4  1  2 -2
 3:  0  0  5  1  3 -1
 4:  0  1  6  2  1 -3
 5:  0  1  7  2  2 -2
 6:  0  1  8  2  3 -1
 7:  0  0 10  3  1 -2
 8:  0  0 11  3  2 -1
 9:  1  0 13  1  1 -3
10:  1  0 14  1  2 -2
11:  1  0 15  1  3 -1
12:  1  1 16  2  1 -3
13:  1  1 17  2  2 -2
14:  1  1 18  2  3 -1
15:  7  0 21  1  1 -2
16:  7  0 22  1  2 -1
17:  7  1 23  2  1 -1
18:  7  0 24  3  1 -2
19:  7  0 25  3  2 -1
20:  7  1 26  4  1 -1
21:  7  0 27  5  1 -1
22:  7  1 28  6  1 -3
23:  7  1 29  6  2 -2
24:  7  1 30  6  3 -1
    id TF rn rl up dn

For the next step, we need the count of changes V1 within each group
tmp[, seq_len(max(rl) - 1L), by = .(id)]

   id V1
1:  0  1
2:  0  2
3:  1  1
4:  7  1
5:  7  2
6:  7  3
7:  7  4
8:  7  5

Now, we create a "cartesian join" of all possible changes with the rows of each group:
# right join with count of changes within each group
tmp[tmp[, seq_len(max(rl) - 1L), by = .(id)], on = .(id), allow.cartesian = TRUE][
  # copy descending counts to rows before the switch
  rl == V1, PM := dn][
    # copy ascending counts to rows after the switch
    rl == V1 + 1L, PM := up][]

    id TF rn rl up dn V1 PM
 1:  0  0  2  1  1 -3  1 -3
 2:  0  0  4  1  2 -2  1 -2
 3:  0  0  5  1  3 -1  1 -1
 4:  0  1  6  2  1 -3  1  1
 5:  0  1  7  2  2 -2  1  2
 6:  0  1  8  2  3 -1  1  3
 7:  0  0 10  3  1 -2  1 NA
 8:  0  0 11  3  2 -1  1 NA
 9:  0  0  2  1  1 -3  2 NA
10:  0  0  4  1  2 -2  2 NA
11:  0  0  5  1  3 -1  2 NA
12:  0  1  6  2  1 -3  2 -3
13:  0  1  7  2  2 -2  2 -2
14:  0  1  8  2  3 -1  2 -1
15:  0  0 10  3  1 -2  2  1
16:  0  0 11  3  2 -1  2  2
17:  1  0 13  1  1 -3  1 -3
18:  1  0 14  1  2 -2  1 -2
19:  1  0 15  1  3 -1  1 -1
20:  1  1 16  2  1 -3  1  1
21:  1  1 17  2  2 -2  1  2
22:  1  1 18  2  3 -1  1  3
23:  7  0 21  1  1 -2  1 -2
24:  7  0 22  1  2 -1  1 -1
25:  7  1 23  2  1 -1  1  1
26:  7  0 24  3  1 -2  1 NA
27:  7  0 25  3  2 -1  1 NA
28:  7  1 26  4  1 -1  1 NA
29:  7  0 27  5  1 -1  1 NA
30:  7  1 28  6  1 -3  1 NA
31:  7  1 29  6  2 -2  1 NA
32:  7  1 30  6  3 -1  1 NA
33:  7  0 21  1  1 -2  2 NA
34:  7  0 22  1  2 -1  2 NA
35:  7  1 23  2  1 -1  2 -1
36:  7  0 24  3  1 -2  2  1
37:  7  0 25  3  2 -1  2  2
38:  7  1 26  4  1 -1  2 NA
39:  7  0 27  5  1 -1  2 NA
40:  7  1 28  6  1 -3  2 NA
41:  7  1 29  6  2 -2  2 NA
42:  7  1 30  6  3 -1  2 NA
43:  7  0 21  1  1 -2  3 NA
44:  7  0 22  1  2 -1  3 NA
45:  7  1 23  2  1 -1  3 NA
46:  7  0 24  3  1 -2  3 -2
47:  7  0 25  3  2 -1  3 -1
48:  7  1 26  4  1 -1  3  1
49:  7  0 27  5  1 -1  3 NA
50:  7  1 28  6  1 -3  3 NA
51:  7  1 29  6  2 -2  3 NA
52:  7  1 30  6  3 -1  3 NA
53:  7  0 21  1  1 -2  4 NA
54:  7  0 22  1  2 -1  4 NA
55:  7  1 23  2  1 -1  4 NA
56:  7  0 24  3  1 -2  4 NA
57:  7  0 25  3  2 -1  4 NA
58:  7  1 26  4  1 -1  4 -1
59:  7  0 27  5  1 -1  4  1
60:  7  1 28  6  1 -3  4 NA
61:  7  1 29  6  2 -2  4 NA
62:  7  1 30  6  3 -1  4 NA
63:  7  0 21  1  1 -2  5 NA
64:  7  0 22  1  2 -1  5 NA
65:  7  1 23  2  1 -1  5 NA
66:  7  0 24  3  1 -2  5 NA
67:  7  0 25  3  2 -1  5 NA
68:  7  1 26  4  1 -1  5 NA
69:  7  0 27  5  1 -1  5 -1
70:  7  1 28  6  1 -3  5  1
71:  7  1 29  6  2 -2  5  2
72:  7  1 30  6  3 -1  5  3
    id TF rn rl up dn V1 PM

Finally, the intermediate result is reshaped from long to wide format.
res <-
  # create a "cartesian join" of all possible changes with the rows of each group
  tmp[tmp[, seq_len(max(rl) - 1L), by = .(id)], on = .(id), allow.cartesian = TRUE][
    # copy descending counts to rows before the switch
    rl == V1, PM := dn][
      # copy ascending counts to rows after the switch
      rl == V1 + 1L, PM := up][
        # reshape from wide to long with the change count as new columns
        , dcast(.SD, id + TF + rn ~ sprintf("PM%02d", V1), value.var = "PM")][
          # join with original df to get NA rows back in
          df, on = .(rn, id, TF)][
            # omit helper column
            , -"rn"]

A: I think the cartesian join is unnecessary:
library(data.table)
tmp <- setDT(df)[, rn := .I][!is.na(TF)][, rl := rleid(TF), by = id][
                 , `:=`(up = 1:.N, down = -.N:-1), by = .(id, rl)][
                 , `:=`(last = (rl == max(rl)) * (-down)), by = id]

up   = dcast(tmp, rn ~ rl, value.var = 'up'  , fill = 0)
down = dcast(tmp, rn ~ rl, value.var = 'down', fill = 0)
last = dcast(tmp, rn ~ rl, value.var = 'last', fill = 0)

rl.max = tmp[, max(rl)]
res = down[, 2:rl.max] + up[, 3:(rl.max+1)] + last[, 2:rl.max]

res[res == 0] = NA
res[, rn := up$rn]

setcolorder(res[df, on='rn'][,-'rn'], c('id','TF', 1:(rl.max-1)))[]
#    id TF   1   2   3   4   5
# 1:  0 NA  NA  NA  NA  NA  NA
# 2:  0  0  -3  NA  NA  NA  NA
# 3:  0 NA  NA  NA  NA  NA  NA
# 4:  0  0  -2  NA  NA  NA  NA
# 5:  0  0  -1  NA  NA  NA  NA
# 6:  0  1   1  -3  NA  NA  NA
# 7:  0  1   2  -2  NA  NA  NA
# 8:  0  1   3  -1  NA  NA  NA
# 9:  0 NA  NA  NA  NA  NA  NA
#10:  0  0  NA   1  NA  NA  NA
#11:  0  0  NA   2  NA  NA  NA
#12:  1 NA  NA  NA  NA  NA  NA
#13:  1  0  -3  NA  NA  NA  NA
#14:  1  0  -2  NA  NA  NA  NA
#15:  1  0  -1  NA  NA  NA  NA
#16:  1  1   1  NA  NA  NA  NA
#17:  1  1   2  NA  NA  NA  NA
#18:  1  1   3  NA  NA  NA  NA
#19:  1 NA  NA  NA  NA  NA  NA
#20:  7 NA  NA  NA  NA  NA  NA
#21:  7  0  -2  NA  NA  NA  NA
#22:  7  0  -1  NA  NA  NA  NA
#23:  7  1   1  -1  NA  NA  NA
#24:  7  0  NA   1  -2  NA  NA
#25:  7  0  NA   2  -1  NA  NA
#26:  7  1  NA  NA   1  -1  NA
#27:  7  0  NA  NA  NA   1  -1
#28:  7  1  NA  NA  NA  NA   1
#29:  7  1  NA  NA  NA  NA   2
#30:  7  1  NA  NA  NA  NA   3
#    id TF   1   2   3   4   5


text:
Q: Multiple symbol definitions when using Visual Studio 2015 I have a autotools project that I've added a Visual Studio solution and project file for, and everything builds fine until I get to the linking stage. I get this output. An excerpt:
error LNK2005: "public: static bool const std::numeric_limits<unsigned short>::is_signed" already defined in abstract_syntax_graph.obj

Basically, a bunch of multiple definitions for C++ standard library stuff. I'm guessing there is something wrong with my project configuration in Visual Studio but I have no idea what would control whatever feature that is.

A: I faced similar errors when compiling a project under VS2015 using the /Za flag. Note that this worked fine under VS2013, but wouldn't build until I removed /Za from the VS2015 project.
This doesn't seem like an actual answer to me, I would have thought that there should be no issue disabling language extensions.


text:
Q: Managing/removing unnecessary scripts in live Kentico site We're building a Kentico 8.2 site using ASPX+portal model. Looking at the rendered HTML on my live site I can see a lot of unnecessary Javascript that Kentico has dumped into my page. What's more this is occurring at the top of my page at the top of the form element.
For example, it's rendering the ASP.NET __doPostBack JS function even though I'm not using any controls that require it. Other scripts are being added as WebResource.axd and ScriptResource.axd includes.
At a glance it would seem these scripts constitute the Microsoft AJAX framework used with UpdatePanel etc. My assumption is that they are there to add portal manager functionality when using the page in the Kentico UI. Presumably they are also used with certain built-in web parts.
However, I am only using custom web parts on my live site so all these scripts are doing nothing and are just slowing down my page and causing poor performance testing results.
I've tried hiding the <ajaxToolkit:ToolkitScriptManager /> and <cms:CMSPortalManager /> controls on my master page when rendering the live site, but this causes templates that have a <cms:CMSWebPartZone /> to break.
Does anyone know how to ensure this bloat is removed when not required? Or at the very least cause these scripts to be rendered at the end of the page so they don't interfere with performance too much?

A: Unfortunately, building sites within Kentico using ASPX and ASPX+Portal Pages will automatically generate additional markup such as __doPostBack, WebResource.axd and ScriptResource.axd.
I wouldn't recommend removing any of the default code in your Masterpage. This will cause things to break (as you've experienced).
However, having this markup in place shouldn't cause a massive issue in page performance. Understandably, this isn't ideal.
What I do to lessen the hit is the following:

*

*Disable the ViewState wherever possible. For example, either at Page Template or Webpart/User control level.

*Move the ViewState to the bottom of the page (in Kentico Settings), so the page is less "top heavy".

*Ensure you are caching everything you can. For example, site furniture used by your webparts and templates (images/js etc) at IIS level and at Kentico level using their API.

Reading this article from the Kentico documentation provides some more information in greater depth: Optimizing website performance
If you really want "full control" over the HTML rendered, Kentico does allow you to create templates using MVC. But this won't give you the flexibility to modify Page Templates by moving around web parts within the CMS Administration. I presume you have chosen the Portal Page approach for this very reason.
I hope this helps.

A: In addition to @sbhomra's great answer I have a few questions, suggestions and comments.
How many seconds or milliseconds are you talking about with performance?  If you think you'll gain a few milliseconds back, it's not worth your effort to try to rebuild all the functionality.  If you're talking a second or two, there about 15 different things you can change within settings and your code to gain it all back.  Think about how much code you're going to write, maintain and upgrade just to gain a second or less back?
The WebResource and SciptResource load resources that are compiled into libraries within the website.  So if someone created an external library and that library was loading an image that was compiled into it, you'd get that WebResource.axd reference on your site.  You'd have to physically remove those libraries from the Kentico instance.
Although I don't recommend it strictly because you lose so much functionality and have so much extra unnecessary code, MVC will give you the control you're looking for.


text:
Q: std::string::iterator to offset and back
*

*Can I set an iterator to position 5 in a string via some member or do I have to do a for(i = 0; i < 5; ++i) iterator++;?

*Given an Iterator, how can I convert that to a numeric offset in the string?

*If this is not possible with std::iterators can boost do it?

Iterators <-> Offsets

A: std::string iterators are random access iterators, which define the +operator. You can get a iterator to position 5 with begin(str) + 5. Offset can be computed via std::distance which uses -operator for random access iterators.

A: *

*you can use
iterator + 4

*try this: iterator - str.begin();

*iterator has operator + and - ; you can use these to convert between iterators and offsets.

A:
Can I set an iterator to position 5 in a string via some member

You can use std::advance
std::advance(iterator, 5);

or
iterator += 5;

Given an Iterator, how can I convert that to a numeric offset in the
  string?

You can use std::distance
std::distance(string.begin(), iterator);

or
iterator - string.begin()