text:
Q: Right function for normalizing input of sklearn SVM I found several questions related to this, but no one solved my doubts.
In particular, the two answers to this question confused me even more.
I'm training a linear SVM on top of a set of features - Convolutional Neural Net features resulting from images. I have, for example, a 3500x4096 X matrix with examples on rows and features on columns, as usual.
I'm wondering how to properly standardize/normalize this matrix before feeding the SVM. I see two ways (using sklearn):

*

*Standardizing features. It results in features with 0 mean and unitary std.
X = sklearn.preprocessing.scale(X)

*Normalizing features. It results in features with unitary norm.
X = sklearn.preprocessing.normalize(X, axis=0)

My results are sensibly better with normalization (76% accuracy) than with standardiing (68% accuracy).
Is it a completely dataset-dependent choice? Or how can one choose between the two techniques?

A: You should choose the scaling scheme based on what makes sense with your data. There are different ways of scaling, and which one you'll use depends on the data. Each scheme brings values of different features into comparable ranges, but each of them preserve different types of information (and distort others) as they do so. And even though there are rational explanations behind why some scaling schemes are better suited for a specific case, there is nothing wrong with just trying these different ones (like you did with standard scaling and normalization) and using the one that works better (as long as you cross-validate or otherwise make sure that your performance measurement is general and accurate).
StandardScaler
This is what sklearn.preprocessing.scale(X) uses. It assumes that your features are normally distributed (each feature with a different mean and standard deviation), and scales them such that each feature's Gaussian distribution is now centered around 0 and it's standard deviation is 1.
It does this by calculating the mean and stdev for each feature, then converts each actual value for the feature into a z-score: how many stdevs away from the mean is this value? z=(value-mean)/stdev
This quite often works well but if the normality assumption is completely wrong for your case, then this may not be the best scaling scheme for you. Practically, in many cases where the normality assumption does not hold, but the distributions are somewhat close, this scheme still works pretty well. However, if the data is completely far away from normality, for example highly skewed, fat-tailed distributions (like a power-law), this scheme will not give good results.
Normalizer
This is what sklearn.preprocessing.normalize(X, axis=0) uses. It looks at all the feature values for a given data point as a vector and normalizes that vector by dividing it by it's magnitude. For example, let's say you have 3 features. The values for a specific point are [x1, x2, x3]. If you're using the default 'l2' normalization, you divide each value by sqrt(x1^2 + x2^2 + x3^2). If you're using 'l1' normalization, you divide each by x1+x2+x3. This makes sure that the values are in similar ranges for each feature, since each feature vector is a unit vector. If feature values for a point are large, so is the magnitude and you divide by a large number. If they are small, you divide them by a small number.
The reasoning is that you can think of your data as points in an n-dimensional space, where n is the number of features. Each feature is an axis. Normalization pulls each point back to the origin in a way that it is only 1 unit distant from the origin. Basically you collapse the space into the unit hypercube. The angles between the vectors for each point (from the origin to the data point) stay the same.
This is used a lot with text data, since it makes a lot of intuitive sense there: If each feature is the count of a different word, 'l1' normalization basically converts those counts to frequencies (you're dividing by the total count of words). This makes sense. If you're using 'l2' normalization, the angle between two vectors (this is called the cosine distance or similarity) will stay the same when you normalize both, and this distance is closer to a meaning distance since it corresponds to ratios of frequencies between words and is not affected by how long of a text each vector represents.
If conserving a cosine distance type of relationship between points is what makes more sense for your data, or if normalization corresponds to a natural scaling (like taking frequencies instead of counts), then this one is more suitable.
MinMaxScaler
You can use this one like sklearn.preprocessing.MinMaxScaler().fit_transform(X). For each feature, this looks at the minimum and maximum value. This is the range of this feature. Then it shrinks or stretches this to the same range for each feature (the default is 0 to 1).
It does this by converting each value to (value-feature_min)/(feature_max - feature_min). It is basically at what percentage of the range am I lying? Remember that the range is only determined by the min and max for the feature. For all this cares, all values might be hanging around 10, 11, or so, and there is a single outlier that's 900. Doesn't matter, your range is 10 to 900. You can see that in some cases that's desirable, and in others this will be problematic, depending on the specific problem and data.
This scheme works much better in certain cases where StandardScaler might not work well. For example, if the standard deviations are very small for features, StandardScaler is highly sensitive to tiny changes between standard deviations of different features, but MinMaxScaler is very robust. Also, for features with highly skewed distributions, or sparse cases where each feature has a lot of zeros that moves the distribution away from a Gaussian, MinMaxScaler is a better choice.


text:
Q: Error : Cannot read property 'token' of null I am heaving some trouble with getting the token for login in my Angular App / API REST
Here is the components et services I used.
The registration part works fine, I even get all the intel in my DB in the right types but the main problem is with login.
All the imports are correct I think.
export class LoginComponent implements OnInit {

  loginForm: FormGroup;
  username = '';
  password = '';
  isLoadingResults = false;

  constructor(private formBuilder: FormBuilder, private router: Router, private authService:
    AuthService) {}

  ngOnInit() {
    this.loginForm = this.formBuilder.group({
      'username': [null, Validators.required],
      'password': [null, Validators.required]
    });
  }

  onFormSubmit(form: NgForm) {
    this.authService.login(form)
      .subscribe(res => {
        console.log(res);
        if (res.token) {
          localStorage.setItem('token', res.token);
          this.router.navigate(['ads']);
        }
      }, (err) => {
        console.log(err);
      });
  }

  register() {
    this.router.navigate(['register']);
  }
}

And here is my authorization service:
const apiUrl = 'http://localhost:9191/';

const httpOptions = {
  headers: new HttpHeaders({
    'Content-Type': 'application/json',
    'Allow-Control-Access-Origin': '*'
  })
};

@Injectable({
  providedIn: 'root'
})
export class AuthService {
  isLoggedIn = false;
  redirectUrl: string;

  constructor(private http: HttpClient) {}

  login(data: any): Observable<any> {
    return this.http.post<any>(apiUrl + 'login', data, httpOptions)
      .pipe(
        tap(_ => this.isLoggedIn = true),
        catchError(this.handleError('login', []))
      );
  }
  register(data: any): Observable<any> {
    return this.http.post<any>(apiUrl + 'users/signup', data, httpOptions)
      .pipe(
        tap(_ => this.log('login')),
        catchError(this.handleError('login', []))
      );
  }
  //handleError and log methods here

redpajama_set_name: RedPajamaStackExchange


text:
Q: Trap key combination and insert string into keyboard buffer The application will run minimized and is used to insert data into applications when the user requests it by a key combination. So using the NuGet package KeystrokeAPI I have made an application that sniffs keystrokes looking for ctrl+alt+w. When that is detected the string "Hello" is inserted into the keyboard buffer using sendKeys.
The problem I am having is that the sendKeys sends the keys into the sniffer application, not the foreground application that the user was in.
In the code below character.CurrentWindow is the IntPtr returned from User32.dll GetForegroundWindow()
using (var api = new KeystrokeAPI())
{
    api.CreateKeyboardHook((character) =>
    {
        if (character.KeyCode == KeyCode.W && character.CtrlPressed && character.AltPressed)
        {
            SetForegroundWindow(character.CurrentWindow);
            SendKeys.Send("Hello");
        }

        Console.Write(character);
    });
    Application.Run();
}

The foreground application doesn't get "Hello".


text:
Q: Scala slick left join doesnt work Im a newbie to Slick.
I would like to get the list of ids from Echo table that DO NOT exist in programs_vw table.
I have written the SQL query which works
SELECT f.`id`
FROM `Full`.`programs_vw` f
LEFT JOIN `FULL`.`Echo` e ON f.`id`=e.`id`
WHERE e.`id` IS NULL
ORDER BY f.`id`;

I have referred to the examples in http://slick.lightbend.com/doc/3.0.0/queries.html and wrote this but it doesnt work
 val query = for {
      (t, f) <- echoQuery.filter(_.id.isEmpty) join programsVwQuery on(_.id === _.id)
      } yield (f.id)
db.run(query.to[List].result)

A: First of all what you did is not a LEFT JOIN (I am talking about Slick version). In order to generate it you need to use joinLeft method.
However this straightforward correction is wrong - it produces subquery which is bad.
for {
      (_, p) <- echoQuery.filter(_.id.isEmpty)
               .joinLeft(programsVwQuery).on(_.id === _.id)
} yield (p.map(_.id))

Side note:
Keep in mind that p above is an Option (it's LEFT JOIN after all).
Corrected solution would be something like this:
for {
      (e, p) <- echoQuery
               .joinLeft(programsVwQuery).on(_.id === _.id) if e.id.isEmpty
} yield (p.map(_.id))

Which in my opinion is a good sign - it actually reads almost like SQL.
Fully correct solution
Above generates a kind of join you want without subqueries but if you compare it to your desired query, it actually doesn't produce what you are aiming at. If Slick can often be read as SQL than if our SQL is like this (your desired version):
SELECT f.`id`
FROM `Full`.`programs_vw` f
LEFT JOIN `FULL`.`Echo` e ON f.`id`=e.`id`
WHERE e.`id` IS NULL
ORDER BY f.`id`;

than exact mapping to Slick version would look like this:
 val query =
 (for {
          (p, e) <- programsVwQuery
                    .joinLeft(echoQuery).on(_.id === _.id) if e.map(_.id).isEmpty
 } yield (p.id))).sortBy(id => id)

db.run(query.result)  // this runs the query

Basically you go exactly as in SQL in this case. It matches your desired query perfectly. If you take a look at generated SQL is exactly what you wanted at the beginning.


text:
Q: Nrwl NX nodejs production build remove comments and minify Inside a Nrwl NX monorepo there's a nodejs app.
When building for production, how can this be achieved:

*

*Remove comments

*Minify the app

I don't get how webpack configuration works in the Nrwl NX namespace or how to install webpack modules like UglifyJSPlugin.
Any help is appreciated.


text:
Q: Toggle a Div with Button changing margin-left property I have a
 and a button

, the div is 220px wide and auto for the height.
The idea is to toggle one of the css properties of the lateral-menu while clicking the .resposive-icon
Seems to be that my code is not working, can someone orient me?
HTML

CSS
.lateral-menu {
height: auto;
background-color: #262525;
overflow: hidden;
position: absolute;
top: 50px;
width: 220px;
margin-left:-220px;
}

JAVASCRIPT
$('.responsive-icon').click(function () {
$(".lateral-menu").animate({
    marginLeft: '0px'
}, 500);
});

I'm trying to toggle the margin-left from -220px to 0 to allow it to appear from the left side. Some suggestions? thanks!

A: There are a few issues with the code sample you pasted that cause it to not work without some changes, but overall there isn't anything wrong with the approach.
If the HTML is meant to be like this:

Then you need to apply a height to this example, as in Lai's 2nd jsfiddle.
If the HTML is meant to be like this:

Then it should be working just fine assuming you have jQuery loaded on the page. I recommend opening the browser console to check for errors or warnings.
Also, you may find better luck using left since it's absolutely positioned like in this example: https://jsfiddle.net/okohrvoL/1/
Edit:
To make the menu collapse again, you can add a simple check in the callback function:
$('.responsive-icon').click(function () {
  var targetValue;

  if ($('.lateral-menu').css('left') == "0px") {
    targetValue = '-220px';
  } else {
    targetValue = '0px';
  }

  $(".lateral-menu").animate({
    left: targetValue
  }, 500);
});

Working example here: https://jsfiddle.net/okohrvoL/2/


text:
Q: Installing APC on CentOS 5.8 with PHP 5.2.17 I'm trying to install APC on CentOS 5.8 with PHP 5.2.17. I ran the dependancies, which weren't needed, and then
pecl install apc
and after a whole bunch of stuff, got:
Build process completed successfully
Installing '/usr/local/lib/php/extensions/no-debug-non-zts-20060613/apc.so'
Installing '/usr/local/include/php/ext/apc/apc_serializer.h'
install ok: channel://pecl.php.net/APC-3.1.9
Extension apc enabled in php.ini
But, I restarted apache, but APC doesn't show up in phpinfo

and there was no apc extension added to php.ini
Can I simply add  extension=apc.so  to php.ini? And if so, where in the file itself?

A: In the same phpinfo page, search for php.ini or simple look for "Loaded Configuration File"
Then you can see a path. edit that file and add  your extension.
It can be just anywhere in the file itself. I suggest looking for Extension comments in php.ini file and add your extension below them.


text:
Q: How to get a response from an API that sits behind an authentication layer? I am trying to get response from an API that sits behind an authentication layer. I first need to POST a request using a json request something like this.
{"username":"apitest",
 "password":"testapi@321"
}

Lets assume that the api url is http://test-oms-test-staging.com.au/test/auth
I get back a json response that has the following in response body:
"token": "abcdefghabcdefgh"

Now I need to pass the token as a header "x-auth-token": into API that has parameters in it to get a response which needs to be displayed in the html page.
So far, i have been able to do the following
function begin() {
var xhr = new XMLHttpRequest();
var url = "http://test-oms-test-staging.com.au/test/auth";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
    var json = JSON.parse(xhr.responseText);
    var string = json['token'];
    console.log(string);
}
                            }
var data = JSON.stringify({"username": "apitest", "password":
"testapi@321"});
xhr.send(data);
}

