How to write an absolute value expression in linear programming?

Question: My objective function for the Xpress-IVE (Mosel lang) model is
minimize |a-b|
where a and b the number of elements in the decision variables which are arrays.
Since there is no function to calculate the absolute value, i want to get something of the form
objective = max(a,b) - min(a,b)
and then minimize the objective
What I have tried:
introduced two variables x and y with the following constraints:
x >= a
x >= b
y => a
y => b
and re-written the objective as x-y
But this gives me zero as the solution.
Could I please get a hint on what i am doing wrong?
Answer: Minimizing
$$
Z=|a-b|
$$
is equivalent to minimizing
$$
Z=\omega,
$$
subject to the constraints
$$
a-b\le \omega\\
b-a \le \omega
$$
Comment: Thanks. Do i define w as an integer?
Comment: No need to. If $a$ and $b$ are integers so will $\omega$.
Comment: Ok. But when i run it, i still get zero as the solution..
Comment: If you are just minimizing $|a-b|$, it is normal: the minimum value of an absolute value is 0. Do you have any other constraints?
Comment: Yes, they are as follows: a,b >= 0; fixed percentage constraints(decimals) for the decision variables U,V which are arrays of multiple variables. Even though, i've fixed U and V to be binary, on running the model, the resulting arrays contains decimals in some places instead of 0 or 1.
Comment: Related? http://www.seas.ucla.edu/~vandenbe/ee236a/lectures/pwl.pdf


Wifi disabled, have to turn off and turn on

Question: Aye,
i recently moved to Xubuntu 15.04 and from time to time when I wake up laptop from suspend wifi cannot connect. It says networking disabled. I tried turnig on option "Enable networking" but that gives me nothing. I have to restart laptop (and It's also a problem as sometimes turning off or trying to restart just logs me off, i have to turn it off the hard way) and then it works.
Any suggestions?
Answer: I had a similar problem on Xubuntu, try to run
sudo apt-get autoremove
sudo apt-get autoclean
sudo dpkg --configure -a

Then restart the PC. Also, you can check for additional drivers on the driver Utility.
If the problem persist, look at
dmesg

And attach the output on a text file.
Also, you can see this entry: WiFi Issues
Comment: Can you explain what those lines does?
I like to know :)
Comment: Sure!, autoremove, uninstall all the residual packages left for some programs after updates or other software removal or installation.

autoclean, erases residual packages from disk, to free disk space.

dpkg --configure -a: Configure a package which has been unpacked but not yet  configured.   If  -a  or  --pending is given instead of package, all unpacked but unconfigured packages are  configured.

For more information, you can do : man , for example,

