How to prove that 3D lines given by their equations are noncoplanar

Question: $(R^3,(R^3,q_0),φ)$
picture for the $(R^3,(R^3,q_0),φ)$
$D_1: \ x_1-3=x_2/2=(x_3-1)/3 $
$D_2: \ x_1=x_2/2=x_3$
Q: Is it true $D_1,D_2$ are noncoplanar ? If yes, why ?
Hi! Has anybody an idea about a formula I should use or an advice on how to proceed ?
Comment: I don't understand your $x$ in $x-3=...$. Is it $x_3= $ ? Could you correct it ? Neither I understand what you mean with $(R^3,(R^3,q0),φ) $ ?
Comment: Please use [MathJax](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) to format your mathematical expressions.
Comment: Hint: What does the point-normal form of the equation of a plane about the relationship between the normal and every point on the plane?
Comment: I have bettered your presentation that will learn you some Latex basics ; I have also taken the liberty to provide a new title, in order that it reflects the content of your question.
Comment: Thx for the changes @JeanMarie , the x in x-3 should have been x1-3 , typo mistake, sorry.
Comment: I see I have been downvoted... for an exact answer...
Answer: First note that their direction vectors are different. It follows that they cannot be parallel. Then note that they never intersect.
The two facts above imply they are skew. Thus, they cannot be coplanar.
Comment: @JeanMarie It is not based on nothing. Please don't be ridiculous. That I don't explicitly show all the work in answering a question doesn't mean I don't know or have not done such work (which again here is trivial if you've tried to solve the resultant equations from assuming the lines intersect).
Comment: @JeanMarie PS. When you delete your comment on parallelism and leave only the other, you make the situation look differently to those who don't know the story from the beginning or who don't have enough reputation to see the true development of things. That's in fact *dishonest.* Also, trying to maintain a spurious claim is also dishonest when the fact is that the work here is easy to do. Also, not taking the hasty advice you'd officiously given me in your deleted comment yourself (after mistakenly discovering you were wrong) shows triply how actually dishonest you're being here, contrary...
Comment: @JeanMarie ...to what you would have us think by using the word *honestly* in a very unnecessary & showy manner. Also, it's very hypocritical of you to blame others for something and then do exactly that. Well, I don't use the word trivial for the funny reasons you cite (perhaps that's how *you* use that word, and are merely projecting); I use it when things are actually trivial, which they are here. But I see that it's all a projection of your mind. I really don't know what motivated your attempts to discredit my answer (which is obviously more helpful than yours), but not only you can talk!
Comment: "Then note they never intersect" ??? You haven't proved anything !
Comment: @JeanMarie *You haven't proved anything!* We don't typically do people's work for them here, especially if it's a trivial observation as seeing that those lines do not intersect. As for your claim that the lines are parallel. Well, I simply don't know what to say to that than to repeat that you note their direction vectors.
Comment: Two things : 1) I maintain that your affirmation "they never intersect" is based on nothing ; moreover, I dislike adjective "trivial" : it is sometimes used as an excuse for hiding misunderstanding and in all cases it appears very contemptuous to people to which it is addressed. 2) But I honestly recognize that I had made an error : the projection of two 3D lines can be parallel without the lines being parallel (which is the case here).
Answer: They cannot intersect because there cannot exist a common point $(x_1,x_2,x_3)$ to them ; indeed, it should verify the different relationships.
But the two first equalities are already incompatible : it is not possible that coordinates $(x_1,x_2)$ verify simultaneously :
$$x_1-3=x_2/2 \ \ \text{and} \ \ x_1=x_2/2\tag{1}$$
It would mean that $x_1-3=x_1$...
(Please note that we haven't used $x_3$ for obtaining the impossibility of a common point).


Playing youtube video using iframe in ionic 2 app

Question: In an Ionic 2 app, I am trying to embed one youtube video using iframe. The code looks like this:

However when I navigate to the page I am getting this error. I can't find a good answer how to fix this.

XMLHttpRequest cannot load https://googleads.g.doubleclick.net/pagead/id. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' header when the credentials flag is true. Origin 'https://www.youtube.com' is therefore not allowed access. The credentials mode of an XMLHttpRequest is controlled by the withCredentials attribute.

Not sure how to fix this. Any help/lead would be appreciated.
BTW, I am developing/testing in chrome browser developer tool.
Thanks,
Answer: You better add this to your config.xml:
<preference name="AllowInlineMediaPlayback" value="true"/>
<access origin="*" subdomains="true" />

Also make sure your android manifest has:
<application android:hardwareAccelerated="true" ...>

Answer: I have solved iframe problem by editing two html_sanitizer.js files. You ca find them under node_modules\@angular\platform-browser\src\security and node_modules\@angular\platform-browser\esm\src\security folders.
Open them and search for this line var BLOCK_ELEMENTS, insert iframe tag name and save. Now it should work, at least it works for me.
Comment: Thanks @DroidX. I will try this out.
Answer: Try using enablejsapi=1 inside the source.


EntityFieldQuery - ordering by multiplication of two fields

Question: I need to order my news by their importance value (1, 2 or 3) which is in the field field_importance and the date they are published. So I would need to order my news by this calculation: created * field_importance and I haven't figured out a way to do it with EntityFieldQuery. If someone knows a way to do it without EntityFieldQuery, that's equally good. This is my code so far:

$query->entityCondition('entity_type', 'node')
      ->propertyCondition('status', 1)
      ->propertyCondition('type', array('news'))
      ->propertyOrderBy('created', 'DESC');
Answer: If you don't have to pull in a whole bunch of linked entity stuff, just run a regular db_query() joining your "importance" field table to your node table.
<code>$query = "SELECT nid, (created * field_importance_value) AS weight
FROM node n
JOIN field_data_field_importance f ON f.entity_id = n.nid
WHERE type = 'news'
AND status = 1
ORDER BY weight DESC";
$result = db_query($query);
// Add foreach loop here...
</code>
I'm just guessing the importance table name and field name from your OP.


Can $f(x)=\int_{0}^{\infty}t^{x^2+1}e^{-2t}dt$ be written as a power series in a neighbourhood of zero?

Question: Let $f(x)=\int_{0}^{\infty}t^{x^2+1}e^{-2t}dt$. Can $f(x)$ be written as a power series in a neighbourhood of zero? In this case, what would its convergence radius be?
Trying to solve this problem I have realized that the function f is similar to Euler's Gamma function, which can be written as a series of powers, so I think the answer should be yes. However I am not able to rigorously prove it.
Comment: Try proving it's homomorphic (eg complex differentiable) in some disc around $0$.
Answer: The answer is yes. In particular, note that with a substitution we can rewrite
$$
f(x) = 2^{-(x^2 + 1)} \int_0^\infty t^{x^2 + 1}e^{-t}\,dt = 2^{-(x^2 + 1)}\Gamma(x^2 + 2).
$$


cftextarea controls not showing when loaded with jQuery ajax .get()

Question: I've got a CFTEXTAREA field, which behaves normally when viewed on its own, but when its loaded via jQuery get() method, the controls do not appear.
ie
The cftextarea is on a product detail pane.
ON the left side of the page is a list of products to edit.
clicking on one on the  elements, loads the product detail pane via ajax and jquery (simulating an old school href)
the content is loading in, but the toolbar does not appear.
hitting the page on its own, the toolbar shows.
here is the jquery (working fine)
$("#productList li").click(function(event) {
$.get(
    'editProduct.cfm',
    {id:$(this).attr('id')},
    function (response) {
        $('#productDetail').html(response);
    }
);
});

and here is the CFTEXTAREA call: (working fine when not loaded via jquery/ajax)
<cftextarea enabled="yes" name="nutrition" rows="5" cols="25" richText="yes"  toolbar="Basic" html="yes" >#DESCRIPTION#  </cftextarea>

It'd be nice to be able to use cftextarea on forms loaded in via ajax.
is it possble?
Answer: All you need to do is include the <cfajaximport> tag on the page that contains your jQuery functionality. ^__^
Comment: jcaito, surround inline code with backticks (**`**) in order to prevent tags being considered HTML.  For other formatting functionality, see the [Markdown Help](http://stackoverflow.com/editing-help) page.


What does "if condition" mean, when the condition is not a statement?

Question: I'm learning about functions at the moment, and this one came up as an example:
def a(x, y, z):
     if x:
         return y
     else:
         return z

I'm not exactly sure what if x actually means, though. x is just a parameter, not a statement, so how can it be true or false?
Comment: http://stackoverflow.com/questions/20420934/python-booleans-if-x-vs-if-x-true-vs-if-x-is-true
Comment: The condition is *never* a statement. A statement is an action such as `y = 0`. The condition is an *expression*, e.g. `len(my_list) > 1`, which has some value. `x` is also an expression.
Answer: It checks if x is "truthy", which means that it shouldn't be :

None
False
Zero
Empty

As an example :
if 1 and True and "string" and ["list"] and {'key' : 'value'} and\
    not None and not 0 and not False and not "" and not [] and not {}:
  print "I understood truthiness!"
# => I understood truthiness!

Comment: @SteveSmith: Because `True`, when evaluated as an integer, means `1`, and `1` is not the same as `2`. An operation between an integer and a logical value (Boolean) is usually treated as an operation between integers. To convert an integer such as `2` to a logical value, use `bool(2)`, which evaluates to `True`, while `bool(0)` is `False`.
Comment: 2 is not `True`, it is only "truthy" :  `bool(2)==True`
Comment: Why, then, if I type `2 == True`, does the console output `False`?
Answer: In python, everything has a truth value associated with it. For example, all numbers except 0 are truthy (evaluate to True in a conditional statement), and 0 is falsey (evaluates to False in a conditional statement). This is because of the __bool__ method in the each class.
For example:
In [140]: def f(x,y,z):
   .....:     if x:
   .....:         return y+z
   .....:     else:
   .....:         return y-z
   .....:

In [141]: f(True, 3, 4)
Out[141]: 7

In [142]: f(False, 3, 4)
Out[142]: -1

In [143]: f(1, 3, 4)
Out[143]: 7

In [144]: f(2, 3, 4)
Out[144]: 7

In [145]: f(863, 3, 4)
Out[145]: 7

In [146]: f(-24, 3, 4)
Out[146]: 7

In [147]: f(0, 3, 4)
Out[147]: -1

Similarly, empty collections (lists, sets, dictionaries, strings, tuples, etc) are falsey, while non-empty collections are truthy.
Answer: If only a variable is given as the condition in an if statement, the condition will be evaluated by Python's standard truth testing procedure. You can try the method out for yourself in the console with the bool method, which maps directly to it. Here are some examples:
>>> bool(1)
True
>>> bool(0)
False
>>> bool([])
False
>>> bool([1,2,3])
True

Answer: In Python, any non-zero value, non-empty string/list/set, etc is considered as True where as None, empty-string/list/set etc and 0 are considered as False by if. This evalution is done by the bool(). Below is the illustration.
my_list = ['a', 100, None, '', 0, {}, {'a': 1}, [], ['a']]
for item in my_list:   # Iterate over each value and checks the condition
    if item:
        print item, ": True", ", Bool value: ", bool(item)
    else:
        print item, ": False", ", Bool value: ", bool(item)

which prints (explicitly formatted for readability):
a :        True ,       Bool value:  True
100 :      True ,       Bool value:  True
None :     False ,      Bool value:  False
 :         False ,      Bool value:  False
0 :        False ,      Bool value:  False
{} :       False ,      Bool value:  False
{'a': 1} : True ,       Bool value:  True
[] :       False ,      Bool value:  False
['a'] :    True ,       Bool value:  True

As you see, execution of if is mapped to the bool() value.
Comment: also empty list, set, dict...


How can I solve Flutter navigation BuilderContext subtype error?

Question:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:flutter_auths/pages/searchservice.dart';
import 'package:flutter_auths/pages/tasks.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var queryResultSet = [];
  var tempSearchStore = [];

  initiateSearch(value) {
    if (value.length == 0) {
      setState(() {
        queryResultSet = [];
        tempSearchStore = [];
      });
    }

    var capitalizedValue =
        value.substring(0, 1).toUpperCase() + value.substring(1);

    if (queryResultSet.length == 0 && value.length == 1) {
      SearchService().searchByName(value).then((QuerySnapshot docs) {
        for (int i = 0; i < docs.documents.length; ++i) {
          queryResultSet.add(docs.documents[i].data);
        }
      });
    } else {
      tempSearchStore = [];
      queryResultSet.forEach((element) {
        if (element['Username'].startsWith(capitalizedValue)) {
          setState(() {
            tempSearchStore.add(element);
          });
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
          title: Text('Firestore search'),
        ),
        body: ListView(children: <Widget>[
          Padding(
            padding: const EdgeInsets.all(10.0),
            child: TextField(
              onChanged: (val) {
                initiateSearch(val);
              },
              decoration: InputDecoration(
                  prefixIcon: IconButton(
                    color: Colors.black,
                    icon: Icon(Icons.arrow_back),
                    iconSize: 20.0,
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                  contentPadding: EdgeInsets.only(left: 25.0),
                  hintText: 'Search by name',
                  border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(4.0))),
            ),
          ),
          SizedBox(height: 10.0),
          GridView.count(
              padding: EdgeInsets.only(left: 10.0, right: 10.0),
              crossAxisCount: 2,
              crossAxisSpacing: 4.0,
              mainAxisSpacing: 4.0,
              primary: false,
              shrinkWrap: true,
              children: tempSearchStore.map((element) {
                return buildResultCard(element);
              }).toList())
        ]));
  }
}

Widget buildResultCard(data) {
  return Card(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10.0)),
      elevation: 2.0,
      child: Container(
          child: Column(
              children: <Widget> [ Text(data['Username'],
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black,
                  fontSize: 20.0,
                ),
              ),
                RaisedButton(
                  onPressed: () {
                    Navigator.push(
                      data,
                      MaterialPageRoute(builder: (data) => ProfilePage()),
                    );
                  },
                  child: const Text('asd', style: TextStyle(fontSize: 12)),
                ),
              ]
          )
      )
  );
}

Here I search for a user from database then it shows me the results in cards, I added a button and by clicking on it I want to navigate the page to another page but the following error occures.
this is the error and the app
So I want to click on specific user's button and redirect the page to that user's profile. How can I do that?
Answer: You are getting this error because instead of passing buildContext you are passing data.
So your error gets removed if you change you code from this
Navigator.push(
   data,
   MaterialPageRoute(builder: (data) => ProfilePage()),
);

to
Navigator.push(
   context,
   MaterialPageRoute(builder: (context) => ProfilePage(username: data['Username']))
);

This is how you should pass the data to the Profile Page.
Also
Widget buildResultCard(data)

be changed to
Widget buildResultCard(context, data)

and
buildResultCard(element);

to
buildResultCard(context, element);

Comment: It's not working. When I change data to context it says it's undefined.
Comment: Alright I changed `Widget buildResultCard(data)` to `Widget buildResultCard(BuildContext context, data)` but this way how can I use buildResultCard in GridView.count? What is the second argument? It's working when I use return `buildResultCard(context,element)` but I got the error: Duplicate GlobalKey detected in widget tree.
Comment: I have updated the answer. If you're getting a Duplicate GlobalKey Error, Please try to restart your IDE (Android Studio/VSCode/XCode). If it still posses error, refer to https://stackoverflow.com/questions/49371221/duplicate-globalkey-detected-in-widget-tree
Comment: thank you, it worked. How can I pass that user's uid instead of it's name?
Answer: First, you need to Navigate to that page with data like
Navigator.push(
   context,
   MaterialPageRoute(builder: (context) => ProfilePage(profileData: data))
);

then you need to receive that data
class ProfilePage extends StatefulWidget {
  var profileData;

  ProfilePage({this.profileData});

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text(widget.profileData['username']),
      ),
    );
  }
}

You can pass and receive data in another way
Navigator.push(
    context,
    MaterialPageRoute(builder: (context) => ProfilePage(),settings: RouteSettings(arguments: data))
);

then
    class ProfilePage extends StatefulWidget {

  @override
  _ProfilePageState createState() => _ProfilePageState();
}

class _ProfilePageState extends State<ProfilePage> {
  var profileData;

  @override
  Widget build(BuildContext context) {
    profileData=ModalRoute.of(context).settings.arguments;
    return Scaffold(
      body: Center(
        child: Text(profileData['username']),
      ),
    );
  }
}

Comment: It's not working. When I change data to context it says it's undefined.
Comment: Alright I changed `Widget buildResultCard(data)` to `Widget buildResultCard(BuildContext context, data)` but this way how can I use buildResultCard in GridView.count? What is the second argument? It's working when I use return `buildResultCard(context,element)` but I got the error: Duplicate GlobalKey detected in widget tree.


How Does One Find A Basis For The Orthogonal Complement of W given W?

Question: I've been doing some work in Linear Algebra for my course at school. I just want to be clear about how to find the orthogonal complement of a subspace. The basis for the subspace, W, is shown below, composed of 3 vectors:$$W = \begin{Bmatrix}\begin{bmatrix}1\\2\\3\\4 \end{bmatrix} \begin{bmatrix}-3\\4\\2\\6\end{bmatrix} \begin{bmatrix}2\\-2\\3\\5\end{bmatrix}\end{Bmatrix}$$
I would like to know if one simply sets $W*W^T$$=0$ and takes the columns of the resulting matrix as the basis of the orthogonal complement of W, provided that row reduction has been performed to make sure the remaining columns are linearly independent.
Please note that I have created an arbitrary set of vectors above that are not orthogonal, and so if they need to be for $W*W^T$$=0$ please point that out. Thank you.
Answer: I'd rather put the matrix in this way, here I just give a very simple example, you can solve your matrix in the same way:
$$W = \begin{bmatrix}
\begin{matrix}1\\0\\0 \end{matrix}
\begin{matrix}0\\1\\0\end{matrix}
\begin{matrix}0\\0\\1\end{matrix}
\begin{matrix}1\\1\\1\end{matrix}\end{bmatrix} $$
Then find the null space of W by solving
$$Wx = 0$$
You will get the basis for the nullspace:
$$v = \begin{bmatrix}
\begin{matrix}-1\\-1\\-1\\1 \end{matrix} \end{bmatrix}$$
the null space is spared by v,
$$null(W) = span(v)$$
you can easily find subspace spanned by W is orthogonal to subspace spanned by v, because every basis (each row of W) is orthogonal to v.
Answer: Think of a system of linear equations you want to solve that will say your vector $\mathbf x$ is orthogonal to $W$.
Comment: I think I now better understand. **x** being orthogonal to _W_, as I just reviewed, means the inner product of **x** with all vectors in a set spanning _W_ must be zero. So doing a little rearranging, I found that the transpose of W times **x** must also equal zero. So is it incorrect for me to say W*W^T = 0 when Row W = perp(Nul W^T)?
Comment: EDIT: In above comment, I meant to ask "Therefore is it incorrect for one to say W*W^T = 0 when Col W = perp(Nul W^T)?" (NOT Row W)
Comment: Yes, $\text{Col}(A)^\perp = N(A^T)$. Your $W$ is a subspace, not a matrix, so what you wrote doesn't quite make sense.
Comment: No, you forget that a matrix can be comprised of vectors, and the subspace above is a basis of vectors, which can, in turn, be considered a matrix. I'm afraid you haven't really answered my question, which is specifically leading to "how can one find a vector perpendicular to a set of vectors?" And no, I am not looking for a simple answer such as "come up with a vector with the same number of elements as the vectors in the set whose inner product with each of the set's vectors is zero". I'm afraid it has to be more elegant than that.


Display heartbeat sensor's readings from python program in a Kivy label

Question: I'm trying to display the values obtained from my heartbeat sensor in my Kivy App. I've tried using the data extraction method applied on the other sensors but it's not working for this sensor as it doesn't contain any functions.
I've tried multiple different approaches but they all haven't returned the desired output. Can someone please have a look at the sensor code and suggest some method to display the output in my kivy app.
Heartbeatsensot.py

import time
# Import the ADS1x15 module.
import Adafruit_ADS1x15

if __name__ == '__main__':

    adc = Adafruit_ADS1x15.ADS1015()
    # initialization
    GAIN = 2/3
    curState = 0
    thresh = 525  # mid point in the waveform
    P = 512
    T = 512
    stateChanged = 0
    sampleCounter = 0
    lastBeatTime = 0
    firstBeat = True
    secondBeat = False
    Pulse = False
    IBI = 600
    rate = [0]*10
    amp = 100

    lastTime = int(time.time()*1000)

    # Main loop. use Ctrl-c to stop the code
    while True:
        # read from the ADC
        Signal = adc.read_adc(0, gain=GAIN)   #TODO: Select the correct ADC channel. I have selected A0 here
        curTime = int(time.time()*1000)

        sampleCounter += curTime - lastTime;      #                   # keep track of the time in mS with this variable
        lastTime = curTime
        N = sampleCounter - lastBeatTime;     #  # monitor the time since the last beat to avoid noise
        #print N, Signal, curTime, sampleCounter, lastBeatTime

        ##  find the peak and trough of the pulse wave
        if Signal < thresh and N > (IBI/5.0)*3.0 :  #       # avoid dichrotic noise by waiting 3/5 of last IBI
            if Signal < T :                        # T is the trough
              T = Signal;                         # keep track of lowest point in pulse wave

        if Signal > thresh and  Signal > P:           # thresh condition helps avoid noise
            P = Signal;                             # P is the peak
                                                # keep track of highest point in pulse wave

          #  NOW IT'S TIME TO LOOK FOR THE HEART BEAT
          # signal surges up in value every time there is a pulse
        if N > 250 :                                   # avoid high frequency noise
            if  (Signal > thresh) and  (Pulse == False) and  (N > (IBI/5.0)*3.0)  :
              Pulse = True;                               # set the Pulse flag when we think there is a pulse
              IBI = sampleCounter - lastBeatTime;         # measure time between beats in mS
              lastBeatTime = sampleCounter;               # keep track of time for next pulse

              if secondBeat :                        # if this is the second beat, if secondBeat == TRUE
                secondBeat = False;                  # clear secondBeat flag
                for i in range(0,10):             # seed the running total to get a realisitic BPM at startup
                  rate[i] = IBI;

              if firstBeat :                        # if it's the first time we found a beat, if firstBeat == TRUE
                firstBeat = False;                   # clear firstBeat flag
                secondBeat = True;                   # set the second beat flag
                continue                              # IBI value is unreliable so discard it

              # keep a running total of the last 10 IBI values
              runningTotal = 0;                  # clear the runningTotal variable

              for i in range(0,9):                # shift data in the rate array
                rate[i] = rate[i+1];                  # and drop the oldest IBI value
                runningTotal += rate[i];              # add up the 9 oldest IBI values

              rate[9] = IBI;                          # add the latest IBI to the rate array
              runningTotal += rate[9];                # add the latest IBI to runningTotal
              runningTotal /= 10;                     # average the last 10 IBI values
              BPM = 60000/runningTotal;               # how many beats can fit into a minute? that's BPM!
              print ('BPM: {}'.format(BPM))

        if Signal < thresh and Pulse == True :   # when the values are going down, the beat is over
            Pulse = False;                         # reset the Pulse flag so we can do it again
            amp = P - T;                           # get amplitude of the pulse wave
            thresh = amp/2 + T;                    # set thresh at 50% of the amplitude
            P = thresh;                            # reset these for next time
            T = thresh;

        if N > 2500 :                          # if 2.5 seconds go by without a beat
            thresh = 512;                          # set thresh default
            P = 512;                               # set P default
            T = 512;                               # set T default
            lastBeatTime = sampleCounter;          # bring the lastBeatTime up to date
            firstBeat = True;                      # set these to avoid noise
            secondBeat = False;                    # when we get the heartbeat back
            print ("no beats found")

        time.sleep(0.005)

** the kivy app that I'm trying to add the readings to**
another.py file
from kivy.app import App
from kivy.uix.screenmanager import ScreenManager,Screen
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.boxlayout import BoxLayout
from kivy.clock import Clock
from kivy.uix.button import Button
from kivy.uix.label import Label
from kivy.lang import Builder

class MainScreen(Screen):
   pass

class ScreenThermo(Screen):

    def __init__(self,**kwargs):
        super(ScreenThermo, self).__init__(**kwargs)
        Clock.schedule_interval(self.displayHR, 10)

    def displayHR(self,dt):
        heartbeat = 'BPM: {}'.format(BPM)
        pulse = heartbeat
        self.manager.screen_thermo.ids.TempLabel.text = str(pulse)

    def on_enter(self, *args):
        self.__init__()
        pass

class ScreenManagement(ScreenManager):
    pass

presentation = Builder.load_file("heartk.kv")

class MenuApp(App):
    def build(self):
       return presentation

if __name__ == '__main__':
    MenuApp().run()

.kv file
ScreenManagement:
    id: screen_manager
    screen_thermo: screen_thermo
    MainScreen:
    ScreenThermo:
        id: screen_thermo
        name: 'thermo'
        manager: screen_manager

<MainScreen>:
    name: "main"
    Label:
        text: "Welcome"
        font_size: 60
        halign: 'center'
        valign: 'middle'
        pos_hint: {'x': .01, 'y': .05}
        on_touch_down: app.root.current = "thermo"

<ScreenThermo>:
    Label:
        text: " Pulse rate"
        font_size: 50
        pos: (35, 100)

    Label:
        id: TempLabel
        font_size: 60
        halign: 'center'
        valign: 'middle'

Comment: I'm not clear what your problem is - do you know how to read your sensor? What is preventing you from using the values you get in the Kivy app?
Comment: Yes, I can read the sensor. The `print ('BPM: {}'.format(BPM))` part in the **heartbeatsensot.py** displays the pulse rate in python program. However, what I can't understand is that how to display it in the kivy app that I've created in **another.py**.
Comment: What's preventing me from using the values i get in the Kivy app:  I made a kivy app to display and continuously update the values from the sensors. It works fine with the other sensors but it's not working with the pulse rate sensor and I fail to understand what I'm doing wrong. The only difference between the other sensors and the heartbeat sensor is that I usually extract the value using a python function in others but in this case, I'm doing it by simply printing the values.
Answer: I think you can accomplish what you want with a few minor modifications. First add a StringProperty to your ScreenThermo class, and in the on_enter() method start a thread to run your Heartbeatsensot code as:
from Heartbeatsensot import hearbeatsensot

class ScreenThermo(Screen):
    BPM_string = StringProperty('BPM: Not Detected')

    def on_enter(self, *args):
        Thread(target=hearbeatsensot, args=(self,)).start()

And in your kv file, add a reference to the new StringProperty:
<ScreenThermo>:
    Label:
        text: " Pulse rate"
        font_size: 50
        pos: (35, 100)

    Label:
        id: TempLabel
        text: root.BPM_string  # references new StringProperty
        font_size: 60
        halign: 'center'
        valign: 'middle'

Now you only need to put whatever you want to display in the TempLabel into the BPM_string property. To do that, change Heartbeatsensot.py to define a method that can be used in a Thread. Simply replace the if __name__ == '__main__': in that file to def hearbeatsensot(screenThermo): like this:
import time
# Import the ADS1x15 module.
import Adafruit_ADS1x15

def hearbeatsensot(screenThermo):

    adc = Adafruit_ADS1x15.ADS1015()
    # initialization
    GAIN = 2/3
    .
    .
    .
    screenThermo.BPM_string = 'BPM: 65'
    .
    .
    .

Then, within that method just use somethink like screenThermo.BPM_string = 'BPM: 65' (or whatever you want to set it to). The reference to BPM_string in the kv file will automatically set up a binding to update the TempLabel whenever BPM_string is modified.
Comment: Thankyou for taking the time to help me out. I've made the modifications you suggested. However, it returns the following error now:

`TypeError: 'NoneType' object is not subscriptable`
Comment: ```Traceback (most recent call last):
   File "heartsensor.py", line 140, in
     presentation = Builder.load_file("heartk.kv")
   File "/usr/local/lib/python3.5/dist-packages/kivy/lang/builder.py", line 301, in load_file
     return self.load_string(data, **kwargs)
      File "/usr/local/lib/python3.5/dist-packages/kivy/lang/builder.py", line 368, in load_string
     parser = Parser(content=string, filename=fn)
   File "/usr/local/lib/python3.5/dist-packages/kivy/lang/parser.py", line 392, in __init__
     self.parse(content)```
Comment: ```File "/usr/local/lib/python3.5/dist-packages/kivy/lang/parser.py", line 501, in parse
     objects, remaining_lines = self.parse_level(0, lines)
   File "/usr/local/lib/python3.5/dist-packages/kivy/lang/parser.py", line 664, in parse_level
     if current_property[:3] == 'on_':
 TypeError: 'NoneType' object is not subscriptable```
Comment: Looks like it is complaining about something in your `kv` file.
Comment: With a few minor changes, I was able to make this to work. Thanks so much for helping!


SQL SERVER PROBLEMA COLLATION

Question: Alguém pode ajudar com esse Union de tabelas com collates, procurei no Google e não entendi muito bem.

erro :   Cannot resolve the collation conflict between
  "SQL_Latin1_General_CP850_CI_AI" and "SQL_Latin1_General_CP850_CI_AS"
  in the UNION operation.

Select MAX(SERV_DH_ULTIMAATU) AS RECEBIMENTO ,EMPR_DS_EMPRESA, DATEDIFF(MI, MAX(SERV_DH_ULTIMAEXEC), GETDATE()) AS PERIODO
                             from  A1.DBO.CS_CDTB_SERVICO_SERV SERV (NOLOCK)
                             INNER JOIN   A1.DBO.CS_CDTB_EMPRESA_EMPR EMPR ON
                             EMPR.ID_EMPR_CD_EMPRESA = SERV.ID_EMPR_CD_EMPRESA
                             where SERV_DS_SERVICO LIKE '%AGENTE DO CLASSIFICADOR DE EMAIL%'
                             AND EMPR.EMPR_IN_INATIVO = 'N'AND EMPR.EMPR_DS_EMPRESA NOT LIKE '%(NÃO USAR)%'
                             GROUP BY EMPR_DS_EMPRESA union

                               Select MAX(SERV_DH_ULTIMAATU) AS RECEBIMENTO ,EMPR_DS_EMPRESA, DATEDIFF(MI, MAX(SERV_DH_ULTIMAEXEC), GETDATE()) AS PERIODO
                             from  A2.DBO.CS_CDTB_SERVICO_SERV SERV (NOLOCK)
                             INNER JOIN   A2.DBO.CS_CDTB_EMPRESA_EMPR EMPR ON
                             EMPR.ID_EMPR_CD_EMPRESA = SERV.ID_EMPR_CD_EMPRESA
                             where SERV_DS_SERVICO LIKE '%AGENTE DO CLASSIFICADOR DE EMAIL%'
                             AND EMPR.EMPR_IN_INATIVO = 'N'AND EMPR.EMPR_DS_EMPRESA NOT LIKE '%(NÃO USAR)%'
                             GROUP BY EMPR_DS_EMPRESA

Answer: Brian, provavelmente os dois bancos de dados estão em COLLATIONS diferentes.
Um está em SQL_Latin1_General_CP850_CI_AI e outro está em SQL_Latin1_General_CP850_CI_AS (note os finais AI e AS que os diferencia no erro apresentado!).
Deste modo, ao realizar o UNION, o SQLServer não consegue unir tipos de Collations diferentes.
Solução 1
Altere o Collation de um dos bancos de dados para ser igual ao do outro.
Solução 2
Utilize COLLATE Latin1_General_CI_AS após cada campo do select para converte-los. Assim o UNION seria capaz de unir os campos. Deste modo:
SELECT
     EMPR_DS_EMPRESA COLLATE Latin1_General_CI_AS,
     CAMPO_2 COLLATE Latin1_General_CI_AS
FROM A2.DBO.CS_CDTB_SERVICO_SERV

Referência: https://stackoverflow.com/questions/25260659/collation-conflict-in-sql-union-all-query
Comment: Deu certo, obrigado

SQL SERVER PROBLEMA COLLATION


Determining orbits and stabilisers

Question: It is given that $$(x,y) \cdot \left [\begin{array}{cc} a & b \\
b & a \end{array}\right] =(ax+by,bx+ay)$$
defines an action on the group
$$G=\left\{\left [\begin{array}{cc} a & b \\
b & a \end{array}\right]:a^2 \neq b^2\right\}$$
1) Determine the orbits
2) Determine the stabilisers of (0,0),(1,0),(1,1)
How do I do this?
Comment: Orbits.  You have have essentially written the answer down,   For a fixed $(x,y),$   you generate new points $(x,y)  \cdot A,$ where $A \in G.$   Can you reach any point $(u,v) \in \mathbb{R}^2$ using some particular $A.$    For the stabilisers, use the definition. e.g.  find all $A\in G$ such that $(1,1)A=(1,1).$   This gives you equations $(a+b,a+b)=(1,1).$   You should work out what subgroup of $G$ this generates.
Comment: So you just use the definitions to get $(1,0)=(a,b)$ and $(0,0)=(0,0)$ But in my notes I have also (1,-1). Why? Also why do we need the subgroups?
Answer: Given a (right) group action by $G$ on a set $S,$ and a point $x\in S,$ the Stabilizer at $x$ is  is the subgroup of $G$ defined as follows:  $$G_x = \{g \in G \ : \ xg=x\}.$$
For your group action, with $A= \left[\begin{array}{cc} a& b \\ b & a \end{array}\right]\in G,$ you have $(1,0)A = (1,0)$ if and only if $a-1=0$ and $b=0.$  Thus
$$
G_{(1,0)} = \left\{ \left[\begin{array}{cc} 1 & 0 \\ 0 & 1 \end{array} \right] \right\}.
$$
Similarly, we have $(1,1)A=(1,1)$ if and only if $a+b=1.$  Therefore,
$$
G_{(1,1)} =  \left\{ \left[\begin{array}{cc} a & 1-a \\ 1-a & a \end{array} \right]  \ : \ a \neq 1 \right\}.
$$
You should verify for yourself that $G_{(0,0)}= G.$

Determining orbits and stabilisers


D7 checkbox default checked

Question: Shouldn't be hard, but it is - how do you make a CCK checkbox default checked?!?
I've tried various responses in the PHP Default Value box:
<code>return array(0 => array('#default_value' => 1));
return array(0 => array('default_value' => 1));
return array(0 => array(1));
return array(0 => 1));
return array(1);
return 1;
</code>
I'm sure you get the point. None of these work?!
Comment: Can you paste here the whole form function or whatever you use here?
Answer: I'm a bit confused where you're entering the code above? If I want a checkbox to default to checked then in the UI you can specify this. See screen shot where I've added a field with a label "Shippable".
Comment: Weird, that spot had a blank check box on mine... maybe it has to do with how I'm setting the values.
Comment: @npc It has a a blank value when you're adding it for the first time because the "field label" hasn't been saved yet. Once you go back to edit it after that first save it has the value so it can populate the checkbox label with it
Comment: More correctly, it's blank if you haven't specified anything for the "On" value or used the field label instead of the "On" value as label.

D7 checkbox default checked


SpriteKit location of SKSpriteNode on screen

Question: I've got a really simple problem, but I've not been able to find a solution...how do I get the screen coordinates of a SKSpriteNode, given that its position property is CGPoint.zero but that its a number of children down from the SKScene and each parent will have applied some translation?
Answer: you'll want to use convert(_ point: CGPoint, to node: SKNode) and convert(_ point: CGPoint, from node: SKNode)
you'll probably have to use both
example
let nestedSpritePos = convert(convert(nestedSpritePos.position, from: nestedSpritePos.parent!), to: self)

assuming self is the scene. You may have to play around with those but they definitely are what you are looking for.
Comment: No need to do it twice. `scene.convert(position,from:node)`. Will take you from node to scene.  `node1.convert(position,from:node2)` will take your position from node2 go up to scene, then down to node1
Comment: great to know! Honestly I find the "convert" funcs the single most poorly written func for description in the Apple docs


Value of a zero sum game

Question: I've been looking some around on the net for some info on zero-sum games,
But I don't think I fully understand the principle;
If we consider the (simple) matrix: $$\begin{pmatrix}\pi&0 \\ 0&e \end{pmatrix}$$
How can I determine the value of this zero-sum game?
Is this the possible correct answer regarding this example?
Let us just call first row R1, first column C1 and so on.
Then, the expectation for R1 is $\pi \cdot p_1$.
Then, the expectation for R2 is $e \cdot p_2$.
Now I have to maximize: $min(E(R1),E(R2))$, which implies $p_1=e:p_2=\pi$.
So we see $p_1=0.464$ and $p_2=0.536$
We can do the same for C1,C2, which will give the same numbers.
Therefore I think the value of this game is $0.464 \cdot \pi=1.457= 0.536 \cdot e$
Is this ok?
Thanks for checking!
Answer: We will denote the mixed strategies of the first player by $(p, 1- p)$ and of the second player by $(q, 1 - q)$ and the payoff function determined by your matrix by $g$.
For the first player, we have to calculate
$$ V = \max_{0 \leq p \leq 1} \min_{0 \leq q \leq 1} g((p,1-p),(q,1-q)) = \max_{0 \leq p \leq 1} \min_{q \in \{0,1\}} g((p,1-p),(q,1-q)). $$
That is,
$$ V = \max_{0 \leq p \leq 1} \min \{ p\pi, (1-p)e \}. $$
Plotting it, we have

So we see that the max-min is attained only at the intersection of $p\pi$ and $(1-p)e$, that is, when $p = \frac{e}{\pi + e} \approx 0.464$ and the value of the game is the payment at $(p,1-p)$ so $V = \frac{\pi e}{\pi + e} \approx 1.457$.
Comment: @amorfati: There is no error. I've only calculated $\max \min$. It is equal to $\min \max$ but there is no need to treat it since this is guaranteed...
Comment: Yeah this is a much better way to denote the answer :) ty for your time!
Comment: You're welcome.
Comment: @levap: You've got an error in the equation: $\max \min=\min \max$, instead of $\max \min = \max \min$.
Comment: You are right. I misunderstood what you actually did. Thank you for the response.
Comment: I have a doubt. For two player zero sum game if security level of player 1 is s1 and player 2 is s2, does that mean s1+s2 = 0?  Or s1=s2? Your answer is making me think that
Comment: If by security level for both players you mean $s_1 = \max_{x \in \Delta_m} \min_{y \in \Delta_n} u_1(x,y)$ and $s_2 = \max_{y \in \Delta_m} \min_{x \in \Delta_n} u_2(x,y)$ (where $u_i(x,y)$ is the expected payoff to player $i$ where player $1$ plays the mixed strategy $x$ and player $2$ plays the mixed strategy $y$ and $u_2 = -u_1$) then yes, $s_1 = -s_2$. This is the content of the famous minmax theorem.

Value of a zero sum game


TypedQuery error "Not all named parameters have been set" when they had. JPA / Hibernate

Question: I'm trying to build and execute a dynamic query that looks like this:
String query = "SELECT e FROM Employee e WHERE (1=1) AND (UPPER(e.lastName) LIKE :lastName)";

final TypedQuery<Employee> dbQuery = entityManager.createQuery(query, Employee.class);
dbQuery.setParameter("lastName", "%" + value.toString().toUpperCase() + "%"));

But it fails with this error:
org.hibernate.QueryException: Not all named parameters have been set: [lastName]

Most interesting is that in debug mod i can see that dbQuery has a bind for "lastName" parameter and contains the specified value inside its "parameterRegistrations" field. So i have no idea.
Alternative with using positional parameters like
 dbQuery.setParameter(1, "%" + value.toString().toUpperCase() + "%")); is not my case, so pls lets do not discuss it.
This question is similar to mine but it's still unanswered.
Comment: Which Hibernate version are you using? Are you sure that there is no typo(upper/lower case) in the parameter name of your real query?
Comment: can you confirm the exception is thrown when you invoke the instruction dbQuery.getResultList()?
Answer: Sorry guys! It was my inattention. A super strange and legacy code was there, which was creating a new instance of TypedQuery much later based on my query, but without parameters. I didn't expect it. That was the reason.


Looking for a function to define a specific curve, given a single parameter

Question: The curve

passes through (0,0) and (1,1),
has an area under the curve from x=0 to x=1 that is equal to the parameter (such that a parameter of .5 returns the line y=x),
has a monotonic second derivative evaluated along the curve, and
is axisymmetric around y=1-x.

It would serve the same purpose if I had a function to define a similar curve that passed through (0,1) and (1,0), yielded the line y=1-x with the parameter of .5, and was axisymmetric around y=x.
I can find many (infinite, I suppose) functions that will define curves that meet 1 and 3, of course. I am willing to optimize another parameter or two to approximate 2, as actual equality is nice but not necessary, as is the simplicity of a single function rather than an optimization function and the curve function. 4 has me stumped, though.
Comment: Give an example of a non-trivial example function that is "axis symmetric around $y = 1-x$," regardless of the other constraints.
Comment: @DavidG.Stork For instance, $y = 1-\frac1x$ is axisymmetric around $y = 1-x$.
Comment: @DavidG.Stork, I'm very willing to concede the non-existence thereof, I simply don't know. I'm a statistician who is well out of his depth in this particular problem!
Comment: Not something generalizable yet, but a bit of fiddling around with Desmos shows that $y = 1 + \phi - \frac{1}{1+\phi}$ meets 1, 3, and 4, but sadly not 2 (even though it looked like it might have).
Comment: Also, I should ask: are you looking for a full solutions, or just some hints?
Comment: @EricSnyder This is a small part of something I'm doing for work, but it's also one of two potential paths I'm going down and I've solved the other, so this is now just my curiosity (and desire for options).
Answer: Here is the way to solve it:

Parameterize your function by an angle $\theta$ centered at $(0,1)$ (blue point), with $\theta = 0$ being downward, and $\theta = \pi/2$ being rightward.  Thus we only care about $0 \leq \theta \leq \pi/2$.  Moreover, we must have $r(0) = r(\pi/2) = 1$.
To ensure the difficult condition that the function is symmetric with respect to the dashed red line $y = 1-x$, we merely need to ensure that the radius function $r(\theta)$ is symmetric with respect to $\theta = \pi/4$.  (Think about it.)
One class of such functions is $r(\theta) = 1 + a \sin (2 \theta)$ for $a$ bounded by some small number.  (You can add more harmonic terms, or terms of the form $r(\theta) \propto (\theta - \pi/4)^2$ and such as you like, so long as you ensure the end conditions $r(0) = r(\pi/2) = 1$.)
Now express the $x$ and $y$ coordinates from an analysis of the basic coordinates:
$x(\theta) = r(\theta) \sin \theta$
$y(\theta) = 1 - r(\theta) \cos \theta$.
Now you merely need to use these to express $y(x;a)$ and you're done.
Of course once you have $y(x)$ you can find the stated area,
$$A = \int\limits_{x=0}^1 y(x;a)\ dx$$
and hence you can find $a(A)$.
Comment: I think there are some problems with this analysis. Consider that at $\alpha = 1$, the function $r(\theta)$ must be a sawtooth wave with $r(0^-)=1, r(0^+)=0$, while at $\alpha = 0$ we need a function that returns the hypotenuse of a triangle with one side of length $1$, and one side of length that you'd think would be the sine of the angle, but isn't due to our parametrization.
Comment: I don't understand your comment.  First, there is no $\alpha$ in sight, and there is no way the parameterization gives a sawtooth in any case.  Mark the key points and state their coordinates.  That should help you figure out your error.
Comment: Apologies, I thought the OP had used $\alpha$ as the name of their parameter for some reason. With their parameter (which I'll call $\alpha$ for now so it has a name), if $\alpha = 1$, the area under the "curve" must be $1$--in other words, $y(\theta) = 1$ for all $\theta$ in your parametrization other than $\theta = 0$. I guess you're right that it's not a sawtooth, it's just a complete discontinuity. However, if we consider $\alpha = 0.999$, then $x(\theta) \approx 0$ for $0<\theta<\pi/4$, and $x(\theta) \approx x$ for $\pi/4<\theta<\pi/2$. With the converse for $y(\theta)$...
Comment: ... (character limit) I guess sawtooth is the wrong name for the function. $r(\theta)$ must drop rapidly from $1$ to $0+\delta$ in the range $0<\theta<(\pi/4 - \epsilon)$, then increase almost linearly from $0+\delta$ to $1$ in the range $(\pi/4 - \epsilon)< \theta<\pi/2$. So a graph of $r(\theta)$ plotted vs $\theta$ on Cartesian coordinates with $r(\theta) \to y$ and $\theta \to x$ would be $y \approx 0$ from $0$ to $\approx pi/4$, then a diagonal from $(\pi/4, 0)$ to $(\pi/2, 1)$.
Answer: All right, so after a bunch of trial and error analysis, I have something that gets most of your requirements, though the scaling on the area under the curve is wrong--I'll let you try to curve fit that if that part is truly necessary.
I figured a hyperbola with the x and y axes as asymptotes might be a good starting place, which led me to this post with some good info. This Desmos sheet shows you some of what I did.
Basically, the top equation using $q$ was a good starting point, but we needed $q = 0$ at $a = 1$, and $q = -1$ at $a = 0$, but also $q = \infty$ at $a = 0.5$ so that we would end up with our line. There's a discontinuity at $a = 0.5, x = 0.5$, but it's not bad.
The rest of the sheet is working out a symmetrical hyperbola for q. Then Wolfram Aplha got me to the final equation:
$$ y\ =\ \frac{\ (2a^{2}-3a)\ x}{\left(2a^{2}-a-1\right)+\left(1-2a\right)x}\  $$
As mentioned, the area under the curve doesn't fit what you want. You could likely map $\alpha$ to a curve-fit function $f(\alpha) = \beta$ to get that.
Hope this helps. Interesting problem.


Aggregate dates monthly and count conditionally in R

Question: I have a dataset as below (name:data) that includes multiple countries with multiple event types in different dates in 3 columns and 251453 rows. I want to count monthly events for each country. For example, I want to see the number of "Battles" in "Yemen" in "August"? I have 6 different event types and 8 different countries in total.
Couldn't have any advance on it despite spending hours of it. Appreciate for any guidance.
|event_date|        |event_type|                |country|
12 March 2021   Explosions/Remote violence;     Yemen;
12 March 2021   Explosions/Remote violence      Yemen
12 March 2021   Battles                         Afghanistan;
12 March 2021   Battles                         Afghanistan
12 March 2021   Protests                        Yemen
12 March 2021   Protests                        Yemen

The output of dput (sample) dput(head(data, 20)):
 structure(list(event_date =
   structure(c(420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L,
   420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L, 420L), .Label = c("01 April
    2018", "01 April 2019", "01 April 2020", "01 August 2018", "01 August 2019",
    "01 August 2020", "01 December 2018", "01 December 2019", "01 December 2020",
    "01 February 2019", event_type = structure(c(2L, 2L, 1L, 1L, 3L, 3L, 3L, 3L, 4L, 1L, 1L, 3L, 4L, 3L, 1L, 1L, 4L, 6L, 6L, 3L), .Label = c("Battles", "Explosions/Remote violence", "Protests", "Riots", "Strategic developments", "Violence against civilians"), class = "factor"), country = structure(c(8L, 8L, 1L, 1L, 8L, 8L, 3L, 5L, 8L, 8L, 8L, 5L, 5L, 5L, 1L, 1L, 5L, 8L, 8L, 4L), .Label = c("Afghanistan", "Colombia", "India", "Iraq", "Lebanon", "Libya", "Mali", "Yemen"), class = "factor")), row.names = c(NA, 20L), class = "data.frame")

Answer: Convert event_date to date class and then count number of rows for each country, month and event_type.
library(dplyr)

data %>%
  mutate(event_date = lubridate::dmy(event_date),
         month = format(event_date, '%b-%Y')) %>%
  count(country, month, event_type)

In base R, you can do this with aggregate :
data$event_date <- as.Date(data$event_date, '%d %B %Y')
data$month <- format(data$event_date, '%b-%Y')
aggregate(event_date~country + month + event_type, data, length)

Comment: Thank you so much @RonakShah. It means a lot. Does the warning message below make sense?  Warning message:
Problem with `mutate()` input `event_date`.
i  153814 failed to parse.
i Input `event_date` is `lubridate::mdy(event_date)`.
Comment: @ÜmitSeven Can you try the updated answer? I could not test the answer since your `dput` did not work for me, it seems to be incomplete.


Change user picture via services 3

Question: I'm update user profile data via services 3 but I have a problem with user picture. I send user picture to my web site via services and it works:
{"fid":"1078","uri":"http://MyDomain/rest/file/1078"}

But how can I pass this "FID" to the user update method ? Which is the correct parameter name ?
Thanks.
M.
Answer: The file ID is stored in the  picture column of the users table

Foreign key: {file_managed}.fid of user's picture.

So your payload to the update resource would look something like
{
  "uid": "123",
  "data": {
    "picture": "1078",
    # rest of user data
  }
}

Comment: @keithm It'd make more sense if that column at least had `fid` in it somewhere I guess, but no, it's the `picture` column that stores the user picture file id
Comment: Nope. It does not works.  All other data are correctly updated, but not the image profile. I have tried to add "data...." to { account : .....} but without success
Comment: According to [`_user_resource_definition()`](http://drupalcontrib.org/api/drupal/contributions%21services%21resources%21user_resource.inc/function/_user_resource_definition/7) the JSON you send should contain 'uid' and 'data' only - there's no 'account' variable involved
Comment: Clive: I have tried in all way without success. All parameters that I pass to update method works, the only with problem is "picture". I have tried to pass the same structure that I get via /user/X.json too, but always without success.
Answer: The fid you pass there is just ignored. You have to write a bit of code in a module to save the fid yourself.
You can find code ready to be copy-pasted here: https://www.drupal.org/node/2471178#comment-9825329
Note: the picture_upload field is processed server-side but it won't actually work either because the file upload module looks at $_FILES and that'll be empty. The $user->picture fid will thus be set to 0 (current avatar, if any, will be removed).

Change user picture via services 3


Efficient allocation of array in r,igraph

Question: I want to create 2 matrices with the same dimensions of the adjacency matrix of the graph i have.The problem is that the graph is way to large.
Here is my code:
AjM<-as_adjacency_matrix(g,attr = "weight")
dim(AjM)

77500 77500
Alpha<-array(0,dim(AjM))

Error: cannot allocate vector of size 44.6 Gb .AjM is of size 18.8Mb.
How can i do that?( i have an 64 bit machine with 12Gb ram )
Comment: Buy more memory?
Answer: Notice that as_adjacency_matrix has an argument sparse. Assuming that your matrix has fewer than 77500 * 77500 / 2 edges,  setting sparse=TRUE may reduce the size of the resulting adjacency matrix significantly. To use this option, you must have the Matrix package installed.


How to calculate odds ratio and p-values for Fisher's test?

Question: I'm trying to perform Fisher's exact test in R. I'm calculating odds ratio like this
$$\frac{(\text{no. of successes in my set}) \cdot (\text{no. of failures in background set})}{\text{(no. of successes in background set)} \cdot (\text{no. of failures in my set})}$$
In the denominator, I get 0 for some cases, because there are 0 failures in my set for some cases.
Can anyone tell me how to calculate p-values from odds ratio?
Also what does it mean if we say odds ratio should be greater or less than 1?
If I want to test over-representation in my set against the background set what should be the odds ratio and how can I calculate that?
Comment: Odds ratios and Fisher's exact test are not the same thing. The function for using Fisher's exact test in R is `fisher.test`. A description of how it computes the p-values is found in the help file `?fisher.test`. See also http://en.wikipedia.org/wiki/Odds_ratio#Statistical_inference for statistical inference on odds ratios.
Comment: see http://stats.stackexchange.com/questions/21752/alternative-argument-in-fisher-test-in-r/21753#21753 about the alternative argument of fisher.test() in R. About the odds ratio you have to understand the statistical model behind Fisher's test. Observations are assumed to be the realizations of two independent binomial random variables, each binomial variable has a "probability of success" parameter and the question is about the comparison of the two probabilities of success
Comment: Is there a way to calculate p-values from odds ratio?In fisher.test I don't understand the alternative hypothesis argument. It says alternative hypothesis must be one of "two.sided", "greater" or "less" and that the alternative for a one-sided test is based on the odds ratio, so alternative = "greater" is a test of the odds ratio being bigger than or? what does less mean?I want to calculate enrichment in my set and if I select greater, it gives me very big p-values most of which are 1 and as much as I know low p-values are significant. If I select less, it gives me small p-values.I'm confused.
Comment: @diana Please register your account [here](http://stats.stackexchange.com/users/login), then I'll try to help  you regaining ownership of your post.
Answer: You can't directly test significance of the odds ratio, instead you have to take log(OR) and then use the standard error
$se = (\frac{1}{n_{00}} + \frac{1}{n_{01}} +\frac{1}{n_{10}} + \frac{1}{n_{11}})^.5$
and log(OR) is approximately distributed $\mathcal{N}(log(OR), \sigma^2)$
but that is asymptotic.
For Fisher's, you probably want two-sided option


Calculate the shortest path from start to end, if we have the ability to overcome at MOST 1 obstacle

Question: We're given a Maze in the form of a 2D Matrix of integers; where 0's are passible space and 1's are walls.
The starting position will always be :array[0][0]  and the end will always be :array[HEIGHT -1][WIDTH-1]
The only possible moves are up, down, right, or left.
I would like to find the shortest path from start to end, considering that we can overcome at most 1 wall inside of the maze. I started out by creating a Maze class and a Vertex Class. My first thought was to use BFS, however, I have recently realized that this of course will not work, and I am now trying Dijkstra's Algorithm. An idea is to give the Wall's weights that are greatly more expensive than the passible space and use Dijkstra's to find the shortest path from start to finish. Then, calculate each Wall's shortest path to the end. After this, I'm thinking that I can compare the paths of the Walls to the end, with the path of the start to the end, and somehow use this to decide if removing a wall will give me a shorter path.
I'm really struggling with Dijkstra and putting all of this together to perhaps get something useful. I started with creating a Maze class, that would take the 2d array input and make a graph out of it. Maze Class :
   class Maze{
     Vertex[][] vertices;
     ArrayList<Edge> edges;
     ArrayList<Vertex> walls;
     HashSet<Vertex> settledVertices;
     HashSet<Vertex> unsettledVertices;
     HashMap<Vertex,Integer> distanceMap;
     HashMap<Vertex,Vertex> predecessors;

     Vertex start, end;
     int width;
     int height;

 //Maze Contructor
  public Maze(int arr[][]){
     this.height = arr.length;
     this.width = arr[0].length;
     this.vertices = new Vertex[height][width];
     this.edges = new ArrayList<>();
     this.walls = new ArrayList<>();

     for(int i = 0 ; i < height; i++){
       for(int j = 0; j < width; j++){
         this.vertices[i][j] = arr[i][j] == 1 ? new Wall(arr[i][j]) : new Vertex(arr[i][j]);
         if(this.vertices[i][j].value == 1)
            this.walls.add(this.vertices[i][j]);
       }
     }

   //Build() sets the Edges and their weights, as well as determine each Vertexs neighbors
     build();

     this.start = this.vertices[0][0];
     this.end = this.vertices[height-1][width-1];

  }

  //Attempting Dijkstra
  public void executeDij(Vertex source){
    this.settledVertices = new HashSet<>();
    this.unsettledVertices = new HashSet<>();
    this.distanceMap = new HashMap<>();
    this.predecessors = new HashMap<>();

    this.distanceMap.put(source,0);
    this.unsettledVertices.add(source);

    while(unsettledVertices.size() > 0){
      Vertex v = getMinimum(unsettledVertices);
      unsettledVertices.remove(v);
      findMinDistance(v);
    }
  }

   public int getDistance(Vertex arrow, Vertex target){
      for(Edge e : edges)
        if(e.source.equals(arrow) && e.destination.equals(target))
       return e.weight;

   throw new RuntimeException("Get distance error");
  }

  public void findMinDistance(Vertex vertex){
       for (Vertex target : vertex.neighbors) {
         if(getShortestDistance(target) > getShortestDistance(vertex) + getDistance(vertex, target))
           distanceMap.put(target, getShortestDistance(vertex) + getDistance(vertex,target));
       }

  }

  public int getShortestDistance(Vertex destination){
    Integer d = distanceMap.get(destination);

    if(d == null)
      return Integer.MAX_VALUE;
    return d;
    }

  public Vertex getMinimum(HashSet<Vertex> set){
    Vertex min = null;

    for(Vertex v : set){
      if(min == null){
        min = v;
      }else{
         if(getShortestDistance(v) < getShortestDistance(min)){
        min = v;
        }
      }
    }
    return min;
  }

  public boolean isSettled(Vertex v){
    return settledVertices.contains(v);
  }

  public LinkedList<Vertex> getPath(Vertex target){
    LinkedList<Vertex> path = new LinkedList<>();
    Vertex singleStep = target;

    if(predecessors.get(singleStep) == null)
        return null;

    path.add(singleStep);

    while(predecessors.get(singleStep) != null){
      singleStep = predecessors.get(singleStep);
      path.add(singleStep);
    }

    Collections.reverse(path);
    return path;

  }

My Vertex Class :
 class Vertex{
    int value;
    boolean visited;
    int distance;
    Vertex previous;
    ArrayList<Vertex> neighbors = new ArrayList<>();

    public Vertex(int value){
      this.value = value;
    }

    public boolean isWall(){
      return this.value == 1;
    }

    public void setVisited(){
      this.visited = true;
    }

    public int getValue(){
      return this.value;
    }

 }

I've basically lost myself at this point and I'm not sure what I'm even doing anymore. When I try to use my getPath method, I get an Null Pointer Exception. In all, I guess my question is how can I get the least expensive path from Start to End, and then the path of the Walls to the end; for each Wall.
Answer: Using Dijkstra's Algorithm to build shortest path to any point is good, but do it both from Start and from End.
Let's say you have this maze, using _ for Space and X for Wall:
s  _  _  X  _  _
X  _  X  X  _  X
_  _  X  _  _  _
_  X  _  _  X  _
_  X  X  _  X  _
_  _  X  _  _  e

First, fill in shortest distance from Start:
s  s1 s2 X  _  _
X  s2 X  X  _  X
s4 s3 X  _  _  _
s5 X  _  _  X  _
s6 X  X  _  X  _
s7 s8 X  _  _  _

If that got you to the end, you're done without having to jump a wall.
Otherwise, fill in shortest distance from End:
s  s1 s2 X  e6 e7
X  s2 X  X  e5 X
s4 s3 X  e5 e4 e3
s5 X  e5 e4  X e2
s6 X  X  e3  X e1
s7 s8 X  e2 e1 e

Now, find walls that are next to a start value and an end value:
s  s1 s2 -- e6 e7
X  s2 X  X  e5 X
s4 s3 -- e5 e4 e3
s5 -- e5 e4  X e2
s6 X  X  e3  X e1
s7 s8 -- e2 e1 e

Choose a wall with the smallest sum of the two distances.
Of the 4 candidates, 3 have sum 8, and 1 has sum 10.
There are here a total of 5 solutions:
s →s1→s2→--→e6 e7 │ s →s1 s2 -- e6 e7 │ s →s1 s2 -- e6 e7 │ s →s1 s2 -- e6 e7 │ s →s1 s2 -- e6 e7
            ↓↓    │    ↓↓             │    ↓↓             │    ↓↓             │    ↓↓
X  s2 X  X  e5 X  │ X  s2 X  X  e5 X  │ X  s2 X  X  e5 X  │ X  s2 X  X  e5 X  │ X  s2 X  X  e5 X
            ↓↓    │    ↓↓             │    ↓↓             │    ↓↓             │    ↓↓
s4 s3 -- e5 e4→e3 │ s4 s3→--→e5→e4→e3 │ s4 s3→--→e5 e4 e3 │ s4 s3→-- e5 e4 e3 │ s4 s3 -- e5 e4 e3
               ↓↓ │                ↓↓ │          ↓↓       │       ↓↓          │    ↓↓
s5 -- e5 e4  X e2 │ s5 -- e5 e4  X e2 │ s5 -- e5 e4  X e2 │ s5 -- e5→e4  X e2 │ s5 --→e5→e4  X e2
               ↓↓ │                ↓↓ │          ↓↓       │          ↓↓       │          ↓↓
s6 X  X  e3  X e1 │ s6 X  X  e3  X e1 │ s6 X  X  e3  X e1 │ s6 X  X  e3  X e1 │ s6 X  X  e3  X e1
               ↓↓ │                ↓↓ │          ↓↓       │          ↓↓       │          ↓↓
s7 s8 -- e2 e1 e  │ s7 s8 -- e2 e1 e  │ s7 s8 -- e2→e1→e  │ s7 s8 -- e2→e1→e  │ s7 s8 -- e2→e1→e

Comment: Okay, I will try that. I will got back to you with stays updates. Thanks
Comment: So, I had a logic error with my Dijkstra implementation, that i corrected. I ended up taking each walls distance from the start and also the end. Of those I take the smallest. I compare it's distance with the shortest path that Dijkstra gives me; but I count it's distance as if the wall were a clear path. if it's smaller, then we update the shortest path.


Displaying radio button number instead of calculating cost

Question: My program is supposed to calculate the cost of a telephone call.  It runs but does not calculate the answer but displays the number of the radio button.
# Import tkinter
import tkinter
import tkinter.messagebox

dayVal = 0
eveVal = 0
off_peak = 0

# Create the class
class MyGUI:
    def __init__(self):

        # Create the main window.
        self.main_window = tkinter.Tk()

        # Create the variable objects to display
        self.rb1_value = tkinter.StringVar()
        self.rb2_value = tkinter.StringVar()
        self.rb3_value = tkinter.StringVar()

        # Create two frames. One for the Radiobuttons
        # and another for the regular Button widgets.
        self.info_frame = tkinter.Frame(self.main_window)
        self.button_frame = tkinter.Frame(self.main_window)
        self.fourth_frame = tkinter.Frame(self.main_window)

        # Create the label for the promt frame.
        self.prompt_label = tkinter.Label(self.fourth_frame, \
                                    text='Enter the length of the call (in minutes):')

        # Create the entry box for the top frame.
        self.minute_entry = tkinter.Entry(self.fourth_frame, \
                                             width=10)

        # Placement of the top label, and the entry box.
        self.prompt_label.pack(side='left')
        self.minute_entry.pack(side ='right')

        # Create an IntVar object to use with the Radiobuttons.
        self.radio_var = tkinter.IntVar()

        # Set the intVar object.
        self.radio_var.set(dayVal)
        self.radio_var.set(eveVal)
        self.radio_var.set(off_peak)

        # Create the Radiobutton widgets in the top_frame.
        self.rb1 = tkinter.Radiobutton(self.info_frame, \
                                       text='Daytime (6:00 am - 5:59 pm), $0.07/minute',
                                       variable=self.radio_var, \
                                       value=1)
        self.rb2 = tkinter.Radiobutton(self.info_frame, \
                                       text='Evening (6:00 pm - 11:59 pm), $0.12/minute',
                                       variable=self.radio_var, \
                                       value=2)
        self.rb3 = tkinter.Radiobutton(self.info_frame, \
                                       text='Off-Peak (midnight - 5:59 pm), $0.05/minute',
                                       variable=self.radio_var, \
                                       value=3)
        # Pack the Radio Buttons
        self.rb1.pack()
        self.rb2.pack()
        self.rb3.pack()

        # Create a Calculate cost button and a Quit button
        self.show_info_button = tkinter.Button(self.button_frame, \
                                        text='Calculate cost', command=self.show)
        self.quit_button = tkinter.Button(self.button_frame, \
                                          text='Quit', command=self.main_window.destroy)

        # Pack the Buttons
        self.show_info_button.pack(side='left')
        self.quit_button.pack(side='right')

        # Pack the frames
        self.info_frame.pack()
        self.fourth_frame.pack()
        self.button_frame.pack()

        # Start the mainloop
        tkinter.mainloop()

    def calculate(self):
        lengthVal = float(self.minute_entry.get())

        dayVal = format(lengthVal * .07, ',.2f')
        eveVal = format(lengthVal * .12, ',.2f')
        off_peak = format(lengthVal * .05, ',.2f')

    # The do something method is the callback function for the Calculate button.

    def show(self):
        tkinter.messagebox.showinfo('The cost of the call is: ', +\
                                    float(self.radio_var.get()))

# Create an instance of the MyGUI class
my_gui = MyGUI()

Comment: After my post I did notice that the do something comment needed to be changed.  :)
Answer: This fixes it. The problem was that you were attempting to manipulate global variables. Once you have set a global variable it typically is not subject to change (more below). To get around this I changed your globals to class attributes.
Also, I should mention further that your globals are subject to change to be more precise. You can use the global command to change them, but since you are already using a class attributes would be more appropriate here. Typically global variables are set for things that are to remain constant throughout your program.
Also, I changed the calculate function slightly to check which radio button is currently set by the user and then a common cost variable to all three. Based upon which is selected it will calculate the cost of the call based upon the what you have set as the cost factors. Also, I should mention that format is a bit redundant here (imo).
 import tkinter
 import tkinter.messagebox

 # Create the class
 class MyGUI:
     def __init__(self):

        # Create the main window.
        self.main_window = tkinter.Tk()
        self.main_window.title("Call Calculator")

        # Create the variable objects to display
        self.rb1_value = tkinter.StringVar()
        self.rb2_value = tkinter.StringVar()
        self.rb3_value = tkinter.StringVar()

        # Create two frames. One for the Radiobuttons
        # and another for the regular Button widgets.
        self.info_frame = tkinter.Frame(self.main_window)
        self.button_frame = tkinter.Frame(self.main_window)
        self.fourth_frame = tkinter.Frame(self.main_window)

        # Create the label for the promt frame.
        self.prompt_label = tkinter.Label(self.fourth_frame, \
                                          text='Enter the length of the call (in minutes):')

        # Create the entry box for the top frame.
        self.minute_entry = tkinter.Entry(self.fourth_frame, \
                                          width=10)

        # Placement of the top label, and the entry box.
        self.prompt_label.pack(side='left')
        self.minute_entry.pack(side ='right')

        # Create an IntVar object to use with the Radiobuttons.
        self.radio_var = tkinter.IntVar()

        #make globals class attributes
        self.dayVal = 0
        self.eveVal = 0
        self.off_peak = 0

       # Set the intVar object.
       self.radio_var.set(self.dayVal)
       self.radio_var.set(self.eveVal)
       self.radio_var.set(self.off_peak)

       # Create the Radiobutton widgets in the top_frame.
       self.rb1 = tkinter.Radiobutton(self.info_frame, \
                                       text='Daytime (6:00 am - 5:59 pm), $0.07/minute',
                                   variable=self.radio_var, \
                                       value=1)
       self.rb2 = tkinter.Radiobutton(self.info_frame, \
                                       text='Evening (6:00 pm - 11:59 pm), $0.12/minute',
                                   variable=self.radio_var, \
                                       value=2)
       self.rb3 = tkinter.Radiobutton(self.info_frame, \
                                       text='Off-Peak (midnight - 5:59 pm), $0.05/minute',
                                   variable=self.radio_var, \
                                       value=3)
       # Pack the Radio Buttons
       self.rb1.pack()
       self.rb2.pack()
       self.rb3.pack()

       # Create a Calculate cost button and a Quit button
       self.show_info_button = tkinter.Button(self.button_frame, \
                                               text='Calculate cost', command=self.show)
       self.quit_button = tkinter.Button(self.button_frame, \
                                          text='Quit', command=self.main_window.destroy)

       # Pack the Buttons
       self.show_info_button.pack(side='left')
       self.quit_button.pack(side='right')

       # Pack the frames
       self.info_frame.pack()
       self.fourth_frame.pack()
       self.button_frame.pack()

       # Start the mainloop
       tkinter.mainloop()

     def calculate(self):
         lengthVal = float(self.minute_entry.get())
         sel_radio = self.radio_var.get()
         if sel_radio == 1:
             cost = format(lengthVal * .07, ',.2f')
         elif self_radio == 2:
             cost = format(lengthVal * .12, ',.2f')
         else:
             cost =  format(lengthVal * .05, ',.2f')
         return cost

    # The do something method is the callback function for the Calculate button.

     def show(self):
         cost = self.calculate()
         tkinter.messagebox.showinfo('Cost of Call:', "Your call has costed the following amount in USD\n\t\t$ %s" % cost)

 # Create an instance of the MyGUI class
 my_gui = MyGUI()

Answer: Your calculate() method modifies local variables for dayVal, eveVal, and off_peak. This is probably not what you wanted.
Comment: So how could that be rectified?
Comment: Either declare them [globals](http://effbot.org/pyfaq/how-do-you-set-a-global-variable-in-a-function.htm) or change the globals to regular instance variables.
Comment: No, why do you think an "if else loop" would help with anything here?
Comment: Is the problem in the self.rb1 = tkinter.Radiobutton(self.info_frame, ... value= ?
Comment: I appreciate your help but being that I am NEW I do not quite fully understand how to implement your suggestions.  I would appreciate a little bit more detail,  thanks!


Saving the date to actual bash history file

Question: When adding "HISTTIMEFORMAT" to bashrc, the timestamps of when a command was executed are made available when running the "history" command.
But the timestamps themselves are not saved to the bash_history file (atleast not in plain text).
I am looking for a solution that will write the timestamp to the file itself so that archived .bash_history files from various workstations can be viewed in an editor outside the userspace and still contain the timestamps of when commands were executed.
If the timestamps are being saved to the history file itself but just not viewable in an editor when opening the bash_history file, and it is still possible to view these timestamps by using the history command itself on a rogue bash history file, then that would also suffice.
Thanks
Comment: Just adding the variable to the bashrc is not enough: you need to source the bashrc in each of your open shells to "activate" the variable.
Comment: And the history file is only written/appended when a shell exits.
Answer: This is a example of bash history ( when using HISTTIMEFORMAT )
#1625963751
sleep 45 ; ssh proxy.lan

the number 1625963751 is the unix timestamp ( https://en.wikipedia.org/wiki/Unix_time ) .
if you are using linux , date has a option to display this date in human form .
em444$ date -d @1625963751
Sat Jul 10 20:35:51 EDT 2021

Comment: How do I append the unix timestamp to each command in a bash file?  When opening old bash historys I have, there is no #number above each command as there is in your example.  Opening a bash_history file in vim just gives a list of commands.  Each line is a command, there's no time stamps above each line.
Comment: if you dont use HISTTIMEFORMAT , you will not have timestamp .
Answer: edit /etc/bashrc and add this line to the bottom:
PROMPT_COMMAND="echo `date +'%F %H:%M'` `whoami` `history|tail -1` >> ~/history.txt; $PROMPT_COMMAND"

I am not sure if you change ~ to root, \root\history.txt can be accessible to all users yet.
Comment: \root\history.txt ???
Comment: `~/history.txt` means the file `history.txt` in current user's home directory. `/root/history.txt` means the file in root directory. I assume you want to save historical commands to a specific file if you want a timestamp on each commands.
Comment: It's only that backslashes have a different meaning on unix.  Apart from that, 'history -1' may be cheaper than piping through tail.
Comment: It seems I cannot get the history|tail -1 output appended to history.txt.  The rest of the command works though.  So my history.txt has date, user, but no command...
Answer: export HISTTIMEFORMAT='(%Y-%m-%d) (%H:%M:%S) '
Try this line.


keepalived virtual_ipaddress and network mask

Question: I have the following keepalived.conf file:
vrrp_script chk_nginx {
  script "curl http://localhost/vrrp_healthcheck/"
  interval 2 # every 2 seconds
  weight 2 # add 2 points if OK
}

vrrp_instance VI_1 {
  interface ens160 # interface to monitor
  virtual_router_id 50
  priority 100
  virtual_ipaddress {
    192.168.120.25 label ens160:10
  }
  track_script {
    chk_nginx
  }
  notify /usr/local/bin/notify.sh
}

On the master node I see the following in the ifconfig output:
ens160: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.120.20  netmask 255.255.255.224  broadcast 192.168.120.31
        ether 00:50:56:a5:c5:3a  txqueuelen 1000  (Ethernet)
        RX packets 138308  bytes 130425415 (124.3 MiB)
        RX errors 0  dropped 73  overruns 0  frame 0
        TX packets 122917  bytes 50788591 (48.4 MiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

ens160:10: flags=4163<UP,BROADCAST,RUNNING,MULTICAST>  mtu 1500
        inet 192.168.120.25  netmask 255.255.255.255  broadcast 0.0.0.0
        ether 00:50:56:a5:c5:3a  txqueuelen 1000  (Ethernet)

lo: flags=73<UP,LOOPBACK,RUNNING>  mtu 65536
        inet 127.0.0.1  netmask 255.0.0.0
        loop  txqueuelen 1  (Local Loopback)
        RX packets 9730  bytes 812897 (793.8 KiB)
        RX errors 0  dropped 0  overruns 0  frame 0
        TX packets 9730  bytes 812897 (793.8 KiB)
        TX errors 0  dropped 0 overruns 0  carrier 0  collisions 0

What worries me, is the different broadcast and network address in the ens160:10 entry (which is the one created by keepalived).
Shouldn't those match the ones from the regular interface?
For the moment, my setup seems to work, but I want to make sure it is setup correctly.
Answer: You can simply modify the virtual ip addresses block to read:
virtual_ipaddress {
  192.168.120.25/27 label ens160:10
}

The default mask is /32 or 255.255.255.255.


Issues retrieving fbsdk Access Token and User ID

Question: I am trying to retrieve the Access Token and User ID of the logged in user in my React Native App. For some reason when I tried to update the fbsdkcore package, it did not exist anymore. So, I tried to resolve it within the general fbsdk package.
I am calling the js file (of which I think retrieves the accesstoken) in the package as:
const AccessToken = require('react-native-fbsdk/js/FBAccessToken');

And subsequently in my code I try to log it so that I can see if it works, simply by:
console.log(AccessToken.getCurrentAccessToken());
console.log(AccessToken.getUserId);

But the log only returns:
2016-05-05 10:22:28.276 [info][tid:com.facebook.React.JavaScript] { _45: 0, _81: 0, _65: null, _54: null }
2016-05-05 10:22:28.277 [info][tid:com.facebook.React.JavaScript] undefined

Which does not seem to be the droids that im looking for.
I inspected the code for the js file in the fbsdk package and the getCurrentAccessToken code looks like this:
  /**
   * Getter for the access token that is current for the application.
   */
  static getCurrentAccessToken(): Promise<?FBAccessToken> {
    return new Promise((resolve, reject) => {
      AccessToken.getCurrentAccessToken((tokenMap) => {
        if (tokenMap) {
          resolve(new FBAccessToken(tokenMap));
        } else {
          resolve(null);
        }
      });
    });
  }

Which of course seems reasonable. But since I get this really weird result when I try to call it, I get worried over that I have done something wrong in the bigger picture. I even modified the resolve(null) part of the code so that I could make sure of what happend. But it still returned the same weird "token".
The log also returns this error when logging in:
2016-05-05 10:22:07.630 AppName[15097:415865] -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"

But I think that is only because I don't have the facebook app on my xcode simulator.
Can anybody throw me a good guess on what I have done wrong??
Answer: GetCurrentAccestoken returns a promise.
Maybe you can try:
AccessToken.getCurrentAccessToken().then(
    (data) => {
        console.log(data.accessToken.toString())
    }
)

Comment: Also, nowadays import with `import { AccessToken } from 'react-native-fbsdk'`
Answer: Try this. It worked for me
AccessToken.getCurrentAccessToken().then(
      (data) => {
            console.log(data.accessToken)
            console.log(data.userID);
  });

Answer: LoginManager.logInWithReadPermissions(['public_profile']).then(
            function (result) {
                if (result.isCancelled) {
                    alert('Login cancelled');
                } else {
                    // alert('Login success with permissions: ' +
                    //     result.grantedPermissions.toString());
                    AccessToken.getCurrentAccessToken().then(
                        (data) => {
                            doLoginViaFb(data.userID, data.accessToken);

                        }
                    );

                    alert(result);
                    console.log(result.toString());
                    console.log(JSON.stringify(result));
                }
            },
            function (error) {
                alert('Login fail with error: ' + error);
            }
        );

Comment: When i m using it. It is pring login failed


Where to modify the logic that calculates the height of a collapsible fieldset?

Question: I'm not sure if this is a theme issue, but I continually get my collapsible fieldsets being 1-2 scanlines too short, causing scroll bars to appear.
This project has heavy use of FAPI, sometimes with collapsible fieldsets inside other collapsible fieldsets, and the vertical scroll bars are eating too much page real estate.
I'm using an unmodified version of Fusion Starter theme, if that helps. And, I'm not a themer, but can usually get by.
I would be perfectly happy modifying the PHP or JavaScript code doing this calculation, if I just knew where it is.
Comment: Did you try changing the used theme, and set (for example) Garland?
Comment: Just tried several different themes - Garland, Minelli & Bluemarine and they all exhibit the same behavior.
Comment: As far as I can remember, there isn't any JavaScript code calculating the field set size.
Comment: I just had a look at the site in Google Chrome - it looks correct, without the scrollbars. I've been using Firefox3 and just tried Firefox4 - both exhibit the problem. Just now testing Safari, and the problem is not there, no scrollbars. AND switching over to my PC: Firefox3 - no scrollbars, IE8 - no scrollbars. Well... looks like its a browser bug. Meaning the solution is either ignore (best) or detect the client browser and adjust fieldset-wrapper height via javascript - ugh.
Comment: I actually had the same problem for a module I was developing, with scroll bars appearing in a field set contained in another field set. At that time, I didn't do anything for that. I didn't verify if the scroll bar were present only in a browser. I am glad I didn't implement any workaround. **:-)**
Answer: Are you sure it can't be solved by CSS? Try adding some padding.
Comment: I'd be added padding individually for each fieldset - there ought to be a central place to correct this.
Comment: There isn't a .fieldset-wrapper?
Comment: actually, its the .fieldset-wrapper that's getting the scrollbars. I'm thinking that the fieldset is too short, causing the scrollbars, but it could just as easily be the fieldset-wrapper that is too short. Either way, I still don't know how to fix. Looking at the markup in firebug, it is the fieldset-wrapper that needs a height adjustment, but I don't want to make individual markup adjustments in my CSS for every fieldset-wrapper - that's a maintenance nightmare.
Comment: I also took a look at collapsible.js inside the misc folder, and it looks like it's doing some height calculations. It even seems to have a handy 'fudge' variable, but making modifications to the value of 'fudge' don't seem to make any visible difference to the fieldsets or their wrappers.
Answer: Not sure if this is exactly what you mean but try setting the #rows attribute. I use something close to this
<code><?php
$form['description'] = array(
  '#type' => 'textarea',
  '#title' => t('Description'),
  '#default_value' => $text,
  '#rows' => count(explode("\n", $text)),
);
?>
</code>
Comment: That's a good suggestion, but according to http://api.drupal.org/api/drupal/developer--topics--forms_api_reference.html/6 the '#rows' attribute is not honored by fieldsets. I have sets of text fields, option widgets and buttons inside these fieldsets, and they get a scrollbar on the right edge of the fieldset box containing them all.


Randomize Fibonacci sequence

Question: We all know that if $a_n$ if the $n^{th}$ Fibonacci number we can say:$$\lim_{n\rightarrow\infty}\frac{a_{n+1}}{a_n}=φ$$
Now let's build another sequence like that:$b_1=b_2=1$ and $b_{n+1}=b_n+b_{n-1}$ or $b_{n+1}\in [b_n,b_{n-1}]$ randomly with chances of $75\%,25\%$ with proportion.
For the second option it's random point in $[b_n,b_{n-1}]$
What will be:$$\lim_{n\rightarrow\infty}\frac{b_{n+1}}{b_n}?$$
Comment: What makes you think a limit will exist, pgp?
Comment: @vonbrand from my sick mind.
Comment: I know, this is a part in the question
Comment: Just curious: Where does this come from?
Comment: So it's either $b_n+b_{n-1}$ or uniform in the interval $[b_{n-1}, b_n]$?
Comment: Fixed it, thanks
Comment: Are we assuming $b_0=b_1=1$?
Comment: @pgp1 Numerical experiments seem to suggest that a limit does not exist, because $\frac{a_{1001}}{a_{1000}}$ varied very much in different runs. $$\lim_{n \to \infty} \mathbb{E}\left( \frac{a_{n+1}}{a_n} \right)$$ seems to converge to around $1.53$ though.
Answer: This limit will almost surely not exist, since the $b_n$ almost surely switch infinitely often between going up and going down. However, the limit
$$
\lim_{n\to\infty}\sqrt[n]{\frac{b_{n+1}}{b_1}}
$$
will almost surely exist. I would expect $\lambda=\frac{b_{n+1}}{b_n}$ to converge in distribution to a limiting distribution, and the above limit would then be the geometric mean of this distribution. Each step of the form $b_{n+1}=b_n+b_{n-1}$ transforms $\lambda$ according to $\lambda\mapsto1+\frac1\lambda$, and each step of the form $b_{n+1}\sim U[b_n,b_{n-1}]$ transforms $\lambda$ according to $\lambda\mapsto\frac1\lambda+u\left(1-\frac1\lambda\right)$. This is a complicated iteration, and I don't see much hope for finding a closed form for the limiting distribution. The first map has an attractive fixed point at the golden section $\varphi$, whereas the second one takes the reciprocal, thus inverting around $1$, and then condenses the distribution towards $1$.
Here's Java code that simulates the process and accumulates the distribution. The geometric mean of $\lambda$ (i.e. $\mathrm e^{\langle\log\lambda\rangle}$) is approximately $1.442$, quite close to $\varphi^\frac34\approx1.435$. If we make the probability for either type of step $\frac12$, the geometric mean is approximately $1.280$, quite close to  $\varphi^\frac12\approx1.272$. Here's a diagram of the empirical distribution for probabilities $\frac12$ (click to get the image in full resolution):

The yellow lines are the distribution of $\log\lambda$. The vertical black lines are at $\log1=0$ and at $\log\varphi\approx0.4812$. The symbols in four colours show the distribution disaggregated according to the last two steps. With F denoting a Fibonacci step and R denoting a random step, the magenta plusses, green crosses, cyan asterisks and orange boxes correspond to the states after steps FF, FR, RF and RR, respectively. A Fibonacci step always results in $\lambda\gt1$, and a random step always takes $\lambda$ to the other side of $1$, so the FR component is entirely below $1$. If we were to disaggregate RR further into FRR, FRRR, etc., the components would alternatingly lie above and below $1$. Similarly, the individual peaks in the FF component correspond to RFF, RFFF, etc., with the peaks on alternating sides of $\varphi$ and each peak closer to $\varphi$ by a factor $\phi^{-2}=\frac{3-\sqrt5}2\approx0.382$.
Here's the diagram for the probabilities $\frac34$ and $\frac14$ that you specified. It's qualititatively similar; I made the other one because the peaks of similar height make it easier to analyze.

Randomize Fibonacci sequence


Percentage of one point composed by two other points

Question: I have a question to calculate the percentage of point $c$ in $c_1$ and $c_2$ points.
$c$ is located on a straight line between $c_1$ and $c_2$. The coordinates are real numbers. (The coordinates represent an RGB color, but it doesn't matter for the geometry aspect of the question.)
The answer to that question uses the distance formula: $$d(c,c_1) = [(x_0-x_1)^2+(y_0-y_1)^2])]^{1/2},$$
and the percentage $p_1$ (which is $c_1$ in $c$) is as follows:
$$P1 = (d(c_1,c_2) - d(c,c_1))/d(c_1,c_2) * 100.$$
Which obviously derived from:
$$(d(c_1,c_2)*p_1)/100 = d(c_1,c_2) - d(c,c_1).$$
The last equation means that $p_1$ is a percentage from the distance of $c_1-c_2$ which equals to the difference between the distances of $c_1-c_2$ and $c-c_1$ (= the distance of $c-c_2$).
A. I am lacking the intuition here, why are we looking at the distance between the point $c_1$ and $c_2$ in order to find the  the percentage of $c$ from $C_1$ ?
B. Why the percentage $P_1$ is equal to the distance of $c-c_2$, shouldn't it be maybe equal to the distance of $c-c_1$ by intuition ? (intuition can be wrong, but something is bothering me about it and I am looking for clarification)
I am sorry about the lack of symbols, I haven't figure out how to add them correctly.
Answer: (A) Suppose $d(c,c_1)=1$.
If the whole line segment $d(c_1,c_2)=2$ then point $c$ is right in the middle, so the color is the "average" (how it is implemented is a different matter).
If $d(c_1,c_2)=100~$ or $~d(c_1,c_2)=200~$ or just some large number, then point $c$ is very close to the endpoint $c_1$, meaning the color of $c$ should be basically just the color of $c_1$. (unless I misunderstand the scenario)
This consideration of the above two cases with the same $d(c,c_1)$ demonstrates that we also need the total length.
(B) Continuing the example above, when point $c$ is close to $c_1$, which distance is larger? Is it $d(c,c_1)~$ or $~d(c,c_2)$? Assuming we want the percentage $P_1$ to be larger to reflect the fact that $c$ is closer to $c_1$, then $P_1$ should be proportional to larger distance, which is $d(c,c_2)$.
Comment: Thanks, I understand why it is correct now. Is there an intuition to how they reached the distinction that (1,2)−(,1) represent correctly the proportion of c from c1 ? I understand this when I am checking example cases but not from the equation itself.
Comment: By definition $d(c, c_2) = d(c_1, c_2) - d(c,c_1)$, namely, "the latter segment equals whole segment minus the first segment". Does this answer your question? Or are you asking something else like "why don't we use the square or other powers of the length?"
Comment: I asked it wrong. It is difficult for me to see the intuition, how did they reach the fact that P1 is ((1,2)−(,1))/(1,2) ? . I understand it from the example cases, but not the intuition on how to get there myself.
Comment: The intuition is a physical one. Consider a metal rod of uniform thickness and density (as in density for weight). The longer the rod the heavier it is, and the weight is directly (linearly) proportional to the length. Namely, if the rod is cut down to a third of its original length, then the weight also becomes exactly a third of its original weight. Last but not least, in this application for the color, the linear dependency is not a "fact" but a model that people can choose to adopt or not adopt.


Alternate double palm mute picking between notes

Question: Some songs that I really like feature double palm-muted notes (usually open strings or low pitch frets) between lead notes. Those are played by one guitar.

Good examples would be:
Parkway Drive - Vice Grip -

Technical Difficulties by Racer X -

I guess you got the idea.
Now, the alternate palm-muted picks obviously happen on another string (usually low E or A), so that means I have to move up to do that. It's fast too, so it requires upside-down (alternate) picking. However, I'm very much struggling.
Are there any good tips on how to achieve it properly?
Thanks.
Answer: I daresay the easiest way to get this kind of thing up to speed is to stick to consequent alternating picking. Of course it needs practise, but... that's sometimes inevitable when you want to go fast...
Another approach that's in principle more economical would be raking technique (or do guitarists call this sweeping?) – you play two notes on adjacent strings in a single movement, but still as two distinct notes. It's not easy to get the timing of both notes right, as well as the dynamic level (in particular if the accent is rather on the second note of a stroke), but with such a technique you're able to play fast with very little mechanical effort.

In either case, there's no way around practising!
Answer: Concerning the tabs and the second video example, note that Paul Gilbert spent his whole life perfecting his picking technique, so it shouldn't come as a surprise that playing his stuff is very challenging, especially for the picking hand. For that riff to sound good you definitely need to use alternate picking (as he does), not raking/sweeping. The latter technique can be useful for other things, such as playing arpeggios or fast linear scale runs.
I believe that there's no other way to learn it than the hard way: practice slowly, cleanly, and with a metronome. If possible, play amplified and with the appropriate distortion sound as often as you can, because otherwise you won't learn to achieve the right sound (e.g. when palm muting) and you won't be able to hear any noises caused by other strings etc. It will take a lot of dedication and time. If you have the feeling that you do not progress, have an experienced teacher look at your technique. This can save you a lot of practice time!
One important thing is to experiment with the angle of your pick. Paul Gilbert holds his pick at an angle of almost 45 degrees to the strings. In this way you will feel less resistance when crossing a string. Another thing to try is pick-slanting, i.e. turning the pick around an axis which is parallel to the strings. Troy Grady has a great youtube channel, mainly dedicated to picking technique. I'm sure his videos will help you a lot.


Is it possible to set custom status message (in utf-8) in http status header?

Question: I want to change http status header with my own status message. For example, change HTTP/1.1 200 OK to HTTP/1.1 200 custom status message in utf-8. To do it, I send some headers with php:
Content-Type: text/html; charset=UTF-8
HTTP/1.1 200 custom status message in utf-8

But in Chrome developer tools I see status message in wrong encoding, for example Status Code:200 УпÑ! ЧÑо-Ñо. Is it possible to fix this?
Answer: (a) the encoding is undefined, so it's not worth trying non-ASCII, furthermore, (b) the reason phrase does not exist anymore in in HTTP/2.
Comment: Ok, the encoding is define in Content-type header. So, can I use my own phrase in other language (differ from English)? If not, can you explain why?
Comment: No, Content-Type defines the payload of the HTTP message, not anything in the headers. I can't explain why it was left undefined, but it is.
Comment: This answer currently misses the sources for the statements. It would be good to have references to the relevant parts of the specifications.
Answer: You just used below line to change HTTP header status code and messages
$msg = "custom status message";

header("Status: 200");
header("HTTP/1.1 200 ".$msg);

Comment: I mean status message in language, different from English (for example in Greek or Russian).