Now when i query the second API URL with the response token in the header, i am getting the following error.
Response for preflight is invalid (redirect)

I do appologise if my request is too broad or not detailed enough, I am very new with programming. I did a bit of research and found out that my request is being re-directed because of the server security. Am I doing the right thing treating this as two individual methods? Thank-you again.
EDIT
This is happening because the API is triggering an OPTIONS request which needs to be authenticated. I am thinking it is because I am doing this as two individual requests(First to POST Request to retrive the token in Response Body and Second 'GET' to pass the token as a header. In the second request the Pre-flight is triggered which sends an OPTION Request which is beign authenticated That is why I am now getting 401 'Unauthenticated' error. In the link provided for possible duplication, there are no answers besides editing the server to "Not Authenticate" which is not a valid solution.

A: You mention that you need to send the token as a header, but in your example, you are sending it as part of the payload. Try the below:
xhr.setRequestHeader("x-auth-token", "<THE_AUTH_TOKEN>");


text:
Q: compute examples (e.g)
V1<-c(1,2,3,4)
V2<-c(1,2,3,4)
FUNCTIONS
V3
[1]4 0
V1<-c(1,1,1,1)
V2<-c(1,2,3,4)
FUNCITONS
V3
[1]1 0
V1<-c(2,2,3,3)
V2<-c(1,2,3,4)
FUNCTIONS
V3
[1]2 0
V1<-c(1,1,3,4)
V2<-c(1,2,3,3)
FUNCTIONS
V3
[1]2 0
V1<-c(4,3,2,1)
V2<-c(1,2,3,4)
FUNCTIONS
V3
[1]0 4
V1<-c(4,3,4,3)
V2<-c(1,2,3,4)
FUNCTIONS
V3
[1]0 2
please have look at these new added examples, the function also need to satisfy this  two conditions
V1<-c(1,1,2,2)
V2<-c(3,3,1,1)
FUNCTIONS
V3
[1]0 2
V1<-c(1,1,2,2)
V2<-c(3,3,3,1)
FUNCTIONS
V3
[1]0 1

A: You might be after something like this.
> func <- function(x, y) {
>   c(sum(x == y),
>     length(y[match(unique(x), y, nomatch = 0)])
>     - sum(x == y))}

> V1<-c(4,3,2,1)
> V2<-c(1,2,3,4)

> func(V1,V2)
[1] 0 4

A: Building off of wkmor1's answer, you can simplify the y part of it using a set intersection.
func <- function(x, y) c(sum(x == y), length(intersect(x,y)))

This way it's a one-liner.


text:
Q: How to use delegation for a slide-out menu in an iOS app I am trying to call a method in a class using delegation, but currently when I call the delegate method the app is crashing with the following error message,
unrecognized selector sent to instance
I have a slide-out menu which contains a table view that is loading a view when the table view item is seleted with the following,
// ViewControllerRootHomeLeftPanel.m
    -(void)showCalibrate{
        ViewControllerCalibrate *calibrateVC = [[ViewControllerCalibrate alloc] initWithNibName:@"ViewControllerCalibrate" bundle:nil];
        [((ViewControllerRootHome *)self.parentViewController).viewControllerRootHomeCenter addChildViewController:calibrateVC];
        [calibrateVC.view setFrame:CGRectMake(0.0f, 64.0f, self.view.frame.size.width, self.view.frame.size.height)];

        [calibrateVC didMoveToParentViewController:((ViewControllerRootHome *)self.parentViewController).viewControllerRootHomeCenter];

        [((ViewControllerRootHome *)self.parentViewController).viewControllerRootHomeCenter.view addSubview:calibrateVC.view];

    // the below delegate method hides the left panel vc (table view) after loading a view on the root home center vc.
        [myDelegate loadVCRH];
    }

I then setup a delegate method in the ViewControllerCalibrate VC as such,
// ViewControllerCalibrate.h
@protocol ViewControllerCalibrateDelegate;
@protocol ViewControllerCalibrateDelegate <NSObject>
- (void) removeCalibrateView;
@end

@interface ViewControllerCalibrate : UIViewController
@property (nonatomic, weak) id<ViewControllerCalibrateDelegate> delegate;
@end

// ViewControllerCalibrate.m
- (void)removeCalibrateView {
    NSLog(@"removeCalibrateView method called");
}

I then try to call the removeCalibrateView method within the ViewControllerRootHomeCenter
// ViewControllerRootHomeCenter.m
- (void)removeSubViews{
    for (UIView *subview in [self.view subviews]){
        NSLog(@"subviews = %@",[self.view subviews]);
        if (subview.tag == 3) {
            // the below delegate method call is causing the app to crash.
            [self removeCalibrateView];
            [subview removeFromSuperview];
        }
    }
}


text:
Q: How to show angles are equal in Young's experiment

Could someone explain to me why $\tan\theta\approx y/s$? I can follow the other approximations, but here I don't see it. I'm guessing we have similar triangles here, but I wouldn't really know how to show it. It seems to me that I have to make one approximation first before showing the triangles are similar. Also, note: it's only given that we have $\theta_m$ in the triangle $(S_1,S_2,B)$. The other two $\theta_m$ are exactly the angles I try to show.

A: My suggestion is not to follow the approximations in the textbooks but rather do it in a rigorous way yourself. So we have
$$r_1-r_2=\sqrt{s^2+(y+a/2)^2}-\sqrt{s^2+(y-a/2)^2}$$
For $s>>y,a$, we have
$$r_1-r_2\approx s\left[1+\frac{1}{2}\frac{(y+a/2)^2}{s^2}-1-\frac{1}{2}\frac{(y-a/2)^2}{s^2}\right]$$
$$=\frac{(y+a/2)^2-(y-a/2)^2}{2s}$$
$$=\frac{ay}{s}$$
which is the final result you want.


text:
Q: Swing Timer stops calling actionPerformed() while the mouse is moving inside a JFrame If I move my mouse inside a javax.swing.JFrame, the javax.swing.Timer stops calling the actionPerformed() method until the mouse stops moving. It only occurs when I move the cursor with my Rocket Kone XTD mouse. When I use my trackpad everything is fine.
How can I fix it? I'm using macOS Sierra.
Here's my code:
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JFrame;
import javax.swing.Timer;

public class Mouse {
    public static void main(String[] args) {
        JFrame frame = new JFrame();

        frame.setSize(500, 500);
        frame.setVisible(true);

        Timer timer = new Timer(10, new ActionListener() {

            @Override
            public void actionPerformed(ActionEvent e) {
                System.out.println("foo");
            }
        });

        timer.start();
    }
}

To get an idea what I'm talking about:

Code that gives more detail:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class Mouse {
    public static void main(String[] args) {
        // Note: Swing/AWT GUIs should be started on the EDT!
        // If the problem displayed here, that is first change I'd make to code.
        final JFrame frame = new JFrame();

        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);

        Timer timer = new Timer(10, new ActionListener() {

            long lastTime = 0;

            @Override
            public void actionPerformed(ActionEvent e) {
                long nowTime = System.currentTimeMillis();
                long difference = nowTime-lastTime;
                lastTime = nowTime;
                Rectangle r = frame.getBounds();
                Point p = MouseInfo.getPointerInfo().getLocation();
                System.out.println(String.format("%1s\t%2s",
                        difference, r.contains(p)));
            }
        });

        timer.start();
    }
}

