text:
Q: Regression tree in R I am having trouble making a regression tree in R. I have a data frame with 17 attributes
library(rpart)
rt.model <- rpart(razlika ~ ., learn)

I get an error:
Error in `[.data.frame`(frame, predictors) : undefined columns selected

Seems weird because I did something like that with a very simillar database. You can dowload the dataframe on http://uploading.com/files/de8a966d/exa.Rda/ -
then load with
load("exa.Rda")

A: Turn your learn matrix into a data frame.
Example:
load("exa.Rda")
library(rpart)
learn <- data.frame(learn)
rt.model <- rpart(razlika ~ ., learn)
rt.model

yields:
n= 226

node), split, n, deviance, yval
      * denotes terminal node

  1) root 226 31417.5100   3.3849560
    2) B.reb>=40.80799 117 12661.2300   0.4871795
      4) B.ft>=0.7666193 31  2685.4190  -5.7741940
        8) A.fg2< 0.4645683 22  1846.7730  -8.3181820
         16) A.ft< 0.7464692 7   365.4286 -14.2857100 *
         17) A.ft>=0.7464692 15  1115.7330  -5.5333330 *
        9) A.fg2>=0.4645683 9   348.2222   0.4444444 *
      5) B.ft< 0.7666193 86  8322.3720   2.7441860
       10) B.avg.conceded.< 98.19592 76  7255.6320   1.7105260
         20) A.reb< 39.29941 19  1520.6320  -3.5789470 *
         21) A.reb>=39.29941 57  5026.2110   3.4736840
           42) A.3pt< 0.3945418 35  2500.1710   0.7714286
             84) A.ft< 0.7460665 17  1270.2350  -2.4705880 *
             85) A.ft>=0.7460665 18   882.5000   3.8333330 *
           43) A.3pt>=0.3945418 22  1863.8640   7.7727270
             86) B.ft>=0.7214165 13   718.9231   4.0769230 *
             87) B.ft< 0.7214165 9   710.8889  13.1111100 *
       11) B.avg.conceded.>=98.19592 10   368.4000  10.6000000 *
    3) B.reb< 40.80799 109 16719.2500   6.4954130
      6) A.fouls>=24.51786 23  2349.9130  -2.2173910
       12) A.fg2< 0.4551468 16  1266.0000  -5.5000000 *
       13) A.fg2>=0.4551468 7   517.4286   5.2857140 *
      7) A.fouls< 24.51786 86 12156.3800   8.8255810
       14) B.fouls< 22.80863 24  3271.9580   2.5416670
         28) A.3pt< 0.3738479 9   626.0000  -6.0000000 *
         29) A.3pt>=0.3738479 15  1595.3330   7.6666670 *
       15) B.fouls>=22.80863 62  7569.8710  11.2580600
         30) A.fouls< 22.32999 18  1650.5000   5.5000000 *
         31) A.fouls>=22.32999 44  5078.4320  13.6136400
           62) A.ft.drawn>=29.18849 7   208.8571   3.8571430 *
           63) A.ft.drawn< 29.18849 37  4077.1890  15.4594600
            126) A.fg2< 0.4588535 18  1696.5000  11.5000000 *
            127) A.fg2>=0.4588535 19  1831.1580  19.2105300 *

A: The problem is not, I believe, that you have a matrix rather than a data frame. When I download and then load you data set, I get a data frame, not a matrix.
The problem is that you have bad characters in the column names. Use gsub to remove the characters "-", " ", "(" and ")" from the column names. Or you can simply redefine the column names yourself entirely using colnames.
Or do as ulvund does and simply call data.frame, which forces R to do the column name cleaning for you, by default.
When I do this, rpart runs just fine.

A: This can also happen if column names are integers (1:N), even though they are stored as characters.


text:
Q: javascript id selector is returning null even when the id is present Somehow in js in  const questionEl = document.getElementById('question'); is returning null. I checked all the id selectors and found out that they were all returning null. I cannot understand the cause of the problem. I have elements with the specified id. Then why is still returning null?

const questionEl = document.getElementById('question');
const a_text = document.getElementById("a");
console.log("This  is >>", a_text);
const b_text = document.getElementById("b");
const c_text = document.getElementById("c");
const d_text = document.getElementById("d");

let currentQuestion = 0;

function loadQuiz() {
  console.log(quizData[currentQuestion].question)
  questionEl.innerHTML = quizData[currentQuestion].question;
  currentQuestion++;
}

loadQuiz();

Question text

      <input type="radio" id="a" name="answer">
      Question

      <input type="radio" id="b" name="answer">
      Question

      <input type="radio" id="c" name="answer">
      Question

      <input type="radio" id="d" name="answer">
      Question

  <button>Next</button>

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the best way to get cyclic substrings I want something like:
var peptide = "LENQ"

peptide[2:3] -> NQ
peptide[2:4] -> NQL
peptide[2:5] -> NQLE

What is the best way in go to do it?  May be there is a library function to get it or do I need to write it by myself ?

A: For example,
package main

import (
    "fmt"
    "unicode/utf8"
)

func cyclicSubstrings(str string) []string {
    n := utf8.RuneCountInString(str)
    substrs := make([]string, 0, n*n)
    cycles := str + str
    for i := range str {
        cycle := cycles[i : i+len(str)]
        for j, r := range cycle {
            substrs = append(substrs, cycle[:j+utf8.RuneLen(r)])
        }
    }
    return substrs
}

func main() {
    peptide := "LENQ"
    fmt.Println(cyclicSubstrings(peptide))
}

Output:

[L LE LEN LENQ E EN ENQ ENQL N NQ NQL NQLE Q QL QLE QLEN]


text:
Q: Javascript conditional-operator operator in string throws error I'm getting this unexpected behavior of an undefined property in the true clauses of the conditional-operator:
Example:
Javascript:
var obj = undefined;

console.log("hello world" + (obj) ? obj.Name.toString(): "Object not defined");

Fiddle
The expeced behaviour is getting a log entry saying hello worldObject"not defined instead an error is thrown: SCRIPT5007: Unable to get value of the property 'Name': object is null or undefined . How can this be, the object is checked an it should never execute htis coe path.
A working example is:
var obj = undefined;

console.log("hello world" + ((obj) ? obj.Name.toString(): "Object not defined"));

Fiddle

A: try this condition:
console.log("hello world" + ((obj || {}).Name) ? ...);

or also
console.log("hello world" + ((obj || 0).Name) ? ...);

so you will check for both obj and obj.Name.
In fact, the condition you defined only checks for obj but not for obj.Name
You could read an explanation about this kind of condition on ajaxian

A: Grouping's the issue here - your line is equivalent to the following:
("hello world" + obj) ? obj.Name.toString(): "Object not defined"

("hello world" + obj) is equal to "hello worldundefined", which is coerced into a true boolean in JavaScript, so the browser attempts to find and run the obj.Name.toString() function, which does not exist.
Also, I'm pretty sure most objects don't have a Name property, unless you set one manually.  The undefined value will never have a Name property, as it's not an object and can't be converted into one, therefore giving the error stated.
If you want to check for that specific property instead, then you'd have to do something like the following:
var obj = undefined;
console.log("hello world" + (typeof obj === 'object' && obj.Name != null ? obj.Name.toString(): " Object not defined"));

A: You should instead do: (obj && obj.Name) ? obj.Name.toString(): "Object not defined"
Your condition
(obj) ? obj.Name.toString(): "Object not defined"

checks only if obj is defined, it does not check if obj.Name is defined before calling .toString() on it.


text:
Q: Android studio cannot create a new flutter project When I use Android studio to create a new flutter project, the following error occurs:Multiple output directories specified.Try moving --org to be immediately following create.
Project configuration Image
Error message Image
The running result of flutter doctor is as follows, the operating system is mac.
flutter doctor Image

A: After searching, I think it's an error in your Android Studio's create command. Try this in your command line
flutter create --org com.yourdomain your_app_name

If this works, then my assumption is right. From your error message, it is saying that --org should be after create. I found a similar issue in Github. A clean installation may solve the issue then.


text:
Q: vector field visualisation R I have a big text file with a lot of rows. Every row corresponds to one vector.
This is the example of each row:
        x           y               dx              dy
99.421875   52.078125   0.653356799108  0.782479314511

First two columns are coordinates of the beggining of the vector. And two second columnes are coordinate increments (the end minus the start).
I need to make the picture of this vector field (all the vectors on one picture).
How could I do this?
Thank you

A: OK, here's a base solution:
DF <- data.frame(x=rnorm(10),y=rnorm(10),dx=runif(10),dy=runif(10))
plot(NULL, type = "n", xlim=c(-3,3),ylim=c(-3,3))
arrows(DF[,1], DF[,2], DF[,1] + DF[,3], DF[,2] + DF[,4])

A: If there is a lot of data (the question says "big file"),
plotting the individual vectors may not give a very readable plot.
Here is another approach: the vector field describes a way of deforming something drawn on the plane;
apply it to a white noise image.
vector_field <- function(
  f,  # Function describing the vector field
  xmin=0, xmax=1, ymin=0, ymax=1,
  width=600, height=600,
  iterations=50,
  epsilon=.01,
  trace=TRUE
) {
  z <- matrix(runif(width*height),nr=height)
  i_to_x <- function(i) xmin + i / width  * (xmax - xmin)
  j_to_y <- function(j) ymin + j / height * (ymax - ymin)
  x_to_i <- function(x) pmin( width,  pmax( 1, floor( (x-xmin)/(xmax-xmin) * width  ) ) )
  y_to_j <- function(y) pmin( height, pmax( 1, floor( (y-ymin)/(ymax-ymin) * height ) ) )
  i <- col(z)
  j <- row(z)
  x <- i_to_x(i)
  y <- j_to_y(j)
  res <- z
  for(k in 1:iterations) {
    v <- matrix( f(x, y), nc=2 )
    x <- x+.01*v[,1]
    y <- y+.01*v[,2]
    i <- x_to_i(x)
    j <- y_to_j(y)
    res <- res + z[cbind(i,j)]
    if(trace) {
      cat(k, "/", iterations, "\n", sep="")
      dev.hold()
      image(res)
      dev.flush()
    }
  }
  if(trace) {
    dev.hold()
    image(res>quantile(res,.6), col=0:1)
    dev.flush()
  }
  res
}

# Sample data
van_der_Pol <- function(x,y, mu=1) c(y, mu * ( 1 - x^2 ) * y - x )
res <- vector_field(
  van_der_Pol,
  xmin=-3, xmax=3, ymin=-3, ymax=3,
  width=800, height=800,
  iterations=50,
  epsilon=.01
)
image(-res)

You may want to apply some image processing to the result to make it more readable.
image(res > quantile(res,.6), col=0:1)

In your case, the vector field is not described by a function:
you can use the value of the nearest neighbour or some 2-dimensional interpolation
(e.g., from the akima package).

A: Here is a example from the R-Help of pracma-package.
library(pracma)
f <- function(x, y) x^2 - y^2
xx <- c(-1, 1); yy <- c(-1, 1)
vectorfield(f, xx, yy, scale = 0.1)
for (xs in seq(-1, 1, by = 0.25)) {
    sol <- rk4(f, -1, 1, xs, 100)
    lines(sol$x, sol$y, col="darkgreen")
}