man dpkg
Comment: Why i have -1 reputation. Something wrong with my answer? :(
Comment: I upvoted. But i think my votes doesnt counts yet
Comment: The problem is still on. Here is link to txt output from dmesg
https://drive.google.com/file/d/0B08bH1wkIXqGOElIUE53b0dSQXc/view?usp=sharing
Comment: Please, post the result of `lsmod` ,  `ifconfig `  and  `iplink `  . You can also try the solution given here: [link] (http://www.linuxquestions.org/questions/ubuntu-63/wireless-became-disabled-how-do-i-enable-858357/) at comment #7. Also, you can try the solution given above by Mark Henderson.
Comment: lsmod:
http://textuploader.com/ao6td
Comment: ifconfig:
http://textuploader.com/ao6tj
Comment: and iplink is unknown command on my system
Comment: I dont know if its relevant but i noticed that when I launch my laptop, I dont get DOS screen. Y'know, "Press F12 to run DOS setup" shit. It's going straight to the Xubuntu login screen
Comment: I cannot see the brcmutil or brcmsmac module on your lsmod file. Have you searched for drivers with your driver utility? .  Which hardware are you using? PC model, processor, ram, OS version and kernel version.  However, here is one solution for this problem, read ahead: [Wifi not working after sleep on Xubuntu 14.04](http://ubuntuforums.org/showthread.php?t=2218043)
Answer: Yeah, seems a little harsh. Possibly an accidental click?
At any rate, have you tried this:
http://www.techytalk.info/ubuntu-fix-network-stopped-working-after-resume-from-sleep/
And if you are struggling to follow that solution, paste the results of "sudo lsmod" and we can go from there.


Casper JS run method firing early

Question: The addition of a this.echo command to a function is causing the casper.run method to be called before the links have been set
var casper = require('casper').create();

function getLinks() {
  this.echo("Getting links"); // <--------- This line cause everything to fail
  var links = document.querySelectorAll('table');
  return Array.prototype.map.call(links, function(e) {
    return e.getAttribute('id');
  });
}

var links = [];

casper.start('example.html', function() {
  links = this.evaluate(getLinks);
});

casper.run(function() {
  this.echo(links.length + ' links found:');
  this.echo(' - ' + links.join('\n - ')).exit();
});

Answer: Never worked with casper.js, but from the documentation:

As a reminder, think of the evaluate() method as a gate between the CasperJS environment and the one of the page you have opened; everytime you pass a closure to evaluate(), you're entering the page and execute code as if you were using the browser console.

So, this probably doesn't refer to casper, but to the global object of the document. this.echo doesn't exist and throws an error, the rest of the function is not executed and no links are collected. So, it's not that the callback function passed to run is executed early, the code to collect the links just never runs.
Try casper.echo("Getting links"); instead, or simply remove the call and move it inside start:
casper.start('example.html', function() {
  this.echo("Getting links");
  links = this.evaluate(getLinks);
});

Casper JS run method firing early


How do I connect to a wireless network, turn off bluetooth and airplain mode, on my Dell inspiron switch?

Question: I originally connected to a wireless network at a friends house and it was all gravy. I turned off my bluetooth and suddenly was unable to find any networks at all. Ubuntu has apparently confused my wireless card with my bluetooth connection.
But my internet server requires me to register my mac address with it in order to gain enternet access. In other words. I can't get access unless it's accessing the net through my wireless card and right now it's using my bluetooth connection to try and connect. Wierd huh?
I have made several attempts to turn on my wireless and it continually shows up grey and inaccessible. It says it's in airplane mode and I cannot get it to turn off airplane mode.
Every time I do and I exit the network manager it turns right back on, and while I'm in the network manager and turn off the airplain mode it still will not allow me to turn on my wireless card or access it at all. It recognises that it's there but will not turn it on.  What do I do guys?
Comment: Welcome to Ask Ubuntu! We need more hardware information to help you, can you look at [this question](http://askubuntu.com/questions/14008/i-have-a-hardware-detection-problem-what-logs-do-i-need-to-look-into) and then edit your question adding the information?
Answer: This bug has been reported here.
https://bugs.launchpad.net/ubuntu/+source/network-manager-applet/+bug/909938
If you've got a launchpad account then you can mark it as affecting you too.
Answer: Totally Agree.  I think the Ubuntu Programmers are loosing their wits.  We see that number 9 top tag is Wireless Issue and Number 12 is Sound.  They cannot fix easy driver issues.  Who wants to drive a really nice European sports car without no steering or braking.  Simple first always folks, I thought that was common sense.  No its up to you Ubuntu to prove us wrong.  We have been thankful but expect much more...
Comment: where is airplane mode on your laptop? In my settings turning off bluetooth, networking, and wireless networking are separate.


Set OnClickListener for custom View dynamically

Question: I add my custom View's dynamically but I don't know how to set click listeners for them.
My code:
rect1.setOnClickListener(new OnClickListener(){
        public void onClick(View v){
            frame_view.addView(new CustomView(getApplicationContext())
            .setOnLongClickListener(listener);
        }
    });

rect1 = my button.
Eclipse underlines addView and shows this error:

The method addView(View) in the type ViewGroup is not applicable for the arguments (void)
Answer: CustomView objCustomView=new CustomView(getApplicationContext());
objCustomView.setOnLongClickListener(listener);
frame_view.addView(objCustomView)

Comment: using `ViewGroup` allows to set click lisnener in method `addView`?


Update shared data between 2 controllers with services

Question: I have 2 controllers where I'd like to share data in between. One controller supports a view with a table that often changes it's "selected item" and the other fetches data from an API using said item information. Since those two controllers support views and are on the same page, they don't have a classic parent/child hierarchy, but are more 'siblings'.
Currently, I'm using a simple 'event bus' service which calls an event on the root scope using $emit which I inject in both controllers, where as one listens for changes using $rootScope.$on. Now I heard many times that this is a bad solution and I should use services to share data, but no one really explains how it's possible to watch the data for changes when also

using $watch is bad
$broadcast is bad

(there seems to be really a war on SO on which solution should more be avoided).
My current solution:
Controller1
export class Controller1 {
    private eventBus : Components.IEventBusService;

    constructor(eventBus: Components.IEventBusService) {
        this.eventBus = eventBus;
    }

    void itemSelected(item : IItemModel) {
        this.eventBus.emit("itemSelected", { "item" : item });
    }
}

Controller 2
export class Controller2 {

    constructor($scope : ng.IScope,
        eventBus : Components.IEventBusService) {

        eventBus.on("itemSelected", (event, data) =>
            this.onItemSelected(data), $scope);
    }

    private onItemSelected(data: any) {
        // do something with data.item!
    }
}

EventBusService
export interface IEventBusService {
    on(event, callback, scope): void;
    emit(event, data): void;
}

class EventBusService implements IEventBusService {

    private rootScope: ng.IRootScopeService;

    constructor($rootScope: ng.IRootScopeService) {
        this.rootScope = $rootScope;
    }

    on(event, callback, scope) : void {
        var unbind = this.rootScope.$on(event, callback);
        if(scope) {
            scope.$on("$destroy", unbind);
        }
    }

    emit(event, data) : void {
        data = data || {};
        this.rootScope.$emit(event, data);
    }

}

Are there any major drawbacks using this solution? Is 'the service way' better regarding to updating data etc?
Answer: You are correct, the $on and $emit should be avoided, as they create unnecessary noise. There's actually a pretty simple solution to this situation, I use it quite a bit.
What you need to have is an object in your service and give one controller a reference to it, and the other that needs to trigger an action can watch the service variable (good job on the TypeScript by the way):
class ItemSelectionWrapper { //just a wrapper, you could have other variables in here if you want
    itemSelected: IItemModel;
}

class EventBusService implements IEventBusService {

    private myObj: ItemSelectionWrapper;
    ...
}

Then in your controller that has itemSelected in its scope (let's assume Controller 1) you refer to the same variable:
export class Controller1 {
    private eventBus : Components.IEventBusService;

    constructor(eventBus: Components.IEventBusService) {
        this.eventBus = eventBus;
        this.eventBus.myObj = this.eventBus.myObj || {};
        this.eventBus.myObj.itemSelected = $scope.itemSelected;
    }
}

Now, since in Controller 2 you'll have the service injected, you'll watch the Service's variable:
$scope.$watch(function(){
        return busService.myObj,itemSelected;
    }, function (newValue) {
        //do what you need
});

Comment: So if I understand $watch correctly, I don't have to do anything other than.. wait for changes? No $broadcast etc.? And what's the point of the wrapper class? **Edit**: Also, is there a reason you made $scope.itemSelected?
Comment: @xvdiff That's right, `$watch` updates you on the change and you don't have to do `$broadcast`. The wrapper class I included since there's sometimes an issue with primitive classes directly on the scope or in a service, but the reason for that eludes me, so I developed a habit of having watched variables inside other objects, you don't have to do it. `$scope.itemSelected` I just assumed it's your variable that gets updated (you said the selected item often changes).
Comment: @xvdiff I added this because the service needs to have a reference for your variable. That way, when you update it, it gets updated in the service as well, and then the watch will trigger in your other controller.
Comment: And that won't happen with private class variables in TS? (Probably an absolut beginner question..)
Comment: @xvdiff Doesn't have to be private, you can make it public. The only thing that matters is that the service and your controller hold the same reference.
Answer:
Is 'the service way' better regarding to updating data etc?

Yes. Reason is that events are like "throw a ball in the air and hope someone catches it". Whereas service is a defined contract on how two controllers would interact.
If you use TypeScript you clearly care about Type Safety, services can give you that.

FYI We have the following guidance internally:
Shared Information between controllers
When a screen is highly nested with various placeholders with their own "html + controller" we need a way to share information (single source of truth) between these controllers.
1 RootController
The main controller for the section. Responsible for exposing the SharedClass instance on the scope (allows nested html segments to have direct access to this model) and any top level controller functions.
2 SharedClass
An angular service as it is easily inject-able into individual controllers / directives. Contains the information / functions that are shared in various portions of the screen e.g. multi select mode, Displayed / selected objects, operations for mutating these objects etc.
3 Individual Html + Controller
These subControllers can request the SharedClass using simple Angular Dependency Injection. The Controller HTML should automatically get access to the SharedClass instance (as that is exposed to scope by RootController).
Comment: Wow, you're everywhere. Like an angularized version of Mr. Skeet. Many thanks. Denoting a "root controller" which is responsible for exposing the shared service seems like a good idea.
Comment: Thanks for your kind words :)


How to extract multiple text and numbers from a string using sed?

Question: How can I extract 3 or more separate text from a line using 'sed'
I have the following line:
echo <MX><[Mike/DOB-029/Post-555/Male]><MX>

So far I am able to extract the 'DOB-029' by doing
sed -n 's/.*\(DOB-[0-9]*\).*/\1/p'

but I am not getting the other texts such as the name or the post.
My expected output should be Mike DOB-029 Post-555
Edited
Say I have a list within a file and I want to extract specific text/IDs from the entire list and save it to a .txt file
Comment: What's your expected output?
Comment: my expected output should be Mike DOB-029 Post-555
Comment: And what about the last block `/Male`? What is the logic underlying the problem? Extract everything `/` separated?
Comment: I don't want everything. The aim is to show only the first 3 text separated by '/'
Answer: sed 's/.*[\(.*\).\(DOB-[0-9]*\).\(Post-[0-9]*\).*/\1 \2 \3/' should do the trick!
Parts in between \( and \) are captured strings that can be called upon using \i with i the index of the group.
Script for custom use:
#! /bin/bash

fields=${1:-123}
file='/path/to/input'

name=$(sed 's/.*\[\([^\/]*\)\/.*/\1/' $file)
dob=$(sed 's/.*\(DOB-[0-9]*\).*/\1/' $file)
post=$(sed 's/.*\(Post-[0-9]*\).*/\1/' $file)

[[ $fields =~ .*1.* ]] && output=$name
[[ $fields =~ .*2.* ]] && output="$output $dob"
[[ $fields =~ .*3.* ]] && output="$output $post"

echo $output

Set the file with the line you want to parse in the file variable (I can add more functionality such as supplying the file as argument or getting it from a larger file if you like). And execute the script with an int argument, if this int contains '1' it will display name, if 2, it will display DOB and 3 will output post information. You can combine to e.g. '123' or '32' or whichever combination you like.
Stdin
If you want to read from stdin, use following script:
#! /usr/bin/env bash

line=$(cat /dev/stdin)

fields=${1:-123}

name=$(echo $line | sed 's/.*\[\([^\/]*\)\/.*/\1/')
dob=$(echo $line | sed 's/.*\(DOB-[0-9]*\).*/\1/')
post=$(echo $line | sed 's/.*\(Post-[0-9]*\).*/\1/')

[[ $fields =~ .*1.* ]] && output=$name
[[ $fields =~ .*2.* ]] && output="$output $dob"
[[ $fields =~ .*3.* ]] && output="$output $post"

echo $output

Example usage:
$ chmod +x script.sh
$ echo '<MX><[Mike/DOB-029/Post-555/Male]><MX>' | ./script.sh 123
Mike DOB-029 Post-555
$ echo '<MX><[Mike/DOB-029/Post-555/Male]><MX>' | ./script.sh 12
Mike DOB-029
$ echo '<MX><[Mike/DOB-029/Post-555/Male]><MX>' | ./script.sh 32
DOB-029 Post-555
$ echo '<MX><[Mike/DOB-029/Post-555/Male]><MX>' | ./script.sh
Mike DOB-029 Post-555

Comment: My pleasure, you can thank me by accepting the answer :)
Comment: Is there a way to modify this code or create a script so I have the option to take text at different times? So if I want to take the Name only or the DOB-029 or Post-555 or both
Answer: A solution with awk:
echo "<MX><[Mike/DOB-029/Post-555/Male]><MX>" | awk -F[/[] '{print $2, $3, $4}'

We set the delimiter as / or [ (-F[/[]). then we just print the fields $2, $3 and $4 which are the 2nd, 3rd and 4th fields respectively.
With sed:
echo "<MX><[Mike/DOB-029/Post-555/Male]><MX>" | sed 's/\(^.*\[\)\(.*\)\(\/[^/]*$\)/\2/; s/\// /g'

Comment: If the OP didn't request it for `sed`, I'd have suggested `awk` too. A scripting language with the power of a programming language, there's just no way to beat it :)
Comment: i fell in love recently.. :-)
Comment: That is a good idea but it may not work on all the fields I may have, what if the fields are not consistent among multiply files? So the DOB-029 may not be in the 2nd field all the time
Comment: @Mikey: Modify your question please, with different scenarios...
Comment: @Mikey: or give a scenario where this is not working.. we can fix that up then.
Answer: use the bash substitution builtins.
line="<MX><[Mike/D0B-029/Post-555/Male]><MX>";
linel=${line/*[/}; liner=${linel%\/*}; echo ${liner//\// }


Workflow for dynamically adding groups for an application

Question: I have done some research on how to check whether a user is within a specific group.
good post:
Restrict my facebook app from other members. But allowed to those who are in a particular group
What I need is to allow users to create there own group but use the custom objects and actions I provide.  The custom object and actions describe or give boundaries to the application I am creating in Facebook.  I think this is done in Mafia Wars ( you only play with your friends maybe? ).
Let me know your thoughts!!!
Markus
Answer: After further review...
I am going about this all wrong.  The platform, Facebook in this case, is designed to segregate users already.  It's called being someone's friend LOL.  If a user logs into my app they will be presented with all of they're friends who have also acquired or accepted the app too.
In other words I need to really read the Facebook API in it's entirety and pay attention.
Markus
Comment: Good job! Helping your self and digging deeper is key to being a successful developer IMO. Plus you learn much more than if someone just posts the answer for you :).


How can I do to make Ubuntu 14.04 to startup where I left in last session?

Question: I just haven't been able to configurate Ubuntu 14.04 so that it starts up in the last session, just like before I shut it down
Comment: Use hibernate / suspend instead of shutdown?
Answer: You can hibernate instead of shutting down.
Run these commands to enable it :
sudo -i

touch /var/lib/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla

echo "[Re-enable hibernate by default in upower]
Identity=unix-user:*
Action=org.freedesktop.upower.hibernate
ResultActive=yes
[Re-enable hibernate by default in logind]
Identity=unix-user:*
Action=org.freedesktop.login1.hibernate
ResultActive=yes" >> /var/lib/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla

Then reboot.
You should now have a Hibernate option in your power menu.
Source : http://ubuntuhandbook.org/index.php/2014/04/enable-hibernate-ubuntu-14-04/
Answer: Unfortunately, hibernate doesn't work in many cases, which can cause you to lose data if you expect your documents and applications to re-open when you switch your computer back on. Therefore, hibernate is disabled by default.
Test if hibernate works
Note : Always save your work before hibernating
You should save all of your work before hibernating the computer, just in case something goes wrong and your open applications and documents cannot be recovered when you switch on the computer again.
You can use the command line to test if hibernate works on your computer.

Open the Terminal by pressing
Ctrl+Alt+T or by searching for
terminal in the Dash.

Type sudo pm-hibernate into the terminal and press
Enter.Enter your password when prompted.

After you computer turns off, switch it back on. Did your open applications re-open?

If hibernate doesn't work, check if your swap partition is at least as large as your available RAM.
Enable hibernate
If the hibernate test works, you can continue to use the sudo pm-hibernate command when you want to hibernate.
You can also enable the hibernate option in the menus. To do that, use your favorite text editor to create /etc/polkit-1/localauthority/50-local.d/com.ubuntu.enable-hibernate.pkla. Add the following to the file and save:
[Re-enable hibernate by default in upower]
Identity=unix-user:*
Action=org.freedesktop.upower.hibernate
ResultActive=yes

[Re-enable hibernate by default in logind]
Identity=unix-user:*
Action=org.freedesktop.login1.hibernate; org.freedesktop.login1.hibernate-multiple-sessions
ResultActive=yes

Source : Official Documentation


How do I adjust bottom of bar chart created with Pandas

Question: I have created a bar chart using the
grouped.plot(kind='bar')
method in Pandas. However the vertical x labels get cut off. when I try to change the bottom variable by saying
grouped.plot(kind='bar',bottom=0.2)
I get an error message:
TypeError: bar() got multiple values for keyword argument 'bottom'
So the method is sending it's own value for bottom and I don't know how to replace that.
I could avoid it and simply use the pyplot bar() method directly, but that means specifying the left and height variables directly and with the groupby object I am using, this will get rather tricky, so I am really hoping not to do that.
 Is there a way I can pass a different bottom variable through Pandas's .plot(kind='bar') method ?
Answer: One option is to adjust the bottom margin after plotting with the following call.
<code>plt.subplots_adjust(bottom=.3)
</code>
Comment: For met it does adjust the bottom margin, but the vertical x labels still get cut off. I just get a blank space below the cut-off x labels
Comment: Actually, disregard my comment, it seems I was messing it up with custom tick formatters :) But if you are interested in adjusting the space between the ticks and the xlabel, see comments discussion about labelpad here: http://stackoverflow.com/questions/21539018/how-to-change-separation-between-tick-labels-and-axis-labels-in-matplotlib


What is the most general distribution for which E[1/x] = 1/E[x]?

Question: What is the most general distribution for which the expected value of the multiplicative inverse equals the multiplicative inverse of the expected value?
Motivation: I'm into modelling dynamics on graphs and I found a problem which is easily solvable in cases where the degree distribution of the vertices is a distribution where $E[1/k] = 1/E[k]$. ($k_i$ is the degree of the $i$th vertex)
From this solution I may gain an insight into how to unify multiple models.
So particularly I'm looking for a distribution which consists of non-negative, finite integers. But I'm also interested in continuous solutions. Distributions where $E[1/k^n]=1/E[k^n]$ may also help unifying the models.
What I do know so far, that $k_i=1$ is a particular solution.
In the continuous case every function where $f(x)=f(1/x)$ and $E[x]=1$ is a solution.
I know what momentum generating functions are and they seem like a good direction to try in, but I failed so far.
What is the most general form of this distribution? Does it have a name? It sounds like something trivial, like a "famous" distribution, but I can't find it.
Comment: similarly $k_i=c$ for any constant $c$ is also a solution. So any regular graph. And that is it.
Answer: By Jensen's inequality applied to the convex function $f(x) = x^{-1}$ on $(0,\infty)$,
$$
\frac{1}{\mathbb{E}[X]} < \mathbb{E} \left[ \frac{1}{X} \right]
$$
for any non-constant nonnegative random variable $X$. (See also this for a discussion of the equality cases of Jensen's inequality.) Thus, the constant random variable is the only such random variable.


Cake HABTM Query, Order By Rand()

Question: I'm aware that Cake HABTM associations are tricky at the best of times, but I seem to be making life even harder for myself...
If I want to return a random Item from the db, I can do it as follows in the Item model:
$random = $this->find('first', array(
    'order' => 'rand()'
));

and if I want to find all the Items that are in a certain Category (where Item has a HABTM relationship to Categories), I know I can get a result set through $this->Categories->find.
My question is: how can I combine the two, so I can return a random Item that belongs to a specified Category?  Is there any easy way?  (If not, I'll gladly take any suggestions for a laborious way, as long as it works ;)
ETA: I can get some of the way with Containable, maybe: say I add the line
'contain' => array('Categories'=>array('conditions'=>array('Categories.id'=>1))),

then the Item results that I don't want come back with an empty Categories array, to distinguish them from "good" items.  But really I don't want said Item results to be returned at all...
ETA(2): I can get a workaround going by unsetting my results in the afterFind if the Categories array is empty (thanks to http://nuts-and-bolts-of-cakephp.com/2008/08/06/filtering-results-returned-by-containable-behavior/ for the tip), and then having my random find function not give up until it gets a result:
while (!is_array($item)) {
    $item = $this->random($cat);
}

but ugh, could this be any clunkier?  Anyway, time for me to stop editing my question, and to go away and sleep on it instead!
Comment: ORDER BY rand() is an antipattern. It will result in an utterly slow query! I guess you just want the first X rows returned: rand() will be generated for all rows, then all rows will be sorted according to it, whereby rand() is not an indexed field. Just thereafter will be the first X of it returned.
Comment: Yeah, I saw some red flags being raised over ORDER BY rand().  It works fine for my tiny test database, I can imagine it being impossible to bear as the db grows.  Still, finding a better way to retrieve a random record seemed like the next problem to tackle, after dealing with my current one!
Answer: Try this:
<?php
$this->Item->bindModel(array('hasOne' => array('ItemsCategory')));
$random = $this->Item->find('all', array(
  'order' => 'rand()',
  'conditions' => array('ItemsCategory.category_id' => '1')
  ));
?>

Comment: Good call, creating an association on the fly, exactly what I needed.  Of course it took me half an hour to get it to work... because I'd forgotten to properly undo my changes to AfterFind.  Thanks!

Cake HABTM Query, Order By Rand()


Differentiate between a unix directory and file in C and C++

Question: Given a path, say, /home/shree/path/def, I would want to determine if def is a directory or a file.  Is there a way of achieving this in C or C++ code?
Answer: The following code uses the stat() function and the S_ISDIR ('is a directory') and S_ISREG ('is a regular file') macros to get information on the file. The rest is just error checking and enough to make a complete compilable program.
#include <stdio.h>
#include <errno.h>
#include <sys/stat.h>

int main (int argc, char *argv[]) {
    int status;
    struct stat st_buf;

    // Ensure argument passed.

    if (argc != 2) {
        printf ("Usage: progName <fileSpec>\n");
        printf ("       where <fileSpec> is the file to check.\n");
        return 1;
    }

    // Get the status of the file system object.

    status = stat (argv[1], &st_buf);
    if (status != 0) {
        printf ("Error, errno = %d\n", errno);
        return 1;
    }

    // Tell us what it is then exit.

    if (S_ISREG (st_buf.st_mode)) {
        printf ("%s is a regular file.\n", argv[1]);
    }
    if (S_ISDIR (st_buf.st_mode)) {
        printf ("%s is a directory.\n", argv[1]);
    }

    return 0;
}

Sample runs are shown here:

pax> vi progName.c ; gcc -o progName progName.c ; ./progName
Usage: progName
       where  is the file to check.

pax> ./progName /home
/home is a directory.

pax> ./progName .profile
.profile is a regular file.

pax> ./progName /no_such_file
Error, errno = 2

Comment: I prefer it with error checking, as that is often left out of examples and people don't necessarily know how to put it back in.
Comment: I've left it in, but clarified in the text what the important bits are.
Comment: your code is a bit cumbersome because of the error checking.  I suggest removing this and adding some comment like "check for errors: file doesn't exist, not enough arguments".  I think it'll make your answer a bit better
Answer: Use the stat(2) system call. You can use the S_ISREG or S_ISDIR macro on the st_mode field to see if the given path is a file or a directory. The man page tells you about all the other fields.
Answer: What about using the boost::filesystem library and its is_directory(const Path& p) ? It may take a while to get familiar with, but not so much. It probably worths the investment, and your code will not be platform specific.
Answer: Alternatively you can use system() function with in built shell command "test".
system returns the exit status of command last executed

 string test1 = "test -e filename" ;
 if(!system(test1))
 printf("filename exists") ;

string test2 = "test -d filename" ;
 if(!system(test2))
  printf("filename is a directory") ;

 string test3 = "test -f filename" ;
 if(!system(test3))
  printf("filename is a normal file") ;

but I am afraid this would work only on linux..
Comment: While this would work, the performance will leave a lot to be desired.  Every call to system() will fork and then exec a new shell to interpret the command.
Comment: Problematic if filename contains whitespace, I think you'd have to escape it.


Jquery Mobile Select not updating to show value after options added

Question: I have a very simple select box:
<select  id="collectorMainsInspEmissSelect">
    <option></option>
</select>

It has a default option that shows nothing and has no value.
Whenever a button is clicked:
Add Emiss
It runs this function:
function addEmiss() {

    var last = $("#collectorMainsInspEmissSelect option:last-child").val();
    if ($.isNumeric(last)) {
        $("#collectorMainsInspEmissSelect option:last").after("<option value=" + (parseInt(last) + 1) + ">" + (parseInt(last) + 1) + "</option>");
        $("#collectorMainsInspEmissSelect option:last").prop('selected', true);
    }
    else {
        $("#collectorMainsInspEmissSelect option:last").after("<option value=1>1</option>");
        $("#collectorMainsInspEmissSelect option:last").prop('selected', true);
    }
    console.log($("#collectorMainsInspEmissSelect").val());
}

What this does is checks the last option in that select.  If it's blank, it makes a new option with a value and text of 1.  Otherwise, it adds a new option which was the previous option incremented.
That part works just fine.  New options are added.
Next, I have it set the value of the select to be the last option.  I want it to visually change the select box to show the last option, and I want the value to be that option as well.
In the background, the value is changing.  Visually, however, it is not.
I've got that console.log there to show that the value increases every time the button is clicked.
Here's a jsfiddle of what I want it to do: https://jsfiddle.net/w5r93t3c/1/
You'll notice that it's working fine in the jsfiddle.  That's my problem, too.  I don't understand why the select isn't visually updating in my Jquery mobile application.  Do I need to somehow refresh the select?
Comment: Solved.  Added `$("#collectorMainsInspEmissSelect").selectmenu('refresh', true);` at the end
Comment: You should post a formal answer to your question and accept it, not just a comment.
Answer: Solved. Added $("#collectorMainsInspEmissSelect").selectmenu('refresh', true); at the end


pyQt5 pass a file object to QWebEngineView

Question: how to send an opened file inside the main application to a page in QWebEngineView and handle it by javascript FileReader() function , as it was opened by an html5 file input inside the QWebEngineView
here is a part of my code
<code># -*- coding: utf-8 -*-
import sys,  os
from PyQt5.QtWidgets import ( QApplication,  QMainWindow)
from PyQt5.QtCore import QUrl
import PyQt5.QtWebEngineWidgets as QtWebEngineWidgets
import interface

class MyWindow(QMainWindow):

    def __init__(self, parent=None):
        QMainWindow.__init__(self, parent)
        self.ui = interface.Ui_MainWindow()
        self.ui.setupUi(self)

        web_view = QtWebEngineWidgets.QWebEngineView()
        self.web_view = web_view
        self.ui.verticalLayout_navigateur.addWidget(web_view)
        url = self.local_url("src/index.html")
        self.web_view.load(url)

        f = open('myfile.json', 'r')
        #send f to self.web_view and handle it by javascript FileReader() function
    def local_url(self, relativePath):
        absolutePath = os.path.abspath(relativePath)
        url = QUrl.fromLocalFile(absolutePath)
        return url
if __name__ == '__main__':
    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())
</code>
thanks
Comment: I'm voting to close this question as off-topic because Stack Overflow is not a code writing service.
Comment: i didn't find how to do it, or even if it's possible to do it, any help would be worth , and i am not asking for full code , just guides
Answer: i found an alternative solution, it's quite simple, instead of sending object file to read with javascript, i have just to read it in the main application and inject the content via a QWebChannel


Is it possible to upsert a subcollection entity for a parent document that does not yet exist?

Question: We are building an auth system that stores a subcollection of Sessions under a User document, which in turn lives under a User collection.
Example pseudocode:
.set("users/{USER_ID}/sessions/{SESSION_ID}", sessionData)

Is it possible to upsert a new session without having created the parent User document (with USER_ID) in the first place?
Answer: Yes, you can create a new document at a nested path even if the parent documents don't exist.
For mobile and web apps, you can also use security rules to make sure that the parent USER_ID exists before allowing a new session document.


Fresnel function and finding its maxima (local maxima)

Question: I have this one problem in my Calculus textbook which consists of finding all of the local maxima of the Fresnel function : $S(x)= \int_0^x\sin(\pi x^2/2) \ dx$
I solved for the critical points of the derivative $S'(x)=\sin(\pi x^2/2)$ and found out that there are two local maximums at $x = -2$ and $x = \sqrt2$.
My question is : Since I'm working with a sinusoidal function (which means that it's constantly repeating itself on a period) how should I denote my answer?
For example :
Should my answer resemble something of this sort?
$$x = \{-2+4n,\sqrt2+4n\}$$ where $n\in \Bbb Z$
Moreover, when you graph the derivative of the Fresnel function I see that the period is gradually shrinking so I wonder how this will affect the answer.
P.S. I recently started solving problems that consist of the Fundamental Theorem of Calculus so I know nothing more than that.
Comment: you are using the same name for the variable of $S$ and the integrand, but they are different
Answer: No, you're not going to be adding something regular to $x$ to find the other maxima. You said it yourself; a "gradually shrinking period" means that it's not actually periodic.
Instead, we're going to have maxima whenever $\frac{\pi x^2}{2}$ reaches certain values; one pattern for positive $x$ and one for negative $x$ (Since $S$ is an odd function, switching between positive and negative $x$ interchanges local maxima and local minima).


Ubuntu 16.04 ping to gateway works, ping to other win pc does not work

Question: I'm new to Ubuntu and started to like Linux but when I have problem with Linux, I have no idea what else to do. I have searched Google but none of the methods works.
Gateway
192.168.1.1
Other win 10 pcs
126.96.36.199
Ping to 192.168.1.8 100% packet loss and also 220.127.116.11
I have checked my /etc/network/interfaces seems to be normal with dhcp setup
Where do I have to look? Please help.
Thanx
Answer: Maybe the problem is on Windows. In most installations by default, Windows doesn't answer to ping requests.


how to find id by class name python selenium

Question: <input class="select_step ON " id="step_9285985_select" name="step_9285985_select" type="checkbox" value="9285985">

I am automating the regular tasks of our project by python selenium. struct at one step, Please help me.
As per the above html code id="step_9285985_select" randomly changing for every time browser opens through webdriver (python Selenium). I want to find the randomly generated "id" by the class="select_step ON or any other alternative.
Comment: I suggest you learn how to accept and answer by selecting the grey tick mark next to an answer. Users take time to answer questions and the least we can do is to reward them with reputation points.
Answer: First find the element by CSS selector:
input_tag = driver.find_element_by_css_selector('input.select_step.ON')

Then get the id attribute:
print(input_tag.get_attribute('id'))


Vertically center child element, but allow parent to expand when child overflows

Question: I'm looking for a css-only solution to this problem. I have a parent and a child div. The parent has a minimum height. When the child div has a smaller height, I want it to be vertically centered in the parent. But when the child div expands past the parent's min-height, I want the parent to expand.
Illustrated in this image:

I can come close; position: relative on the child allows me to affect the parent height while still positioning the child, but I can't figure out how to determine the correct position (top: 50% plus transform: translateY won't work for me since the parent's height is not fixed).
This one has me stumped! Thanks in advance for any suggestions.
Answer: You can easily do this with flex:

.container {
  min-height: 300px;
  display: flex;
  background: red;
  justify-content: center; /* Center horizontally */
}

.container>div {
  height: 200px;
  width: 200px;
  background: blue;
  margin: auto; /* Center vertically */
}

some content

With bigger content height:

.container {
  min-height: 300px;
  display: flex;
  background: red;
  justify-content: center;
}

.container>div {
  height: 800px;
  width: 200px;
  background: blue;
  margin: auto;
}

some content

Comment: Thanks for the answer, looks good! I won't be able to test before Monday, I'll get around to accepting a working answer after that.


cannot run mysqld on fedora 36 after enabling the service with systemctl

Question: I am not able to run mysqld, the socket connects without problem but there are some issue creating configurations files:
joy@fedora /]$ mysqld
2022-11-12 12:38:24 0 [Note] mysqld (mysqld 10.5.16-MariaDB) starting as process 4650 ...

2022-11-12 12:38:24 0 [Warning] Can't create test file /var/lib/mysql/fedora.lower-test

mysqld: Can't create file '/var/log/mariadb/mariadb.log' (errno: 13 "Permission denied")

2022-11-12 12:38:24 0 [ERROR] mysqld: File '/var/lib/mysql/aria_log_control' not found (Errcode: 13 "Permission denied")

2022-11-12 12:38:24 0 [ERROR] mysqld: Got error 'Can't open file' when trying to use aria control file '/var/lib/mysql/aria_log_control'

2022-11-12 12:38:24 0 [ERROR] Plugin 'Aria' init function returned error.

2022-11-12 12:38:24 0 [ERROR] Plugin 'Aria' registration as a STORAGE ENGINE failed.

2022-11-12 12:38:24 0 [ERROR] InnoDB: The innodb_system data file 'ibdata1' must be writable

2022-11-12 12:38:24 0 [ERROR] InnoDB: The innodb_system data file 'ibdata1' must be writable

2022-11-12 12:38:24 0 [ERROR] Plugin 'InnoDB' init function returned error.

2022-11-12 12:38:24 0 [ERROR] Plugin 'InnoDB' registration as a STORAGE ENGINE failed.

2022-11-12 12:38:24 0 [Note] Plugin 'FEEDBACK' is disabled.

2022-11-12 12:38:24 0 [ERROR] Could not open mysql.plugin table: "Table 'mysql.plugin' doesn't exist". Some plugins may be not loaded

2022-11-12 12:38:24 0 [ERROR] Failed to initialize plugins.

2022-11-12 12:38:24 0 [ERROR] Aborting

When running with superuser:
[joy@fedora /]$ sudo mysqld

2022-11-12 12:41:13 0 [Note] mysqld (mysqld 10.5.16-MariaDB) starting as process 4679 ...

mysqld: Please consult the Knowledge Base to find out how to run mysqld as root!

2022-11-12 12:41:13 0 [ERROR] Aborting

Answer: the problema was solved connecting as root with the command mariadb -u root


Specifying file path in Mac

Question: I shifted to Mac last week and trying to run python code that i used in my windows machine.  However, I could not specify the file path correctly and repeatedly getting error.
File path as seen from machine:

The code i used is as follows:
<code> for line in open('Macintosh HD/Users/mageshpoondi/Documents/2015/Travel/IPL2015-5.5.2015.txt')
</code>
I tried including Magesh's MacBook Pro before Macintosh HD, replaced forward slash with backward ones, removed the space between Macintosh & HD...nothing seem to work...getting an error..."No such file or directory".
I am sure this is a trivial question....but fighting for an answer for couple of hours is frustrating.
Can someone help please?
Answer: What you really want is <code>/Users/mageshpoondi/Documents/2015/Travel/IPL2015-5.5.2015.txt</code>.  It's a standard UNIX path.
Comment: That, or `/Volumes/Macintosh HD/Users/`... All mounted volumes live in /Volumes.

Specifying file path in Mac


Move text in EditText to the right

Question: I want the text in the EditText to move to the right. Becouse if not the the first leter is covered by the border of the EditText.
Answer: Use android:paddingLeft="Xdp"
Replace X with the right number to make it work good, for instance, 10dp
Answer: Try to increase the padding of the EditText in the XML. That should work.
Answer: Use android:gravity="right", That should work

Move text in EditText to the right


Is the following function bounded or no?

Question: Is the following function bounded or no?
$$g(x) = 3 + \frac{2}{\sqrt{9-x^2}},$$
My professor said that it is not bounded as $g(x) \geq \frac{11}{3}$, but when I solved I found that $ 3 + \frac{2}{3} \leq g(x) < 3$ , so what is right ?
Thanks!!
Comment: How can g (x) < 3 if $\sqrt {9-x^2}\ge 0$?
Comment: And how can g (x) \le 3 +\frac 23$ if $\sqrt {9-x^2}\le 3$?
Comment: Btw $a > c< b$ is not a proper statement.  You mean $a>c $ and $b>c $.  You can't combine them like that.  You can combine them as $c< \min (a,b)$.  But you did this wrong as $g (x)>3$ and $g (x)\ge 3+\frac 23$.
Answer: Its not bounded since $f(x) \to +\infty$ when $x \to 3^{-}$.


Charting out a Mathematical Learning path for a future career in Computer Science

Question: I'm looking for advice on what all things to learn . I am aware of the fact that CS makes heavy use of Discrete Mathematics , Probability , Calculus , Algebra , Statistics .
What all topics from the above , and apart from them , should I study , and in which order ?
I'd also love it if any entry level texts for the same can be pointed out .
Thanks in advance :)
Comment: My recommendation would be to look at the undergrad and grad math CS programs requirements of several of the big name schools around the nation and write out a list. See where they intersect and then repeat it with second tier schools. This will generate a very realistic list.
Comment: My advice to you would be to start with Linear Algebra and/or Probability. With high school math you can get pretty far into the concepts especially linear algebra. Eventually you will hit topics where derivatives and integrals come up. Once this happens you will need to get up to speed with differential and integral  calculus. You could do calculus first but it may be more discouraging.
Comment: Speaking as a mathematician who's working as a programmer, I'd pick a CS problem you find interesting  (theoretical or practical) and work on it until you find some math concept you need and don't know. Learn that, then get back to the problem. Build a web scraper for your favorite sites, or a twitter bot that searches for and replies to very specific phrases. Both will get you knee deep into concurrency and complexity if you want to do them at moderate scale, which will generate plenty of math problems.
Answer: I suppose you are a high school student. If there advisers who are familiar with your background in math so far and who know about CS, then give first priority
to their advice. Second, I like @Moo's suggestion because that method is
empirical and not just based on opinions of people with unknown reputations;
my only modification might be to put some emphasis on requirements at
universities you might feasibly attend.
Now, for my personal opinions, which might be of some use.
I would put primary emphasis on discrete mathematics because it is
directly relevant and perhaps most feasible for self study.
If you have not already done so, you might try learning a few
computer languages and getting familiar with UNIX (LINUX) operating
systems. Many high school students have done self study of computer languages
that has been helpful later on.
You might consider taking AP statistics if it is taught by someone with actual applied
experience. In my experience, some students are not really ready for
calculus in high school, and get off to a much better start with
college math if they get ready to start lower division calculus
in their first year, with strong backgrounds in algebra, trigonometry, analytic geometry,
and perhaps the beginnings of linear algebra. Take a formal course in
linear algebra at the first opportunity,
usually immediately following beginning calculus. If number theory
is a separate course, take it.
Do some reading about various professional opportunities in CS.
Consider which of them appeal to you most and what topics, possibly
including some non-mathematical ones, might be relevant.
In particular, you might read some introductory books on linguistics, neural nets, or quantum mechanics. If you are a US citizen, you might consider
what kinds of computer careers lead to jobs that are not likely to
get routinely sent to other countries.


Will this equation with $\sin$ and $\arcsin$ cancel?

Question: It can be said that $\arcsin(\sin(x))= x$ are inverses if $x \lt 2\pi$.
Can it also be generalized so that $\arcsin(\sin(d\cdot x))= d\cdot x$ if $x \lt 2\pi\cdot d$ for a constant $d$?
Answer: $\arcsin$ is the invese function of $\sin x$ only if $x$ is restricted to the range $[-\frac \pi 2, \frac \pi 2]$.  It is true that $\arcsin (\sin (d\cdot x))=d\cdot x$ for $-\frac \pi 2\le d\cdot x \le\frac \pi 2$
Answer: You are incorrect about the domain of arcsine. Arcsine has a domain of values $y$ where $-1 \leq y \leq 1$, which means if we take $y = \sin(x)$ our values of $x$ are restricted by $-\pi/2 \leq x \leq \pi/2$. So as long as your constant $d$ is such that $zd = x$ where $x \in [-\pi/2, \pi/2]$ then we do know $\arcsin(\sin(dz)) = dz$. To say that this idea is "generalized" is also not true though, since it requires us to introduce a constant $d$ in addition to our variable $x$. The true generalization is that $\arcsin(\sin(x)) = x$ for $x \in [-\pi/2, \pi/2]$. It is trivial that we can write $x$ as a product of another variable and a constant. Choose any $c \neq 0$ and set $z = \frac{x}{c}$ to see what I mean.


Convert Time Stamps to Different Timezone in JavaScript

Question: I have this list of times in timezone "-07:00" and I want to convert them to "+05:00".
<code>"hours": [
    {
      "from": "11:00",
      "to": "21:00",
      "dayOfWeek": "MONDAY"
    },
    {
      "from": "11:00",
      "to": "21:00",
      "dayOfWeek": "TUESDAY"
    },
    {
      "from": "11:00",
      "to": "21:00",
      "dayOfWeek": "WEDNESDAY"
    },
    {
      "from": "11:00",
      "to": "21:00",
      "dayOfWeek": "THURSDAY"
    },
    {
      "from": "11:00",
      "to": "21:00",
      "dayOfWeek": "FRIDAY"
    }
  ]
</code>
How to do this efficiently using a library like moment.js? I have worked on a method but it's not up to par.
<code>function formatDates(hoursList, shopDate, userDate){
    var moment = require('moment');
    var selectedDateText = "";
    var convertedDateList = [];

    for (var x = 0; x < hoursList.length; x++) {
        var fromDate = shopDate.clone();
        var fromMoment = moment(fromDate.format(), "YYYY-MM-DD HH:mm Z");
        var fromTime = fromMoment.utcOffset(userDate.utcOffset());
        fromTime.hours(parseInt(hoursList[x].from.split(":")[0]));
        fromTime.minutes(parseInt(hoursList[x].from.split(":")[1]));
        fromTime.seconds(0);
        fromTime.milliseconds(0);
        console.log(fromTime.format());

        var toDate = shopDate.clone();
        var toMoment = moment(toDate.format(), "YYYY-MM-DD HH:mm Z");
        var toTime = toMoment.utcOffset(userDate.utcOffset());
        toTime.hours(parseInt(hoursList[x].to.split(":")[0]));
        toTime.minutes(parseInt(hoursList[x].to.split(":")[1]));
        toTime.seconds(0);
        toTime.milliseconds(0);
        console.log(toTime.format());

        var initialDay = {
            "from": "",
            "to": "",
            "dayOfWeek": ""
        };
        initialDay.dayOfWeek = fromTime.format("dddd").toUpperCase();
        initialDay.from = fromTime.format("HH:mm");

        if (toTime.format("DDD") != fromTime.format("DDD")) {
            var secondaryDay = {
                "from": "",
                "to": "",
                "dayOfWeek": ""
            };
            initialDay.to = "24:00";

            secondaryDay.dayOfWeek = toTime.format("dddd").toUpperCase();
            secondaryDay.from = "00:00";
            secondaryDay.to = toTime.format("HH:mm");

            convertedDateList.push(secondaryDay);
        } else {
            initialDay.to = toTime.format("HH:mm");
        }

        convertedDateList.push(initialDay);
    }
    console.log(convertedDateList);
    return selectedDateText;
}
</code>
Major problem is, some time stamps when converted will be in 2 different days. Hence the initial and secondary day in the code. Ex: When it's some 6 hours and it gets split in two, it should be added as Monday 9PM - 12PM and Tuesday 12AM - 3AM. And this is even trickier when it's an instance where the hours have all 7 days and some days, after conversion will even have hours from 12AM - 3AM and 9PM to 12PM.
How to tackle this properly?
Thanks.
Comment: So all you need to do is add 12 hours, modulo 24, and bump the day if necessary, right? Or do you need something else?
Comment: Yikes! I am sorry you have such messy input, without time zones. Ouch. What a mess. May I ask, what does `dayOfWeek` refer to? The start time or the end time? Are you able to change the input format? (Because that makes your problems go away.)
Comment: @RayToal Basically it's like Open Hours of a shop. "dayOfWeek" represent the day that it's open. Some shops are open on particular days only.
Comment: Got it--so these are local times. Can you just use dayOfWeek to refer to the starting time?
Comment: @RayToal The list of times are for the shop. Which is in a different timezone("-07:00"). I want to convert the list of times in accordance to the client side, which is in "+05:00".
Answer: For timezone related Moment has made a module dependent on moment.js - please find the documentation here
Comment: I don't get the region string. Just the offset value. Ex: "-07:00"


Logging of MySQL Queries and Forwarding to Syslog/Event log

Question: I was to able to enable Error log, General Query log, Slow Query Log and Binary Log and was able to forward the logs to Syslog. I have few questions about logging.
1) The error log is automatically forwarded to Event log in Windows. How do I forward the other logs to event log as well?
2) Is it possible to convert the multiline mysql logs to single line.
3) Is it possible to add some header to the log files or some tag at the beginning of each log line  so that it is easy to identify which log file it is.
4) In the slow query logs, some information is commented. When forwarded using rsyslog, will these commented lines be forwarded in all the Unix systems?
# User@Host: debian-sys-maint[debian-sys-maint] @ localhost []
# Query_time: 0.000297  Lock_time: 0.000220 Rows_sent: 0  Rows_examined: 0
SET timestamp=1539924163;
select count(*) into @discard from `information_schema`.`EVENTS`;