Output:
If the mouse is not moving, the output it looks like this:
11  true
13  true
13  true
10  true
12  true
13  true
12  true
13  true
10  true.
While the mouse is moving (fast) there is no output. When the mouse stops moving the output is: 2406    true (depending how long I moved my mouse).
If the mouse is moving slowly, the output looks like this: 17   true
5   true
8   true
16  true
4   true
11  true
16  true
44  true
11  true
28  true
48  true
77  true
11  true
7   true
15  true
8   true
9   true
12  true
24  true
13  true
4   true
12  true
32  true
13  true
8   true
8   true
13  true
10  true
15  true.

A: I solved the problem as I reduced the polling-rate of my mouse from 1000Hz to 500Hz. Now everything works perfect. I think the problem was that the UI-Thread was overextended handling the 1000 polls per second so it was to busy to handle the Timer.


text:
Q: How do I add to and traverse through a LinkedList (Java) I can't seem to get the printing and adding to the LinkedList working as it is now.
When I add one or two nodes, it works fine. Any more than that it doesn't work as expected.
For example: adding 4 and 3 using adding first
3->4->
But when I add one more, this is what I get:
2->3->3->
Can anyone tell me with this is the case. I am fairly new to programming.
public class LinkedListPractice{

public static void main(String[]args){
//add items to the LinkedList
GenericLinkedList<Integer> gLink = new GenericLinkedList<>();

gLink.addFirst(4);
gLink.addFirst(3);
gLink.addFirst(2);
gLink.addFirst(1);

gLink.printList();

 }//main method

} //LinkedListPractice

class GenericLinkedList<E>{
int size; //represents number of nodes in the LinkedList
Node<E> head;

public GenericLinkedList(){
  size = 0;
  head = null;
} //GenericLinkedList no parameter constructor

//printList
public void printList(){
 Node<E> current = head;

  for(int i = 0; i < size; i++){
  System.out.print(current.getData() + "->");
  current = head.next;
} //for
} //printList

  public void addFirst(E element){
    Node<E> newNode = new Node<E>(element);
    if(head == null){head = newNode;}
    else{
      newNode.next = head;
      head = newNode;
   }
    size++;
  } //addFirst

  public boolean isEmpty(){
      if(head == null){
          return true;
      }else
          return false;
   } //isEmpty

  //inner node class
  private static class Node<E>{
    //private data fields
    private E data;
    private Node<E> next; //represents the next link in the LinkedList

    public Node(E element){
        data = element;
        next = null;
    } //Node class constructor

    public E getData(){
      return data;
    } //getData

  } //Node class
} //GenericLinkedList

A: There's a problem in printList(). Head never seems to get updated, so you are always printing the node after head which would be 3 in this case.
A better solution could be to update current after each iteration of a loop.


text:
Q: Tensorflow: Compute inverse counts of labels I have a tensor labels of shape (b,n) of integers with values in [0,1,2,3,4,5].
I want to create a tensor weights of shape (b,n) that carries at position (i,j) the inverse of the number of times that the integer labels[i,j] occurs in labels.
Working example code:
import tensorflow as tf
import numpy as np
tf.InteractiveSession()
labels=tf.convert_to_tensor(np.array([[1,0,0,1,2,4],[2,2,2,4,2,1]]), dtype=tf.int32)
weights=tf.ones_like(labels, dtype=tf.float32)
bc=tf.bincount(labels, minlength=6, maxlength=6)
for i in range(6):
    cur_count = 1.0/(1e-10+tf.cast(bc[i], tf.float32))
    count_tensor = tf.ones_like(labels, dtype=tf.float32)*cur_count
    weights = tf.where(tf.equal(labels,i), count_tensor, weights)
weights.eval()
# array([[0.3333, 0.5, 0.5, 0.3333, 0.2, 0.5],
#        [0.2, 0.2, 0.2, 0.5, 0.2, 0.3333]], dtype=float32)

So for example, the label 1 appears three times in the labels tensor so that in weights the value 1/3 appears at each position, where a 1 is in labels.
Now what I don't like about this code is that tf.bincount does not work on the GPU in my tensorflow version (1.4.0) and I cannot update.
Also, I am not sure how the for loop is handled by tensorflow and how much overhead is created by this.
I suppose that there is a more elegant solution to my problem. Any ideas?

A: About the loop, you can replace it with a call to tf.gather:
import tensorflow as tf
import numpy as np

tf.InteractiveSession()
labels = tf.convert_to_tensor(
    np.array([[1, 0, 0, 1, 2, 4], [2, 2, 2, 4, 2, 1]]), dtype=tf.int32)
bc = tf.bincount(labels, minlength=6, maxlength=6)
weights = tf.gather(1.0 / (1e-10 + tf.cast(bc, tf.float32)), labels)
print(weights.eval())

Output:
[[0.33333334 0.5        0.5        0.33333334 0.2        0.5       ]
 [0.2        0.2        0.2        0.5        0.2        0.33333334]]

About tf.bincount being CPU-only, that does not seem to be the case currently. In fact, a GPU implementation seems to have been available since v1.5.0.
If you wanted an alternative implementation, you could do something like this:
import tensorflow as tf
import numpy as np

tf.InteractiveSession()
labels = tf.convert_to_tensor(
    np.array([[1, 0, 0, 1, 2, 4], [2, 2, 2, 4, 2, 1]]), dtype=tf.int32)
eq = tf.equal(labels[:, :, tf.newaxis], tf.range(6, dtype=labels.dtype))
bc = tf.reduce_sum(tf.cast(eq, tf.float32), axis=[0, 1])
weights = tf.gather(1.0 / (1e-10 + tf.cast(bc, tf.float32)), labels)
print(weights.eval())
# Same output

However tf.bincount is likely to be more efficient than this.


text:
Q: Format date using angular-moment.js I have a date with thi format:"YYYY-MM-DD HH:mm:ss"
and I'm trying to format that to: "DD/MM/YYYY às HH:mm"
So a date like: 2015-01-22 15:01:45 would be formatted to: 22/01/2015 às 15:01
I'm using angular-moment.js to do that, here is what I tried:
amDateFormat:"DD/MM/YYYY 'as' hh:mm"

But the output is not what I was expecting:
22/01/2015 am0 12:00
What am I doing wrong?

A: You are still using format character in 'as'.
'a' means displaying AM or PM in lowercase format.
's' means displaying seconds.
To achieve what you want, escape the 'as' character. So your format should look like:
amDateFormat:"DD/MM/YYYY [as] hh:mm"

See the reference
I also not sure what 'as' means in Thai, perhaps you also want to check the internationalization part.


text:
Q: Deleting multiple tasks in IntelliJ 11 I have many unused tasks which I would like to delete, but can't find any good way do it beside deleting them one by one. I can see in intelliJ 12 help, that you can do multiple selection of tasks and delete them, but that doesn't seem to work in IntelliJ 11.
Will it be safe to delete all the tasks from the workspace.xml file? I can see all my tasks there but not their contexts.

A: You should be able to remove them by selecting the task from the task dropdown, hovering ove the task to be deleted, and then selecting the right arrow key (yes, this could be made easier).
Once done you should have 2 options:

*

*Switch to

*Remove

The remove option will (obviously) delete the task.

I hope that this helps :-)

A: Here is the how to. You can do multiple selection and delete all of them in one go.
http://www.jetbrains.com/idea/webhelp/deleting-tasks.html


text:
Q: How to iterate in R to save multiple files simultaneously and avoid "Error in absolute_path(target) : 'x' must be a single character string"? I'm using the officer package, and I want to make a one-slide PowerPoint document for each row in my data. My for loop works except for the file name. Whenever I try to give multiple file names, I get this error:
Error in absolute_path(target) : 'x' must be a single character string

I can only get my for loop to work when I have everything go to one file path--which then just overwrites everything.
Here's my data--note, to replicate, you'll need to add in the file path you'll want the documents to save:
library(dplyr)
my_data <- tibble(first_name = c("Justin", "Corey", "Sibley"),
                  full_name = c("Justin S", "Corey X", "Sibley X"),
                  num_cakes = c("6 cakes", "7 cakes", "0 cakes")) %>%
  mutate(file_pathway = paste0("edit/with/your/file/path/", full_name, ".pptx")) #edit here

Here's my code that doesn't work and throws the above error:
library(dplyr)
library(officer)

#Custom function
dessert_slide <- function(file_pathway, data, first_name, num_cakes, left = 0.5, top = 1.2, width = 5.5, height = 3){
  out <- read_pptx() %>%
  add_slide(layout = "Two Content", master = "Office Theme")

subtitle <- paste0(data$first_name, ", let's see what desserts you ate!")
subtitle_properties <- fp_text(color = "#63666A", font.size = 20, bold = FALSE, font.family = "Arial")
normal_properties <- fp_text(color = "#63666A", font.size = 20, bold = TRUE, font.family = "Arial")
cake_properties <- fp_text(color = "#C8102E", font.size = 20, bold = TRUE, font.family = "Arial")
formatted_subtitle <- ftext(subtitle, subtitle_properties)

centered <- fp_par(text.align = "center")

out %>%
  ph_with(value= fpar(formatted_subtitle), location = officer::ph_location(
    width = 12, height = .5, left = .7, top = 1)) %>%
  ph_with(value= fpar(ftext("You ate ", normal_properties), ftext(data$num_cakes, cake_properties), ftext(".", normal_properties), fp_p = centered), alignment = "c", location = officer::ph_location(
    width = 2.36, height = .67, left = .78, top = 4.43)) %>%
  base::print(target = data$file_pathway) #The issue is here
}

#For loop the runs the custom function

for (row in 1:nrow(my_data)) {
  dessert_slide(data = my_data, file_pathway = data$file_pathway, first_name = first_name,
              num_cakes = num_cakes)
}

I'm sure the issue is on the line I adjust because this below code works when I only allow for 1 filepathway. This is undesirable because now all the information is jammed on one slide:
library(dplyr)
library(officer)