You can use quiver also.
library(pracma)
xyRange <- seq(-1*pi,1*pi,0.2)
temp <- meshgrid(xyRange,xyRange)
u <- sin(temp$Y)
v <- cos(temp$X)
plot(range(xyRange),range(xyRange),type="n",xlab=expression(frac(d*Phi,dx)),ylab=expression(d*Phi/dy))
quiver(temp$X,temp$Y,u,v,scale=0.5,length=0.05,angle=1)

A: With ggplot2, you can do something like this :
library(grid)
df <- data.frame(x=runif(10),y=runif(10),dx=rnorm(10),dy=rnorm(10))
ggplot(data=df, aes(x=x, y=y)) + geom_segment(aes(xend=x+dx, yend=y+dy), arrow = arrow(length = unit(0.3,"cm")))

This is taken almost directly from the geom_segment help page.


text:
Q: Spinner force closing Im trying to test the functionality of my spinner with a toast.  I am having trouble because instead of toasting ShowTime, it force closes. my logcat is posted below the code.  If anybody can help me read my logcat code and figure out whats wrong.  Thanks in advance!
 public class Spinner extends Activity {
        Spinner bus;
        String GetTime;
        int ShowTime;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

            final String[] Log_Array = new String[9];
            {
                Log_Array[0] = "5 min";
                Log_Array[1] = "10 min";
                Log_Array[2] = "30 min";
                Log_Array[3] = "50 min";
                Log_Array[4] = "100 min";
                Log_Array[5] = "300 min";
                Log_Array[6] = "400 min";
                Log_Array[7] = "500 min";
                Log_Array[8] = "600 min";

                bus= (Spinner) findViewById(R.id.timer);

                ArrayAdapter NoCoreAdapter = new ArrayAdapter(this,
                        android.R.layout.simple_spinner_item, Log_Array);
                bus.setAdapter(NoCoreAdapter);

                bus.setSelection(1);
            }

            bus.setOnItemSelectedListener(new OnItemSelectedListener() {

                public void onItemSelected(AdapterView<?> parent, View view,
                        int pos, long id) {

                    GetTime = parent.getItemAtPosition(pos).toString();

                    if (pos == 0) {
                        GetTime.equals(Log_Array[0]);
                        ShowTime = 5;
                    }
                    if (pos == 1) {
                        GetTime.equals(Log_Array[1]);
                        ShowTime = 5;
                    }
                    if (pos == 2) {
                        GetTime.equals(Log_Array[2]);
                        ShowTime = 5;
                    }
                    if (pos == 3) {
                        GetTime.equals(Log_Array[3]);
                        ShowTime = 5;
                    }
                    if (pos == 4) {
                        GetTime.equals(Log_Array[4]);
                        ShowTime = 5;
                    }
                    if (pos == 5) {
                        GetTime.equals(Log_Array[5]);
                        ShowTime = 5;
                    }
                    if (pos == 6) {
                        GetTime.equals(Log_Array[6]);
                        ShowTime = 5;
                    }
                    if (pos == 7) {
                        GetTime.equals(Log_Array[7]);
                        ShowTime = 5;
                    }

                    if (pos == 8) {
                        GetTime.equals(Log_Array[8]);
                        ShowTime = 6;
                    }
                    Toast.makeText(getApplicationContext(), ShowTime,
                            Toast.LENGTH_LONG).show();
                }

                public void onNothingSelected(AdapterView parent) {
                    // Do nothing.
                }
            });
        }

My LogCat
07-01 16:12:14.348: E/AndroidRuntime(21733): FATAL EXCEPTION: main
07-01 16:12:14.348: E/AndroidRuntime(21733): android.content.res.Resources$NotFoundException: String resource ID #0x5
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.content.res.Resources.getText(Resources.java:210)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.widget.Toast.makeText(Toast.java:258)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at com.settings.Settings$1.onItemSelected(Settings.java:88)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.widget.AdapterView.fireOnSelected(AdapterView.java:871)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.widget.AdapterView.access$200(AdapterView.java:42)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.widget.AdapterView$SelectionNotifier.run(AdapterView.java:837)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.os.Handler.handleCallback(Handler.java:587)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.os.Handler.dispatchMessage(Handler.java:92)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.os.Looper.loop(Looper.java:143)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at android.app.ActivityThread.main(ActivityThread.java:4196)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at java.lang.reflect.Method.invokeNative(Native Method)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at java.lang.reflect.Method.invoke(Method.java:507)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
07-01 16:12:14.348: E/AndroidRuntime(21733):    at dalvik.system.NativeStart.main(Native Method)

A: Toast has a convenience method that allows you to pass it a resource ID(integer) that is a pointer to a string resource.
so this line of code:
Toast.makeText(getApplicationContext(), ShowTime,Toast.LENGTH_LONG).show();

is telling the program to make a Toast and fill it with the String resource that the Integer ShowTime is the ID for. In your project that String resource doesn't exist so you are getting this exception.
To fix you'll need to use the makeText() method that takes a String as the second parameter, rather than an int. Like this:
Toast.makeText(Spinner.this, String.ValueOf(ShowTime),Toast.LENGTH_LONG).show();

Also note that your Activity is a context, so you should be using this (your activity) instead of the getApplicationContext() method. And because you are inside of a Listener object declaration you need to put the name of your Activity infront of this
Edit: I would also suggest that you do not name your activity "Spinner". Since there is a UI component object that is called Spinner this adds a level of connfusion. I would refactor it and change the name of the Activity to SpinnerActivity if I were you.


text:
Q: Computing the value of a fraction involving summation can we compute this term without using calculator?
$$\frac{1+\frac{1}{3^2}+\frac{1}{5^2}+\frac{1}{7^2}+...+\frac{1}{997^2}+\frac{1}{999^2}-\frac{1}{1002^2}-\frac{1}{1004^2}-\frac{1}{1006^2}-...-\frac{1}{1998^2}-\frac{1}{2000^2}}{1+\frac{1}{2^2}+\frac{1}{3^2}+\frac{1}{4^2}+...+\frac{1}{999^2}+\frac{1}{1000^2}}$$
I can't see any pattern.
I tried to add and substract as mentioned in the comments but can't see how it helps.
thanks.

A: The given fraction
$$\frac{1+\frac{1}{3^2}+\frac{1}{5^2}+\frac{1}{7^2}+...+\frac{1}{997^2}+\frac{1}{999^2}-\frac{1}{1002^2}-\frac{1}{1004^2}-\frac{1}{1006^2}-...-\frac{1}{1998^2}-\frac{1}{2000^2}}{1+\frac{1}{2^2}+\frac{1}{3^2}+\frac{1}{4^2}+...+\frac{1}{999^2}+\frac{1}{1000^2}}$$
can be rewritten as
$$\frac{\left(1+\frac{1}{2^2}+\frac{1}{3^2}+\frac{1}{4^2}+...+\frac{1}{999^2}+\frac{1}{1000^2}\right)-\left(\frac{1}{2^2}+\frac{1}{4^2}+...+\frac{1}{1000^2}+\frac{1}{1002^2}+...+\frac{1}{1998^2}+\frac{1}{2000^2}\right)}{1+\frac{1}{2^2}+\frac{1}{3^2}+\frac{1}{4^2}+...+\frac{1}{999^2}+\frac{1}{1000^2}}$$
by adding and subtracting $\frac{1}{2^2}+\frac{1}{4^2}+...+\frac{1}{1000^2}$ to the numerator of the fraction. The above fraction can now be written as:
$$1 - \frac{\frac{1}{2^2}+\frac{1}{4^2}+...+\frac{1}{1000^2}+\frac{1}{1002^2}+\frac{1}{1004^2}+...+\frac{1}{1998^2}+\frac{1}{2000^2}}{1+\frac{1}{2^2}+\frac{1}{3^2}+\frac{1}{4^2}+...+\frac{1}{999^2}+\frac{1}{1000^2}}$$
$$ = 1 - \frac{\frac{1}{2^2}\left(1+\frac{1}{2^2}+\frac{1}{3^2}+...+\frac{1}{999^2}+\frac{1}{1000^2}\right)}{1+\frac{1}{2^2}+\frac{1}{3^2}+...+\frac{1}{999^2}+\frac{1}{1000^2}} = 1 - \frac{1}{2^2} = \frac{3}{4}.$$


text:
Q: Changing UIButton text So I'm trying to update the text on a UIButton when I click it. I'm using the following line to change the text:
calibrationButton.titleLabel.text = @"Calibration";

I have verified that the text is changing, but when I run the app and I click on the button, it changes to "Calibration" for a split second and then goes right back to its default value.  Any ideas why this might be happening? Is there some sort of refresh function I need to be calling?

A: programmatically you can set button title like below:
[myButton setTitle:@"buttonTitle" forState:UIControlStateNormal];

you can also set button title property from storyboard.

A: To set button text use the following method:
[calibrationButton setTitle: @"Calibration" forState: UIControlStateNormal];

See UIButton class reference for more details...
http://developer.apple.com/library/ios/#documentation/uikit/reference/UIButton_Class/UIButton/UIButton.html
Or in Swift 3:
calibrationButton.setTitle("Calibration", for: .normal)

A: When laying out its subviews, a UIButton will set its titleLabel's text value using its own title values, so that you can set up to four different strings for the four states (normal, highlighted, selected, disabled).
Because of this feature, setting the titleLabel's text directly won't persist, and will be reset by the button when it lays out its subviews.
This is what you have to do to change the title text for a button's state.
[calibrationButton setTitle:@"Calibration" forState:UIControlStateNormal];

A: Not a huge deal, and possibly obvious, but there are several states available for buttons. If you provide the 'wrong' one, you will not see the text change as desired.
I noticed that my button was not showing the text I added, using the methods shown here. Check this link to make sure you are providing the UIControlState that you intend.
What's the difference between UIControlStateHighlighted and UIControlStateSelected?

A: For Swift 3.0
let button = UIButton(type: .system)
button.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
button.setTitle("set here", for: .normal)
button.addTarget(self, action: #selector(TableViewController.actionButtonTocuh), for: .touchUpInside)
button.titleLabel?.textColor  = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1)
view.addSubview(button)

A: If you don't want to set the title for all states, just set it for the normal state since the title for the unset states will default to the title of the normal state.
btn.setTitle("Some text", for:.normal)

A: For Swift 2.0:
let btnObject : UIButton  = UIButton()
btnObject.frame = CGRect(x: 8, y: 89, width: 70, height: 22)
btnObject.setTitle("Button Title", forState: UIControlState.Normal)
btnObject.titleLabel?.font = UIFont(name: "Helvetica Neue", size: 13)
btnObject.titleLabel?.textColor = UIColor.whiteColor()
btnObject.backgroundColor = UIColor(red: 189/255, green: 176/255, blue: 0/255, alpha: 1)
btnObject.titleLabel?.textAlignment = NSTextAlignment.Center
btnObject.addTarget(self, action: "btnbtnObjectClick:", forControlEvents: UIControlEvents.TouchUpInside)
subView.addSubview(btnObject)


text:
Q: user defined language comment style needs /n newline in notepad++ I am trying to setup a user defined language in notepad++ for a language that uses the letter C on its own line to begin a block of comments and a $ to close the comment.
I have set the following in Comment Style:
Comment open: C
Comment close: $
Using just the letter C as the open character for the comment will work until the letter C is used somewhere else in the code. eg. "device" will begin a comment colored block.
Is there a way to specify that the comment open character needs a \n so only a letter C on its own line and not part of other words will trigger a comment section?

A: Use
((EOL))

Notepad will understand this as \n in configuration of comment styles whereas \n or \n\n will not work.