5) mysqlbinlog can be used to convert the binary log to human readable format. Is there a way where I can convert the binary file and forward it to syslog without writing any custom script? Is there a way in mysql or rsyslog?
Comment: The `SET timestamp` is allided if it is the same as before.
Answer:
1) The error log is automatically forwarded to Event log in Windows.
  How do I forward the other logs to event log as well?

There is no feature to do this in MySQL.

2) Is it possible to convert the multiline mysql logs to single line.

You can't change the format of the slow-query log without modifying the MySQL source code. It's hard-coded:
  ...
  if (my_b_printf(&log_file,
                  "# Query_time: %s  Lock_time: %s"
                  " Rows_sent: %lu  Rows_examined: %lu\n",
                  query_time_buff, lock_time_buff,
                  (ulong)thd->get_sent_row_count(),
                  (ulong)thd->get_examined_row_count()) == (uint)-1)
    goto err;
  ...

And further, for the other lines for each query logged.
But you can get related query performance information from the PERFORMANCE_SCHEMA, and you can even get summaries by query type. There are advantages and disadvantages. See for example this blog: https://www.percona.com/blog/2014/02/11/performance_schema-vs-slow-query-log/

3) Is it possible to add some header to the log files or some tag at
  the beginning of each log line so that it is easy to identify which
  log file it is.