#setting just one file path which overwrites everything :(
just_one_path <- paste0("edit/to/have/your/filepath/, "just one file.pptx")

# Custom function
dessert_slide <- function(file_pathway, data, first_name, num_cakes, left = 0.5, top = 1.2, width = 5.5, height = 3){
  out <- read_pptx() %>%
  add_slide(layout = "Two Content", master = "Office Theme")

subtitle <- paste0(data$first_name, ", let's see what desserts you ate!")
subtitle_properties <- fp_text(color = "#63666A", font.size = 20, bold = FALSE, font.family = "Arial")
normal_properties <- fp_text(color = "#63666A", font.size = 20, bold = TRUE, font.family = "Arial")
cake_properties <- fp_text(color = "#C8102E", font.size = 20, bold = TRUE, font.family = "Arial")
formatted_subtitle <- ftext(subtitle, subtitle_properties)

centered <- fp_par(text.align = "center")

out %>%
  ph_with(value= fpar(formatted_subtitle), location = officer::ph_location(
    width = 12, height = .5, left = .7, top = 1)) %>%
  ph_with(value= fpar(ftext("You ate ", normal_properties), ftext(data$num_cakes, cake_properties), ftext(".", normal_properties), fp_p = centered), alignment = "c", location = officer::ph_location(
    width = 2.36, height = .67, left = .78, top = 4.43)) %>%
  base::print(target = file_pathway)
}

#For loop running function
for (row in 1:nrow(my_data)) {
  dessert_slide(data = my_data, file_pathway = just_one_path, first_name = first_name,
              num_cakes = num_cakes)
}

Here's the code that runs but puts everything on one slide:
In my dataset, I made a column that contains the file path for each document (e.g., it adds the person's name in the file name).

A: In the first function, the file_pathway is taking the full rows of 'file_pathway' column resulting in the error.  Instead it should be a single path i.e. change the code from file_pathway = data$file_pathway to file_pathway = data$file_pathway[row]
for (row in 1:nrow(my_data)) {
  dessert_slide(data = my_data, file_pathway = data$file_pathway[row], first_name = first_name,
              num_cakes = num_cakes)
}


text:
Q: Cancelling Futures in Java Suppose, I have code something like this (note that my syntax is not 100% correct)
// This is how I am collecting the futures:
int index = 0;
for(Future<Boolean> future : futures) {
  try {
   Boolean canCancelOtherTasks = future.get();
   if (canCancelOtherTasks) {
      cancelAllFuturesFromIndex(index + 1, futures);
      break;
   }
  } catch (Exception e) {
     // handle exception
     break;
  }
  index++;
}

=====

cancelAllFuturesFromIndex(index, futures) {
   for(int k = index; k < futures.size(); k++) {
       futures.get(k).cancel(true);
   }
}

For a specific job, I essentially need to run N callables in parallel, and I would like to exit early after the first callable yields in true without having to wait for the other callables in the list. Note that the futures in the list are already in order of importance.
Would the above work? Is this efficient (i.e. would it help with the overall runtime of my application assuming each callable has a task with different runtimes)?

A: I was going to make this a comment but it's a bit wordy so I'm making it an answer to format it better.
Calling future.get() blocks the calling thread until the computation is done. See here
So this won't work, as it will just wait until the first future in the list in order is done and then cancel everything else. Assume the we have 3 futures in the list. future[0] takes 500ms, future[1] takes 50ms, and future[2] takes 45ms. With your current implementation, it will wait for the first item, future[0] to finish, since you are calling future.get() on the first iteration of the loop, which waits an unlimited amount of time for the future to return. It will wait all 500ms, despite future[1] and future[2] finishing much quicker
One way you could work around it is to use get(timeout, unit) to only wait on each future in the list for a minimal amount of time and then check the next one. This isn't perfect, as worst case you'll miss the first finished future task while waiting on another one. You'll have to make this loop infinitely until it successfully returns, or else you could end up missing the first execution if none of them happen before you leave the loop.
If you really need to make it stop at the earliest possible time, I would recommend using Threads.


text:
Q: Unordered list with reset.css I have included reset.css which is pretty common for most websites that use, on one of the page in my website I have a unordered list and I have a problem knowing what were their defaults.

Item 1

First item

Second item

Third item

Item 2

Item 3

Like this:

*

*Item 1

*

*First item

*Second item

*Third item

*Item 2

*Item 3

Can I have the defaults which I can set in CSS (when including reset.css). I don't want to remove ul and li from the reset.css since I have used styling for an unordered list on different pages, so if I remove it, it would affect the whole website.
Cheers.

A: The whole point of the reset stylesheet is to make all the browsers behave the same with respect to HTML elements. That means there is no single set of styles that apply to those elements across the various browsers. So "defaults" is kind of a meaningless term here.'
The
 especially is subject to wildly different renderings. Your only hope, if you really really really want to go through with it, is to look at the computed styles for each element on each browser and try to do something with those values, but I don't see this as being of much value.


text:
Q: in jersey 2.x am getting the error like java.util.concurrent.ExecutionException
*

*i have used the jersey implementation of a jaxrs but iam unable to the programme following is case where i am getting problem any idea help me
in following programme i used the jersy 2.x implementaion of jaxrs
i implemented the programme using jersey implemetation of jax-rs(restfull)
2 classes i have written instead of web.xml i used the class
MyResource.java
package com.rest.application;

import java.util.HashSet;
import java.util.Set;

import javax.ws.rs.ApplicationPath;

import com.rest.webservice.SampleService;
@ApplicationPath("rest")
public class MyResource {
    private Set s;
    public MyResource() {
        s=new HashSet();
        s.add(new SampleService());
    }
     public Set getSingletons() {
        return s;
    }
}

SampleService.java
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

@Path("sample")
public class SampleService {
    @GET
    @Produces("text/html")
    @Path("{username}")
    public String sayHello(@PathParam("username")String s) {
        return "Hello:" +s+ "";
    }
    @GET
    @Produces("text/plain")
    public String sayBye() {
    return "Bye";
}
}

i added the all jars needed to this programm
still i am getting following error
java.util.concurrent.ExecutionException:
org.apache.catalina.LifecycleException:
Failed to start component [StandardEngine[Catalina].
StandardHost[localhost].StandardContext[/RestApp2]]
Caused by: org.apache.catalina.LifecycleException:
Failed to start component [StandardEngine[Catalina].
StandardHost[localhost].StandardContext[/RestApp2]]

like this same error is displaying everywhere
when i changed the server tomcat 7 to 6
it is working but not displaying the output
will anybody have any idea thanking you in advance

A: This says, @ApplicationPath("rest") may be applied only to the subclass of Application.
Can you share more on what are you trying to do and what is the complete stack trace. Are you using web.xml ?

A: As @MSD mentioned, your use of @ApplicationPath is incorrect. See the Jersey documentation on Application Deployment to see all the different deployment options, and how they work in different environments.
Basically, the easiest way put the @ApplicationPath on an empty Application class
@ApplicationPath("/rest")
public class MyApplication extends Application {}

This will scan the entire classpath for @Provider and @Path annotated classes, to register with the application. Though this may seem easier, the more common approach, when working with Jersey is to use it's ResourceConfig class, which is a subclass of Application. You can register packages, which will scan the packages and subpackages
@ApplicationPath("/rest")
public class MyApplication extends ResourceConfig {
    public MyApplication() {
        packages("com.my.packages");
    }
}

One benefit is that sometimes there will be third party dependencies that are annotated, but you don't want registered. To register individual classes just use register(...class) in the ResourceConfig.
Now the reason for the error in Tomcat 7 and not 6, is most likely because Tomcat 6 (servlet 2.5) does not have the sevlet pluggability mechanism, which uses the ServletContainerInitializer. The Jersey implementation of this initializer loads the application, looking for the @ApplicationPath on the Application subclass. If you're not in a 3.0 environment, this functionality will not work.
Note the Jersey initializer is included in the jersey-container-servlet jar. You can read more about it here


text:
Q: Call willAnimateRotationToInterfaceOrientation programmatically in iOS 6 In my viewController that has other viewControllers, in iOS 5, it acts all right because it calls willAnimateRotationToInterfaceOrientation method. If I rotate the device, iOS will call willAnimateRotationToInterfaceOrientation, and the app acts right, but when the app first launches, it does not. Then I try to call willAnimateRotationToInterfaceOrientation in viewWillAppear, but it does not help.
How can I call willAnimateRotationToInterfaceOrientation programmatically or something else?

A: willAnimateRotationToInterfaceOrientation:duration: is one of several methods that should only be called by the device. The only thing that is special about it is when it is called, so if you extract its functionality to another method you should be able to call that functionality as you will (in this case, in viewWillAppear).
-(void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration {
    [self prepareToRotate];
}

-(void)prepareToRotate {
    // existing functionality goes here
}

Note that if you use toInterfaceOrientation or duration you should also include them as parameters in prepareToRotate.


text:
Q: Get easy commenter and Bootstrap to work with same version of jQuery? I am using bootstrap 3 and jQuery version 1.10.2
I am also using easy commenter and they require jQuery version 1.5.2 I have tried to just keep version 1.10.2 , just keep version 1.5.2 and keep both of them. But in every case one of them does not behave as expected. With version 1.5.2 the collapsible menu in header stops working with version 1.10.2 easy commenter stops working. How should I deal with this problem?
Here is a link to the page I am working on http://8mags.com/lessons/php/phpcalendar.php

A: Use the newer JQuery plus the migrate plugin

A: The correct answer is: If the "easy commenter" plugin doesn't work with a current version of jQuery, rather than one from three years ago, you want to find a different plugin or take the existing one and modify it so that it works with the current jQuery. The differences between 1.5.2 and 1.11.2 (the current version as of this writing) aren't really all that big, and are easily updated.
If you don't want to do that (why not?), then you can use both versions of jQuery on your page, but it doubles the size of an already-large library, increasing page load time.
Here's how:
<script src="jquery-1.5.2.js"></script>
<script src="easy-commenter.js"></script>
<script>
var $old = jQuery.noConflict(true);
</script>
<script src="jquery-1.11.2.js"></script>
<!-- all your other plugins and such, including bootstrap -->

You load jQuery 1.5.2, load the easy commenter plugin, then use noConflict to release both the $ and jQuery symbols, and load jQuery 1.11.2.
When you want to use the easy commenter plugin, use $old rather than $.


text:
Q: PySpark equivalent to a groupby categories in pandas? On Pandas, we can group by a categorical series and then when aggregating, it displays all the categories, regardless it contains any records or not.
import pandas as pd

df = pd.DataFrame({"Age": [12, 20, 40, 60, 72]}, dtype=np.float64)
cuts = pd.cut(df.Age, bins=[0, 11, 30, 60])
df.Age.groupby(cuts).agg(mean="mean", occurrences="size")

#           mean  occurrences
# Age
# (0, 11]    NaN            0
# (11, 30]  16.0            2
# (30, 60]  50.0            2

As you can see, the first bin is displayed even though it does not appear in the dataset.
How could I achieve the same behaviour on PySpark?

A: The following is quite much, but I'm not aware of any nicer method.
from pyspark.sql import functions as F
df = spark.createDataFrame([(12,), (20,), (40,), (60,), (72,)], ['Age'])

bins = [0, 11, 30, 60]

conds = F
for i, b in enumerate(bins[1:]):
    conds = conds.when(F.col('id') <= b, f'({bins[i]}, {b}]')
df2 = spark.range(1, bins[-1]+1).withColumn('_grp', conds)

df = df2.join(df, df2.id == df.Age, 'left')
df = df.groupBy(F.col('_grp').alias('Age')).agg(
    F.mean('Age').alias('mean'),
    F.count('Age').alias('occurrences'),
)

df.show()
# +--------+----+-----------+
# |     Age|mean|occurrences|
# +--------+----+-----------+
# |(11, 30]|16.0|          2|
# | (0, 11]|null|          0|
# |(30, 60]|50.0|          2|
# +--------+----+-----------+


text:
Q: Node GDAL for ogr2ogr conversion I currently have some scripts that use OGR2OGR to translate data form various source formats like ESRI Shapefile, GML etc to other file formats but especially to my PostGIS database.
My normal command would be:
ogr2ogr -f PostgreSQL PG:"pg conn settings" shapefile.shp

I now need to do this in a Node script so have installed the node gdal module (https://github.com/naturalatlas/node-gdal) which seems to have a lot of functionality of the GDAL library.
So I tried to use the example here to a least connect to my PostGIS database.
var connString = "PG: host=%s dbname=%s user=%s password=%s" %(databaseServer,databaseName,databaseUser,databasePW)

var conn = gdal.open(connString)

However, I receive an error saying gdal.open expects a path.
Has anyone got examples of using Node GDAL for ogr2ogr translations or loading to PostGIS.

A: Are you sure that the driver is implemented? I have no experience with node-gdal myself, but I don't see it in the list of bundled drivers. There is also an open issue concerning PostgreSQL support.
Otherwise you might want to add a driver to the gdal.open() method, but as I said, I couldn't find it in the bundled drivers. I looked for the PG: string which indicates the PostgreSQL driver.


text:
Q: CallContext.LogicalGetData() vs ThreadLocal/ThreadStatic I am currently using Threadlocal for holding the current user's id to use throughout the app per each user's web request. I don't have access to the HttpContext in lower environments, but want to access a static UserId without passing it as a parameter everywhere.
Recently, I've been adding parallel operations via async/await. This no longer can guarantee I have the proper value in each Task.
I research and discovered AsyncLocal in .Net 4.6, but am currently limited to .Net 4.5.1. As an alternative, is CallContext.LogicalGet/SetData() able to achieve what I am looking for?

A: Yes, the logical call context will work as an async-local.
AsyncLocal<T> uses the logical call context on the full .NET framework - it just has a nicer API and will work with the upcoming .NET Core platform while the logical call context will not.
Remember to only store immutable data, as I describe on my blog.
Also, there is a definite performance impact with async-local values. It would almost definitely be more performant to pass the parameter explicitly, perhaps as part of your own RequestContext type. ASP.NET vCore is moving away from HttpContext.Current; it still has the concept of HttpContext, but it doesn't act as an async local anymore - it's passed explicitly.


text:
Q: Is it wrong or not advised to have a thread locked for a long time? Tcp related I am working on a server program with a slotmanager thread (queue of references to other tcpthreads waiting for a connection). Sort of like when you are waiting in queue for a game server. My initial plan was to have the slotmanager thread wait and then will continue if notified(client waiting). Then the tpcthreads would just request an update on the status every X ms.
My other options would be to have the slotmanager thread finish when the queue is empty then start a new one if its not already running and the queue has a waiting client in or have the TCPthread wait, which could result in the connection timing out.


text:
Q: Multiple language support in Universal App This is not a question about standard localization - I know how to localize the app, use resources, Uid's and so on - this works perfectly.
The problem is that the app comes within a bundle, therefore when the user installs the app it covers only languages that are selected in device/phone settings. But I would like to provide an option in settings that would allow choosing a language regarding the settings. For this purpose, I can use ApplicationLanguages.PrimaryLanguageOverride, which works very nice when deployed via VS, but as I've mentioned - version from the store lacks resources, as not all are installed.
Does anybody know how to bypass this bundle behavior?
The problem is also that I'm using MAT (multilingual app toolkit) and my translation comes with xliff files. I've spent quite a lot of time to find a way to convert them to resw files, without success. Is there any way to do it (or I've to write my own converter)?

A: You need to use ResourceContext:
var context = new ResourceContext(); // deliberately not using getForCurrentView()
context.Languages = new string() {"fr-fr"};
ResourceMap resourceMap = ResourceManager.Current.MainResourceMap.GetSubtree("Resources");
String str = resourceMap.GetValue("string1", context).ValueAsString;

More info at:
'How to load string resources' and
'ResourceContext class'ResourceContext class'.
PS. I have app in store and there is no problem with changing language without reinstall so all resources must be there

A: Check out this: UWP: Resource file for languages is not deployed correctly you need to get rid of bundle in order for my code from above to work. Or you could check if chosen language is installed in OS and if not you could not allow user to choose it using:
Windows.System.UserProfile.GlobalizationPreferences.Languages


text:
Q: Page auto jump top after reload in jqm I am using jquery mobile to create second page, In my second page, I have list of images. I have a js function to handle page load to bottom when the second page is created. When I click the second page, the page is scroll to bottom successful. But when page is finished load. the page jump to top itself. My js function as below:
function scrolltobottom() {
    var areachat = document.getElementById('indexbody');
    areachat .scrollTop = textareachat.scrollHeight;
}

$(document).ready(function () {
    $(document).on("pagecreate", "#secondpg", function () {
        setTimeout(scrolltobottom, 1000);
    });
});

My sample html code:

   Page2

How do I solve this? Thanks


text:
Q: CUDA 6.5, Mathematica 10.0.2, and Ubuntu 14.04 I have CUDA 6.5 working fine on Ubuntu 14.04.  Mathematica recognizes the driver (Nvidia 340), but CUDAQ[] returns False and I cannot get any CUDA functions to work in Mathematica.
I have created symbolic links to /usr/lib64/ for the CUDA libraries.
Has anyone successfully gotten CUDA 6.5 to work with Mathematica in Ubuntu 14.04?

A: I have managed to get CUDALink working on an ubuntu 14.04 with an NVidia GTX 750 Ti with CUDA 7 toolkit (installed the toolkit following these instructions; http://www.r-tutor.com/gpu-computing/cuda-installation/cuda7.0-ubuntu ).
I have never been able to change NVIDIA_DRIVER_LIBRARY_PATH and CUDA_LIBRARY_PATH using env variables and get CUDALink to work.
I assume the Mathematica CUDA and Nvidia library paths as hardwired and I use symlinks from the libraries to the default locations where Mathematica is looking. It works for me! Mathematica is looking in /usr/lib64, this does not exist on my system, so;
cd /usr
sudo mkdir lib64

Locate your libnvidia-tls.so file, I used find
stuart@stuart-2015:~$ find / -name libnvidia-tls.so* 2>/dev/null
/usr/lib/nvidia-346/libnvidia-tls.so.346.82
/usr/lib/nvidia-346/tls/libnvidia-tls.so.346.82
/usr/lib32/nvidia-346/libnvidia-tls.so.346.82
/usr/lib32/nvidia-346/tls/libnvidia-tls.so.346.82

I have a 64bit system, I ignore the lib32 libraries, I have 2 choices;
/usr/lib/nvidia-346/libnvidia-tls.so.346.82
/usr/lib/nvidia-346/tls/libnvidia-tls.so.346.82

these are actually different files, I dont know what the difference is, or which is preferred, but there are only two choices, so I try the second file first and symlink like so;
sudo ln -s /usr/lib/nvidia-346/tls/libnvidia-tls.so.346.82 /usr/lib64/libnvidia-tls.so.346.82

With the cuda library, we find these files;
find / -name libcuda.so 2>/dev/null
/usr/lib/i386-linux-gnu/libcuda.so
/usr/lib/x86_64-linux-gnu/libcuda.so
/usr/local/cuda-7.0/targets/x86_64-linux/lib/stubs/libcuda.so

I need the 64-bit version, issue the symlink command;
sudo ln -s /usr/lib/x86_64-linux-gnu/libcuda.so.346.82 /usr/lib64/libcuda.so

Now open Mathematica and test;
Needs["CUDALink`"]
CUDADriverVersion[]
CUDAResourcesInformation[]
SystemInformation[]
CUDAQ[]

A: I figured it out.
The library file libcuda.so was in /usr/lib/x86_64-linux-gnu
I just created a sym link there and Mathematica was able to find it and it is working fine now.


text:
Q: Invisible cursor over panel in Gnome 3.14 I just installed Gnome 3.14 from PPA under Ubuntu 14.10 and, upon rebooting, the mouse cursor only shows over applications. Moving the mouse over the gnome panel hides the cursor. Same thing when opening the dashboard. When I launch Gnome Tweak, the "Cursor" dropdown selection is disabled.
I have been installing up-to-date Gnome for a while and I'm not sure how I can fix this. Most "resolutions" for this issue dates quite a while back.
Any idea how this can be resolved?
Thanks!
** Edit **
I have installed a cursor theme under ~/.icons and, while I now have a cursor over the gnome panel, the cursor theme is not applied. And I believe that the mouse cursor I see over applications is X11's default cursors (the ones we used to have ions ago with Linux).
** Update **
Following this youtube video, I got the cursor working again... except in Google Chrome.


text:
Q: How to prove if dividing a set of natural numbers into two groups with the same average, their average will be equal to the average of original set? I am doing a leetcode problem:
https://leetcode.com/problems/split-array-with-same-average/description/
The solutions are all assuming "the average of each partition is the average of the entire array when they are equal", but I cannot figure out why? Does anyone know why the assumption is true?
The solutions is here:

*

*https://leetcode.com/problems/split-array-with-same-average/discuss/120678/5ms-Short-C++-dfs-solution-with-pruning

*https://www.youtube.com/channel/UC1kBxkk2bcG78YBX7LMl9pQ

A: The sum of values of a group with $N$ members and group average $\overline x$ is simply $S = N\overline x$. This follows immediately from the definition of the average, $\overline x = \frac SN$.
Let's say a group of size $N$ is split into two sub-groups with sizes $N_1$ and $N_2$ and a common average $\overline x$.
The total sum $S$ of the original group will be the summed totals of both sub-groups, so:
$S = N_1\overline x + N_2\overline x = (N_1 + N_2)\overline x = N\overline x$.
So the original group average will also be $\overline x$, as required.

A: Let's say that original values are
$$
x_1, \ldots, x_n, y_1, \ldots, y_k.
$$
Then the average of these is
$$
A = \frac{1}{n+k}(x_1 + \ldots + x_n + y_1 + \ldots y_k)
$$
while the averages of the individual parts are
$$
B = \frac{1}{n}(x_1 + \ldots + x_n)
C = \frac{1}{k}(y_1 + \ldots + y_k)
$$
Now suppose that $B$ and $C$ are equal -- just use the letter $B$ -- then we get that
$$
nB = (x_1 + \ldots + x_n),
kB= (y_1 + \ldots + y_k)
$$
Summing, we get
$$
(x_1 + \ldots + x_n) + (y_1 + \ldots + y_k) = nB + kB = (n+k)B
$$
so that
$$
\frac{1}{n+k}\left[(x_1 + \ldots + x_n) + (y_1 + \ldots + y_k)\right] = B
$$
But the left hand side is exactly the overall average $A$. So $A = B$ as required.

A: Let $A$ but one group with $a$ elements  and $B$ be the other group with be elements and let $K_A = \sum_{a\in A} a$ and $K_B = \sum_b{\in B} b$.
And we are told $\frac {K_A}a = \frac {K_B}{b}$.  We need to prove $\frac {K_A + K_B}{a+b} = \frac {K_A}a = \frac {K_B}{b}$.
$\frac {K_A}a = \frac {K_B}{b}\implies \frac {K_A b}a = K_B $
So $\frac {K_A}a= \frac {K_A*\frac {a+b}{a}}{a\frac {a+b}a}=\frac{\frac {K_Aa + K_Ab}a}{a+b}=\frac {K_A + \frac {K_A*b}a}{a+b}=\frac {K_A + K_b}{a+b}$


text:
Q: Is it possible with Print.js to send the PDF to storage in a folder online instead of printing it? I am trying to use print.js(crabbly) https://github.com/crabbly/print.js to send a PDF to a folder on my website instead of printing it.
My task is to save form data into a PDF and save the PDF in a folder on my website once the user submits. I like the way print.js creates the PDF and sends it to print but I need it to send to my folder...maybe through php?
Thanks for anyone's help!!

A: You need to handle that form submission on the server side. Once you receive the form request or the payload, you can then use it to create your own PDF.
Looks like you may be using Php in the back-end, if that's the case, the FPDF class should have everything you need to create your PDF:
http://www.fpdf.org/
If you use Laravel, here is a convenient package wrapping the FPDF class so we can import it with composer:
https://github.com/crabbly/fpdf-laravel


text:
Q: Как стримить поток с tcpdump ? Хочу постримить данные tcpdump,  в поток на комп где есть wireshark .
Делал ли кто нибудидь такое  ?

A: нашёл на  Микротике решение и на Циске   если кому надо то вот ссылки .
http://blog.mistifiks.ru/2015/06/mikrotik-tcpdump-wireshark.html
http://avz.org.ua/wp/2009/09/14/catalyst-port-mirroring/


text:
Q: In tikzposter how to align blocks? I want to arrange blocks in the following manner:

Basically none of the blocks are aligned in a single column or row.
Number of blocks does not matter. I just want blocks to cross over the column or row.
Any idea would be helpful.
Thank You.

A: An alternative to tikzposter could be tcbposter part of tcolorbox package. It uses a regular scheme (rows and columns) to place boxes, but it's flexible enough to adjust boxes widths and heights. Even box placement and size can be relative to other boxes.
Something similar to OPs scheme could be:
\documentclass[12pt]{article}
\usepackage[poster]{tcolorbox}
\pagestyle{empty}
\begin{document}
\begin{tcbposter}[
coverage = {spread, interior style={blue!20}},
poster = {
    %showframe,
    columns=2,rows=7},
boxes = {enhanced, colback=white, colframe=brown, valign=center, halign=center}
]
\posterbox[colback=brown!70!black]{name=title, column=1, span=2, below=top, rowspan=1}{Poster title}
\posterbox{name=box1, column=1, row=2, rowspan=2, span=1.2}{Box 1}
\posterbox{name=box2, column*=2, row=2, span=.8}{Box 2}
\posterbox{name=box3, column*=2, row=3, span=.8}{Box 3}
\posterbox{name=box4, column=1, row=4, rowspan=.9, span=.8}{Box 4}
\posterbox{name=box5, column*=2, row=4, rowspan=1.1, span=1.2}{Box 5}
\posterbox{name=box6, column=1, below=box4, rowspan=.9, span=.8}{Box 6}
\posterbox{name=box7, column*=2, below=box5, rowspan=1.1, span=1.2}{Box 7}
\posterbox{name=box10, column=1, above=bottom, span=1.2, rowspan=1}{Box10}
\posterbox{name=box11, column*=2, above=bottom, span=.8, rowspan=1}{Box11}
\posterbox{name=box8, column=1, between=box6 and box10, span=.8}{Box 8}
\posterbox{name=box9, column*=2, between=box7 and box11, span=1.2}{Box 9}
\end{tcbposter}
\end{document}


text:
Q: Reading input from a text file, omits the first and adds a nonsense value to the end? When I input locations from a txt file I am getting a peculiar error where it seems to miss off the first entry, yet add a garbage entry to the end of the link list (it is designed to take the name, latitude and longitude for each location you will notice). I imagine this to be an issue with where it starts collecting the inputs and where it stops but I cant find the error!! It reads the first line correctly but then skips to the next before adding it because during testing for the bug it had no record of the first location Lisbon though whilst stepping into the method call it was reading it. Very bizarre but hopefully someone knows the issue. Here is firstly my header file:
#include <string>

struct locationNode
{
    char nodeCityName [35];
    double nodeLati;
    double nodeLongi;

    locationNode* Next;

void CorrectCase() // Correct upper and lower case letters of input
    {

        int MAX_SIZE = 35;
        int firstLetVal = this->nodeCityName[0], letVal;
        int n = 1; // variable for name index from second letter onwards

        if((this->nodeCityName[0] >90) && (this->nodeCityName[0] < 123)) // First letter is lower case
        {
             firstLetVal = firstLetVal - 32; // Capitalise first letter
             this->nodeCityName[0] = firstLetVal;
        }

        while(n <= MAX_SIZE - 1)
        {
            if((this->nodeCityName[n] >= 65) && (this->nodeCityName[n] <= 90))
            {
                letVal = this->nodeCityName[n] + 32;
                this->nodeCityName[n] = letVal;
            }
            n++;
        }
        //cityNameInput = this->nodeCityName;
    }

};

class Locations
{
private:
    int size;

public:

    Locations(){

    }; // constructor for the class

    locationNode* Head;

    //int Add(locationNode* Item);

};

And here is the file containing main:
// U08221.cpp : main project file.

#include "stdafx.h"
#include "Locations.h"
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int n = 0,x, locationCount = 0, MAX_SIZE = 35;
string cityNameInput;
char targetCity[35];
bool acceptedInput = false, userInputReq = true, match = false, nodeExists = false;// note: addLocation(), set to true to enable user input as opposed to txt file

locationNode *start_ptr = NULL; // pointer to first entry in the list
locationNode     *temp, *temp2; // Part is a pointer to a new locationNode we can assign changing value followed by a call to Add
locationNode *seek, *bridge;

void setElementsNull(char cityParam[])
{
    int y=0, count =0;
    while(cityParam[y] != NULL)
    {
        y++;
    }

    while(y < MAX_SIZE)
    {
        cityParam[y] = NULL;
        y++;
    }
}
void addLocation()
{

    temp  = new locationNode; // declare the space for a pointer item and assign a temporary pointer to it

    if(!userInputReq) // bool that determines whether user input is required in adding the node to the list
    {
cout << endl << "Enter the name of the location: ";
cin >> temp->nodeCityName;
temp->CorrectCase();
setElementsNull(temp->nodeCityName);
cout << endl << "Please enter the latitude value for this location: ";
cin >> temp->nodeLati;
cout << endl << "Please enter the longitude value for this location: ";
cin >> temp->nodeLongi;
cout << endl;
    }
temp->Next = NULL; //set to NULL as when one is added it is currently the last in the list and so can not point to the next

if(start_ptr == NULL){ // if list is currently empty, start_ptr will point to this node

    start_ptr = temp;
}

else
       { temp2 = start_ptr;
         // We know this is not NULL - list not empty!
         while (temp2->Next != NULL)
           {
               temp2 = temp2->Next; // Move to next link in chain until reach end of list
           }

         temp2->Next = temp;
       }

++locationCount; // increment counter for number of records in list
if(!userInputReq){
cout << "Location sucessfully added to the database! There are " << locationCount << " location(s) stored" << endl;
}
}

void populateList(){

    ifstream inputFile;
    inputFile.open ("locations.txt", ios::in);
    userInputReq = true;
    temp  = new locationNode; // declare the space for a pointer item and assign a temporary pointer to it

 do
 {

      inputFile.get(temp->nodeCityName, 35, ' ');
      setElementsNull(temp->nodeCityName);
     inputFile >> temp->nodeLati;
    inputFile >> temp->nodeLongi;
    setElementsNull(temp->nodeCityName);

        if(temp->nodeCityName[0] == 10) //remove linefeed from input
        {
            for(int i = 0; temp->nodeCityName[i] != NULL; i++)
            {
                temp->nodeCityName[i] = temp->nodeCityName[i + 1];
            }
        }
     addLocation();
 }
  while(!inputFile.eof());

  userInputReq = false;
  cout << "Successful!" << endl << "List contains: " << locationCount << " entries" << endl;
  cout << endl;

  inputFile.close();
  }

bool nodeExistTest(char targetCity[]) // see if entry is present in the database
{

    match = false;

    seek = start_ptr;

    int letters = 0, letters2 = 0, x = 0, y = 0;

    while(targetCity[y] != NULL)
    {
        letters2++;
        y++;
    }

while(x <= locationCount) // locationCount is number of entries currently in list
{
    y=0, letters = 0;
    while(seek->nodeCityName[y] != NULL) // count letters in the current name
    {
        letters++;
        y++;
    }

    if(letters == letters2) // same amount of letters in the name
    {
        y = 0;

            while(y <= letters) // compare each letter against one another
                {

                    if(targetCity[y] == seek->nodeCityName[y])
                        {
                            match = true;
                            y++;
                                }
                    else
                    {
                    match = false;
                    y = letters + 1; // no match, terminate comparison
                    }
                }

    }
    if(match)
    {

        x = locationCount + 1; //found match so terminate loop

    }

    else{
        if(seek->Next != NULL)
        {
        bridge = seek;
        seek = seek->Next;
        x++;
        }
        else
        {
            x = locationCount + 1; // end of list so terminate loop
        }
    }

}
  return match;
}

void deleteRecord() // complete this
{
    int junction = 0;
    locationNode *place;
    cout << "Enter the name of the city you wish to remove" << endl;
    cin >> targetCity;
    setElementsNull(targetCity);

if(nodeExistTest(targetCity)) //if this node does exist
{
    if(seek == start_ptr) // if it is the first in the list
    {
        junction = 1;
   }

    if(seek != start_ptr && seek->Next == NULL) // if it is last in the list
    {
        junction = 2;
   }

switch(junction) // will alter list accordingly dependant on where the searched for link is
{
case 1:
    start_ptr = start_ptr->Next;
        delete seek;
        --locationCount;
            break;

case 2:

        place = seek;
        seek = bridge;
        delete place;
        --locationCount;
            break;

default:
    bridge->Next = seek->Next;
    delete seek;
    --locationCount;
    break;
}
}

else
{   cout << targetCity << "That entry does not currently exist" << endl << endl << endl;
    }

}

void searchDatabase()
{
    char choice;
    cout << "Enter search term..." << endl;
    cin >> targetCity;

    if(nodeExistTest(targetCity))
    {
        cout << "Entry: " << endl << endl;
    }
    else
    {
        cout << "Sorry, that city is not currently present in the list." << endl << "Would you like to add this city now Y/N?" << endl;
        cin >> choice;

        /*while(choice != ('Y' || 'N'))
        {
            cout << "Please enter a valid choice..." << endl;
            cin >> choice;
        }*/

        switch(choice)
        {
        case 'Y':
            addLocation();
            break;

        case 'N':
            break;

        default :
            cout << "Invalid choice" << endl;
            break;
        }
    }
}

void printDatabase()
{
    temp = start_ptr; // set temp to the start of the list
do
  {  if (temp == NULL)
  {
       cout << "You have reached the end of the database" << endl;
  }
     else
       {  // Display details for what temp points to at that stage
          cout << "Location : " << temp->nodeCityName << endl;
          cout << "Latitude : " << temp->nodeLati << endl;
          cout << "Longitude : " << temp->nodeLongi << endl;
          cout << endl;

          // Move on to next locationNode if one exists
          temp = temp->Next;
       }
  }
while (temp != NULL);
}

void nameValidation(string name)
    {
        n = 0; // start from first letter
        x = name.size();

    while(!acceptedInput)
    {

        if((name[n] >= 65) &&  (name[n] <= 122)) // is in the range of letters
            {
                while(n <= x - 1)
                {
            while((name[n] >=91) && (name[n] <=97)) // ERROR!!
            {
            cout << "Please enter a valid city name" << endl;
            cin >> name;
            }
            n++;
                }
            }
        else {
            cout << "Please enter a valid city name" << endl;
            cin >> name;
        }

    if(n <= x - 1)
    {
        acceptedInput = true;
    }
    }
    cityNameInput = name;
    }

int main(array<System::String ^> ^args)
{
//main contains test calls to functions at present

    cout << "Populating list...";
    populateList();
    printDatabase();

    deleteRecord();
    printDatabase();
    cin >> cityNameInput;

}

The text file contains this (ignore the names, they are just for testing!!):
Lisbon 45 47
Fattah 45 47
Darius 42 49
Peter 45 27
Sarah 85 97
Michelle 45 47
John 25 67
Colin 35 87
Shiron 40 57
George 34 45
Sean 22 33

The output omits Lisbon, but adds on a garbage entry with nonsense values. Any ideas why? Thank you in advance.

A: The main function creates a new locationNode and stores it in the global variable temp, then reads the first dataset and stores it in that node.
Then you call addLocation() which starts by creating another new locationNode which replaces the existing one in temp. This new node is then inserted into the list.
The next iteration of the main loop then fills that temp value with values and addLocation() inserts another brand new locationNode into the list. So the first dataset isn't stored in the list and each iteration ends up by inserting an uninitialized new node.
As you see using global variables can lead to confusing situations and you code would surely become clearer if you were passing the nodes as parameters to your functions.


text:
Q: How to submit additional data along the file upload in dropzone.js? I have this form in my html code:
<form action="upload" id="upload-dropzone" class="dropzone">
    <input type="hidden" name="browser-path" id="browser-path" value="/">

        Upload

</form>

As this document said, the hidden input field browser-path will automatically be submitted as POST data to server.
I have this code in my server side:
System.out.println(request.getParameter("browser-path"));

But this code always prints null to output!
How can I submit this hidden field to my server and how can I read it?
Edit:
Thanks to steeno, the form enctype is multipart/form-data so I have to read the fields from another way.

A: I assume you use Java as backend language?
As mentioned in the following question: HttpServletRequest get JSON POST data
the problem yould be the encoding of the post request. Maybe try to get the post data with getReader instead of getParameter.


text:
Q: Detect keypress event after enter has been hit I am building a search functionality where if the the user types in, an autosuggestion box appears. As soon as he hits enter, the autosuggestion box disappears, the search results get appended and the cursor in the search bar disappears. Now when the user again focuses on the search(to type again), the autosuggestion box appears again.
I am unable to achieve the latter part of the statement.
In the below code, consider "child-div" as the autosuggestion box.
So far, I am able to achieve -

*

*As soon as the user enters three letters, the box appears.

*On hitting enter, it disappears.

What I want to achieve further -

*

*After the second step above, the "I" cursor should disappear from the search box.

*On focusing on the search box again, the auto-box should appear again.

              <input type="text" class="form-control form-rounded rounded-pill" placeholder="Text input" id="searchbar">

                CHILD DIV

$('#searchbar').on('input keydown', function (e) {

    if ($('#searchbar').val().length >= 3) {
        $('.child-div').show();
    }

    if( e.which == 13){
        $('.child-div').hide();
    }

})

How to achieve the last scenario? Can anyone please help?
Thankss !!

A: You can use JQuery blur() and focus() event. When the user press enter, we will programmatically close the box and trigger input blur() event to unfocus it. Then register a focus() event that show the box whenever the input is focus.

*

*https://api.jquery.com/blur/

*https://api.jquery.com/focus/

A: The simplest way to do it would be as follows

$('#searchbar').on('input keydown', function (e) {
    if ($('#searchbar').val().length >= 3) {
        $('.child-div').show();
    }

    if( e.which == 13){
        $('.child-div').hide();
        e.target.blur();
    }
})

$('#searchbar').on('focus', function (e) {
    if ($('#searchbar').val().length >= 3) {
        $('.child-div').show();
    }
})

              <input type="text" class="form-control form-rounded rounded-pill" placeholder="Text input" id="searchbar">

                CHILD DIV

Here you just perform a blur event after hitting enter and also register focus event, which checks if it should open the child div or not


text:
Q: Query works in MySQL but not via Lumen/Laravel - Numeric value out of range: 1416 I am stumped... Quite simply, I am trying to update a geometry record in a MySQL database and for some reason, it is failing. However, when Lumen throws the QueryException, it shows the query that is being executed;
UPDATE `user_locations` SET `current_location` = ST_GeomFromText('POINT(1 1)') WHERE user_id = 1

The above query works when I execute it in MySQL via command line, but for some reason, it does not work via Laravel/Lumen/PDO/Eloquent (not sure which one is causing the issue).
This is the error that is thrown:
SQLSTATE[22003]: Numeric value out of range: 1416 Cannot get geometry object from data you send to the GEOMETRY field (SQL: update `user_locations` set `current_location` = ST_GeomFromText('POINT(1 1)') where `user_id` = 1)

I have tried everything that I can think of;

*

*Downgrading MySQL (I saw others having similar issues with Mysql 5.7)

*Dumping the query and bindings directly from Eloquent to see what is actually being sent to MySQL (see below)

*Changing the engine of the database (it is currently InnoDB)

*Removing the spatial index on the current_location column

What else could be causing this? It cannot be MySQL as it works via command line, so it has to be something within Laravel/Eloquent/PDO surely?
Additional Information

*

*I am running MySQL 5.7 (I have also tried 5.6 and it threw exactly the same error)

*I am using Lumen but don't think this is relevant as both Laravel and Lumen use Eloquent

*I am using https://github.com/grimzy/laravel-mysql-spatial and this (I believe) is the relevant code:

*Update - I don't think this is relevant, but there is another point field on this particular table but as I am not updating that field, it should be completely ignored in the query, thus, not relevant...

Builder extends Illuminate\Database\Eloquent\Builder
/**
 * Update a record in the database.
 *
 * @param   array $values
 * @return  int
 */
public function update(array $values) : int
{
    foreach ($values as $key => &$value) {
        if ($value instanceof GeometryInterface) {
            $value = $this->asWKT($value);
        }
    }

    return parent::update($values);
}

/**
 * Set the MySQL for the geometry field.
 *
 * @param   GeometryInterface $geometry
 * @return  string
 */
protected function asWKT(GeometryInterface $geometry) : string
{
    return $this->getQuery()->raw("ST_GeomFromText('" . $geometry->toWKT() . "')");
}

In addition, I have also tried the following:
Illuminate\Database\Query\Builder
public function update(array $values)
{
    $sql = $this->grammar->compileUpdate($this, $values);

    dd($sql, $values, $this->cleanBindings(
        $this->grammar->prepareBindingsForUpdate($this->bindings, $values)
    ));

    return $this->connection->update($sql, $this->cleanBindings(
        $this->grammar->prepareBindingsForUpdate($this->bindings, $values)
    ));
}

This outputs:
string(70) "update `user_locations` set `current_location` = ? where `user_id` = ?"
array(1) {
  ["current_location"]=>
  &string(47) "ST_GeomFromText('POINT(1 1)')"
}
array(2) {
  [0]=>
  &string(47) "ST_GeomFromText('POINT(1 1)')"
  [1]=>
  int(1)
}

A: See here:
Illuminate\Database\Query
/**
 * Create a raw database expression.
 *
 * @param  mixed  $value
 * @return \Illuminate\Database\Query\Expression
 */
public function raw($value)
{
    return $this->connection->raw($value);
}

The return of raw is not a string, it is \Illuminate\Database\Query\Expression. Therefore, by casting the return value of asWkt, to a string, it is forcing Eloquent to wrap it with quotes, thus throwing the error we are seeing.


text:
Q: Pattern for sharing SQLiteCursorLoader object between activities Default Android CursorLoader uses ContentProvider and knows about all inserts, updates, ... SQLiteCursorLoader doesn't know, but I'm curious about the best pattern for sharing SQLiteCursorLoader object between activities. Is it possible at all?

A: Do not share loaders, period, whether it is SQLiteCursorLoader, CursorLoader, or any other Loader. They are only for use by the activity/fragment that created them.


text:
Q: Android In-App Purchase Presently I am developing one application in android.I want to implement in app purchase in my app when i click a button.
Please help me with simple example to implementing in app purchase for our app.
Thanks in advance.

A: I am sorry to answer in this manner, but the documentation from Google is pretty good on the subject; http://developer.android.com/guide/market/billing/index.html
The "Dungeons" example provides sample code that is pretty good.
In app billing is a bit complex, and uses some advanced Android techniques like IPC. I have been experimenting with this for the last two-three days, and I think you will have to do like me; close the office door and dig into the sample code & docs.
good luck! Please ask any specific question along the way. I am sure people will be more than willing to help.


text:
Q: Nvidia graphics driver problem on Ubuntu 18.04 (GPU at BusId doesn't have a supported video decoder) I'm running Ubuntu 18.04 with Nvidia MX110 graphics, and I have recently had problems with installing drivers. After numerous tries, I've succeeded in installing 440 driver somehow, although I still have one warning when I run nvidia-settings in terminal.
(nvidia-settings:16242): GLib-GObject-CRITICAL **: 16:33:57.281: g_object_unref: assertion 'G_IS_OBJECT (object)' failed
GPU at BusId 0x1 doesn't have a supported video decoder
** Message: 16:33:57.471: PRIME: Requires offloading
** Message: 16:33:57.471: PRIME: is it supported? yes
** Message: 16:33:57.531: PRIME: Usage: /usr/bin/prime-select nvidia|intel|query
** Message: 16:33:57.531: PRIME: on-demand mode: "0"
** Message: 16:33:57.531: PRIME: is "on-demand" mode supported? no

Graphics card and driver are recognized by system, I can switch between performance and power saving modes (my integrated graphics), but I noticed little bugs, such as couple of seconds of freeze when closing some program or switching focus to another. I wonder if this may be linked to that, because I did not have this problem before, when my driver wasn't working and when I ran it only on integrated intel graphics.

A: It caused due to your chips don't have a working video decoding hardware. For now video decoding capabilities on systems may only supported by the embedded Intel iGPU.
Regards,


text:
Q: PHP & MySQL secure web application - Whole web site as single index.php file yes or no? I am working on web application that will use PHP & MySQL. Application will process confidential data. I need to make it as secure as possible.
I dont want password for MySQL user that application is using to connect to database to be written in PHP file in clear text format(root account for example).
Because of that I made pseudo MySQL Role system with stored procedures. Users will login to application with their MySQL username and password. They will have privilege only to execute MySQL stored procedures but not SELECT, INSERT, UPDATE, DELETE privileges on tables that are used inside of stored procedures. Definer of stored procedures will be root account.
I have one problem with that. And that is: I dont want to store login form data ( password for examole) in session in clear text format. I cant transfer mysql connection resource object from one page to another using session.
I am thinking right now to make whole web application as one big index.php file. That way I will have MySQL connection resource allways available when I need it.
Are there batter ways to do this? Probably. I dont want to regret my choice after too much work wasted :).
Thank you in advance.

A: You still have to save the username and password to session. but dont save password in clear text , use openssl_encrypt and openssl_decrypt with your own hash.
http://php.net/manual/en/function.openssl-encrypt.php
but this function appears from PHP 5.3.0 above

A: You should never need to store passwords in the session and there is no need to create individual MySQL users for each user of your application. These things don't make your application more secure and could actually make it less secure.
Here are some suggestions:

*

*Create one MySQL user with only the necessary permissions to read the data you need.

*Store the MySQL connection information in a PHP file that is outside the document root and include this file in your PHP files that need access to the database.

*Create a table in the database to store user accounts and always hash their password before saving it to the table. You can use this table to authenticate your users when they sign in.

*When the user signs in, simply store a flag in the session, like their user_id. This is enough to identify who they are and that they are signed in. If the value is not in the session, then they are not signed in.

*You don't need to put everything in one PHP file. It's OK to have more than one file.

You may want to try using a framework, like Symfony, CodeIgniter, or CakePHP because they will have tutorials that can help you create a secure application. Keep in mind that security goes beyond just passwords. As Kishor points out, you also need to worry about XSS, SQL injection, CSRF, etc. A framework will really help you out with these things.

A: No, don't make your application one giant file.
Put your DB credentials in an include outside of the web root.  Then, make sure only the users that need it can open it.  That's how this is generally done.

A: There exists a design pattern called Front Controller, basically what it does is the entire application is served through one page. You implement your own dispatcher and the dispatcher handles all the requests. Such as which object to instantiate or which page to include. This limits the security exploitation for unknown objects.
Also, for the Session hijacking you can implement your prevention mechanisms by monitoring and checking for

*

*User Agent

*Session regenerate id

*Tokens

The database part is fairly impressive but may add additional complexities if someone else has to extend, debug your application. You can use prepared statements or even a better alternative an ORM such as Doctrine or Data Objects.
The major security exploits are through XSS and CSRF for that you will have to implement token passing mechanism within your forms and check for " origin of request".
Lastly, i would like to point out there are various security exploits possible in an web application. To counter these exploits lots of good frameworks exist. These issues and vulnerabilities are pre-dealt there. You can consider on the bussiness logic and let someone else handle that for you. Contrary to popular belief using frameworks will actually steepen your growth over the architectures, security and requests.
Hope this help !! cheers !


text:
Q: android device ID (not IMEI) I use the command: adb devices to list the attached devices.
On my computer I get :
List of devices attached
HT9CTP820988 device
My question is: how can I get this id (HT9CTP820988) programmatically ?

A: What you're seeing with the adb devices command is the serial number:

Serial number — A string created by
  adb to uniquely identify an
  emulator/device instance by its
  console port number. The format of the
  serial number is -.
  Here's an example serial number:
  emulator-5554

(refererence: http://developer.android.com/guide/developing/tools/adb.html)
When you ask "how can I get this id programmatically" what exactly do you mean? From an Android app or from a desktop app?

A: How about this one?
http://developer.android.com/reference/android/provider/Settings.Secure.html#ANDROID_ID
edit: Hmm I recall this, it can't be right; the ANDROID_ID is supposed to be 64-bit. Maybe the string you see is given by the USB driver?

A: Look at Settings.ACTION_DEVICE_INFO_SETTINGS and answers that have already been given in the past How to find serial number of Android device?

A: I think the emulator id's purpose is to identify the emulator and devices in the development environment. And it may not be accessible from the phone.

A: It's possible by changing *strings_dev* struct from drivers/usb/gadget/android.c

A: I'm Using the following code...
String aid = Settings.Secure.getString(getContext().getContentResolver(), "android_id");

    Object obj = null;
    try {
        ((MessageDigest) (obj = MessageDigest.getInstance("MD5"))).update(                                   aid.getBytes(), 0, aid.length());

        obj = String.format("%032X", new Object[] { new BigInteger(1,                                   ((MessageDigest) obj).digest()) });
    } catch (NoSuchAlgorithmException localNoSuchAlgorithmException) {
        obj = aid.substring(0, 32);
    }


text:
Q: How to allow your data structure to take in objects of any class - C++ How do I do that? Like you know in Java, you can use an ArrayList and it will take any object as long as you cast it down to whatever it is when you're retrieving the object.
Even better, you can specify what class of objects that ArrayList would store by doing...

new ArrayList()< whateverObject >

I've implemented a linked list data structure in C++ and I'd like to know how I can allow it to do this...
At the moment, I'm just using...

typedef whateverObject ItemType

at the start of my header file for my linked list and then manipulating "ItemType" throughout the implementation of the linked list. So every time I want to change the type, e.g. instead of using the list for storing strings, I want to store an int, I'll have to change the typedef in my linked list's header but I want to be able to  simply use it for any object so...
How?!
Thanks.

A: Templates are the answer to your question.
Define your linked list as follows :
template<typename ItemType>
class ArrayList
{
  // What's inside your class definition does not need to be changed
  // Include your method definitions here and you'll be fine
};

The type to use is then ArrayList<WhateverObject>.

A: Use templates. It's a lot to explain so I'll just give you a link where it's explained much better than I'll ever be able to do here: C++ FAQ - Templates.
While you're at it, if you have the time, I suggest you read the whole FAQ, it's really a great resource!

A: If I have understood well what you ask, templates is what you want.
Take a look here:
http://www.cplusplus.com/doc/tutorial/templates/

A: In java you can do so, because all classes are inherited from one base class Object. In C++ you do not have it. The reason is that Object base class impose overhead for all objects, while C++ do not like any unnecessary overhead.
If you want to store any object - you can store "void *" data type. The question remained - what you will be able to do with objects, without the knowledge of the type? If you do know - you can cast to the needed type and use it. The practice described above is not safe, and templates are better in most cases.