A: I'm not sure this question is still current as Notepad++ now seems to have options for where the starting character of the comment must be (eg. start of line) but I had a similar problem.
I needed a comment that could start with && anywhere in the line and finish at the end of the line. So the Comment Style clearly Opened with && but specifying the Close seemed impossible. I tried the normal \n \r /n /r #10; etc but they didn't work.
Finally I found that using the NumPad on the keyboard works (on Windows)! In the Close box hold down the [Alt] key and type in 010 on the numeric keypad. Nothing will appear but the comments now end properly.
If you Export the language to XML you'll find it's saved this as:

in the Keywords, Comments section.


text:
Q: Qlikview project will not disappear after delete files/folder Hi i have disabled and deleted tasks and also deleted files/folders "resrpt". But it still remains in the QMC. Is this normal?
Screenshot of QMC

A: This means that that model had some attributes like assigned doc licenses or a reload scheduled.
solution
recreate the directory structure and create an empty qvw with the same name.
once the qmc recognize it, go through the document settings in the qmc and reset anything that is set. if there are license - remove them, disable the reload option, etc...
now you can delete it.

A: You will to readd back to the Server location, then unallocate the DocCals and UserCals in QMC assigned to it.
Once you've done this you can then remove the files after disabling any related tasks
We've had a similar issue where the files had actually been deleted, so if you've done this without a backup, just create a new QVD that has the same filename as those on the server - then the assigned licenses will get recognized on QMC


text:
Q: Add button to the footer of a Lightning Quick Action component Can you add an additional footer button next to Cancel for a Lightning Quick Action?
<aura:component implements="force:lightningQuickAction">
    <ui:button label="Save Button" />
</aura:component>

I'm aware that I can use force:lightningQuickActionWithoutHeader and customize the whole design. Just wondering in the Lightning System provides a built in way of doing this.
<aura:component implements="force:lightningQuickActionWithoutHeader">
    <ui:button label="Save Button" />
    <ui:button label="Cancel Button" />
</aura:component>

A: Try this. After few css trick, I managed to fix it myself. This solution override the dialog box height which you mentioned while creating custom action on an object. I hope this will help someone needed.
<aura:component implements="force:lightningQuickActionWithoutHeader,force:hasRecordId" controller="MilindTest">

Milind Test

    <lightning:button variant="neutral" label="Cancel" onclick="{! c.cancelClick }" />
    <lightning:button variant="brand" label="Save" onclick="{! c.saveClick }" />

A: I'm afraid you can't. I would like to be able to do it to, at least customize the behavior of the "Save" button, but unfortunately it's not possible.
As you said, you need either to put the button inside your component with force:lightningQuickAction, or recreate everything in a component with force:lightningQuickActionWithoutHeader. Solution 1 is easier but not good looking and not consistent with the standard UI, but solution 2 needs more work.
You can use Salesforce Lightning Design System modal as a starting point for solution 2, but bear in mind that the look & feel is different in Salesforce1, if you use it.
Also, you can create a Idea for that and post the link here, I would be the first one to vote for it.
Last point, if you have access to the Partner Community, I asked the question here so I guess you can add your own comment to the thread to show the PMs I'm not the only one interested.

A: Duplicate to this:
how to access the save button in a modal when implementing the force:lightningQuickAction
And an idea was created here:
https://success.salesforce.com/ideaView?id=0873A000000cNRIQA2

A: My solution was:
<aura:component implements="force:lightningQuickActionWithoutHeader">

            <button class="slds-button slds-button_neutral">Cancel</button>
            <button class="slds-button slds-button_brand">Save</button>

</aura:component>

CSS
.THIS .attach-to-bottom{
    position: absolute;
    bottom: 0px;
    right: 0px;
    width: 100%;
}

Hope it helps.

A: I basically use sticky css on the footer making sure the footer element is with the modal content, which is the complete modal content for a force:lightningQuickActionWithoutHeader
With this, the footer will always be sticky to the bottom of the body and the all the content in Body1 div will be scrollable and will scroll under the footer.
<aura:component implements="force:lightningQuickActionWithoutHeader">
    <aura:html tag="style">
        .slds-modal__container{
        max-width: 70rem !important;
        width:70% !important;
        }
        .slds-modal__container .cuf-content {
        padding:0 !important;
        }
        .slds-modal__container .slds-p-around--medium {
        padding: 0rem !important;
        }
        .slds-modal__content {
        height: unset !important;
        max-height: unset !important;
        border-bottom-left-radius: unset !important;
        border-bottom-right-radius: unset !important;
        }
    </aura:html>

Body1

       FooterBody

</aura:component>

Custom CSS for Footer:
footer {
    position:stikcy,
    bottom:0,
    z-index:2
}


text:
Q: Google Analytics API returns 0 value for some websites I have a Google Analytics account where multiple companies have shared their website with me. Now trying to get visitors/sessions/hits data from those websites using the API. It works perfectly fine for 2 websites, but 4 others aren't returning any data. It's a consistent problem and it doesn't matter whether I select the past week, or a week in the past. I'm also not getting any error, or message, just a 0 for all 3 dimensions. This is the exact response I'm getting:
{
  "reports": [
    {
      "data": {
        "isDataGolden": true,
        "totals": [
          {
            "values": [
              "0",
              "0",
              "0"
            ]
          }
        ]
      },
      "columnHeader": {
        "dimensions": [
          "ga:segment",
          "ga:pagePath",
          "ga:date"
        ],
        "metricHeader": {
          "metricHeaderEntries": [
            {
              "type": "INTEGER",
              "name": "ga:users"
            },
            {
              "type": "INTEGER",
              "name": "ga:sessions"
            },
            {
              "type": "INTEGER",
              "name": "ga:hits"
            }
          ]
        }
      }
    }
  ]
}

Update: I selected a week 6 years back when the website got ~400 visitors a day, instead of the ~10k it is getting to day, and it does seem to work now. Is there a way to make it work with large number of visitors as well? I'm just using the analytics.reports().batchGet function of the Python SDK.

A: The solution was using 'operator': 'PARTIAL' instead of 'operator': 'EXACT'.


text:
Q: SWIFT: How to scale down a UIGraphics/imageContext without losing quality? I have a box that the user taps on to draw circles. On the screen, the graphics are tack sharp and look great.  I also give the user the ability to email or text the graphic, however, the quality is pretty poor.  I also have to draw the circles back on the box at the proper position.
The box assets are @2x 908 × 534 pixels and @3x 1362 × 801 pixels.  I'd like to scale down the image so I don't have to send out such a large PNG file.
let hockeyNetImageView   = UIImageView(frame: CGRect(x: 0, y: 0, width: 340, height: 200))
hockeyNetImageView.image = UIImage(named: "hockeyNet")

UIGraphicsBeginImageContext(CGSize(width: 340, height: 200))

let context: CGContext = UIGraphicsGetCurrentContext()!
hockeyNetImageView.layer.render(in: context)
let img = UIGraphicsGetImageFromCurrentImageContext()!

UIGraphicsEndImageContext()

//Resize the image
let size = (img.size).applying(CGAffineTransform(scaleX: 1.0, y: 1.0))

let hasAlpha = true
let scale: CGFloat = 0.0

UIGraphicsBeginImageContextWithOptions((img.size), !hasAlpha, scale)
img.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: size))

let scaleImage = UIGraphicsGetImageFromCurrentImageContext()

goalieNetArray.append(UIImagePNGRepresentation(scaleImage!)!)

UIGraphicsEndImageContext()


text:
Q: Equivalence of bounded in probability of stochastic integrals and continuity under uniform convergence While reading the following post : https://almostsuremath.com/2010/03/03/existence-of-the-stochastic-integral/#scn_intexists_eq3
there is a statement I don't understand. It states here that the boundedness in probability of the set in (3) below is equivalent to the statement that for any sequence $\xi^n$ of bounded predictable processes converging uniformly to zero $\int_0^t \xi^n dX$ converges to zero in probability?
The definition of elementary predictable processes are given below.
Why are these two equivalent?


text:
Q: Mysql code to trigger update on column from different table I am using a database that has 2 tables for city and country. City table has ID(PK), population and country code. Country table has Code(PK) and population.
If an update happens to city population, the country population should be updated automatically.The issue is how to implement this in a proper update statement.
It should follow the general pattern below:
  CREATE TRIGGER diff_pop
  AFTER UPDATE
  ON city
  FOR EACH ROW
  ...
  UPDATE country SET NEW.population=country.population-city_old+city_new
WHERE country.population=new.population;

I think there could be many ways to solve this, so any input is appreciated.

A: CREATE TRIGGER diff_pop
AFTER UPDATE
ON city
FOR EACH ROW
UPDATE country
SET population = population - OLD.population + NEW.population
WHERE country.code = NEW.countrycode;

If it is possible that the city may be moved from one counntry to another then
CREATE TRIGGER diff_pop
AFTER UPDATE
ON city
FOR EACH ROW
BEGIN
    UPDATE country
    SET population = population - OLD.population
    WHERE country.code = OLD.countrycode;
    UPDATE country
    SET population = population + NEW.population
    WHERE country.code = NEW.countrycode;
END

PS. Do not forget to create AFTER INSERT and AFTER DELETE triggers...

That does not work, it is ambiguous syntax according to mysql, since there is no distinction between population column on city and country. – seneca

fiddle. Try to refute it.


text:
Q: Access inner class private vars from outer class I am trying to access private val inside an inner class, from the outer class without creating an instance of the inner class.
Is this even possible to access private inner class values from the outer class ?
Thanks in advance.

A: If the field is static, you already can access it from the outer class even if it's private. You don't need an instance of either the inner or the outer class:
public class Clazz {
    class Inner {
        private static final int N = 10;
    }
    public static void main(String[] args) {
        System.out.println(Inner.N);
    }
}

If the inner class field is not static, it does not exist without an instance of the inner class. You can't access something that doesn't exist.

A: The short answer is no.
The longer answer is the following. Inner class is just a regular class that has "magic" reference to instance of its outer class that can be accessible via OuterClass.this. Creating of instance of outer class does not create instance of inner class automatically. This means that you cannot by definition access members of inner class from outer class without creating instance of inner class unless inner class itself and its members are static.
Indeed you can create one instance of outer class and 10 instances of corresponding inner class. How can you access member of inner class without creating its instance?
BTW the general advice: avoid creating inner classes unless you really  need them.


text:
Q: AngularJS : factory $http service I am trying to understand the concept of factory and service in Angular. I have the following code under the controller
init();

    function init(){
        $http.post('/services', {
            type : 'getSource',
            ID    : 'TP001'
        }).
        success(function(data, status) {
            updateData(data);
        }).
        error(function(data, status) {

        });

        console.log(contentVariable);
    };
    function updateData(data){
        console.log(data);
    };

This code works fine. But when i move $http service into factory, i am not able to return data back to controller.
studentApp.factory('studentSessionFactory', function($http){
    var factory = {};
    factory.getSessions = function(){
        $http.post('/services', {
            type : 'getSource',
            ID    : 'TP001'
        }).
        success(function(data, status) {
            return data;
        }).
        error(function(data, status) {

        });
    };
    return factory;
});

studentApp.controller('studentMenu',function($scope, studentSessionFactory){
    $scope.variableName = [];
    init();
    function init(){
        $scope.variableName = studentSessionFactory.getSessions();
        console.log($scope.variableName);
    };
});

Is there any advantage to using factory, since $http works even under controller