Not without changing the source code.

4) In the slow query logs, some information is commented. When
  forwarded using rsyslog, will these commented lines be forwarded in
  all the Unix systems?

You can't forward the slow query log to syslog.

5) mysqlbinlog can be used to convert the binary log to human readable
  format. Is there a way where I can convert the binary file and forward
  it to syslog without writing any custom script? Is there a way in
  mysql or rsyslog?

No.
But you can use the mysqlbinlog tool to download remote binary logs as a way of backing them up. See https://dev.mysql.com/doc/refman/8.0/en/mysqlbinlog-backup.html
Comment: Thank you Bill. I will check this. Any idea about the other questions?
Comment: The timestamp in the logs seems to differ in 5.x and 8.0. Do you have any idea on what are all the possible timestamp formats in mysql logs?
Comment: I don't know offhand. You can research the source code as easily as I can. I already gave you a link to the file that implements the slow query log output.


Set peek height programmatically in BottomSheetDialogFragment

Question: I have a BottomSheetDialogFragment that I want to be able to show on any screen. I've spent the day trying to programmatically change the peek height of the sheet, but nothing seems to be changing it.
Here is my layout, bottom_sheet.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <LinearLayout
        android:id="@+id/bottom_sheet"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@color/white"
        android:orientation="vertical"
        app:behavior_hideable="true"
        app:behavior_peekHeight="96dp"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <androidx.core.widget.NestedScrollView
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </LinearLayout>

</LinearLayout>

You will notice I have an empty NestedScrollView. This is because I have made my content customizable when I show the bottom sheet on different screens, so I load a custom layout into it through code.
Here is my fragment class:
public class BottomSheetFragment extends BottomSheetDialogFragment {

    private LinearLayout bottomSheet;
    private NestedScrollView contentView;

    public BottomSheetFragment() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.bottom_sheet, container, false);
    }

    @Override
    public void onViewCreated(@NotNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        bottomSheet = view.findViewById(R.id.bottom_sheet);
        contentView = view.findViewById(R.id.content);
    }

    // Set the layout of the NestedScrollView by passing a layout ID
    public void setLayout(int layoutId) {
        if (contentView != null) {
            contentView.removeAllViews();

            View view = getLayoutInflater().inflate(layoutId, contentView, false);

            if (view != null) {
                contentView.addView(view);
            }
        }
    }
}

Then, where I want to show the bottom sheet, I do:
BottomSheetFragment bottomSheetFragment = new BottomSheetFragment();
bottomSheetFragment.show(getSupportFragmentManager(), bottomSheetFragment.getTag());

I want the peek height of the sheet to be 64dp from the top of the screen. How and where would I do this programmatically?
I also found that, even if I change the value of app:behavior_peekHeight="96dp" in the layout to something like 500dp, it still doesn't change anything when I show the sheet.
Answer: There is no view element in your bottom_sheet. Thats why you dont see any change when play around with peekheight.
Set some height to  bottom_sheet to view changes.
If you set the height (300) for example, you will clearly see the peek height taking effect.
For example,
<LinearLayout
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:background="@color/colorPrimary"
            android:orientation="vertical"
            android:id="@+id/bottom_sheet"
            app:layout_behavior="@string/bottom_sheet_behavior"
            app:behavior_peekHeight="96dp"
            app:behavior_hideable="true">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/content"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>