A: The purpose of moving your studentSessions service out of your controller is to achieve separation of concerns.  Your service's job is to know how to talk with the server and the controller's job is to translate between view data and server data.
But you are confusing your asynchronous handlers and what is returning what.  The controller still needs to tell the service what to do when the data is received later...
studentApp.factory('studentSession', function($http){
    return {
        getSessions: function() {
            return $http.post('/services', {
                type : 'getSource',
                ID    : 'TP001'
            });
        }
    };
});

studentApp.controller('studentMenu',function($scope, studentSession){
    $scope.variableName = [];

    var handleSuccess = function(data, status) {
        $scope.variableName = data;
        console.log($scope.variableName);
    };

    studentSession.getSessions().success(handleSuccess);
});

A: The first answer is great but maybe you can understand this:
studentApp.factory('studentSessionFactory', function($http){
    var factory = {};

    factory.getSessions = function(){
        return $http.post('/services', {type :'getSource',ID :'TP001'});
    };

    return factory;
});

Then:
studentApp.controller('studentMenu',function($scope, studentSessionFactory){
      $scope.variableName = [];

      init();

      function init(){
          studentSessionFactory.getSessions().success(function(data, status){
              $scope.variableName = data;
          });
          console.log($scope.variableName);
     };
 });


text:
Q: how to sort xml data using javascript? This is my sample xml
<markers>
    <marker location_id="1" title="test 1" distance="0.0832"/>
    <marker location_id="2" title="test 2" distance="3.1852"/>
    <marker location_id="3" title="test 3" distance="4.3761"/>
    <marker location_id="4" title="test 4" distance="3.3761"/>
</markers>

var entries = xml.documentElement.getElementsByTagName('marker');

How can I sort this entries by distance, ascending order ? I want to do it using Javascript.

A: You can use the sort method:
var $markers = $('.marker', xml);
$markers.find('marker').sort(function(a, b) {
     return parseFloat($(a).attr('distance')) > parseFloat($(b).attr('distance'));
}).appendTo($markers);

This code assumes that the XML you have is stored in the xml variable.


text:
Q: How to access Pandas series value in a custom function I'm working on a project to monitor my 5k time for my running/jogging activities based on their GPS data. I'm currently exploring my data in a Jupyter notebook & now realize that I will need to exclude some activities.
Each activity is a row in a dataframe. While I do want to exclude some rows, I don't want to drop them from my dataframe as I will also use the df for other calculations.
I've added a column to the df along with a custom function for checking the invalidity reasons of a row. It's possible that a run could be excluded for multiple reasons.
In []:
    # add invalidity reasons column & update logic
    df['invalidity_reasons'] = ''

    def maintain_invalidity_reasons(reason):
        """logic for maintaining ['invalidity reasons']"""
        reasons = []
        if invalidity_reasons == '':
            return list(reason)
        else:
            reasons = invalidity_reasons
            reasons.append(reason)
            return reasons

I filter down to specific rows in my df and pass them to my function. The below example returns a set of five rows from the df. Below is an example of using the function in my Jupyter notebook.
In []:
    columns = ['distance','duration','notes']

    filt = (df['duration'] < pd.Timedelta('5 minutes'))
    df.loc[filt,columns].apply(maintain_invalidity_reasons('short_run'),axis=1)

Out []:
    ---------------------------------------------------------------------------
    NameError                                 Traceback (most recent call last)
    <ipython-input-107-0bd06407ef08> in <module>
          2
          3 filt = (df['duration'] < pd.Timedelta('5 minutes'))
    ----> 4 df.loc[filt,columns].apply(maintain_invalidity_reasons(reason='short_run'),axis=1)

    <ipython-input-106-60264b9c7b13> in maintain_invalidity_reasons(reason)
          5     """logic for maintaining ['invalidity reasons']"""
          6     reasons = []
    ----> 7     if invalidity_reasons == '':
          8         return list(reason)
          9     else:

    NameError: name 'invalidity_reasons' is not defined

Here is an example of the output of my filter if I remove the .apply() call to my function
In []:
columns = ['distance','duration', 'notes','invalidity_reasons']

filt = (df['duration'] < pd.Timedelta('5 minutes'))
df.loc[filt,columns]

Out []:

It seems that my issue lies in not knowing how to specify that I want to reference the scalar value in the 'invalidity_reasons' index/column (not sure of the proper term) of the specific row.
I've tried adjusting the IF statement with the below variants. I've also tried to apply the function with/out the axis argument. I'm stuck, please help!
if 'invalidity_reasons' == '':
if s['invalidity_reasons'] == '':

A: This is pretty much a stab in the dark, but I hope it helps. In the following I'm using this simple frame as an example (to have something to work with):
df = pd.DataFrame({'Col': range(5)})

Now if you define
def maintain_invalidity_reasons(current_reasons, new_reason):
    if current_reasons == '':
        return [new_reason]
    if type(current_reasons) == list:
        return current_reasons + [new_reason]
    return [current_reasons] + [new_reason]

add another column invalidity_reasons to df
df['invalidity_reasons'] = ''

populate one cell (for the sake of exemplifying)
df.loc[0, 'invalidity_reasons'] = 'a reason'

   Col invalidity_reasons
0    0           a reason
1    1
2    2
3    3
4    4

build a filter
filt = (df.Col < 3)

and then do
df.loc[filt, 'invalidity_reasons'] = (df.loc[filt, 'invalidity_reasons']
                                        .apply(maintain_invalidity_reasons,
                                               args=('another reason',)))

you will get
   Col          invalidity_reasons
0    0  [a reason, another reason]
1    1            [another reason]
2    2            [another reason]
3    3
4    4

Does that somehow resemble what you are looking for?


text:
Q: Transaction (Process ID 98) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction As far as i understand, this exception is thrown because multiple of my threads try to access the same data on the database. But the exception is thrown in a line where i convert an enumerable to a list.
Can anyone explain this?
(The Program.GetContext(), is used to get the current threads context to the database, since it's multithreaded, and uses EF this is a way to do it)
var loadedSammenSat = Program.GetContext().SammensatKodetVaerdier.Where(o => (o.Kode == kode) && (o.Kodetekst == kodetekst) && (o.Forkortelse == forkortelse) && (o.Navn == navn)).Include(b => b.Tillaegskode).ToList();

    if (!sammensatKodet.Tillaegskode.Any())
    {
        var selceted = loadedSammenSat.FirstOrDefault(o => (o.Tillaegskode == null || o.Tillaegskode.Count == 0));
        if (selceted != null)
            return selceted;
    }
    else
    {
        var selcetedWithOutList = loadedSammenSat.Where(o => (o.Tillaegskode != null && o.Tillaegskode.Count() == sammensatKodet.Tillaegskode.Count()));
        var selceted = selcetedWithOutList.ToList(); //LINE THAT THROW EXCEPTION!!
        if (selceted.Count() > 0)
        {
            List<DBTillaegsKode> list = new List<DBTillaegsKode>();
            sammensatKodet.Tillaegskode.ForEach(p => list.Add(new DBTillaegsKode(p.KodetVaerdi)));

            foreach (var dbSammensatKodetVaerdi in selceted)
            {
                var mismatch = dbSammensatKodetVaerdi.Tillaegskode.Except(list);
                if(mismatch.GetEnumerator().Current != null)
                    if (mismatch.Count() == 0)
                    {
                        return dbSammensatKodetVaerdi;
                    }
            }
        }
    }

A: LINQ is lazy-loaded - it's only when you do something with the resultset (in this case doing a .ToList() operation) that the query is executed.


text:
Q: Bucketing data in R is giving error I am trying to bucket my data into various categories and facing an issue while doing the same. I couldnt understand on where its going wrong. Any help please.
new_df<-original_df
new_df$bucket_column<-cut(
                as.numeric(
                  new_df$value_for_bucket_column),
                breaks=c(0,1,2,3,4,5,6,7,14,21,28,60,90,180,365,Inf),
                labels = c("1 Day","1-2 Days","2-3 Days","3- Days",
                "4-5 Days","5-6 Days", "1 Week",
                "1-2 Weeks","2-3 Weeks","3-4 Weeks",
                "1-2 Months","2-3 Months","3-6 Months",
                "6-12 Months","More than a Year"))

When I try to do the bucketing, I am facing an error as below:
Error in `$<-.data.frame`(`*tmp*`, "bucket_column", value = integer(0)) :
  replacement has 0 rows, data has 24783

Please let me know where I am doing it wrong. Thanks


text:
Q: Running multiple instances of the same application on a single machine in the cloud I have a worker application (non-web facing) which processes some jobs from an AWS SQS. I want to run multiple instances of this application but with different command-line arguments (maybe 30 processes in the end), so:
myApp arg1 arg2
myApp arg3 arg4

My infrastructure needs are pretty basic, but specifically I want each instance of the application to

*

*Restart automatically if it goes down

*Have some sort of basic monitoring + log retrieval

*Support auto deployment from git

*Run on a dedicated IP

What is the best infrastructure for hosting this? Preferred in Amazon ecosystem, but not required.
In Amazon:

*

*Amazon Kinesis + Amazon Lambda doesn't support the dedicated IP part

*Amazon EC2 + CodeDeploy and then I can configure UpStart or something on the EC2 image to keep the processes alive?

*Amazon EC2 Container Service (ECS) could run one docker container per process. I currently consider this my best option.

Not Amazon:

*

*Heroku supports "process types" which can run each process easily, but this requires one "dyno" per process. This seems to end up being ~$25/process which doesn't scale.

I'm just reaching out for ideas. Don't have much experience in Amazon. What other infrastructure options are particularly well suited to this problem?

A: Docker or rkt is your solution. You can be up and running in munites, all within one EC2 instance. Keep in mind that the number of your application instances will be limited by the number of IP addresses AWS allows for each instance type.
Take a look at how many IPv4 and IPv6 addresses you can have at http://docs.aws.amazon.com/AWSEC2/latest/UserGuide/using-eni.html#AvailableIpPerENI.
If you need more, ask AWS support to increase limits in advance.


text:
Q: VScode Python "Run Cell" does nothing I'm using VScode on mac and configured an anaconda environment. When I insert # %% and hit "Run Cell", nothing happens at all.
How can I fix this?
EDIT: the solution was simply to reboot my machine :)

A:
When I insert and hit "Run Cell", nothing happens at all

If you can create .ipynb file which can be successfully run, there should be no problem.
Try reload window and give the interactive window more time to load:


text:
Q: problem is in ASyncTask class in Android basically i am reading image bytes from file i have a loop which has to read almost 20 images from file and in this loop i have making the object of my class which extends ASyncTask class and i am reading bytes and drawing on canvas in doItBackground() method and setting my image on onPostExecute() method. so basically Asynchronously 20 threads starts execution in background. now problem is it is not showing any image.
anybody have any idea how to handle multiple AsyncTask class? here is my code.
    @Override
    protected Void doInBackground(Void... params)
    {
//      Log.i("start background thread", "start background thread");
        Set<Integer> keys;
        keys = iTileListOffsets.keySet();
        boolean found = false;
        Object key[] = keys.toArray();
        int k = 0;

        for (int i=0; i < key.length && found==false ; i++)
        {
            k = (Integer) key[i];
            MapTileHeader tileHeader = iTileListOffsets.get(k);
            if (tileHeader.equalsWith(mapTile.getiMapTileHeader()) )
            {
                found = true;
            }
        }

        if(found)
        {
            try
            {
                synchronized (MapMaker.getSingletonObject())
                {
                    fc.position(0);
                    input.skipBytes(k);
                    int tSizeOfTile = input.readInt();
                    mapTile.loadTileWithFileHeader(input, tSizeOfTile, headerBytesArray);
                }

                mapMaker.getBufferedTilesDataList().add(mapTile);
            }
            catch (Exception e)
            {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            byte imageTile[] = mapTile.getImageTilesBytes();             //bufferedTile.getImageTilesBytes();

            if(mapTile.getImageTilesBytes() != null)
            {
                try
                {
                    Bitmap tileBitmap = BitmapFactory.decodeByteArray(imageTile, 0, imageTile.length);
                    canvas.drawBitmap(tileBitmap, rect.left, rect.top, null);
                    tileBitmap = null;
                }
                catch(Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
//      Log.i("ENDDDD background thread", "ENDDD background thread");
        return null;
    }

    @Override
    protected void onPostExecute(Void result)
    {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        Log.i("start POSTECEXCUTE thread", "start POSTECEXCUTE thread");

        MyRect mapRect = aBufferArea.GetScreenRectangle(buffer, aScrnArea);
        Bitmap smallBitmap = Bitmap.createBitmap(bitmap, mapRect.left, mapRect.top, mapRect.width, mapRect.height);
        image.setImageBitmap(smallBitmap);

        Log.i("ENDDDDD POSTECEXCUTE thread", "ENDDDD POSTECEXCUTE thread");
    }

thanks

A: I dont think you can update the UI directly from doInBackground, as the code in this method is run in a backgound thread and does not have direct access to the IU thread.  You can update the UI either from onPostExecute or from onProgressUpdate.  You can call the latter of these from doInBackground by calling publishProgress.
There is a simple example in the documentation for AsyncTask, and this one is a little more complex.

A: I'd like to suggest a slightly different way of thinking about the problem. Instead of having a thing in the background which both downloads and draws the bitmaps, you might try making the doInBackground method decode and return the Bitmap, then draw it onto the canvas in onPostExecute. This arrangement should prevent you from having contention on the canvas.
Looking at the code you've posted, the loaded bitmaps get drawn onto canvas. Then bitmap gets displayed in image. I can't see, in the code you posted, anywhere that the loaded bitmaps canvas gets sent to the screen.
It might be worth double-checking that the image you're drawing to has a large enough height and width.


text:
Q: Calling a Function but code says no matching function in C++ This is my code and the error which comes is
no matching function for call to to_reduced_row_echelon_form(float[((unsigned int)((int)r))][((unsigned int)((int)c))])'

#include <algorithm> // for std::swap
#include <cstddef>
#include <cassert>

// Matrix traits: This describes how a matrix is accessed. By
// externalizing this information into a traits class, the same code
// can be used both with native arrays and matrix classes. To use the
// default implementation of the traits class, a matrix type has to
// provide the following definitions as members:
//
// * typedef ... index_type;
//   - The type used for indexing (e.g. size_t)
// * typedef ... value_type;
//   - The element type of the matrix (e.g. double)
// * index_type min_row() const;
//   - returns the minimal allowed row index
// * index_type max_row() const;
//   - returns the maximal allowed row index
// * index_type min_column() const;
//   - returns the minimal allowed column index
// * index_type max_column() const;
//   - returns the maximal allowed column index
// * value_type& operator()(index_type i, index_type k)
//   - returns a reference to the element i,k, where
//     min_row() <= i <= max_row()
//     min_column() <= k <= max_column()
// * value_type operator()(index_type i, index_type k) const
//   - returns the value of element i,k
//
// Note that the functions are all inline and simple, so the compiler
// should completely optimize them away.
template<typename MatrixType> struct matrix_traits
{
  typedef typename MatrixType::index_type index_type;
  typedef typename MatrixType::value_type value_type;
  static index_type min_row(MatrixType const& A)
  { return A.min_row(); }
  static index_type max_row(MatrixType const& A)
  { return A.max_row(); }
  static index_type min_column(MatrixType const& A)
  { return A.min_column(); }
  static index_type max_column(MatrixType const& A)
  { return A.max_column(); }
  static value_type& element(MatrixType& A, index_type i, index_type k)
  { return A(i,k); }
  static value_type element(MatrixType const& A, index_type i, index_type k)
  { return A(i,k); }
};

// specialization of the matrix traits for built-in two-dimensional
// arrays
template<typename T, std::size_t rows, std::size_t columns>
 struct matrix_traits<T[rows][columns]>
{
  typedef std::size_t index_type;
  typedef T value_type;
  static index_type min_row(T const (&)[rows][columns])
  { return 0; }
  static index_type max_row(T const (&)[rows][columns])
  { return rows-1; }
  static index_type min_column(T const (&)[rows][columns])
  { return 0; }
  static index_type max_column(T const (&)[rows][columns])
  { return columns-1; }
  static value_type& element(T (&A)[rows][columns],
                             index_type i, index_type k)
  { return A[i][k]; }
  static value_type element(T const (&A)[rows][columns],
                            index_type i, index_type k)
  { return A[i][k]; }
};

// Swap rows i and k of a matrix A
// Note that due to the reference, both dimensions are preserved for
// built-in arrays
template<typename MatrixType>
 void swap_rows(MatrixType& A,
                 typename matrix_traits<MatrixType>::index_type i,
                 typename matrix_traits<MatrixType>::index_type k)
{
  matrix_traits<MatrixType> mt;
  typedef typename matrix_traits<MatrixType>::index_type index_type;

  // check indices
  assert(mt.min_row(A) <= i);
  assert(i <= mt.max_row(A));

  assert(mt.min_row(A) <= k);
  assert(k <= mt.max_row(A));

  for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
    std::swap(mt.element(A, i, col), mt.element(A, k, col));
}

// divide row i of matrix A by v
template<typename MatrixType>
 void divide_row(MatrixType& A,
                  typename matrix_traits<MatrixType>::index_type i,
                  typename matrix_traits<MatrixType>::value_type v)
{
  matrix_traits<MatrixType> mt;
  typedef typename matrix_traits<MatrixType>::index_type index_type;

  assert(mt.min_row(A) <= i);
  assert(i <= mt.max_row(A));

  assert(v != 0);

  for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
    mt.element(A, i, col) /= v;
}

// in matrix A, add v times row k to row i
template<typename MatrixType>
 void add_multiple_row(MatrixType& A,
                  typename matrix_traits<MatrixType>::index_type i,
                  typename matrix_traits<MatrixType>::index_type k,
                  typename matrix_traits<MatrixType>::value_type v)
{
  matrix_traits<MatrixType> mt;
  typedef typename matrix_traits<MatrixType>::index_type index_type;

  assert(mt.min_row(A) <= i);
  assert(i <= mt.max_row(A));

  assert(mt.min_row(A) <= k);
  assert(k <= mt.max_row(A));

  for (index_type col = mt.min_column(A); col <= mt.max_column(A); ++col)
    mt.element(A, i, col) += v * mt.element(A, k, col);
}

// convert A to reduced row echelon form
template<typename MatrixType>
 void to_reduced_row_echelon_form(MatrixType& A)
{
  matrix_traits<MatrixType> mt;
  typedef typename matrix_traits<MatrixType>::index_type index_type;

  index_type lead = mt.min_row(A);

  for (index_type row = mt.min_row(A); row <= mt.max_row(A); ++row)
  {
    if (lead > mt.max_column(A))
      return;
    index_type i = row;
    while (mt.element(A, i, lead) == 0)
    {
      ++i;
      if (i > mt.max_row(A))
      {
        i = row;
        ++lead;
        if (lead > mt.max_column(A))
          return;
      }
    }
    swap_rows(A, i, row);
    divide_row(A, row, mt.element(A, row, lead));
    for (i = mt.min_row(A); i <= mt.max_row(A); ++i)
    {
      if (i != row)
        add_multiple_row(A, i, row, -mt.element(A, i, lead));
    }
  }
}

// test code
#include <iostream>
#include <vector>

using namespace std;
int main()
{
  int r=0,c=0,i,j;
  cout << "Enter no of rows of the matrix";
  cin >> r;
  cout << "Enter no of columns of the matrix";
  cin >> c;

  float l[r][c];

  int p = 0, q = 0;

  while (p < r) {
    while (q < c) {

      cin >> l[p][q];

      q = q + 1;
    }
    p = p + 1;
    q = 0;
  }
  to_reduced_row_echelon_form(l);

  for (int i = 0; i < r; ++i)
  {
    for (int j = 0; j < c; ++j)
      std::cout << l[i][j] << '\t';
    std::cout << "\n";
  }
  system("pause");
  return EXIT_SUCCESS;
}

calling the function whose code i took from https://rosettacode.org/wiki/Reduced_row_echelon_form

A: Variable length arrays (VLAs) like float l[r][c]; are not part of standard C++, so any attempt to reason when they might or might not work is fruitless.
The requirements of the type passed to to_reduced_row_echelon_form are clearly described in the comment starting 'Matrix traits'. You need to define a class with those features. Something like this
class MyMatrix
{
public:
    MyMatrix(int r, int c) : r(r), c(c), l(r, std::vector<int>(c)) {}
    std::vector<int>& operator[](int r) { return l[r]; }
    const std::vector<int>& operator[](int r) const { return l[r]; }
    using index_type = int;
    using value_type = int;
    value_type& operator()(index_type i, index_type j) { return l[i][j]; }
    value_type operator()(index_type i, index_type j) const { return l[i][j]; }
    index_type min_row() const { return 0; }
    index_type max_row() const { return r - 1; }
    index_type min_column() const { return 0; }
    index_type max_column() const { return c - 1; }
private:
    int r, c;
    std::vector<std::vector<int>> l;
};

Not the most elegant or efficient code, but it does compile and hopefully works.
Then use it like this
MyMatrix l(r, c);
...
to_reduced_row_echelon_form(l);


text:
Q: How to synchronize thread in TIdTCPServer OnExecute Someone who knows Delhi Indy 10 Sockets ? the component TIdTCPServer. I have a service where instantiate multiple threads ( multithreading ) using TIdTCPServer to process requests from several clients ( tidTCPClient ) .
It's all working, no problem , but in the service ( the server) I have a screen where update a log and a list of connected users and log what they are doing and view this log in the memo main screen.
It turns out that being Multithreaded must use the Syncronize to update the memo that is in thread main . So far so ok right?
The memo will be updated in the event idTCPServerExecute component , only that what I have just as event argument is ( AContext : TIdContext ) where I caught the instance of the thread running to her can call the syncronize ?
wanted to do something like:
AContext.thread.Syncronize ( LogMemo ); // Will write in the memo on the main thread.
But I searched and not found the thread object. Does anyone know where is this object?
or how I could update the screen in this event without being in competition with other threads ?
procedure TfrmMainServer.TCPServerExecute(AContext: TIdContext);
var
     Cmd : String;
begin
     if AContext.Connection.IOHandler.Connected then
     begin
       If not AContext.Connection.IOHandler.InputBufferIsEmpty Then Begin
          Cmd  := AContext.Connection.IOHandler.ReadLn;

    // This is not acceptable in this way :

           memoFile.Lines.Add ('TESTING');
           txtInfoLabel.Caption := 'Arquivo enviado';
       End;
     end;
end;

A: You can derive a class from Indy's TIdSync or TIdNotify class and override the TIdSync.DoSynchronize() or TIdNotify.DoNotify() method to do what you need.
Or, in recent Delphi versions, you can use the anonymous procedure version of the static TThread.Synchronize() or TThread.Queue() methods.
Examples of both approaches have been posted many times before on Embarcadero's forum, Indy's forum, StackOverflow, etc.  Search around.

A: I have a similar issue with TIdTCPServer.OnConnect(AContext: TIdContext)
In my event handler I need to manipulate a TVirtualStringTree in the main thread.
I googled this article:
http://www.delphigroups.info/2/4/211251.html
Code for me, running Delphi Rio 10.3 Indy 10, is:
uses IdSync;

procedure TMyClass.OnConnectFromClientChangedProc;
begin
  // Code to be executed in main thread
end;

procedure TMyClass.OnMyClientConnect(AContext: TIdContext);
begin
  TIdSync.SynchronizeMethod(OnConnectFromClientChangedProc);
end;

In a similar way can be managed the OnExecute event.


text:
Q: Meteor find is returning null with variable Description of the problem:
I have two collections videos and specs. videos collection has a key called spec which corresponds to a specs id. Both collections are not empty.
My Template Helper:
  Template.List.helpers({
    videos: function(){
      var vids = Videos.find({ online: false}).fetch();
      return vids.map(function(value){
        console.log("id: " + value.spec);
        console.log(Specs.find({ id: value.spec }).fetch());

        //Issue here
        value.specName = Specs.find({ id: value.spec }).fetch()[0].name;
        return value;
      });
    }
  });

As you can see in my template helper I loop through the video array and add specName to the array.
The main problem comes from this specific line:
value.specName = Specs.find({ id: value.spec }).fetch()[0].name;

and more specifically this line: Specs.find({ id: value.spec }).fetch()
which will return null every time.
What I've tried:
Naturally, my first thought would be to check what value.spec returns. And it returns an int between 1 and 15 (included) which is right. If value.spec is right, then how come the find() doesn't return anything?
I then decided to hard set it and tried this:
Specs.find({ id: 2}).fetch()

And this worked. Which is weird because on multiple occasions value.spec returns 2...
I've also tried intParse(value.spec) just in case, however that didn't work either.
Question
Why does Specs.find({ id: value.spec }).fetch() return null knowing that value.spec is set correctly and that a hard coded number works?
Requested json data: (from meteor mongo)
specs:
{ "_id" : "XKXHtQuiFsAew3dDy", "id" : 1, "name" : "Endocrine surgery" }
{ "_id" : "68jFidAMXTXpQtQye", "id" : 2, "name" : "General and digestive" }
{ "_id" : "GZSXToRXMfJgnH3CY", "id" : 3, "name" : "Pediatric surgery" }
{ "_id" : "T2mBz2gsXEqQaybmq", "id" : 4, "name" : "Thoracic surgery" }
{ "_id" : "hnuQzZiPKvYYDZhc8", "id" : 5, "name" : "Equipment" }
{ "_id" : "byE3A6HchvfhKdmR8", "id" : 6, "name" : "Gynecology" }
{ "_id" : "u5rrPB7asGW3NC6B2", "id" : 7, "name" : "Urology" }
{ "_id" : "umxKvR66oEx5dRppf", "id" : 8, "name" : "Cardiovascular surgery" }
{ "_id" : "bPcBTZn3t5ubRRcrQ", "id" : 9, "name" : "Endoscopic surgery" }
{ "_id" : "yNyAqQPoreNtdRZ34", "id" : 10, "name" : "NOTES" }
{ "_id" : "KG794eakRaztEqehG", "id" : 11, "name" : "Robotic surgery" }
{ "_id" : "QBrtvTg4GT7Tf7cAJ", "id" : 12, "name" : "Skull base surgery" }
{ "_id" : "HEhq6oBjuuMnrxE5a", "id" : 13, "name" : "Arthroscopy and upper limb surgery" }
{ "_id" : "xwpgHqZpBQP7WAnd5", "id" : 14, "name" : "Single port surgery" }
{ "_id" : "K4BgFupwNdDGD3449", "id" : 15, "name" : "Telemicrosurgery" }

videos:
{ "_id" : "L5Qi7YRRhn6Sfcjk8", "id" : "vd01en1065e", "title" : "Right inguinal hernia: open plug technique", "authors" : [ "E Pelissier" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false }
{ "_id" : "M8cuLW6KNCqKeP9vF", "id" : "vd01en1074e", "title" : "Laparoscopic splenectomy, posterior approach", "authors" : [ "D Mutter", " F Rubino" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false }
{ "_id" : "Ptzrxw8GifeMvQk9k", "id" : "vd01en1090e", "title" : "Intussusception of the intestine in the newborn", "authors" : [ "F Becmeur", " D Christmann", " I Kauffmann" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 3, "private" : true, "online" : false }
{ "_id" : "oHWcX3vCBHuZQM9hR", "id" : "vd01en1103e_2", "title" : "Appendicular peritonitis: laparoscopic conversion", "authors" : [ "B Navez" ], "date_published" : "2001-11-05", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false }
{ "_id" : "6uzmxYxhd5DDuS2gG", "id" : "vd01en1108e", "title" : "Diaphragmatic hernias", "authors" : [ "F Becmeur" ], "date_published" : "2001-11-28", "abstract" : "", "tags" : [ "" ], "spec" : 3, "private" : true, "online" : false }
{ "_id" : "yHqruiQYeeQ9SDHpH", "id" : "vd01en1112e", "title" : "Laparoscopic excision of the cystic stump", "authors" : [ "J Leroy" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false}
{ "_id" : "fmjtk5WAEKitMxyGj", "id" : "vd01en1114e", "title" : "Laparoscopic gastric banding in a patient with a BMI of 40", "authors" : [ "JM Zimmermann", " D Fölscher" ], "date_published" : "2004-09-27", "abstract" : "", "tags" : [ "" ], "spec" : 2, "private" : true, "online" : false}

I've been stuck on this problem for a couple hours, I didn't want to post this on SO since I do believe it's a simple problem. However, it is mind boggling.

A: The problem here is the publication/subscription issue. You did not mention it, how do you handle publications and subscriptions but that is most likely the issue. What is happening is that when you browse your videos collection, which subscription is ready (since you hae any data in it) here: Videos.find({ online: false}) that not necessarly means that (in that precise moment) subscription handling Spec collection is ready as well. So even if on the server the query is working, on the client it's null, because the data are not synced between client and server YET. so you have to wait until both subscriptions are ready somehow. You can use template subscriptions, or waitOn function in your router.

A: First of all check on server side  that your publication and subscription is   ready and returning you back data check this like as
 Meteor.publish('Videso', function () {

  var result= Videso.find({});
  console.log(result);
   return result
   });

if console.log returning you records on server side i have a solution then your
 problem
the solution of your problem is that
   Template.List.helpers({
   videos: function(){

    var vids = Videos.find({ online: false}).map(function (value) {
             console.log("id: " + value.spec);
             var idValue  = Specs.findOne({ "id": value.spec })
             console.log("idValue===",idValue)
             return _.extend(value, idValue);
       });
           console.log(vids);      //here merged data of both table having
                                  // relvent record will returned
           return vids;

       }

  });

Just implement it and check data on your template it will be ready for you and vote me then :)


text:
Q: Verifying email and hashed password always returns None when details are definitely in DB I have a simple program to check if an email and hashed password are in a Postgres database (It's meant to be a cgi app, but because it fails, I'm testing it as a script first):
import cgi
import cgitb
import hashlib
import psycopg2
from dbconfig import *
cgitb.enable()
print "Content-Type: text/plain\n\n";

def checkPass():
    email = "person@gmail.com"
    password = "mypassword"
    password = hashlib.sha224(password.encode()).hexdigest()
    result = cursor.execute('SELECT * FROM logins WHERE email=%s AND passhash=%s', (email, password))
    print result

if __name__ == "__main__":
    conn_string = "host=%s dbname=%s user=%s password=%s" % (host, database, dbuser, dbpassword)
    conn = psycopg2.connect(conn_string)
    cursor = conn.cursor()
    checkPass()

This program always returns None on the print. The email and hashed password are definitely in the database though. I put them there with this:
email = "person@gmail.com"
allpass = "mypassword"
password = hashlib.sha224(allpass.encode()).hexdigest()
cursor.execute('INSERT INTO logins (email, passhash) VALUES (%s, %s);', (email, password))
conn.commit()

And checking the db shows there's that email and hashed password. So why doesn't the first program return something upon the SELECT statement? Are hashes not stored in the same way? Any help would be greatly appreciated.

A: I worked out what was wrong. As it happens, cursor.execute() doesn't actually return anything. You have to use fetchone() for that.
cursor.execute('SELECT * FROM logins WHERE email=%s AND passhash=%s;', (email, password))
result = cursor.fetchone()
print result

This prints a tuple of the correct results.


text:
Q: Best practise: How to implement plugins for spring jpa projects? i always wondering what is the best practise to implement a plugin for a spring jpa project.
For example i would have such structure of java projects:
server-core
@Entity
public class User {

    private String name;

}

Now i would like to have separate java projects as plugins for the server project.
first-plugin
The first plugin is supposed to add another field to the user entity for example users age.
second-plugin
The second plugin is supposed to add a new table and a relation from the new table to the users table for example:
@Entity
public class Usergroup {

    private Set<User> users;

}

Now my question
The used database is sql server. Is there any good practise to realize such plugins without make changes to the server-core project so a plugin always can be appended and uncoupled without impacts for the server-core project? Is sql server the right database for such architecture or should i use a no-sql database instead?

A: If you don't want the plugins to link/include the binaries of the original project, you can mark the original project as a provided (maven) or compileOnly (gradle) dependency:
<groupId>your.group.id</groupId>
<artifactId>server-core</artifactId>
<version>your-core-version</version>
<scope>provided</scope>

compileOnly your.group.id:server-core:your-core-version

Adding this to the build configurations of the plugin means that server-core is available when compiling the plugin but it will not be included in binaries (like fat JARs).
If you fear that a plugin corrupts your database and that it won't work when removing the plugin, this is the responsibility of the plugin.
If you want to make custom login that is executed when the plugin is removed, you can include an API for this (e.g. plugins can contain sql scripts with certain names, those are saved when the plugin loads and will be executed if the program is started without the plugin).
However, plugins should not change your core data structure or add constraints to existing tables used by the core dependency anyways.
Instead, the plugins should access other tables in order to add their own data, there.
Using a NoSQL database works fine too. For example, you could use a document-store database like MongoDB. If you do so, plugins can easily add content without interfering with the core project. If the plugin is removed afterwards, the data can persist without interfering with the core project. If you use an SQL database, I would just recommend you not to use the same tables for the core and the plugin project. IYou may event want to use a different schema for every plugin.


text:
Q: Can't open Google Chrome, can't search applications in dash, startup applications stopped running I am experiencing many issues with my fresh installation of Ubuntu 14.04:

*

*I can't open Google Chrome from the sidebar.

*I can't search any applications in the dash.

*f.lux and Screencloud have stopped running on startup.

As far as I can recall I began experiencing these issues after setting up the Google App Engine SDK for PHP, but it's possible this is being caused by something else entirely.
Running google-chrome in the terminal returns:
[6119:6119:0511/161156:ERROR:process_singleton_linux.cc(903)] Failed to create socket directory.
[6119:6119:0511/161156:ERROR:chrome_browser_main.cc(1198)] Failed to create a ProcessSingleton for your profile directory. This means that running multiple instances would start multiple browser processes rather than opening a new window in the existing process. Aborting now to avoid profile corruption.

Screencloud displays an alert box on startup saying

ScreenCloud is already running. Please close the running instance before starting a new one.

Lastly, there is an error icon in the system tray which has displayed a few different error messages:

*

*http://imgur.com/PuVmsy8

*http://imgur.com/LtKoqAy
I have researched each of these issues individually, tried every solution I could find, rebooted a hundred times, but nothing has changed. What can I do?

A: To solve this problem needs to give sudo permissions to /tmp it is where those/certain programs/apps write their temporary stuff to. For this run in Terminal:
sudo chmod 1777 /tmp


text:
Q: How to set up Brother MFC 7460DN printer on network? I bought Brother MFC 7460DN and wanted to print things wirelessly. The printer itself does not have Wifi, so I wired it to my router.
Things I have tried:

*

*reset the printer's network setting

*upgraded its firmware

*updated driver for my computer (I am using a mac, os Yosemite)

*downloaded BRAdmin Light (provided tool to look for network printers) and tried to find the printer, but no luck

*tried to look for it using a PC, but still no luck

Seems like the printer itself is not configured to the network correctly, but I might be wrong. I did read the manual, but there were too many useless information and I did not find any solutions. Any help will be appreciated. Thanks.

UPDATE:
I printed user settings and found that no ip was issue. I did not touch anything, what changes do I need to do?
Here is the information I got:

*

*boot method: AUTO

*ip address: 0.0.0.0

*subnet mask 0.0.0.0

*gateway 0.0.0.0

*wins config: 0.0.0.0

*wins server primary 0.0.0.0

*wins server secondary 0.0.0.0

*DNS Server primary 0.0.0.0

*DNS Server secondary 0.0.0.0

*APIPA: on

*ipv6: off

*ethernet auto

A: Start by printing out a configuration page, which will tell you the printer's IP address. To print a configuration page, follow the steps below.

*

*Press the Menu button.

*Press 4 for "Print Reports."

*Press 5 for "User Settings."

*Press the Start button.

To test it, try pinging the printer. This should work if the printer and mac are on subnets connected by the router.
On the Mac, go to Apple menu > System Preferences, then click Printers & Scanners. If you don't see your printer listed, click the "+" at the bottom of the list. It should now show your printer. It may take a minute or two for your printer to appear. Select your printer when it appears in the list, then click Add. If you see a message prompting you to download new software, make sure to download and install it.


text:
Q: Running jacoco check goal with maven 3.5 My jacoco plugin configuration in a pom likes below
<plugin>
            <groupId>org.jacoco</groupId>
            <artifactId>jacoco-maven-plugin</artifactId>
            <version>0.7.5.201505241946</version>
              <executions>
                <execution>
                  <id>pre-unit-test</id>
                  <goals>
                      <goal>prepare-agent</goal>
                  </goals>
                  <configuration>
                    <destFile>${jacoco.ut.execution.data.file}</destFile>
                  </configuration>
                </execution>
                <execution>
                  <id>merge-execs</id>
                  <phase>pre-site</phase>
                  <inherited>false</inherited>
                  <goals>
                      <goal>merge</goal>
                  </goals>
                  <configuration>
                   <fileSets>
                     <fileSet>
                       <directory>${basedir}</directory>
                       <includes>
                         <include>**/target/*.exec</include>
                       </includes>
                     </fileSet>
                   </fileSets>
                    <destFile>${jacoco.ut.merged.exec}</destFile>
                  </configuration>
                </execution>
                  <execution>
                      <id>jacoco-check</id>
                      <phase>verify</phase>
                      <goals>
                          <goal>check</goal>
                      </goals>
                      <configuration>
                          <rules>
                              <rule>
                                  <element>BUNDLE</element>
                                  <limits>
                                      <limit>
                                          <counter>LINE</counter>
                                          <value>COVEREDRATIO</value>
                                          <minimum>0.80</minimum>
                                      </limit>
                                  </limits>
                              </rule>
                          </rules>
                          <dataFile>${jacoco.ut.merged.exec}</dataFile>
                      </configuration>
                  </execution>
             </executions>
         </plugin>

But when I am running mvn jacoco:check it is failing with the below error
[ERROR] Failed to execute goal org.jacoco:jacoco-maven-plugin:0.7.5.201505241946:check (default-cli) on project main: The parameters 'rules' for goal org.jacoco:jacoco-maven-plugin:0.7.5.201505241946:check are missing or invalid -> [Help 1]

Can someone let me know what is going wrong?

A: Behavior that you observe is not specific to jacoco-maven-plugin, it is how Maven works - see https://maven.apache.org/guides/mini/guide-default-execution-ids.html
mvn jacoco:check

uses execution id default-cli, while your pom.xml defines configuration in execution with id jacoco-check bound to phase verify.
So either use this phase:
mvn verify

Or provide configuration outside of executions block (i.e. in <plugin><configuration>) so that it will be inherited in all executions.
Or explicitly specify execution id jacoco-check:
mvn jacoco:check@jacoco-check


text:
Q: Need correct syntax for using a role with chef knife ec2 I'm trying to use knife ec2 from examples that I've seen online but for whatever reason the --run-list option is not recognizing that I am supplying it a role:
knife ec2 server create --run-list 'role[linux_server]' -I  ami-9aaa1cf2 -f t2.small  -S chef -i C:\Users\admin\Documents\Dev\Chef\chef.pem --ssh-user ubuntu --subnet subnet-xxxxxxx --associate-eip xxx.xxx.xxx.xxx

I get this error:
 resolving cookbooks for run list: ["roles"]

 Error Resolving Cookbooks for Run List:

 Missing Cookbooks:
 ------------------
 The following cookbooks are required by the client but don't exist on the server:
 * roles

 Expanded Run List:
 ------------------
 * roles


text:
Q: gradle wrapper fails for Spring Boot application on Java 8, Gradle 3: can't find cacerts I have encountered a problem when creating my gradlew file using the gradle wrapper command. My setup is simple: Ubuntu 14.04 + Java 8 (openjdk version "1.8.0_91") + Gradle 3.0
tutorials used:

*

*https://spring.io/guides/gs/spring-boot/#scratch

*https://docs.gradle.org/current/userguide/gradle_wrapper.html
The curious thing of this problem is that the reason why gradle wrapper fails is because the cacerts file or directory is apparently missing - but it's not (see 'check cacerts file/directory' below). Though - and please let me know if this is the issue - it's a link and not the actual file/dir. I don't know if there are any other problems given the missing cacerts error seems to be at the end of a cascade of errors, but any help to debug this would be appreciated.
My relevant files and outputs are listed below.
Cheers
AHL

build.gradle:
buildscript {
    repositories {
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'idea'
apply plugin: 'spring-boot'

jar {
    baseName = 'gs-spring-boot'
    version =  '0.1.0'
}

repositories {
    mavenCentral()
}

sourceCompatibility = 1.8
targetCompatibility = 1.8

dependencies {
    // tag::jetty[]
    compile("org.springframework.boot:spring-boot-starter-web") {
        exclude module: "spring-boot-starter-tomcat"
    }
    compile("org.springframework.boot:spring-boot-starter-jetty")
    // end::jetty[]
    // tag::actuator[]
    compile("org.springframework.boot:spring-boot-starter-actuator")
    // end::actuator[]
    testCompile("junit:junit")
}

issue/error:
org.apache.http.ssl.SSLInitializationException: /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts (No such file or directory)

check cacerts file/directory:
vagrant@vagrant:/vagrant/BootTutorial$ ll /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts
lrwxrwxrwx 1 root root 27 Apr 22 13:29 /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts -> /etc/ssl/certs/java/cacerts
vagrant@vagrant:/vagrant/BootTutorial$

output from running gradle wrapper:
vagrant@vagrant:/vagrant/BootTutorial$ gradle wrapper --gradle-version 3.0 --info
Initialized native services in: /home/vagrant/.gradle/native
Connected to daemon DaemonInfo{pid=21004, address=[61084cbc-02a2-47e1-9f7b-07d285c509b7 port:43425, addresses:[/0:0:0:0:0:0:0:1%lo, /127.0.0.1]], idle=true, lastBusy=1473685805551, context=DefaultDaemonContext[uid=b5dcb202-0edb-4f81-bd5b-bd4b828045a5,javaHome=/usr/lib/jvm/java-8-openjdk-amd64,daemonRegistryDir=/home/vagrant/.gradle/daemon,pid=21004,idleTimeout=10800000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=US,-Duser.language=en,-Duser.variant]}. Dispatching request Build{id=ac0e688f-bffe-4828-abe8-58f12354dcf6.1, currentDir=/vagrant/BootTutorial}.
Received result org.gradle.launcher.daemon.protocol.BuildStarted@6986852 from daemon DaemonInfo{pid=21004, address=[61084cbc-02a2-47e1-9f7b-07d285c509b7 port:43425, addresses:[/0:0:0:0:0:0:0:1%lo, /127.0.0.1]], idle=true, lastBusy=1473685805551, context=DefaultDaemonContext[uid=b5dcb202-0edb-4f81-bd5b-bd4b828045a5,javaHome=/usr/lib/jvm/java-8-openjdk-amd64,daemonRegistryDir=/home/vagrant/.gradle/daemon,pid=21004,idleTimeout=10800000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=US,-Duser.language=en,-Duser.variant]} (build should be starting).
The client will now receive all logging from the daemon (pid: 21004). The daemon log file: /home/vagrant/.gradle/daemon/3.0/daemon-21004.out.log
Starting 7th build in daemon [uptime: 39 mins 8.147 secs, performance: 91%]
Executing build with daemon context: DefaultDaemonContext[uid=b5dcb202-0edb-4f81-bd5b-bd4b828045a5,javaHome=/usr/lib/jvm/java-8-openjdk-amd64,daemonRegistryDir=/home/vagrant/.gradle/daemon,pid=21004,idleTimeout=10800000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=US,-Duser.language=en,-Duser.variant]
Starting Build
Settings evaluated using settings file '/master/settings.gradle'.
Projects loaded. Root project using build file '/vagrant/BootTutorial/build.gradle'.
Included projects: [root project 'BootTutorial']
Evaluating root project 'BootTutorial' using build file '/vagrant/BootTutorial/build.gradle'.

FAILURE: Build failed with an exception.

* What went wrong:
A problem occurred configuring root project 'BootTutorial'.
> Could not resolve all dependencies for configuration ':classpath'.
   > Could not resolve org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE.
     Required by:
         :BootTutorial:unspecified
      > Could not resolve org.springframework.boot:spring-boot-gradle-plugin:1.4.0.RELEASE.
         > Could not get resource 'https://repo1.maven.org/maven2/org/springframework/boot/spring-boot-gradle-plugin/1.4.0.RELEASE/spring-boot-gradle-plugin-1.4.0.RELEASE.pom'.
            > org.apache.http.ssl.SSLInitializationException: /usr/lib/jvm/java-8-openjdk-amd64/jre/lib/security/cacerts (No such file or directory)

* Try:
Run with --stacktrace option to get the stack trace. Run with --debug option to get more log output.

BUILD FAILED

Total time: 1.391 secs
Received result Failure[value=org.gradle.initialization.ReportedException: org.gradle.internal.exceptions.LocationAwareException: A problem occurred configuring root project 'BootTutorial'.] from daemon DaemonInfo{pid=21004, address=[61084cbc-02a2-47e1-9f7b-07d285c509b7 port:43425, addresses:[/0:0:0:0:0:0:0:1%lo, /127.0.0.1]], idle=true, lastBusy=1473685805551, context=DefaultDaemonContext[uid=b5dcb202-0edb-4f81-bd5b-bd4b828045a5,javaHome=/usr/lib/jvm/java-8-openjdk-amd64,daemonRegistryDir=/home/vagrant/.gradle/daemon,pid=21004,idleTimeout=10800000,daemonOpts=-XX:MaxPermSize=256m,-XX:+HeapDumpOnOutOfMemoryError,-Xmx1024m,-Dfile.encoding=UTF-8,-Duser.country=US,-Duser.language=en,-Duser.variant]} (build should be done).
vagrant@vagrant:/vagrant/BootTutorial$

A: You are probably hitting a bug that left your symlink to the certs dangling as reported here and here. One suggested solution is to reinstall the ca-certificates-java package. Like this:
$ sudo dpkg --purge --force-depends ca-certificates-java
$ sudo apt-get install ca-certificates-java


text:
Q: Assign values in one dataframe if date is in date range in another dataframe and projects are equal I have two dataframes. One that has timestamps and projects in it. The other has date ranges, projects and maturities, which have to be mapped to the corresponding project within a date range.
My problem is similar to this question, however the provided answer is very slow and I have an extra condition to be fulfilled. For starters my two dataframes kind of look like this:
In:
import pandas as pd
df_a = pd.DataFrame({'time': ('06.05.2015  16:15:16', '22.06.2015  08:52:05', '28.05.2015  18:20:21','28.06.2015  16:19:21'),
                     'project': ('project1', 'project2', 'project2', 'project1')})

df_b = pd.DataFrame({'start-date':  ('02.05.2015 00:00:00', '26.06.2015 00:00:00', '16.05.2015 00:00:00', '30.05.2015 00:00:00'),
                     'end-date':('24.06.2015 00:00:00', '27.07.2015 00:00:00', '27.05.2015 00:00:00', '27.06.2015 00:00:00'),
                     'project': ('project1','project1','project2','project2'),
                     'maturity': ('one','two', 'one','two')})

My code looks like this:

for i in df_a.project.unique():
    for j in df_b.project.unique():
        if i == j:
            for index_df_a, row_df_a in df_a.iterrows():
                for index_df_b, row_df_b in df_b.iterrows():
                    if (row_df_a['time'] >= row_df_b['start-date']) & (row_df_a['time'] <= row_df_b['end-date']):
                        df_a.loc[index_df_a, 'maturity'] = row_df_b.loc['maturity']
                        break

Out:
                   time   project maturity
0  06.05.2015  16:15:16  project1      one
1  22.06.2015  08:52:05  project2      one
2  28.05.2015  18:20:21  project2      NaN
3  28.06.2015  16:19:21  project1      NaN

Expected result:
                   time   project maturity
0  06.05.2015  16:15:16  project1      one
1  22.06.2015  08:52:05  project2      one
2  28.05.2015  18:20:21  project2      two
3  28.06.2015  16:19:21  project1      two

*

*The code I wrote with the help of the similar question is very slow. When I am applying it to my dataframe (df_a has ~ 900k rows and df_b has ~1.7k maturity to map), it takes a really long time to process even a thousand rows. Is there a way to speed up the process?

*I think my if i==j:statement is wrong. As seen in line 4 of the result: even though the project is mapped to project1 and the timestamp 28.06.2015  16:19:21is within the range of start:26.06.2015 00:00:00 | end: 27.07.2015 00:00:00 the maturity is NaN instead of two.

*Lastly, is it possible to create a condition, where even if the timestamp is not within give date ranges, the next provided maturity for each project is mapped (line 3)? So if 28.05.2015  18:20:21 is not in any date range, the next date range provides the maturity. In this case two.

Excuse if I am asking too much at once. I know it is best practice to derive the answer by asking the simple questions and achieve results stepwise, however I am not nearly experienced enough to be able to split the problem into smaller parts.

A: *

*This should be significantly faster than the current implementation

*If you find yourself iterating through a dataframe, you're probably doing it wrong

*Use pd.date_range with start-date and end-date to add a d_range column to df_b, then .isin can be used to find time from df_a inside of d_range

*

*d_range will be a list of dates between start and end.

*If time is not properly formatted, it will not be match the dates inside d_range.

*The implementation will clean up the time columns in each dataframe

*

*Set columns to datetime format

*We only care about the date, not the time

*As already stated, the datetime format is integral.  If the columns are not properly formatted, time will not be found inside d_time.

Update the two dataframes:
import pandas as pd

# create dataframes from your test set and clean-up the datetime columns
df_a['time'] = (pd.to_datetime(df_a['time'], format='%d.%m.%Y %H:%M:%S')).dt.date
df_b['start-date'] = pd.to_datetime(df_b['start-date'], format='%d.%m.%Y %H:%M:%S').dt.date
df_b['end-date'] = pd.to_datetime(df_b['end-date'], format='%d.%m.%Y %H:%M:%S').dt.date

# df_a view

       time   project
 2015-05-06  project1
 2015-06-22  project2
 2015-05-28  project2
 2015-06-28  project1

# df_b view

start-date   end-date   project maturity
2015-05-02 2015-06-24  project1      one
2015-06-26 2015-07-27  project1      two
2015-05-16 2015-05-27  project2      one
2015-05-30 2015-06-27  project2      two

# add d_range to df_b
df_b['d_range'] = df_b[['start-date', 'end-date']].apply(lambda x: pd.date_range(x[0], x[1]), axis=1)

Add maturity to df_a

*

*mask is the result of searching df_b for the date from df_a

*

*mask matches the date of any project

*return only the result for the matching project

def date_query(x):
    mask = df_b[['project', 'maturity']][df_b['d_range'].apply(lambda y: y.isin([x[0]]).any())].reset_index(drop=True)
    result = mask['maturity'][mask['project'] == x[1]].reset_index(drop=True)
    return result

# call function
df_a['maturity'] = df_a.apply(lambda x: date_query(x), axis=1)

# df_a updated

       time   project maturity
 2015-05-06  project1      one
 2015-06-22  project2      two
 2015-05-28  project2      NaN
 2015-06-28  project1      two

Item 3:

*

*result from def date_query is a pandas.Series, if there is no matching date range, it will be empty, which can be checked with .empty

*Update def date_query to check if result is empty.  Call def check_min_timedelta if result is empty.

*If there are multiple matching minimum values, .idxmin will return the first occurence

def check_min_timedelta(x):
    """
    Create a timedelta between time and end-date
    Return maturity for the row with the minimum time date
    """
    end_diff = abs(df_b['end-date'][df_b['project'] == x[1]] - x[0]).idxmin()
    return df_b['maturity'].loc[end_diff]

# update def date_query
def date_query(x):
    mask = df_b[['project', 'maturity']][df_b['d_range'].apply(lambda y: y.isin([x[0]]).any())].reset_index(drop=True)
    result = mask['maturity'][mask['project'] == x[1]].reset_index(drop=True)
    if result.empty:
        result = check_min_timedelta(x)
    return result

# call function
df_a['maturity'] = df_a.apply(lambda x: date_query(x), axis=1)

# final df_a:

       time   project maturity
 2015-05-06  project1      one
 2015-06-22  project2      two
 2015-05-28  project2      one
 2015-06-28  project1      two

Alternate Approach:

*

*This is similar to your original approach of using inequalities to compare time to start-date & end-date

*This approach does not rely on creating a column of date range lists

*def date_query(x): has been updated and .dt.date has been removed.

df_a['time'] = pd.to_datetime(df_a['time'], format='%d.%m.%Y %H:%M:%S')
df_b['start-date'] = pd.to_datetime(df_b['start-date'], format='%d.%m.%Y %H:%M:%S')
df_b['end-date'] = pd.to_datetime(df_b['end-date'], format='%d.%m.%Y %H:%M:%S')

def check_min_timedelta(x):
    """
    Create a timedelta between time and end-date
    Return maturity for the row with the minimum time date
    """
    end_diff = abs(df_b['end-date'][df_b['project'] == x[1]] - x[0]).idxmin()
    return df_b['maturity'].loc[end_diff]

# update def date_query
def date_query(x):
    mask = df_b[['project', 'maturity']][df_b[['start-date', 'end-date']].apply(lambda y: ((x[0] >= y[0]) & (x[0] <= y[1])), axis=1)].reset_index(drop=True)
    result = mask['maturity'][mask['project'] == x[1]].reset_index(drop=True)
    if result.empty:
        result = check_min_timedelta(x)
    return result

# call function
df_a['maturity'] = df_a.apply(lambda x: date_query(x), axis=1)


text:
Q: Looking for Euclidean TSP example with known solution I'm looking for an instance of Euclidean TSP problem (shortest path among a number of points) on a complete graph with a known perfect solution. Has anybody encountered such examples? Or is there a simple algorithm to generate such instance that there will certainly be no shorter route than generated?

A: I'm pretty sure there are libraries of problems for this. Looking at http://comopt.ifi.uni-heidelberg.de/software/TSPLIB95/TSPFAQ.html I see
Q: Are the given solution values only the best ones known?.
A: No, for every problem either the value of a provably optimal solution or an interval given by the best known lower and upper bound is listed. The optimality of solutions has been proven by branch-and-cut or branch-and-bound algorithms.
Also see at http://comopt.ifi.uni-heidelberg.de/software/TSPLIB95/STSP.html
When I published TSPLIB more than 10 years ago, I expected that at least solving the large problem instances to proven optimality would pose a challange for the years to come.
However, due to enormous algorithmic progress all problems are now solved to optimality!!


text:
Q: SaveChanges vs. AcceptAllChanges in Entity Framework What's the difference between, _context.SaveChanges and _context.AcceptAllChanges(), is the AcceptAllChanges() is sort of reloading data from Database or rolling back (discarding) changes made by the user when he didn't use SaveChanges()

A: From the Accessing Data with Microsoft .Net Framework 4 book:

When working with the Entity Framework, the submission of changes to
  the database is automatically handled within a transaction when you
  call the SaveChanges method on the ObjectContext object. Also, the
  AcceptAllChanges method is automatically called if no exception is
  thrown when updating, which will reset the state of all objects to
  Unchanged. Although the SaveChanges method is executed within a
  transaction, you might need to create your own transaction if you need
  to perform other operations within the same transaction

A: ObjectContext.AcceptAllChanges Method  - MSDN

If the SaveChanges method was called and the AcceptAllChangesAfterSave
  was not specified, the user must call the AcceptAllChanges method. The
  AcceptAllChanges method is useful in the scenario where a transaction
  has failed and a user wants to retry.

You may see this: http://blogs.msdn.com/b/alexj/archive/2009/01/11/savechanges-false.aspx

If you call SaveChanges() or SaveChanges(true),the EF simply assumes
  that if its work completes okay, everything is okay, so it will
  discard the changes it has been tracking, and wait for new changes.
Unfortunately though if something goes wrong somewhere else in the
  transaction, because the EF discarded the changes it was tracking, we
  can't recover.
This is where SaveChanges(false) and AcceptAllChanges() come in.
SaveChanges(false) tells the EF to execute the necessary database
  commands, but hold on to the changes, so they can be replayed if
  necessary.
Now if the broader transaction fails you can retry the EF specific
  bits, with another call to SaveChanges(false). Alternatively you can
  walk through the state-manager to log what failed.
Once the broader transaction succeeds, you simply call
  AcceptAllChanges() manually, and the changes that were being tracked
  are discarded.