will Result in

To  set peekheight programatically
First you have to put your bottomsheet in coordinate layout like that
<androidx.coordinatorlayout.widget.CoordinatorLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">
        <LinearLayout
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            android:layout_width="match_parent"
            android:layout_height="300dp"
            android:background="@color/colorPrimary"
            android:orientation="vertical"
            android:id="@+id/bottom_sheet"
            app:layout_behavior="@string/bottom_sheet_behavior"
            app:behavior_peekHeight="96dp"
            app:behavior_hideable="true">

            <androidx.core.widget.NestedScrollView
                android:id="@+id/content"
                android:layout_width="match_parent"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </androidx.coordinatorlayout.widget.CoordinatorLayout>

In your class, you do that.
@Override
    public void onViewCreated(final View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        View bottomSheet = view.findViewById(R.id.bottom_sheet);
        BottomSheetBehavior behavior = BottomSheetBehavior.from(bottomSheet);
        behavior.setPeekHeight(150);
    }

Comment: Is there a way to do it without putting it in a Coordinator Layout? I've found that if I use it, it breaks other things.
Comment: Not really. You have to stick to Coordinator Layout. According to Docs, BottomSheetBehavior is an interaction behavior plugin for a child view of CoordinatorLayout
Comment: CoordinatorLayout works for this height without programmatically changing height. Thank you
Answer: You can set state STATE_EXPANDED on BottomSheetShow.
here's my working code snippet.
@Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        BottomSheetDialog dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);

        dialog.setOnShowListener((DialogInterface.OnShowListener) dialog1 -> {
            BottomSheetDialog d = (BottomSheetDialog) dialog1;
            FrameLayout bottomSheet = (FrameLayout) d.findViewById(com.google.android.material.R.id.design_bottom_sheet);
            if (bottomSheet != null)
                BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
        });

        return dialog;
    }

Answer: To set the peek height programmatically, you can:

Override onCreateDialog in your BottomSheetDialogFragment
Cast as BottomSheetDialog
Call setPeekHeight(int, boolean) on the behavior (BottomSheetBehavior)

override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    return super.onCreateDialog(savedInstanceState).apply {
        (this as? BottomSheetDialog)
                ?.behavior
                ?.setPeekHeight(BottomSheetBehavior.PEEK_HEIGHT_AUTO, true)
    }
}

The BottomSheetBehavior.PEEK_HEIGHT_AUTO sets a 16:9 ratio, and true is whether to animate.
Answer: You can set the peek height to your bottom sheet by getting its reference by override OnCreateDialog method inside your BottomSheetFragment
public class BottomSheetFragment extends BottomSheetDialogFragment {

    private LinearLayout bottomSheet;
    private NestedScrollView contentView;

    public BottomSheetFragment() {

    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.bottom_sheet, container, false);
    }

    @Override
    public void onViewCreated(@NotNull View view, Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        bottomSheet = view.findViewById(R.id.bottom_sheet);
        contentView = view.findViewById(R.id.content);
    }

    /**
     *
     * Your code to modify the bottom sheet behavior to set peek height which will be used in collapsed state
     * Here I set it to 80 percent of height of my screen
     * You can directly setPeekHeight() to your requirement
     */
    @NonNull @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        dialog = (BottomSheetDialog) super.onCreateDialog(savedInstanceState);

        dialog.setOnShowListener(new DialogInterface.OnShowListener() {
            @Override
            public void onShow(DialogInterface dialog) {
                BottomSheetDialog bottom_dialog = (BottomSheetDialog) dialog;

                FrameLayout bottomSheet = (FrameLayout) bottom_dialog.findViewById(com.google.android.material.R.id.design_bottom_sheet);
                assert bottomSheet != null;
                //BottomSheetBehavior.from(bottomSheet).setState(BottomSheetBehavior.STATE_EXPANDED);
                DisplayMetrics displayMetrics = requireActivity().getResources().getDisplayMetrics();
                int height = displayMetrics.heightPixels;
                int maxHeight = (int) (height*0.80);
                BottomSheetBehavior.from(bottomSheet).setPeekHeight(maxHeight);
            }
        });

        return dialog;
    }

    // Set the layout of the NestedScrollView by passing a layout ID
    public void setLayout(int layoutId) {
        if (contentView != null) {
            contentView.removeAllViews();

            View view = getLayoutInflater().inflate(layoutId, contentView, false);

            if (view != null) {
                contentView.addView(view);
            }
        }
    }
}

Answer: You have to overrride onCreateDialog and cast the super.onCreateDialog(savedInstanceState) to BottomSheetDialog that content  the methd behavior.setPeekHeight(Int)
override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    return (super.onCreateDialog(savedInstanceState) as BottomSheetDialog).apply {
      behavior.setPeekHeight(resources.displayMetrics.heightPixels / 2)
    }
}


Cayley-Bacharach for higher degree curves

Question: The Cayley-Bacharach theorem (also known as the 9 point theorem or the $8 \rightarrow 9$ theorem states that if two cubic curves intersect in 9 points, and C is any curve through 8 of those points, then C also passes through the 9th point.
Suppose we replaced the word cubic with quartic or quintic? Suppose I have two curves of order $d$ that meet in $d^2$ points (by Bezouts), how many of these points does another degree $d$ curve C have to pass through before we an say it passes through all points?
My intuition tells me that the answer would be ${d+2} \choose 2$$ -2$ - but is this accurate? I derive this from the dimension of the vector space = number of linear conditions imposed by points + 2 (our two curves which we want to span the vector space of vanishing polynomials).
I am new to this area, so forgive any faux pas made with notation, convention, etc.
Answer: Cayley-Bacharach theorem indeed can be generalized to any plane curve. If $C_1$ and $C_2$ are plane curves, $\deg C_1 = n_1$ and $\deg C_2 = n_2$ meeting at $n_1 n_2$ distinct points, then any curve of degree $n_1+n_2-3$ that passes through all but one point of $C_1 \cap C_2$ also passes through the remaining point.
In this form it is proven in Griffith-Harris in chapter on residues, so you need to know multi-dimensional residues to understand the proof.
There is also very nice paper Cayley-Bacharach theorems and conjectures  on the Cayley-Bacharach theorem, its applications and variations.


Ubuntu 14.04 Amd Catalyst drivers installation

Question: Following this guide I'm trying to get AMD Catalyst drivers installed using this command:
sudo apt-get install fglrx fglrx-amdcccle

But I'm getting...
kayl669@kayl669-pc:/usr/share/ati$ sudo apt-get install fglrx fglrx-amdcccle
Reading package lists... Done
Building dependency tree
Reading state information... Done
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies.
 fglrx : Depends: xorg-video-abi-11 but it is not installable or
                  xorg-video-abi-12 but it is not installable or
                  xorg-video-abi-13 but it is not installable or
                  xorg-video-abi-14 but it is not installable or
                  xorg-video-abi-15
E: Unable to correct problems, you have held broken packages.

Being very new to Ubuntu I'm meeting a lot of frustration when trying to install things where it seems that there are dependencies which won't install for this reason. Perhaps somebody could suggest a general procedure to follow to get past this type of issue. What is the problem in general terms - a conflict or corruption?
I'm actually using Lubuntu and my goal is to get a dual-monitors setup working.
What should I try next in this instance? Thanks
Answer: Turns out I already had a suitable driver. I just needed to use the xrandr command to expand my desktop across two monitors.


Switch user after upgrade to 14.04 not working

Question: i did an upgrade from 13.10 to 14.04.
Now the switch user option does not work any more.
the logged in user has to log out before any other user can log in.
Any idea how to fix this ?
Peter
Comment: Is this on the panel menu or from the lock screen? For the latter see: https://askubuntu.com/questions/453765/is-there-a-way-to-switch-users-from-the-new-lock-screen
Comment: Hi Takkat, the switching user works neither from the panel nor from the lock screen. Just nothing happens if i click on the switch account or a another specific user. :-(
Comment: weird... it works as expected on all my 14.04 machines here.
Answer: I had the same problem and the problem was the display manager. I previously had "gdm" and solved my problem by switching to "lightdm" Display Manager.
Run:
sudo dpkg-reconfigure lightdm

In my case I had "gdm" selected and I selected "lightdm" instead. Reboot and login again. Now, account switching should work both while logged in and from the lock screen.
Potentially you need to install lightdm.
sudo apt-get install lightdm

My machine was initially installed as a 12.04 server, and then I added Unity and finally upgraded to 14.04.1.
Answer: In some cases, both users must be running the same display manager. This is true on my machine that has multiple DMs available.


Is it safe to rely on an ASPX file being valid XML?

Question: If an aspx file compiles, is it safe to assume that it is valid XML?
Does ASP.NET work by parsing the server controls as XML?
Comment: Are you asking just for fun, or do you have a specific problem you're trying to solve?
Comment: @Tony Casale, I want to load an ASPX file as a text stream and get all the server controls.  I guess I could try this with regex, but I was hoping for something easier like XElement.Parse().Descendants().  Any ideas?
Comment: I don't know where you'd look exactly, but I'm sure you could utilize the parser libraries in the compiler to get an AST of the ASPX file.  That might be more work than you're looking to put in, though.  I think the regex solution is a viable one. One other suggestion might be to pre-process your ASPX files to turn anything that isn't a server control into CDATA nodes, then you would be able to use XElement and friends with impunity.  I'm on Linux these days, so I can't go poking around in .NET myself :)
Comment: I looked there (http://stackoverflow.com/questions/5274272/how-does-asp-net-parse-an-aspx-file-into-executable-code), but the complexity scared me a little.  I've found over and over again that if I have to think really hard about a problem I'm probably doing it the wrong way.  I like your idea about turning everything invalid into CDATA, but right now I'm working on an altogether different approach to the problem.
Comment: Well good luck - if you figure something out let us know how you solved it!
Answer: No - only the asp controls need to be valid XML.  It is completely "legal" to write non-XHTML code in an ASPX file.
Comment: No, it can even have invalid html!
Comment: Can I accurately interpret that to mean that everything inside an asp:Content must be valid XML?
Comment: No, asp:Content can have regular HTML in it, even if it's not valid XML.
Answer: I don't think you can assume that it's valid Xml for the simple reason that it can contain markup that's not valid xml or xhtml.
One quick example: You can write
 for the "break" tag, and this will display fine in all browsers.  The valid Xhmtl version is
, but this is not required.
Answer: XML != XHTML != ASPX
You can test this by making a DIV and putting "Hello's to all of you" which would be valid ASP and XHTML but not valid XML: "Hello's to all of you"


Proving prime divisibility relation between $a^2-a+3$ and $b^2-b+25$.

Question: Let $p$ be a given prime number. Prove that there exists an integer $a$ such that $p|a^2-a+3$ if and only if there exists an integer $b$ such that $p|b^2-b+25$.
I've managed to prove that if $p|a^2-a+3$ for some $a$, then $p|b^2-b+25$ for some $p$ like so:
Working mod $p$, we have $a^2-a+3=0$. Hence $9a^2-9a+27=0$, which implies $9a^2-6a+1=3a-26$. Rearranging this, we find that $$(3a-1)^2=(3a-1)-25$$ so simply taking $b=3a-1$ proves this part.
I had the idea of multiplying everything by $9$ because $3\times 9\approx 27$, and because $9$ is a square. However, I can't find a similar relation for turning $b^2-b+25$ into $a^2-a+3$.
According to the person I found this question from, this question is from a very old TST (I think it was from China, but we're not sure).
Comment: You have a flipped sign... $9a^2 - 6a + 1 = 3a - 26$
Comment: @DougM thanks, fixed
Comment: What this is saying is that any (odd) prime for which $-11$ is a quadratic residue can be expressed as $x^2 + xy + 3y^2.$ If $p \equiv 1 \pmod 3,$ we also have $p = u^2 + uv + 25 v^2.$ If $p \equiv 2 \pmod 3,$ we also have $p = 5s^2 + st + 5 t^2.$ Of course, $3$ does not work right, there is an imprimitive  form $3x^2 + 3xy+9y^2$ of discriminant $-99$
Answer: $3a - 1\equiv b\pmod p$
for any prime $p \ne 3$
$3$ has a multiplicative inverse.
$a \equiv 3^{-1}b + 3^{-1}\pmod p$
And if $p=3$ let $a = 1$
Comment: What's a multiplicative inverse?
Comment: The integers modulo $p$ forms a group under multiplication.  ($\mathbb Z_p^\times$)  Which means that every member of the group (excluding 0) has a counterpart such that their product equals 1.
Answer: $a^2-a+3\equiv0\pmod p$
$\iff(2a-1)^2\equiv-11$   for odd $p$
$4(b^2-b+25)=(2b-1)^2+99$
So, we need $(2b-1)^2\equiv-99\pmod p$
$\implies(2b-1)^2\equiv3^2(2a-1)^2\pmod p$
$\iff2b-1\equiv\pm3(2a-1)$
Comment: @user574848, $$4(a^2-a+3)=(2a-1)^2+11$$
Answer: Here is another proof, via quadratic residues. Note that, $a^2-a+3$ is odd, hence $p\neq 2$. Now, $p\mid a^2-a+3\iff p\mid (2a-1)^2+11$. Similarly, $p\mid b^2-b+25 \iff p\mid (2b-1)^2+99$. Namely, the goal is to prove,
$$
\exists a: p\mid (2a-1)^2+11 \iff \exists b: p\mid (2b-1)^2+99
$$
which is equivalent to proving,
$$
\left(\frac{-11}{p}\right) =1 \iff \left(\frac{-99}{p}\right) =1,
$$
where, $(a/p)$ is the standard Legendre's symbol. But this last statement is obvious, since $(-99/p)=(9/p)(-11/p)=(-11/p)$, as $(9/p)=1$, due to the fact that $9$ is a quadratic residue modulo $p$.


Refining Ticket Overflow

Question: At the beginning of each day, the player can receive 3 Refining Tickets as a login bonus. On that same screen, it says that up to 10 Refining Tickets can be saved. However, if someone wanted to save up their Refining Tickets over 4 days, they would end up with 12 from their login bonuses.
What would happen to the other 2 Refining Tickets received, as only 10 can be saved? Are they lost forever or do they get temporarily stored until the user can receive them.
This also applies to a 5th or 6th day of login bonus tickets being received. Basically anything over the max of 10.
Answer: A player can only ever have the maximum number of tickets, which I've only ever seen as 10 but I suppose it could change or they may add a way to increase it.  If you log in with 9/10 tickets on the day you should receive 6, you will be given 1 to bring your total to 10/10.
I generally keep 4 tickets, and each day either use the 3 given on a yellow ore or if it's the 6 day, use all 10 on a purple.  You can spend single tickets to speed up the current ore refinement by 1 hour, so when I get 6 I generally spend 2 on a yellow or purple.

Refining Ticket Overflow


Invalid literal for Decimal: u'3,982.75'

Question: I'm having trouble with a localized form field not accepting localized input. Entering a number with a comma as a decimal separator triggers a validation error. How to fixed it? How to make that value valid for decimal field?
Here's my sample models.py
class BankAccount(models.Model):
    balance = models.DecimalField(max_digits=10,
        decimal_places=2, default="0.00")

In my views.py where the error trigger:
def manual_opening(request):
    if request.method == 'POST':
       opening_bal = request.POST.get('opening_bal')
       form = AddBankAccountForm(request.POST)
       if form.is_valid():
           form.cleaned_data['balance'] = Decimal(opening_bal)
           .....

When my user input a value, for ex. 3,485.78, for their opening_bal. The system trigger an error that the Decimal function not allow the operation because the number has a comma.
Answer: A google search has revealed the truth!
Format Localization
revenue = forms.DecimalField(max_digits=4, decimal_places=2, localize=True)

Comment: You also need to add `USE_THOUSAND_SEPARATOR = True` to `settings.py`


Linear function preserving the Gram determinant

Question: In Euclidean space $X$ the Gram's  determinant of a system of vectors $x_1,...,x_k\in X$ is called the determinant of $k\times k$ matrix  $ [\langle x_i,x_j \rangle]$:
$
G(x_1,..,x_k)=\det[\langle x_i,x_j \rangle].
$
In $n$ dimensional Euclidean space $X$, let $f: X\rightarrow X$ be a linear mapping and let $k\in \{2,...,n-1\}$ be a fixed number.
I wish to prove not using exterior algebra that if
$
G(f(x_1),...,f(x_k))=G(x_1,...,x_k)
$
for each $x_1,...,x_k\in X$,
then $f$ is orthogonal mapping.
Thanks
Answer: You can solve this problem using polar decomposition. Write $f = o \circ p$ where $o \colon X \rightarrow X$ is orthogonal and $p \colon X \rightarrow X$ is self-adjoint and positive semi-definite. To show that $f$ is orthogonal, it is enough to show that $p = \operatorname{id}$.
Choose an orthonormal basis of eigenvectors $v_1, \dots, v_n$ of $p$ with $p(v_i) = \lambda_i v_i$ where $\lambda_i \geq 0$ and choose two distinct indices $1 \leq i < j \leq n$. Since $k \leq n-1$, we have $k - 1 \leq n - 2$ and so we can choose distinct indices $l_1, \dots, l_{k-1}$ such that $l_1,\dots,l_{k-1},i,j$ are all distinct. Then
$$ G(v_i,v_{l_1},\dots,v_{l_{k-1}}) = 1 $$
while
$$ G(f(v_i),f(v_{l_1}),\dots,f(v_{l_{k-1}})) = G(p(v_i), p(v_{l_1}), \dots, p(v_{l_{k-1}})) \\
= G(\lambda_i v_i, \lambda_{l_1} v_{l_1}, \dots, \lambda_{l_{k-1}} v_{l_{k-1}}) = \lambda_i^2 \cdot \prod_{r = 1}^{k-1} \lambda_{l_r}^2 $$
so
$$ \lambda_i^2 \prod_{r=1}^{k-1} \lambda_{l_r}^2 = 1. $$
In particular, $\lambda_{l_r} > 0$ for all $r$ and since the eigenvalues are non-negative, we get
$$ \lambda_i \prod_{r=1}^{k-1} \lambda_{l_r} = 1. $$
The same holds with $i$ replaced by $j$ and so we get
$$ \lambda_i \prod_{r=1}^{k-1} \lambda_{l_r} = \lambda_j \prod_{r=1}^{k-1} \lambda_{l_r} \implies (\lambda_i - \lambda_j) \prod_{r=1}^{k-1} \lambda_{l_r} = 0 \implies \lambda_i = \lambda_j. $$
Thus, we deduce that $\lambda_1 = \dots = \lambda_n$ and $\lambda_i^k = 1$ which implies that $\lambda_i = 1$ for all $1 \leq i \leq n$ so $p = \operatorname{id}$.


what to use to get data from the gridpanel?

Question: What is the difference between itemdblclick and rowdblclick?  Both of these methods seem to work well for gridpanel. Which is preferable for getting data from a row?
Answer: As you mention itemdblclick this seems to be the classic framework.
itemdblclick ( grid, record, item, index, e, eOpts )
rowdblclick ( grid, record, element, rowIndex, e, eOpts )

itemdblclick and rowdblclick are fired from different sources, but otherwise both are equally good to use. For both you receive the record, which holds the data and you receive an index, if you need it.
For me it is more about, what you want to tell another programmer, what you are listening for. And that's where you can differ between cell and row.
The record will be the same for both.
Comment: Okay, thank you! Now I get it


Twig generate url / Routing error / Function unknow

Question: I'm  using Silex 1.2 and Twig 1.0.
I'm trying to generate an URL with Twig.
Sign Up
However I get this error :
Twig_Error_Syntax Unknown "path" function.
So, like on this post (Silex - Twig_Error_Syntax: The function "path" does not exist) I added this on my boostrap.php.
$app->register(new UrlGeneratorServiceProvider());
$app['twig']->addFunction(new \Twig_SimpleFunction('path', function($url) use ($app) {
    return $app['url_generator']->generate($url);
}));

But I get this error :
RouteNotFoundException Unable to generate a URL for the named route "signUp" as such route does not exist.
Routing file
<?php

$routes = $app['controllers_factory'];

$routes->get('/', function () use ($app){
    return $app['twig']->render('home.html.twig');
});

$routes->get('/signUp', function () use ($app){
    return $app['twig']->render('signUp.html.twig');
});

$routes->get('/signIn', function () use ($app) {
    return $app['twig']->render('signIn.html.twig');
});

return $routes;

Can you help me ?
Thank's !
Comment: You didn't give your routes names. See the [examples](https://silex.symfony.com/doc/1.3/providers/url_generator.html) regarding the `bind()` method.
Comment: Indeed, thank's a lot !
Answer: The path /signUp is not the same as the route name you provide in path. You probable want a named route using bind like this:
$routes->get('/signUp', function () use ($app){
    return $app['twig']->render('signUp.html.twig');
})->bind('signUp');

Comment: Yes that's was the problem. Thank's !
Answer: Adding this to config/services.yaml solved it for me:
services:
    Twig\Environment:
        calls:
            - [addExtension, ['@Symfony\Bridge\Twig\Extension\RoutingExtension']]

    Symfony\Bridge\Twig\Extension\RoutingExtension:


Early money making strategies

Question: So I have read all the answers to this question here about how to grind money. This however seems to be an end-game money grind as they all mention Le Wow and the one indepth answer says two level 100 pokemon with this that and the other along with a 100,000 buy in.
What I want are good locations and/or strategies to use to get money along the way until the end game. I may have a pokemon catching addiction but 90% of my money goes into pokeballs and even with a good capture rate I am having a hard time keeping enough Poke Balls in my stock to catch new pokemon as I run into them.
I have played up to meeting Professor Sycamore so far and pretty much all of my money has come from trainer battles. What other options do I have?
Answer: The Battle Chateau is a good way to get early cash and help prepare for late-game money grinding. You gain access to the Chateau after defeating the first gym and heading to Route 7. If you start battling here early, you can cut out some of the monotony involved in trying to grind to Grand Duke/Duchess later in the game because the trainers will be right around your level (~15).
Comment: May seem like a dumb question.. What is the Battle Chateau?
Comment: @James: [It's a place where you can battle Trainers.](http://bulbapedia.bulbagarden.net/wiki/Battle_Chateau)  Defeated Trainers can be rebattled after an hour, and defeating enough Trainers will gradually unlock harder ones.
Answer: Other than the Battle Chateau, there are a few things you can do to gain money quicker in XY:

Find the Amulet Coin in Parfum Palace. Leave it on your lead Pokemon whilst battling trainers & gyms. It will double the Prize Money earned.
Unlock the Prize Money O-Power in Cyllage City (the 2nd Gym town) from Mr. Bonding in the Hotel, and use it before battling trainers & Gyms. Each level increases the output of Prize Money for 3 minutes:

Level 1: 1.5x
Level 2: 2x
Level 3: 3x

There are also ways you can save yourself money in the field:

Walk/Rollerskate/Ride back to town to heal up instead of using items, or take advantage of 'healer trainers' in certain longer Routes & Caves.

This means usually the only use you'll have for the Pokemart for a while will be Pokeballs.
It also means that any items you pick up along the way will be there for the important battles, when you really need them.

As an alternative to the above, get stuck into Berry farming for a while. There's usually a Berry equivalent for every item you can buy in the mart. For example:

PLZ Heal : Cheri Berry
BRN Heal : Rawst Berry
Antidote : Pecha Berry
Awakening : Chesto Berry
Full Heal : Lum Berry
Potion : 2x Oran Berry

Don't sell items like Nuggets, Stardust & Mushrooms (until you actually need the money for something). This might seem counter-intuitive, but think about it for a second.

When you lose a battle, you give up a percentage of your current in-wallet money. The lower your current money, the less you give out. Use these items as a 'safe' of sorts to store your real worth in.

Hold off on big purchases like TMs until you've unlocked the Bargain O-Power (Hotel Richissime in Lumiose).

Don't buy the other Mega Stones until you've maxed out your style. You can get them for as low as $10,000.
Comment: @James Yes, you have the option to use it on yourself or give it to other people. Using it on other people costs less power, however.
Comment: Can I actually use the O-Powers and level them with out having other people to game with?
Answer: 1.) One of the best ways to get money in X/Y is working at Hotel Richissime. You can do three jobs a day and earn 1,000 for each job. At first it might not seem like much, but the more you work, the more money you'll earn until eventually, you get 50k per job.
2.) Another way to earn money early on is working at the berry fields. After you harvest  the berries, you can put 3 of them in the compacter to make 3 bags of Mulch, each worth 100. It may seem boring and tedious, but it really works.
Answer:
As soon as you're able to reach it ingame, head to Hotel Richissime and speak to Mr. Bonding. He'll give you the Bargain O-Power. Use it for a 10%, then 25%, and finally, 50% off any Poke Mart purchases. Level it up by usage.
Trade with other players to obtain Happy Hour Smeargle. It doubles prize money when Smeargle uses the move in battle, and it stacks with the Amulet Coin for quadrupling the money.

Early money making strategies


Ubuntu Server 11.10 from USB?

Question: I tried 'burning' the .iso onto a USB like I normally would with Ubuntu Desktop or Server 12.04, but it gives me an error during installation and tells me that it can't get files from CD or something.  So, is a USB installation of Server 11.10 not possible?
P.S. I need to install 11.10 because 12.04 is giving me a LOT of problems trying to convert to a static IP.
Comment: What do you use to create the USB boot drive ? UNetBootin ?
Answer: I have personally installed various Ubuntu server versions from USB. I use the Ubuntu Startup Disc Creator (installed by default in Ubuntu desktop editions). I do remember something like this happening to me with another distro, and I think it had to do with the way I made the USB stick. This http://ubuntuforums.org/showthread.php?t=1369628 thread suggests that unetbootin could be the source of the issue in at least one instance, which also confirms my experience. If you haven't already, I'd try the Ubuntu Startup Disc Creator.
I have assumed you have an Ubuntu desktop install, my apologies if not.
Goodluck!
Answer: To install the desktop version of Ubuntu via USB drive, I used this tool: http://www.linuxliveusb.com/
Certainly it won't be much different with the server version.

Ubuntu Server 11.10 from USB?


Rails search form with multiple params

Question: I am working on a search form which should accept multiple params. But it currently accepts only one.
My Controller action:
def index
  @halls = Hall.order(:name).page(params[:page]).per(9)
  @city = City.all
  @venue_type = VenueType.all
  @event_type = EventType.all

  if !params[:city].blank?
    session[:city] = params[:city]
    city = City.find_by(name: params[:city])
    @halls = @halls.where(:city => city)
  end

  if !params[:venue_types].blank?
    session[:venue_types] = params[:venue_types]
    venue_types = VenueType.find_by(name: params[:venue_types])
    @halls = @halls.where(:venue_types => venue_types)
  end

 if !params[:event_types].blank?
    session[:event_types] = params[:event_types]
    event_types = VenueType.find_by(name: params[:event_types])
    @halls = @halls.where(:event_types => event_types)
  end

end
My view:

  <%= form_tag(halls_path, :method => "get", class: "navbar-form", id: "search-form") do %>

<%= select_tag "city", options_from_collection_for_select(City.all, "name", "name") %>

            <% @venue_type.each do |venue| %>

                  <%= check_box_tag 'venue_type[]', venue.name -%>
                  <%=  venue.name -%>

            <% end %>

            <% @event_type.each do |event| %>

                  <%= check_box_tag 'event_type[]', event.name -%>
                  <%=  event.name -%>

            <% end %>

      <button class="btn" type="submit">Search</button>
<% end %>

I bet the mistake is in the controller but as a newbie I can't find it.
Would be grateful for the answers.
Comment: try to print the `params` using `puts` in the `index` action and see whether you receive the correct params..
Answer: Your view defined the check_box_tag with:
<%= check_box_tag 'venue_type[]', venue.name -%>
<%=  venue.name -%>

<%= check_box_tag 'event_type[]', event.name -%>
<%=  event.name -%>

As you see, your controller must get :value_type & :event_type from params instead of :value_types & :event_types. So you can change from either view or controller, it should work, but I recommend change from view like this:
<%= check_box_tag 'venue_types[]', venue.name -%>
<%=  venue.name -%>

<%= check_box_tag 'event_types[]', event.name -%>
<%=  event.name -%>

Comment: thanks. Did that. But still doesn't show results matching the search query.
Comment: Could you log your params & update to your question?

Rails search form with multiple params


Temporary Credentials using AWS IAM

Question: I have a server, which should provide temporary AWS credentials to the client. The credentials will be transmitted using HTTPS.
The client should be able to upload S3 files, as well as download them. The concern I have is the following:
I have multiple users accessing ONLY their own directory: /Users/someUser/myfile.png
You can set policies to allow or deny S3 in general, but you can't grant only the access to a specific path.
What should I do about this? Will the HTTPS transmission be enough?
Then my second question.
If I hear "temporary credentials", I have a key in mind, that is valid for a couple of hours and then expires. But I'm not sure if IAM is really built for that.
Should I provide the same credentials for all users?
Or do I generate a key-pair for each client?
The server runs with PHP, the client with Objective-C.
Answer: You can specify permissions on a path in Amazon S3.  For more details see the following:
Using IAM Policies
Also, if you want to create "temporary credentials" you can use the AWS Security Token Service.  This service allows you to create credentials that last from 1 - 36 hours and you can put a policy on those credentials to limit their access.  For more details about the service see:
Security Token Service API Reference
Finally, there is an article written for the AWS Mobile SDKs that does something similar.  It has a server to issue temporary credentials to users that use an Amazon S3 bucket.  It limits the users to a "sub-folder" of the bucket and also limits their actions.  You can read and this sample here:
Credential Management for Mobile Applications
Hope this helps you get to the information you need.
Comment: how you have used the Security token service in AWS

Temporary Credentials using AWS IAM


How to locate element by partial XPath

Question: Trying to locate a text input box by its Xpath which dynamically changes some of the last elements every time the page is loaded.
This is the HTML for it.
<input type="text" value="" name="client[phones_attributes][1654091616613][number]" id="client_phones_attributes_1654091616613_number" class="placeholderField-input">

It's XPath is //*[@id="client_phones_attributes_1654091616613_number"]
The numbers change every load. I tried locating it by using this line but it didn't find it.
search = driver.find_element_by_xpath("//*[contains(@id, 'client_phones_attributes_')]")

Comment: Try to use [wait](https://selenium-python.readthedocs.io/waits.html#waits)
Comment: The page is already loaded I've done inputs before this point.
Comment: Then check if your `input` node located inside an `iframe`
Answer: you need to search as:
on last versions of selenium:
search = driver.find_element(By.XPATH, '//input[contains(@id, "client_phones_attributes_")]')

on your version
search = driver.find_element_by_xpath("//input[contains(@id, 'client_phones_attributes_')]")

Comment: Still doesn't fix the problem though.

How to locate element by partial XPath


How to add custom post fields in Uppy XHR request?

Question: Used Uppy XHR Upload. Docs: https://uppy.io/docs/xhr-upload/
How to add custom post fields in Uppy XHR request?
My params are:
endpoint: '/?test1=test2',
formData: true,
method: 'post',
fieldName: 'files[]',
// metaFields: [{ cmd: 'test1', name2: 'test2' }],
metaFields: [
  ['command', 'myvalue']
]

It is need to add my additional "post" fields for server, but test1=test2 are "get" params, 'command' and 'myvalue' - params without values (only keys are send via XHR). How to add "post" params and it`s values in Uppy XHR (or other uppy plugins, if in XHR not available)?
Answer: You should use meta in Uppy.Core to pass post parameters with values.
Eg:
Uppy.Core({

        meta: {
            professional_id: professional_id,
            client_id: client_id,
            post_id: post_id,
            proposal_id: proposal_id,
            folder_id: folder_id,
            version_no: version_no
        },

Answer: An alternate syntax would be:
 uppy.setMeta({content_type:2})
 uppy.use(Uppy.XHRUpload, { endpoint: 'document_uppy.cfm'
    ,id:'xhrupload_doc'
     ,bundle:false })

Please ensure you have set bundle to false