text: Q: In Git for xml '<' replaced with '<' When I checkin my xml file , '<' is replaced with & lt; . I can see it in the diff. I am in linux box and core.autocrlf=input for git settings. Do i need to modify any other settings, to avoid this change from happening ?


text:
Q: How can I create a user that can login through SSH but not on the local desktop in MacOS X El Capitan? I would like to have a user account in my MacOS X El Capitan system which is limited to login through SSH. I do not want that user to be able to use the system through any other means, especially not on the local desktop. I would like that user not to be listed as possible options when logging into the desktop.
Obviously the user needs to be allowed to access via SSH on the Sharing preferences menu. Setting the user's shell to /usr/bin/false, a usual way to disable login for users on MacOS X without deleting them, seems to disable SSH access as well as desktop access. Currently the only way I could come up with is setting a password for the user that the user doesn't know, but I suppose users could then change the password by themselves.
On Debian GNU/Linux for example I would be able to disable the password and/or login altogether. Is there something similar on MacOS?

A: Set up your new User as a Sharing Only account, this gives them no actual account on the computer itself that they can log into…
System Prefs > Users & Groups

*

*Click the lock

*Click the + sign to add a new User

*Set the new account to sharing only from the drop menu [stepped out on the pic for clarity]

Ref : Apple KB -  OS X Yosemite: Create a sharing-only user account
After Comments...
Apparently, this works, but only in combination with some other tweaks.
You need to set up a new group, 'remote users'.
Add your sharing only user to that, then add that group to Remote Login
It seems that Sharing Only users by default have the shell /usr/bin/false and the home directory /dev/null.
Both of these values seem to be magic values for some PAM modules to block the user from connecting.
You have to change both and have the user added to the remote users group to make it work.

A: You can create a low-numbered user via dscl, as per this Apple support page and it will be hidden from most views.
Also, I believe that if you set the user home directory to something like /var/empty then ssh will log in but the gui will not.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Angular 2 - Return data directly from an Observable I've been banging my head against this one trying to figure it out, and no amount of documentation I've been able to read has given me an answer to my question.
I have a service which is speaking directly to an API and returning an observable event which under normal circumstances I would subscribe to and do what I want with the data, however in a secondary service which utilizes the requests from the restful service, I need to be able to return values from the request.
getSomething() {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                res;
            },
            err => {
                console.error(err);
            }
        );
}

returnSomething() {
    return this.getSomething();
}

In the quick example above, I want to know if there is any way I can return res from getSomething() within returnSomething(). If it's not achievable in this way, what is the alternative? I will add that the _restService is pretty heavily relied upon and I don't really want to start messing with that.

A: Since http calls and the like are async, you get an Observable instead of a synchronous value returned. You have to subscribe to it, and in the callback in there you get the data. There is no way around that.
One option would be to place your logic in the subscribe call
getSomething() {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                // do something here
                res;
            },
            err => {
                console.error(err);
            }
        );
}

But the way I like doing it is to add a callback, to inject the logic from outside (maybe a component, maybe another service):
getSomething(callback: (data) => void) {
    return this._restService.addRequest('object', 'method').run()
        .subscribe(
            res => {
                callback(res);
            },
            err => {
                console.error(err);
            }
        );
}

And in your component or wherever:
this._yourService.getSomething((data) => {
    // do something here
    console.log(data);
});

A: I had a similar issue. My solution was to convert the observable into a promise with .toPromise() (and use async - await to return it and catch errors). You can convert your code into something like:

 async getSomething() {
     try{
         return await this._restService.addRequest('object', 'method').run().toPromise()
      } catch (err){
       console.error(err);
   }
  }

A: I didn't use this myself, but I believe it should work in theory (:
// service.ts
getSomething() {
  let subject: Subject = new Subject();
  this._restService.addRequest('object', 'method').run()
    .subscribe(subject);
  return subject;
}

// this can be removed (;
returnSomething() {
  return this.getSomething();
}

// component.ts
ngOnInit() {
  this.service.returnSomething()
    .subscribe(res => console.log(res), err => console.log(err));
}

Check subject docs for more info. You can use different types of subject, for example BehaviorSubject has value property you can access...
ngOnInit() {
  // if you use BehaviorSubject
  this.service.returnSomething().value
}

Here's the working plunker...


text:
Q: having this issue where the code does not recognize whether or not the password inputted is correct I have an issue making the program understand if the answer inputted by the user is correct or not. I tried using String.Empty instead but that did nit work im super confused right now as to why this isnt working, i did also try userInput = password and vice versa but that made it so the answer was always correct i honestly couldn't think of anything else this is how my code looks now:
       string password = "abcd1234";
        string userInput = String.Empty;
        string Text1 = "Please Insert Your Password";
        string Text2 = "Incorrect Password!";
        string Text3 = "Correct You May Proceed!";

        Console.WriteLine(Text1);
        Console.ReadLine();
        if (userInput == password)
            Console.WriteLine(Text3);

        if (userInput != password)
            Console.WriteLine(Text2);

A: Can I assume you have to hit enter before seeing your Text1 prompt, too?
string userInput = Console.ReadLine(); is listening for your input before anything else you see in your app. This line should be moved to after you prompt for your password.
The other ReadLine should be removed:
    Console.ReadLine(); \\this doesn't assign your input to anything

This line is waiting for input but doesn't do anything with it.
You do want the '==', by the way - this returns true if the two are equal. Single '=' is used for assignment, like you have earlier in this code.

A: please use this:
        string password = "abcd1234";
        string Text1 = "Please Insert Your Password";
        string Text2 = "Incorrect Password!";
        string Text3 = "Correct You May Proceed!";
        string userInput = Console.ReadLine();
        Console.WriteLine(Text1);
        if (password.Equals(userInput))
            Console.WriteLine(Text3);
        else
            Console.WriteLine(Text2);


text:
Q: mingew32-g++.exe stopped working in CodeBlocks I am using CodeBlocks in Windows 10 64-bit. It says 'mingew32-g++.exe' stopped working every time I want to build my code. I have tried reinstalling CodeBlocks many times.

A: Rename the file to mingw32-g++ : Go to C:\mingew32\bin -> find a file with -g++ at the end, make sure to save the current name for a backup file, then rename it to mingw32-g++. After that check to see if there's anything with -g++ at the end in C:\mingw64\bin.
If renaming to mingw32-g++ doesn't work, the next place to check would be in Programs and Features to find which program installed mingew32-g++.exe. You don't need to uninstall that program in order to check if it has a legitimate looking name. If it also looks wrong in Programs and Features, you can uninstall it, download it again and reinstall it.


text:
Q: Step-up power module XL6009 converter and >4Amp power source! I want to power up for an hour or two a 6W LED panel (17,8V at 200mAh) from a 12v 7Ah gel battery. I want to use a DC-DC step up convertor with XL6009 to increase the voltage (made in China, Ebay, Amazon), like this:
LINK EBAY HERE

This module only allows for a max of 4Amp input and my DC battery goes up to 7Ah and 120Amp peak. Can I still use the module given the low discharge rate (low LED panel power consumtion)? How can I make this safe to work and not burn in ashes?
Thankful in advance,
Sam

A: Here is the way to evaluate this. Your LEDs will consume 3.56 watts (17.8 volts * 0.2 amps). The battery must supply this power. But the battery is at 12 volts (perhaps slightly more) so there will be 0.3 amps (3.56 watts / 12 volts) drawn from the battery through the boost converter. And actually it is a little more than that since the boost converter burns up some power as well. If we assume it is 90% efficient then the amps on the battery side will be 0.33 amps (0.3 amps / 0.9).
The battery supplies amps to a load. The less amps drawn, the longer the battery will last before needing recharging. Your battery is rated at 7 Ah.  This is calculated over a 20 hour period for most batteries. This means 0.35 amps for 20 hours (7 Ah / 20 hours). But you will be drawing 0.33 amps. So your battery life will be about 21 hours (7 Ah / 0.33 amps).
Take care when using a boost converter such as this. Left unattended, it can draw down your battery voltage to the point of damaging the battery. So stop using your LED when the battery voltage drops to 10.8 volts and then start charging the battery. If you would like your battery to support more charge/discharge cycles, bump that limit up to 11.6 volts.


text:
Q: How to use categorical variable to color geom_path I have a question that probably has a simple answer, but I can't figure it out. I'm making a graphic using ggplot2, specifically geom_path(). The path is colored according to a categorical variable intersects, which takes the value TRUE if the path crosses a certain polygon and FALSE otherwise (I assigned group=1 so the paths are not grouped by the variable).
It is working almost as I would like it to, except that the color is applied to the following path segment instead of the preceding segment. For example,  if observation i = TRUE, and i + 1 = FALSE, the resulting path is colored TRUE between positions i, i+1; and FALSE between positions i+1, i+2.
I would like the path between positions i-1, i to be colored TRUE, and i, i+1 to be FALSE.
# Create polygon.
boundary_x <- c(640343.419, 640341.452, 640339.242, 640337.471, 640339.538, 640341.603)
boundary_y <- c(4858742.348, 4858733.404, 4858722.512, 4858722.853, 4858732.737, 4858742.649)
boundary <- data.frame(x = boundary_x, y = boundary_y)

# Sample data
x <- c(640338.007929366, 640338.077929366, 640338.857929366, 640338.867929366, 640338.459933366, 640338.407929366, 640338.174617366, 640338.139168366, 640338.070599366, 640337.747929366, 640337.847929366, 640338.439430366, 640338.777929366, 640338.877929366, 640339.444178366, 640339.557929366, 640340.247929366, 640340.927929366, 640340.977929366, 640341.107929366, 640341.157929366, 640341.427929366, 640341.477929366, 640341.807929366, 640341.847929366, 640342.427929366, 640342.642404366, 640342.867436366, 640342.878517366, 640343.116330366, 640343.097929366, 640343.007929366, 640342.387929366, 640341.929667366, 640341.837929366, 640339.927929366, 640339.847929366, 640336.427929366, 640335.717929366, 640335.057929366, 640334.967929366, 640334.681813366, 640334.208384366, 640334.172648366, 640334.417929366, 640334.587929366, 640334.777929366, 640334.987929366, 640334.925775366, 640338.257929366, 640338.187929366, 640338.057929366, 640338.077929366, 640338.077929366, 640340.200274366, 640341.037929366, 640341.114123366, 640341.187929366, 640341.237929366)
y <- c(4858731.28088173, 4858731.24088173, 4858730.80088173, 4858730.79088173, 4858728.57674273, 4858728.30088173, 4858727.05816773, 4858726.86768973, 4858726.36255673, 4858722.41088173, 4858722.03088173, 4858721.55321173, 4858721.29088173, 4858721.27088173, 4858721.16125073, 4858721.13088173, 4858721.06088173, 4858720.89088173, 4858720.90088173, 4858720.86088173, 4858720.85088173, 4858720.83088173, 4858720.84088173, 4858721.10088173, 4858721.14088173, 4858722.17088173, 4858722.50853873, 4858722.94242373, 4858722.98987973, 4858725.39572673, 4858725.44088173, 4858725.57088173, 4858725.69088173, 4858725.44266973, 4858725.40088173, 4858721.90088173, 4858721.81088173, 4858721.76088173, 4858721.93088173, 4858722.11088173, 4858722.18088173, 4858722.67533273, 4858723.32189973, 4858723.40558473, 4858727.23088173, 4858727.71088173, 4858728.14088173, 4858728.61088173, 4858730.42873273, 4858728.23088173, 4858727.62088173, 4858726.41088173, 4858726.32088173, 4858726.32088173, 4858726.02508273, 4858726.13088173, 4858726.13140073, 4858726.19088173, 4858726.23088173)
intersects <- c(FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE)
df <- data.frame(x = x, y = y, intersects = intersects)

# Plot
ggplot() +
  geom_polygon(data = boundary, aes(x, y)) +
  geom_path(data = df, aes(x, y, col = intersects, group = 1)) +
  geom_point(data = df, aes(x, y, col = intersects)) +
  coord_cartesian(xlim = c(640334, 640343), ylim = c(4858721, 4858731))

When you view the plot, you'll see the blue segments represent intersects = TRUE, and they occur right after the path crosses the polygon. I'd like to shift the color back, so to speak, so the segment actually crossing the polygon is colored.
I'm new around here and don't have enough reputation to post an image..sorry!

A: The issue here is that you assign the colour (through the column intersects) to the points, not the lines that will actually carry the colour. ggplot2 considers each point to be the start of a line, which is then coloured, while you consider them to be the end of a line to be coloured.
You could, of course, just change your definition of the column intersection to go along with how ggplot2 handles the situation. Alternatively, you can modify the column when creating the plot using lead() from the dplyr package:
ggplot() +
  geom_polygon(data = boundary, aes(x, y)) +
  geom_path(data = df, aes(x, y, col = dplyr::lead(intersects, default = FALSE), group = 1)) +
  geom_point(data = df, aes(x, y, col = intersects)) +
  coord_cartesian(xlim = c(640334, 640343), ylim = c(4858721, 4858731)) +
  labs(col = "intersects")

The function lead() simply takes a vector and shifts its contents by one element to the left:
dplyr::lead(1:3)
## [1]  2  3 NA

Obviously, the function cannot know what to do with the last element of the vector, but you can provide the value that you want:
dplyr::lead(1:3, default = 7)
## [1] 2 3 7

There is also an analogous function dplyr::lag() that shifts in the other direction.


text:
Q: Simple linear regression fit manually via matrix equations does not match lm() output I am trying to fit a linear model using matrices to my data set even though I can use OLS and do it without matrices as a simple tutorial for myself to better understand both R and matrix notation.
This is the model I am trying to fit:
$$\bf Y=X\boldsymbol\beta+\varepsilon$$
where $\bf Y$ is a $1\times n$ matrix, $\bf X$ is a $n\times k$ matrix (where $k$ is the number of $\beta$'s, which in this case is 2), $\boldsymbol \beta$ is a $k\times 1$ matrix and lastly our error term is $n\times 1$. I understand this portion.
When I simply use the lm() command to fit my data, I get the following from the summary() command:
Call:
lm(formula = y ~ x)

Residuals:
    Min      1Q  Median      3Q     Max
-4.0503 -1.4390  0.4921  1.0589  3.9446

Coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)   2.9849     0.8219   3.632  0.00191 **
x             0.5612     0.1084   5.178 6.32e-05 ***

So the summary() is telling me that the $\beta$ matrix is a $2\times 1$ matrix, with the first number (which is $\beta_0$) as 2.0949 and the second number (which is $\beta_1)$ as 0.1084. My question is this:
We know that the matrix $\beta$ is actually:
$$\boldsymbol\beta=(\bf{X}^T\bf{X})^{-1}(\bf{X}^T\bf{Y})$$
and when I try to simply carry out this calculate by hand using R using b=(t(x)*x)^-1*t(x)*y, I get a $1\times 20$ vector (where $20$ of course is $n$, the number of observations). Why am I not getting a $2\times 1$ matrix like I should be getting?

A: You need to include a column of ones in your matrix x, which corresponds to the intercept. The lm() function does this for you automatically, but you need to add this yourself when you calculate the answer using the normal equations.
See this previous question on this site: Using the normal equations to calculate coefficients in multiple linear regression. There is example code which you should be able to copy-and-paste directly.
This is a great introductory book that explains why you have to add the column of ones: http://www.amazon.com/Applied-Regression-Models-Edition-Student/dp/0073014664
You will also need to follow the advice given by @user777

A: You've made two mistakes in your R code for b.

*

*solve is used for matrix inversion. Raising X to the $-1$ power inverts each element of X, which can occasionally be useful, but is not what we want here.

*R uses the operator %*% for matrix multiplication. Otherwise, it does element-wise multiplication and requires your arrays to be conformable according to R's handling of vectors. Again, occasionally useful.

This is all explained in more detail in the R documentation, or the nigh-uncountable intro to R materials online, such as this one.
b<-solve(t(X)%*%X)%*%t(X)%*%y is the literal representation of the normal equations, while b<-solve(crossprod(X), crossprod(X,y)) is faster and more idiomatic, and matches the output of lm(). But you definitely don't want to explicitly compute the normal equations directly for numerical reasons (and R won't warn you until you lose all significant figures). The lm method uses QR decomposition by default, which is more numerically stable. If you apply the correct "hand cranked" computation and it still differs from the R output, it's plausibly because of loss of numerical precision due to the explicit inversion of $X^TX$.
Don't forget to add a column of $1$ for the intercept!

A: This R code can be used to calculate Y (a vector of y values, the fitted values) and Beta (a vector of the coefficients) via matrix regression for a given dataset which I called insert.dataset. This should work even if you add additional numeric variables to the formula.
library(matlib) # enables function inv() to calculate a matrix's inverse

model <- lm(formula = y ~ x, data = insert.dataset) # save linear model
beta0 <- rep(1, nrow(model$model)) # column of 1s representing coefficient beta0 (intercept)
X <- as.matrix(cbind(beta0, model$model[,-1]), nrow=nrow(model$model)) # create X matrix, replacing column of outcomes with beta0

# Matrix equation to create Y (fitted values), using X and coefficients
Y <- X %*% model$coefficients
model$fitted.values # should be identical to Y

# Matrix equation to create Beta (coefficients), using X and Y
Beta <- inv(t(X) %*% X) %*% t(X) %*% model$fitted.values
model$coefficients # should be identical to Beta

It should be noted that the output from lm already has vectors representing Y (model$fitted.values) and Beta model$coefficients, but some small modification is needed to obtain X (the matrix of observed predictor values). That small modification replaces the column containing the observed y values with a column full of 1s (this is needed for multiplication with beta0) and is why you are not getting the 2 * 1 matrix that you want.


text:
Q: Android REST with Spring handle too long request I am building a REST App with Spring. I am doing it the POJO way. Now I want to handle a GET Request that takes too long (lets say because the user has a very bad connection). What can I do to handle this (in Spring), maybe by canceling the request after 5000ms?
My approach:
So I guess there is a need for some kind of timeout. On my google-tour I found that there is a HttpComponentsClientHttpRequestFactory and a so called setConnectTimeout() Function. I tested that but I can't handle the thrown Exception because its "to deep inside" and it gets passed out as a Fatal Exception of the AsyncTask. So I failed.
Whats the best practice? Any Idea?
edit:
Spring is set, so please only Spring solutions.
edit:
According to my research its not possible. Even @ Spring Forums is no answer yet: http://forum.springsource.org/showthread.php?135656-How-can-I-handle-GET-requests-that-are-taking-to-long

A: First of all, don't use an AsyncTask to perform network request because if you change the orientation of your device, Activity is destroyed and after recreated but the AsyncTask keep a reference on the destroyed Activity and cause some memory leaks.
Use Service instead. I suggest you to use RoboSpice. It's a library to easily make REST request with POJO and Spring.
If you're interesting in automatic local & remote data persistency management, you can use RestDroid to handle that (also with POJO).
Both library use RequestListeners to manage the case you're talking about. When your request failed, the UI is notify.

A: Why not taking a simpler approach,
try this code and you'll get a more explicit exception:
HttpParams httpParameters = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParameters, 5000);
HttpConnectionParams.setSoTimeout(httpParameters, 10000);

HttpClient client = new DefaultHttpClient(httpParameters);
HttpGet request = new HttpGet(url);

HttpResponse response = client.execute(request);


text:
Q: How to set CAEmitterLayer background transparent?     var emitter = CAEmitterLayer()
    emitter.emitterPosition = CGPoint(x: self.view.frame.size.width / 2, y: -10)
    emitter.emitterShape = kCAEmitterLayerLine
    emitter.emitterSize = CGSize(width: self.view.frame.size.width, height: 2.0)
    emitter.emitterCells = generateEmitterCells()
    self.view.layer.addSublayer(emitter)

here, CAEmitterLayer covers my view... the content of self.view not visible..
Ref. code : https://oktapodi.github.io/2017/05/08/particle-effects-in-swift-using-caemitterlayer.html
I want to set this animation on my view.

A: I don't know if I understand you correct, but if this is the effect you are looking for:

Then you need to:

*

*Add a "container view" for your your emitter to live in

*Create an outlet for that view

*set clipsToBounds to true for your container view

Here is my ViewController which produced the above screenshot
import UIKit

enum Colors {
    static let red = UIColor(red: 1.0, green: 0.0, blue: 77.0/255.0, alpha: 1.0)
    static let blue = UIColor.blue
    static let green = UIColor(red: 35.0/255.0 , green: 233/255, blue: 173/255.0, alpha: 1.0)
    static let yellow = UIColor(red: 1, green: 209/255, blue: 77.0/255.0, alpha: 1.0)
}

enum Images {
    static let box = UIImage(named: "Box")!
    static let triangle = UIImage(named: "Triangle")!
    static let circle = UIImage(named: "Circle")!
    static let swirl = UIImage(named: "Spiral")!
}

class ViewController: UIViewController {
    @IBOutlet weak var emitterContainer: UIView!

    var emitter = CAEmitterLayer()

    var colors:[UIColor] = [
        Colors.red,
        Colors.blue,
        Colors.green,
        Colors.yellow
    ]

    var images:[UIImage] = [
        Images.box,
        Images.triangle,
        Images.circle,
        Images.swirl
    ]

    var velocities:[Int] = [
        100,
        90,
        150,
        200
    ]

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        view.backgroundColor = UIColor.red

        emitter.emitterPosition = CGPoint(x: emitterContainer.frame.size.width / 2, y: -10)
        emitter.emitterShape = kCAEmitterLayerLine
        emitter.emitterSize = CGSize(width: emitterContainer.frame.size.width, height: 2.0)
        emitter.emitterCells = generateEmitterCells()
        emitterContainer.layer.addSublayer(emitter)
        emitterContainer.clipsToBounds = true
    }

    private func generateEmitterCells() -> [CAEmitterCell] {
        var cells:[CAEmitterCell] = [CAEmitterCell]()
        for index in 0..<16 {
            let cell = CAEmitterCell()

            cell.birthRate = 4.0
            cell.lifetime = 14.0
            cell.lifetimeRange = 0
            cell.velocity = CGFloat(getRandomVelocity())
            cell.velocityRange = 0
            cell.emissionLongitude = CGFloat(Double.pi)
            cell.emissionRange = 0.5
            cell.spin = 3.5
            cell.spinRange = 0
            cell.color = getNextColor(i: index)
            cell.contents = getNextImage(i: index)
            cell.scaleRange = 0.25
            cell.scale = 0.1

            cells.append(cell)
        }

        return cells
    }

    private func getRandomVelocity() -> Int {
        return velocities[getRandomNumber()]
    }

    private func getRandomNumber() -> Int {
        return Int(arc4random_uniform(4))
    }

    private func getNextColor(i:Int) -> CGColor {
        if i <= 4 {
            return colors[0].cgColor
        } else if i <= 8 {
            return colors[1].cgColor
        } else if i <= 12 {
            return colors[2].cgColor
        } else {
            return colors[3].cgColor
        }
    }

    private func getNextImage(i:Int) -> CGImage {
        return images[i % 4].cgImage!
    }
}

Hope that helps you.

A: It is working fine check output of my simulator. Background images are added from storyboard and blue color is done by code. Still working fine.
OUTPUT:

A: You can fix your problem by changing the way you add the layer right now your adding it on top of everything which sometimes hide other layers and view objects.
change
self.view.layer.addSublayer(emitter)

To
self.view.layer.insertSublayer(emitter, at: 0)

A: Hello change emitterPosition X of each like below:-
    let emitter1 = Emitter.getEmitter(with: #imageLiteral(resourceName: "img_ribbon_4"), directionInRadian: (180 * (.pi/180)), velocity: 50)
    emitter1.emitterPosition = CGPoint(x: self.view.frame.width / 3 , y: 0)
    emitter1.emitterSize = CGSize(width: self.view.frame.size.width, height: 2.0)
    self.view.layer.addSublayer(emitter1)

    let emitter2 = Emitter.getEmitter(with: #imageLiteral(resourceName: "img_ribbon_6"), directionInRadian: (180 * (.pi/180)), velocity: 80)
    emitter2.emitterPosition = CGPoint(x: self.view.frame.width / 2, y: 0)
    emitter2.emitterSize = CGSize(width: self.view.frame.size.width, height: 2.0)
    self.view.layer.addSublayer(emitter2)

I hope it will help you,
thank you.


text:
Q: Which storage interface(s) to use on a Gigabyte-EX58-UD5 motherboard? I have a Gigabyte-EX58-UD5 (rev. 1.0) motherboard (reference docs here). The motherboard has a number of SATA connectiors, 6 are powered by an Intel southbridge and 4 are powered by some Gigabyte SATA2 chip.
Additionally, I have 3 hard disks:

*

*a 64GB Kingston SSD

*a 1TB Western Digital Black HDD

*a 2TB Western Digital Green HDD

(you can google these if you want, they are pretty standard ones)
My goals would be to have a stable system that also have acceptable performance. I don't really care for RAID setups and such, I have external backups of all my important data.
So my questions are:

*

*to which SATA connectors should I connect my disks?

*what BIOS settings would you recommend regarding AHCI and similar things?

*to which disc should I install Windows 7? (I'd really go for the SSD if nobody convinces otherwise)

A: To answer your questions:

*

*The SATA connectors controlled by the Intel ICH10R Southbridge will give you better performance than the Gigabyte SATA2 chip (Which is actually a JMicron controller). i.e. you should connect your hard disks to any of the blue coloured ports labelled SATA2_0, SATA2_1, SATA2_2, SATA2_3, SATA2_4, SATA2_5. Also, since these ports are native to the chipset you won't have to deal with any JMicron drivers.

*You should set the SATA mode to XHD which means the ports will be controlled by Intel RAID BIOS (even though you won't be implementing RAID it doesn't matter), which automatically enables AHCI (essential for SSD's) and provides better flexibility and compatability.

*Windows 7 should be installed on the SSD for optimal performance. Programs that you use frequently (eg. browsers, Office etc.) should also be installed on the SSD so they load fast and snappy for you. If you have big programs/games to install that won't fit on the SSD then you should install them on the WD 1TB Black HDD as the Black series has better performance than Green. Everything else such as documents, videos, photos etc. can go on the Green drive.


text:
Q: How disable SSL redirect for specific URL? I have a specific URL that has to be accessible without SSL, so that some old devices can access it. The reason is those old devices have the URL hardcoded.
The URL is http://domain.com/server
My .htaccess looks like this:
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>

Redirect 301 /server http://sub.domain.com/server

However, the devices can't even access the first URL because it keeps redirecting to https://domain.com/server

A: Your URL http://domain.com/server should work without problems.
Most likely you have activated an HTTPS redirection for your website.
You should check:

*

*If you have a security or other type of plugin that forces the HTTPS redirection and deactivate the redirection. (Most likely they will edit your .htaccess file in order to force the HTTPS)

*Check your .htaccess file for a custom snippet that forces the HTTPS redirection

*Check your Hosting Settings. The HTTPS Redirection might be activated from there.


text:
Q: Python: initiated Logger with dataclass field param This is my Logger class:
import logging
import os
import datetime

class Logger:
    _logger = None

    def __new__(cls, user: str, *args, **kwargs):
        if cls._logger is None:
            cls._logger = super().__new__(cls, *args, **kwargs)
            cls._logger = logging.getLogger("crumbs")
            cls._logger.setLevel(logging.DEBUG)
            formatter = logging.Formatter('[%(asctime)s] [%(levelname)s] [%(filename)s] [%(funcName)s] [%(lineno)d]: %(message)s')
            now = datetime.datetime.now()
            directory_name = f'./log/{now.strftime("%Y-%m-%d")}'
            base_log_name = f'/{user}'
            log_file_extension = '.log'
            if not os.path.isdir(directory_name):
                os.mkdir(directory_name)
            file_handler = logging.FileHandler(f'{directory_name}{base_log_name}{now.strftime("%d-%m-%Y")}{log_file_extension}', 'w', 'utf-8')
            stream_handler = logging.StreamHandler()
            file_handler.setFormatter(formatter)
            stream_handler.setFormatter(formatter)
            cls._logger.addHandler(file_handler)
            cls._logger.addHandler(stream_handler)
        return cls._logger

And this is my class that accept user argument and I want my log file to be created with my user name in the file name:
@dataclass(kw_only=True)
class RunningJobManager:
    user: str = field(init=True)
    password: str = field(init=True)
    logging: Logger = field(init=False, default_factory=Logger(user=user))

So currently my user field inside Logger class is with type of dataclasses.Field instead of string.
I also try to use default instread of default_factory
And I got this error:

Curerenly my code crash with OSError, [Errno 22] Invalid argument:
'G:\my_project\log\2023-01-20\Field(name=None,type=None,default=<dataclasses._MISSING_TYPE
object at
0x0000017B1E78DB10>,default_factory=<dataclasses._MISSING_TYPE object
at
0x0000017B1E78DB10>,init=True,repr=True,hash=None,compare=True,metadata=mappingproxy({}),kw_only=<dataclasses._MISSING_TYPE
object at 0x0000017B1E78DB10>,_field_type=None)20-01-2023.log'

At this line:
file_handler = logging.FileHandler(f'{directory_name}{base_log_name}{now.strftime("%d-%m-%Y")}{log_file_extension}', 'w', 'utf-8')

EDIT
"stdout_handler": {
                    "formatter": "std_out",
                    "class": "logging.StreamHandler",
                    "level": "DEBUG"
                }

A: Here is example with dictConfig:
import logging
import os
from dataclasses import dataclass, field
from logging import Logger
from logging.config import dictConfig

@dataclass(kw_only=True)
class AbstractJobManager:
    user: str = field(init=True)

    @property
    def logger(self) -> Logger:
        return logging.getLogger('crumbs')

    def __post_init__(self):
        if not os.path.isdir('log'):
            os.mkdir('log')

        # some config from YAML, TOML or hardcoded - doesn't matter...
        config = {
            'version': 1,
            'loggers': {
                'crumbs': {
                    'level': 'INFO',
                    'handlers': ['file_handler'],
                },
            },
            'handlers': {
                'file_handler': {
                    'level': 'INFO',
                    'class': 'logging.handlers.RotatingFileHandler',
                    'filename': f'./log/{self.user}.log',  # I skipped %Y-%m-%d...
                    'backupCount': 3,
                    'formatter': 'simple',
                },
            },
            'formatters': {
                'simple': {
                    'format': '%(pathname)s:%(lineno)d %(asctime)s - %(levelname)s - %(message)s',
                },
            },
        }

        dictConfig(config)

@dataclass(kw_only=True)
class RunningJobManager(AbstractJobManager):
    password: str = field(init=True)

    def run(self):
        self.logger.info('user = %s, password = %s', self.user, self.password)

RunningJobManager(user='falukky', password='Hello World!').run()
RunningJobManager(user='ridley', password='scott').run()
RunningJobManager(user='jimi', password='hendrix').run()

A: This is not the way dataclasses handle initialization of a field depending on other fields. The default_factory parameter of field is expected to be a zero-argument callable. The standard library documentation states:

default_factory: If provided, it must be a zero-argument callable that will be called when a default value is needed for this field...

Said differently it is not possible to pass any argument to default_factory.
The correct way to initialize a field using values of other fields is to use a __post_install__ method:
@dataclass(kw_only=True)
class RunningJobManager:
    user: str = field(init=True)
    password: str = field(init=True)
    logging: Logger = field(init=False, default=None)

    def __post_init__(self):
        if self.logging is None:
            self.logging = Logger(self.user)


text:
Q: Is that good to improve the performance to split the critical section and lock mutex twice? I am trying to optimize some multi-threads code. I know the way I should focus on is make the critical section smaller, but I meet some code structure and I am not sure what is the best way to improve the performance.
the first question is like this:
mutex.lock();
critical Section A;
func_A(); //func_A() is just a function which will not create confliction.
critical Section B;
mutex.unlock();

func_A() is just a function which will not create confliction.
I treat A and B as a whole critical section, If I split the section, let's say, make A and B not in the same critical section like:
mutex.lock();
critical Section A;
mutex.unlock();
func_A(); //func_A() is just a function which will not create confliction.
mutex.lock();
critical Section B;
mutex.unlock();

will this improve my code performance?
Second question is I have some code like:
func1(){
    mutexA.lock();
    critical Section for varibale A;
    mutexB.lock();
    critical Section for varibale B;
    mutexB.unlock();
    critical Section for varibale A;
    mutexA.unlock();
}
func2(){
    if (some condition){
      mutexB.lock();
      critical Section for varibale B;
      mutexB.unlock();
    }
}

Here func1 is a time-consuming function and func2 is not.
also, critical Section for variable B is a fast part.
Is that OK for the performance to put one lock inside of another lock? Will it affect the performance too much? Is that OK to just use one mutex for both func1 and func2 rather than 2?
It is really hard to figure out how much these mutexes will cost. I really have no idea for them.

A: First of all, keep it simple, but correct. Then profile. Then, only if required, improve.
Unfortunately I can't provide a more concrete answer here because:
mutex.lock();
critical Section A;
database.loadPetabyteOfData() // just a single line
critical Section B;
mutex.unlock();

Here it makes a perfect sense. If your "few lines which will not create conflict" are fast - don't bother.
Regarding your last example about using a separate mutex for each variable: usually this doesn't make sense too. If you modify a bunch of variables usually together, protect them by the same mutex. Start from a simpler version.

A:
will this improve my code performance?

Instead of worrying about performance you should be thinking in terms of correctness. Does it make sense for A and B to happen independently, or should they be a single "atomic" (i.e. indivisible) operation?
If they're separate, independent actions then it might make sense to do:
{
  lock_guard<mutex> l(mutex);
  critical section A
}
func_A();
{
  lock_guard<mutex> l(mutex);
  critical section B
}

But be aware that this will allow your program to do AAAAAABAABBBBABBBB.
If it's important that it does ABABABABABABABABAB then you need to treat them as a single critical section.
So talking about performance without considering how that affects the actual behaviour is misguided. It's impossible to answer your questions about performance without knowing far more detail about the specifics. But performance is probably not what you should be worrying about anyway.

A: About your first question: If critical sections A and B are time consuming (and independant), then having two separate sections helps two threads to run them concurrently. So, yes, in some cases it may improve the performance.
About your second Q: for light critical sections I always recommend to put them under the same lock. Having less locks helps to avoid deadlocks happening due to programmers mistake as well.


text:
Q: The order structure of the dual space of $C(X)$ A "state" is positive linear functional on a partially ordered vector space with order unit that sends the order unit to $1$.  This definition can be extended uniquely to complex-valued linear functionals.  What I would like to know is why a state of $C(X)$ has norm $1$.  If a linear functional $
\phi$ is a hermitian state on $C(X)$, then $\phi(\overline{f}g)$ defines an inner product, so by Cauchy-Schwarz it has norm equal to $1$.  But why does this follow for any state?  It does not seem to me that an arbitary state needs to be positive or real-valued or hermition.  Of course an arbitary state decomposes as the sum of hermitian states, but this only shows that it has norm less than or equal to $2$.


text:
Q: .net Support in Google App engine Is .net runtime supported by Google App engine? I see we can use custom runtime to use other runtimes other than the ones directly supported by GAC.
We use .net heavily and are planning to move to a cloud solution and hence evaluating GAC.

A: You can run your .Net code on Windows instances in Google Compute Engine.
https://cloud.google.com/compute/docs/instances/windows
From there, you can run your existing code, or take advantage of Google's services like Pub/Sub.  Here's a sample that shows .Net code being invoked from an app-engine front end.
https://github.com/GoogleCloudPlatform/pubsub-shout-csharp


text:
Q: Does integral by parts apply when the integrand is discontinuous at some point? Suppose we have: $H(x)=a (x\ge0); H(x)=0 (x<0)$, where $a>0$ is a constant. Define $K(x)=ax (x\ge0); K(x)=0(x<0)$.
When evaluate the integral:
$$
\int_{-\infty}^{+\infty} H(x) f(x) dx
$$
where $f(x)$ is continuous and differentiable.
Does the above integral equal to the following expression?
$$
-\int_{-\infty}^{+\infty} K(x)\frac{df(x)}{dx} dx + f(x)K(x)|_{-\infty}^{+\infty}
$$
If not, please give me the reasons and a particular example.

A: On $[-C,C]$, apply integration by parts on $[-C,0]$ and $[0,C]$ respectively (both functions are continuous and differentiable here, so you're allowed to use the ordinary results).
Then, $\int_{-C}^C H(x)f(x)\textrm{d}x=-\int_{-C}^0 K(x)f'(x)\textrm{d}x+[K(x)f(x)]_{-C}^0-\int_0^C K(x)f'(x)\textrm{d}x+[K(x)f(x)]_0^C.$ Now, analysing this bit, you see that we are done if we are allowed to say that $[K(x)f(x)]^0_{-C}+[K(x)f(x)]_{0}^C=[K(x)f(x)]_{-C}^C$ and this holds, since $K$ is continuous.
The situation becomes more tricky when you're trying to fit the result on a function, the anti-derivative of which is not continuous. If the anti-derivative is bounded and $f(0)=0,$ then the result still works (just check the proof above).


text:
Q: haproxy tcp roundrobin loadbalancing not working as expected I'm new to haproxy, and using it for TCP load balancing of rsyslog logs to ArcSight connectors.  For the life of me, I cannot get traffic to evenly balance across all of the nodes in the pool (which is the desired behavior).   I've tried many permutations of weights and maxconn's to no avail.
It feels like this should be an easy problem, but the per pool node behaviors are very confusing.   Also, since most people use haproxy for http load balancing, I'm finding scant documentation about the best way to go about what I am trying to do.
Anyone have any insights, proven configs, or troubleshooting steps to recommend?
Thanks!
Here is our current config:
global
    log 127.0.0.1       local0
    log 127.0.0.1       local1 notice
    maxconn 256000
    user haproxy
    group haproxy
    spread-checks 5
    daemon
    quiet

defaults
    log global
    option dontlognull
    option redispatch
    option allbackups
    maxconn 256000
    timeout connect 5000

listen stats :1936
    mode http
    stats enable
    stats realm Haproxy\ Statistics
    stats uri /
    stats auth admin:savetheday

frontend rsyslog_netscreen
    bind 127.0.0.1:8514
    mode tcp
    option tcplog
    option contstats
    option tcpka
    default_backend rsyslog_netscreen_backend

backend rsyslog_netscreen_backend
    balance roundrobin
    mode tcp
    option tcpka
    option srvtcpka
    server netscreen1 localhost:9515 weight 1 maxconn 1024 check
    server netscreen2 localhost:9516 weight 1 maxconn 1024 check
    server netscreen3 localhost:9517 weight 1 maxconn 1024 check
    server netscreen4 localhost:9518 weight 1 maxconn 1024 check
    server netscreen5 localhost:9519 weight 1 maxconn 1024 check
    server netscreen6 localhost:9520 weight 1 maxconn 1024 check

A: Note that roundrobin is not a good strategy to achieve even load. It will make sure that each backend receives the same number of connections over time, but does not care how long each connection last.
In your stats view, it should be apparent that the total number of sessions per backend server is almost equal (if their uptimes are equal). The number of current sessions can vary quite a bit, though.
We have found that using leastconn instead of roundrobin yields a much more even load. This makes sense, because servers that happen to be stuck with many long-lived clients that hold on to their connection need not be burdened with new incoming connections.

A: use roundrobin for short lived connections and use leastconn for fairly long lived connections.


text:
Q: What should be done about a user who makes a threat? I have recently come across an answer on one of Stack Exchange's sites (Skeptics) that was quite surprising to me. I have been a part of the Stack Exchange network for a while, and this is the first time I have ever seen someone actually attempt to threaten Stack Exchange itself!
The question is about whether it is worth it to own a handgun. A visitor saw the post, and made a threat (deleted now, but 10k users can see it)  against Stack Exchange. They had posted that they would attempt to get as many people as they could to try to start a DDoS attack against Stack Exchange!

I am going to broadcast this question in all it ridiculousness far and wide and you will be hit with every NRA member in the country and then some. Hope your sever can handle it

Now while I highly doubt that they will be successful, action should still be taken against someone who makes a threat like that. I'm not just talking about a user who makes a threat against Stack Exchange, but also about a user who makes a threat against another user (be that digital, or physical).
The user had just created an account, so removing the answer and banning the account is not necessarily enough. I believe further action should be taken to ban the user's IP address from ever using (and possibly even visiting) any of the Stack Exchange site's again. I am not a moderator, nor do I work for Stack Exchange, so I have no authority to do this
myself. However, if there are other users who agree with me, or have other ideas about what should be done to such users, please comment, or provide your own answer.

Edit: I am not asking this because of an individual post, as he was obviously just a troll, and likely, nothing will come of it. I am creating this because I have noticed that Stack Exchange does not have an existing policy on threats. Wikipedia has one, and I think we should too.

A: Fear not, he's just a troll...

Now while I highly doubt that they will be successful, action should still be taken against someone who makes a threat like that.

Nah, not worth the time or the effort. The moderators should just destroy the account, and forget all about it.

The user had just created an account, so removing the answer and banning the account is not necessarily enough.

You're right, that's a problem. Stack Exchange doesn't make it too hard for someone to create an account just to post crap. So far though, the benefits far outweigh the troubles, and although at times it gets a bit tedious for us moderators, let's just concentrate on the positives.

I believe further action should be taken to ban the user's IP address from ever using (and possibly even visiting) any of the Stack Exchange site's again.

IP address bans don't really work, we can never be certain where (s)he's posting from.

I am creating this because I have noticed that Stack Exchange does not have an existing policy on threats. Wikipedia has one, and I think we should too

Well there is a policy:

4. Restrictions
Subscriber is responsible for all of its activity in connection with the Services and accessing the Network. Any fraudulent, abusive, or otherwise illegal activity or any use of the Services or Content in violation of this Agreement may be grounds for termination of Subscriber's right to Services or to access the Network. Subscriber may not post or transmit, or cause to be posted or transmitted, any communication or solicitation designed or intended to obtain password, account, or private information from any Network or Service user.
(blah blah blah, more legalese)

A:
I am going to broadcast this question in all it ridiculousness far and wide and you will be hit with every NRA member in the country and then some. Hope your sever can handle it

I'm not sure how worried Joel and Shog should be about a bunch of gun-toting rednecks launching a distributed denial of service attack against their network.
As random said, this is just a novice troll.
Appendix A: the SE Sys-Admin team of gun-toting rednecks

A: From the FAQ on every site:

Civility is required at all times; rudeness will not be tolerated.

This is pretty broad... If someone makes threats against another user, it's hard to argue that's not at least rude.
As others have noted, preemptive IP address bans have issues that make them a bad idea in general. There are other tools for moderators and administrators to use in dealing with troublesome users, with banning IP address ranges being suitable in limited situations only.
And as Nick subtly notes, we're kind of used to dealing with folks abusing the servers. If someone goes beyond threats and actually starts causing problems, we'll handle that regardless of whether or not they have an account on the site.

A: The rest of the answers have dealt with the main issue here. I'd just like to explain why IP address banning should never be used on Stack Overflow.
IP address bans are a Very Bad Thing
They raise these questions:

*

*What if he's using a cyber cafe?

*What if he's part of a shared-IP address network? Many workplaces have these where the external IP address is the same (this is called something, but I don't know)

*What if he's at a friends place?

*What if his IP address is dynamic? A WHOIS can tell you this, though.

*What if he's using a proxy? A WHOIS usually tells you this as well, otherwise there are lists of proxies available

They're easy to bypass:

*

*Switch to a different computer

*If you use a dynamic IP address, renew it.

*Use a proxy. And no, this doesn't mean we should rangeblock all proxies like Wikipedia does.

The other issue is, we need a way to appeal against these. And that means another system.
You mentioned Wikipedia. Well, you're right, Wikipedia employs IP address blocks extensively. But, there are a lot of mechanisms required to appeal against blocks. There are a lot of "collateral damage" cases, where too many others are affected by the blocks. I used to help out at their Account request system (this deals with people who cannot create accounts, due to blocks, rangeblocks, accessibility issues and whatnot). And a lot of its requests are due to the collateral damage of blocks (it surprisingly gets a sizable number of requests per day). There's a separate mailing list monitored by a whole bunch of people for editing-blocks as well. And, blocks can be appealed on the IP address talk page itself (though these appeals are usually a bunch of drama).
Anyway, if we started IP address banning, we'd need a similar system in place to appeal them. I guess emailing team@SE.com would work, but that really doesn't cut it when you want to tell apart "someone who's been wrongly affected" and "someone who's been collateral-damaged".
Basically an IP address ban is a whole lot of work for the banner, when it is easily bypassed by the.. uh.. bannee.
So, I say that IP address bans should be reserved for extremely special cases, where they are absolutely necessary. This is not a special case, this is just a troll talking big.

A:
Hope your server can handle it

Bring it.

A: It's fairly simple, he doesn't need any special treatment so don't handle him differently from any other user that posts such trolling crap. Allowing him to participate in the comment thread or stay on the site and cause more posts / comments like these is what needs to be prevented (as it makes your community look bad if he does); so, flag it for moderator attention and they will most likely warn or suspend the user. If he returns multiple times, valued associated can take further actions if required...

The Stack Exchange network is prepared against DDoS attacks:

The rate limiting that has been implemented should fend off a good deal of basic crap.  The team is obviously on top of their infrastructure as is evidenced by this post on the new Serverfault Blog.  Also others on the Stackoverflow blog.  The measures in place already should go a fair distance in preventing a DDoS, and with constant monitoring I would expect that an attack would be quickly noticed and addressed.  I would wager that their relationship with the Peer1 would be such that they would get some priority assistance in the case that an attack ensues.

Even if it were serious, he surely won't get every NRA member to do a DoS so the amount of people participating will most likely be negligible. Stack Exchange doesn't run SOHO material, so just like most of the other popular sites it should be able to withstand it.
At its best it is an useful stress test for us, at its worst they're just wasting their own bandwidth and time...


text:
Q: Bootstrap chosen add new item if no exist I am trying add new item if not exist. This code working but i dont know how add item directly on list of selected.
Chosen.prototype.no_results = function(terms) {
  var no_results_html;
  no_results_html = $('
' + this.results_none_found + '"" kao' +
    ' <button class="add" id="interni" class="submit"> Interni tip </button> ' +
    ' <button class="add" id="eksterni" class="submit"> Eksterni tip</button> ' +
    '
 ');
  no_results_html.find("span").first().html(terms);
  no_results_html.find(".add").click(function() {

    var terms1 = terms + ' (' + this.id + ')';

    $('.chosen-select').chosen().append('<option>' + terms1 + '</option>');
    $('.chosen-select').chosen().trigger('chosen:updated');

  });
  return this.search_results.html(no_results_html);
};

resolved: Add selected atribute on option tag.
 $('.chosen-select').chosen().append('<option selected>' + terms1 + '</option>');


text:
Q: What are the challenges of installing Shopify on a root domain and Wordpress as a subfolder? We have a Shopify store and a Wordpress CMS site.  Currently the shop is on the root domain and Wordpress is on a subdomain (help.domain.com).  Everything is fine, life is good.
Our SEO company, predictably, is now asking us to merge the Wordpress side at help.domain.com into the root by installing Wordpress in a subfolder.
Is it even possible?
My understanding is that such an architecture introduces a slew of technical issues and potential headaches.
I suppose my question is how big of a challenge is this and what types of issues should I expect to face.  Moreover, does the benefit outweigh the cost.

A: You cannot make WP a subdirectory of Shopify. You must continue to keep it as a subdomain. So while your Shopify can be domain.com, your WP must continue to be something like help.domain.com.
Your SEO company is flailing at windmills. Not unusual. If they were good, you might instead be receiving advice on how to leverage the content of your domain as a total package, rather than how you choose to organize it. The organization in terms of domain setup is so not important compared to the content within.


text:
Q: Rails - Cannot create New rails Application I already have a live Rails application which is running in rails 5.0.1. Now, when I try to create new rails version I get the following error
Could not find proper version of railties (4.2.7.1) in any of the sources
Run `bundle install` to install missing gems.

When I run 'bundle install' I get the following error
Could not find spork-1.0.0rc4 in any of the sources

How can I solve this error?
My System only have Rails 5.0.1 version and Ruby version 2.3.1.
PS: When I keep Ruby version in 2.2.5, I am able to create my rails app successfully.

A: If you're trying to create a new rails application, try setting it up in a new folder.
If you're trying to update the rails version of your current project update the rails version in your Gemfile and run bundle update rails.
Prepending the command that's giving you
Could not find proper version of railties (4.2.7.1) in any of the sources
Run `bundle install` to install missing gems.

with bundle exec may solve your problem.
If you're using something like rbenv to manage your ruby version, you may have to update your .ruby-version file, and then run
rbenv install
gem install bundler
bundle install

to install that new version of ruby, bundler and your gems.


text:
Q: Magento 2: Problem overriding product/view/form.phtml in custom module I tried using this in my catalog_product_view.xml:
<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
    <!-- <referenceContainer name="content">
        <referenceContainer name="product.info.main">
        <referenceContainer name="alert.urls">

        <referenceBlock name="product.info">
                <action method="setTemplate">
                    <argument name="shopmethtempindex" xsi:type="string">Interjar_ConfigurableChildVisibility::product/view/form.phtml</argument>
                </action>
            </referenceBlock>
            </referenceContainer>
    </referenceContainer>
    </referenceContainer> -->

    <!-- <referenceContainer name="content">
    <referenceContainer name="product.info.main">
            <referenceBlock name="product.info">
                <action method="setTemplate">
                    <argument name="shopmethtempindex" xsi:type="string">Interjar_ConfigurableChildVisibility::product/view/form.phtml</argument>
                </action>
            </referenceBlock>
    </referenceContainer>
    </referenceContainer> -->

    <referenceContainer name="content">
        <referenceContainer name="product.info.main">

            <block class="Magento\Catalog\Block\Product\View" name="product.info" template="Interjar_ConfigurableChildVisibility::product/view/form.phtml">
            </block>

        </referenceContainer>

    </referenceContainer>
    </body>
</page>

But it is not working.
Any help would be appreciated.

A: templates are a Ui components not templates
you can also review this
Want to override Magento 2 Contact Form Block


text:
Q: Java StackOverflow encapsulation Trying to set up a Person class I have run into a problem trying to encapsulate the information in the class so that it cannot be changed by accident. The class works perfectly fine except for when I try to encapsulate by using setters/getters. The prblem I think is that the methods end up looping eachother until the stack is full.
This is the working code (a cut):
// Set this persons father
public void setFather(Person father) {
    // Adding or changing father
    if (father != null && father.isMale()) {
        // If old father, remove as child
        if (this.father != null)
            this.father.removeChild(this);
        this.father = father;
        this.father.children.add(this);  //######//
    }

    // Removing father
    if (father == null) {
        // Removing old father
        if (this.father != null)
            this.father.removeChild(this);
        this.father = null;
    }
}

// Add a child to this person
public void addChild(Person child) {
    // Add child to this persons children if not already a child
    if (!this.children.contains(child)) {
        // Add this person as mother to child if female
        if (this.isFemale()) {
            child.setMother(this);
        }

        // Add this person as father to child if male
        if (this.isMale()) {
            child.setFather(this);
        }
    }
}

Now notice if I change the line marked with //#####// to: this.father.addChild(this); I get a stackoverflow.
private String name = null;
    private char gender;
    private Person father;
    private Person mother;
    ArrayList<Person> children = new ArrayList<Person>(0);

I would like children to be private but I don't know how to escape this loop.
This is somewhat homework related but the assignment is done and corrected with a full score, I just want to encapsulate my data.

A: Your call to addChild (from setFather) calls setFather again.
try changing
    if (this.isMale()) {
        child.setFather(this);
    }

to something along the lines of
    if (this.isMale() && child.father != this) {
        child.setFather(this)
    }

This check will break you out of your infinite loop. Just make sure that in your setFather method you set the father before calling the setChild method.


text:
Q: Image Processing ERRORR Images have been corrupted I have to use open eVision with Visual Studio for image processing . In my project ,Firstly, I need to take a Picture from my computer and convert JPEG to bmp (bitmap) with this function
private void BitmaptoEImageBW8(ref Bitmap bitmap)
    {
        EImageBW8 eImageBW8 = null;

        try
        {
            eImageBW8 = new EImageBW8();

            Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);

            bitmapdata = bitmap.LockBits(rect, ImageLockMode.ReadWrite, bitmap.PixelFormat);

            eImageBW8.SetImagePtr(bitmap.Width, bitmap.Height, bitmapdata.Scan0);

            bitmap.UnlockBits(bitmapdata);

            ShowImage(eImageBW8, pictureBox1);

        }
        catch (EException e)
        {
            Console.WriteLine(e.ToString());
        }

    }

After that I will show this picture in picturebox with this function
private void ShowImage(EImageBW8 img, PictureBox pb)
    {
        try
        {
            Bitmap bmp;
            bmp = new Bitmap(pb.Width, pb.Height); //bitmap boyu picturebox boyunda alınır //   1920/3 - 1200/3 ayarladım.
            float PictureBoxSizeRatio = (float)pb.Width / pb.Height; //picturebox oranı
            float ImageSizeRatio = (float)img.Width / img.Height; //resim boyutunun oranı
            if (ImageSizeRatio > PictureBoxSizeRatio) //resmin oranı picturebox oranından büyükse.
                ScalingRatio = (float)pb.Width / img.Width;
            else
                ScalingRatio = (float)pb.Height / img.Height; //ölçek oranı
            EBW8ScaleRatio = ScalingRatio; //oranlar birbirine eşitlenir
            if (pb.InvokeRequired)
            {
                pb.Invoke(new MethodInvoker(delegate () {
                    img.Draw(Graphics.FromImage(bmp), ScalingRatio);
                    pb.BackgroundImage = bmp; //arka planı bmp
                }));
            }
            else
            {
                img.Draw(Graphics.FromImage(bmp), ScalingRatio);
                pb.BackgroundImage = bmp;
            }
        }
        catch (Exception e)
        {
            Console.WriteLine(e.ToString());

        }
    }

}

}
I write a code and it works and doesn't give any error but Image is too big for Picturebox even I used different function for arrange the size of image and it is corrupted.You can see my code and my problem's screenshoot . Can you give me any advise?
you can see my all code below.
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }
    BitmapData bitmapdata = new BitmapData();
    float ScalingRatio = 0;
    float EBW8ScaleRatio = 0;
    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog choose =new OpenFileDialog();
        choose.Filter = "Image Files(*.jpeg; *.jpg; *.bmap;)| *.jpeg; *.jpg; ; *bmp";
        if(choose.ShowDialog() == DialogResult.OK)
        {
            textBox1.Text = choose.FileName;
            Bitmap bmp =new Bitmap(choose.FileName);
            BitmaptoEImageBW8(ref bmp);

You can see here the result of my project and corrupted image


text:
Q: How to prove $\lim_{n\to \infty} \frac{n!}{n^n}$ is zero? I am struggling in this limit: $$\lim_{n\to \infty} \frac{n!}{n^n}$$
I really worked on this for few days: clearly, it goes to zero but I couln't do it rigorously. I'd really appreciate your help. Thanks from now.

A: You may use the quotient criterion for series:
$$a_n = \frac{n!}{n^n}\Rightarrow \frac{a_{n+1}}{a_n}=\frac 1{\left(1+\frac 1n\right)^n}\stackrel{n\to\infty}{\longrightarrow}\frac 1e<1$$
Hence, the series $\sum a_n$ is convergent and hence $\lim_{n\to\infty} a_n = 0$.

A: A quick and dirty way to show it goes to 0 really fast:
$$
n! \leq n^{\lfloor n/2\rfloor}\cdot (n/2)^{\lceil n/2\rceil}
$$
So
$$
\frac{n!}{n^n} \leq \frac{1}{2^{\lceil n/2\rceil}}
$$

A: $\begin{aligned} y=& \lim _{n \rightarrow \infty} \frac{n !}{n^{n}} \\ \ln y &=\lim _{n \rightarrow \infty} \ln \frac{n !}{n^{n}} \\ &=\lim _{n \rightarrow \infty}(n \ln n-n-n \ln n) \\ &=\lim _{n \rightarrow \infty}-n \\ &\\ \ln y \rightarrow-\infty \\ \Rightarrow & y \rightarrow 0 \end{aligned}$


text:
Q: Firefox cookies on Linux Im using Firefox 3 now. I found out that cookies are stored inside a database file called cookies.sqlite
Is there any way that I can make my Firefox saves it cookies inside a txt ?

A: Assuming you still have this problem 2 years later..
You can use sqlite3 in Python to retrieve the data from cookies.sqlite. The current version of Firefox is 15.0.1 and there have been a few changes to the format of the database since Firefox 3. You didn't say whether you are on Windows or Linux, but if you want to see what's in the cookies.sqlite file with SQLite Expert Personal 3.4.31.2253 or later will show you what is there. That is a Windows only application, but there are many Linux based SQlite browsers available. Just beware that SQLite Browser on SourceForge uses a version of the SQLite package that is too old to read the current Firefox files..


text:
Q: Best way in Java to convert a double (representing a price) to a long with a price scale of 8 In Java code where a double is used to represent a price, what is the best way to convert the double to a long with a price scale of 8? For example, {Double} 17.99 would convert to {Long} 1799000000. The double may contain 2 to 4 decimal places.
Simple code such as the following sometimes works correctly:
 Double dprice = 17.99;
 Long lprice = (long) (dprice * 100000000);

However, for known reasons (floating point guide), it may create an unexpected result. For example, in one test {Double} 17.99 converts to {Long} 1798999999.
What are the best options in Java to safely do this conversion? Is BigDecimal necessary in this case?

A: In order to keep the precision, as Andy Turner pointed out in the comments, you have to use BigDecimals when doing the multiplications, etc, until the very end. The following should work:
import java.math.BigDecimal;
import java.math.RoundingMode;

class Main {
  public static void main(String[] args) {
    BigDecimal dprice = BigDecimal.valueOf(17.99).setScale(2, RoundingMode.HALF_UP);
    Long lprice = dprice.multiply(BigDecimal.valueOf(100000000)).longValue();
    System.out.println(lprice);
  }
}

The setScale call can be used to set the exact amount of decimal digits you would like to keep.


text:
Q: how do I check & change brick`s status in Javascript? I make brick-breaker game.
making brick`s row = 3, column = 5.
I want to make bricks(their status = 2) in row[0]
and change their status, color if they collide with ball.
(if their status = 2, change their status = 1 & color = "gray tone")
but my code does not correctly works.
I am trying to fix it, but it does not easy.
here is my code:
(Omit variable declaration & irrelevant function.)
function init(){
    canvas = document.getElementById("myCanvas");
    canvas.width = 500;
    canvas.height = 480;
     if (canvas == null || canvas.getContext == null) return;
    ctx = canvas.getContext("2d");
    ballColor = "black";
    ballRadius = "30";
    changeBallColor();
    changeBallRadius();

    x = canvas.width/2;
    y = canvas.height-30;
    dx = 3;
    dy = -3;

    paddleHeight = ballRadius;
    paddleWidth = 300;
    paddleX = (canvas.width-paddleWidth)/2;
    rightPressed = false;
    leftPressed = false;

    brickRowCount = 3;
    brickColumnCount = 5;
    brickWidth = 80;
    brickHeight = 40;
    brickPadding = 13;
    brickOffsetTop = 10;
    brickOffsetLeft = 20;

    bricks = [];
    for(var c=0; c<brickColumnCount; c++) {
        bricks[c] = [];
        for(var r=0; r<brickRowCount; r++) {
            bricks[c][r] = { x : 0, y : 0, status : 1 };
            if(r==0) {
                bricks[c][r] = { x: 0, y : 0, status : 2 };
            }
        }
    }

    s = 0; //score.
    lives = 2;
}

function collisionDetection() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
      var b = bricks[c][r];
      if(b.status == 2) {
        if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
          dy = -dy;
          b.status = 1;
        }
      }
      else if(b.status == 1) {
        if(x > b.x && x < b.x+brickWidth && y > b.y && y < b.y+brickHeight) {
          dy = -dy;
          b.status = 0;
          s++;
          document.getElementById("score").innerHTML=s;
          if (s == 15) {
            level2();
          }
          if (s == 30) {
            level3();
          }
          if (s == 45) {
            gameClear();
          }
        }
      }
    }
  }
}

function drawBricks() {
  for(var c=0; c<brickColumnCount; c++) {
    for(var r=0; r<brickRowCount; r++) {
        var b = bricks[c][r];
      if(b.status == 2) {
        var brickX = (c*(brickWidth+brickPadding))+brickOffsetLeft;
        var brickY = (r*(brickHeight+brickPadding))+brickOffsetTop;
        bricks[c][r].x = brickX;
        bricks[c][r].y = brickY;
        ctx.beginPath();
        ctx.rect(brickX, brickY, brickWidth, brickHeight);
        ctx.fillStyle = "red";
        ctx.fill();
        ctx.closePath();
      }
      else if(b.status == 1) {
        var brickX = (c*(brickWidth+brickPadding))+brickOffsetLeft;
        var brickY = (r*(brickHeight+brickPadding))+brickOffsetTop;
        bricks[c][r].x = brickX;
        bricks[c][r].y = brickY;
        ctx.beginPath();
        ctx.rect(brickX, brickY, brickWidth, brickHeight);
        ctx.fillStyle = "EAEAEA";
        ctx.fill();
        ctx.closePath();
      }
    }
  }
}

function draw() {
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    drawBall();
    drawPaddle();
    drawBricks();
    collisionDetection();

    if(x + dx > canvas.width-ballRadius || x + dx < ballRadius) {
    dx = -dx;
   }

   if(y + dy < ballRadius) {
    dy = -dy;
   }

   else if(y + dy > canvas.height-ballRadius) {
    if(x > paddleX && x < paddleX + paddleWidth) {
        dy = -dy;
    }
    else {
      lives--;
      if(!lives) {
        alert("GAME OVER.");
        document.location.reload();
      }
      else {
        x = canvas.width/2;
        y = canvas.height-30;
        dx = 3;
        dy = -3;
        paddleX = (canvas.width-paddleWidth)/2;
       }
     }
   }

   if(rightPressed && paddleX < canvas.width-paddleWidth) {
        paddleX += 5;
   }
   else if(leftPressed && paddleX > 0) {
        paddleX -= 5;
   }

    x += dx;
    y += dy;
}

ball = setInterval(draw, 10);


text:
Q: Ios Google Map Cluster item click event not work I am working with Google Map for IOS .Where i have implemented clustering but cluster and cluster item marker click event not work . But individual google map marker click event is working .
Here is my full code
import UIKit
import GoogleMaps
import Alamofire
import SwiftyJSON

let kCameraLatitude = 22.3475
let kCameraLongitude = 91.8123

/// Point of Interest Item which implements the GMUClusterItem protocol.
class POIItem: NSObject, GMUClusterItem {
    var position: CLLocationCoordinate2D

     var currencies = "currencies";
     var phone = "phone";
     var dateTime = "dateTime";
     var location = "location";
     var link = "link";
     var exchangeLimits = "exhangeLimits";
     var id = "id";
     var updated_at = "updated";
     var operationName = "opeationName";
     var email = "email";
     var address = "address";
     var createdAt = "createdAt";
     var workingDays = "workingDays";
     var longitude = "longitude";
     var latitude = "latitude";
     var exchange = "exChange";

    init(position: CLLocationCoordinate2D, operationName: String) {
        self.position = position
        self.operationName = operationName
    }
}

class FirstViewController: UIViewController  , GMUClusterManagerDelegate, GMSMapViewDelegate{
    private var mapView: GMSMapView!
    private var clusterManager: GMUClusterManager!

    override func loadView() {
        let camera = GMSCameraPosition.camera(withLatitude: kCameraLatitude,
                                                          longitude: kCameraLongitude, zoom: 6)
        mapView = GMSMapView.map(withFrame: CGRect.zero, camera: camera)
        mapView.delegate = self
        self.view = mapView

    }

    override func viewDidLoad() {
        super.viewDidLoad()

        // Set up the cluster manager with default icon generator and renderer.
        let iconGenerator = GMUDefaultClusterIconGenerator()
        let algorithm = GMUNonHierarchicalDistanceBasedAlgorithm()
        let renderer = GMUDefaultClusterRenderer(mapView: mapView, clusterIconGenerator: iconGenerator)
        clusterManager = GMUClusterManager(map: mapView, algorithm: algorithm, renderer: renderer)

        getAllMapsData()

        clusterManager.cluster()

        // Register self to listen to both GMUClusterManagerDelegate and GMSMapViewDelegate events.
        clusterManager.setDelegate(self, mapDelegate: self)

    }

    func mapView(_ mapView: GMSMapView, didTapAt coordinate: CLLocationCoordinate2D) {
        print("You tapped at \(coordinate.latitude), \(coordinate.longitude)")

        var alert = UIAlertController(title: "Choose Media type" , message: "post any" , preferredStyle: .actionSheet);

        var photos = UIAlertAction(title : "Photos" , style: .default , handler: nil)
        var videos = UIAlertAction(title : "Videos" , style: .default , handler: nil)

        var cancel = UIAlertAction(title : "Calcel" , style: .default , handler: nil)
        alert.addAction(photos)
        alert.addAction(videos)
        alert.addAction(cancel)
        present(alert, animated: true , completion: nil)

    }

    // MARK: - GMUClusterManagerDelegate
    func clusterManager(clusterManager: GMUClusterManager, didTapCluster cluster: GMUCluster) {
        let newCamera = GMSCameraPosition.camera(withTarget: cluster.position,
                                                           zoom: mapView.camera.zoom + 1)
        let update = GMSCameraUpdate.setCamera(newCamera)
        mapView.moveCamera(update)
    }

    // MARK: - GMUMapViewDelegate
    func mapView(mapView: GMSMapView, didTapMarker marker: GMSMarker) -> Bool {
        if let poiItem = marker.userData as? POIItem {
            NSLog("Did tap marker for cluster item \(poiItem.operationName)")
            print("clicked cluster")
        } else {
            NSLog("Did tap a normal marker")
            print("clicked marker")
        }
        return false
    }

    var allDataList = [[String:AnyObject]]()

    public func getAllMapsData(){

        Alamofire.request("http://coinatmfinder.com/getDatas").responseJSON { response in

            if let JSON = response.result.value {

                self.allDataList = JSON as! [[String : AnyObject]]

                for eachData in self.allDataList {

                    //let allDataModel = AllDataModel()

                   // allDataModel.address = eachData["address"] as! String

                    var operatorName = eachData["operatorName"]

                    var lat = eachData["latitude"]
                    var latDouble = 0.0;

                    if let lats = lat {
                        latDouble  = (lats as! NSString).doubleValue
                    }

                    var longs = eachData["longitude"]

                    var longsDouble = 0.0;

                    if let longs = longs {
                        longsDouble  = (longs as! NSString).doubleValue
                    }

                    let item = POIItem(position: CLLocationCoordinate2DMake(latDouble, longsDouble), operationName: operatorName as! String)

                    self.clusterManager.add(item)

                }

                print("JSON: \(self.allDataList)")
            }
        }

    }

}

A: Was working on this today and also tried the same function and found it wasn't working because it was the wrong one. Instead of:
func clusterManager(clusterManager: GMUClusterManager, didTapCluster cluster: GMUCluster) {
    let newCamera = GMSCameraPosition.camera(withTarget: cluster.position,
                                                zoom: mapView.camera.zoom + 1)
    let update = GMSCameraUpdate.setCamera(newCamera)
    mapView.moveCamera(update)
}

Try this one: (it looks almost the same as the one above except it has a return type of Bool).
func clusterManager(_ clusterManager: GMUClusterManager, didTap cluster: GMUCluster) -> Bool {
    let newCamera = GMSCameraPosition.camera(withTarget: cluster.position,
                                             zoom: mapView.camera.zoom + 1)
    let update = GMSCameraUpdate.setCamera(newCamera)
    mapView.moveCamera(update)

    return false
}

(Using Swift 3)


text:
Q: Counting how many MySQL fields in a row are filled in Codeigniter I need to write a method that would allow me to calculate how many fields in a row have been filled by a user.
For example:
 User    Name    Age    Country    Gender    Height
    1       Mike    34     USA        Male      6
    2       Bill    23     CA                   5
    3       Jane    31     USA

In the above example, I would like to query the database and return a value that would reflect the degree of completion of the user's record. Such as:
User 1 = 100% complete
User 2 = 80% complete
User 3 = 60% complete

I am using Codeigniter 3. Can you guys help me.

A: You may try like this way ::
$result = mysql_query('SELECT * FROM `MyTable`');
while($row = mysql_fetch_row($result)){
$empty_count = 0;
$count = count($row);
for($i = 0; $i < $count; $i++)
    if($row[$i] === '' || $row[$i] === 'NULL')
        $empty_count++;
echo 'User '.$row[0].' = '.((int)(100*(1-$empty_count/($count-1)))).'% complete';
}

Hope it will work.

A: Make a method pass a parameter in method
  function profileCompleted($user){
         $percentage = 0;
         $sql ="SELECT * FROM user  WHERE user=$user"
       $query = $this->db->query($sql);

      if ($query->num_rows() > 0)
          {
            $notEmpty =   0;
            $totalField =5;
            foreach ($query->result() as $row)
              {
               $notEmpty +=  ($row->Name != '') ? 1 : 0;
                //do with all field
              }
          $percentage = $notEmpty/$totalField *100;
          }
        return $percentage.'%';
    }

A: I think it can be done by SQL query also:
SELECT id,
(
    CASE name WHEN NULL THEN 0 ELSE 1 END
    +
    CASE WHEN age IS NULL THEN 0 ELSE 1 END
    +
    CASE country WHEN '' THEN 0 ELSE 1 END
    +
    CASE gender WHEN '' THEN 0 ELSE 1 END
    +
    CASE WHEN height IS NULL THEN 0 ELSE 1 END
) * 100 / number_of_fields AS complete
from your_table;


text:
Q: Java - getting the signature of a method in an interface, and the same for its Proxy implementation I'm looking for a way to extract the essence of a signature in Java. The reason is that I want to use the signature as a unique key in a Map for my java.lang.reflect.Proxies.
With this code:
public interface MyInterface {
  public int compute(String s);
}

...
public static void main (String... args) throws Exception {
  InvocationHandler handler = ...;
  MyInterface i = (MyInterface) Proxy.newProxyInstance(
      Beans.class.getClassLoader(),
      new Class<?>[] { MyInterface.class },
      handler);

  Method m1 = MyInterface.class.getMethod("compute", String.class);
  Method m2 = i.getClass().getMethod("compute", String.class);
  System.out.printf("%b%f", m1.equals(m2));
}

The result is obviously false.
This code is not the code I'll use, because I need it inside the InvocationHandler, but I'm wondering if regarding the Proxy implementations and the interface, getting method.getName() and method.getParameterTypes() is enough or I should use method.getTypeParameters() and method.getParameterAnnotations() as well?
In short: how to get a method signature that is the same for an interface and its java.lang.reflect.Proxy implementations?

A: I think you want the Method passed in the InvocationHandler.
package playtest;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;
import static junit.framework.Assert.*;

interface MyInterface {
    void run();
    void about();
    void run(String j);
}

public class TestProxyClass {
    @Test
    public void testDeclaringClass() throws Exception {
        final Map<Method, Runnable> actions = new HashMap<Method, Runnable>();

        actions.put(MyInterface.class.getMethod("run"), new Runnable() {

            @Override
            public void run() {
                System.out.println("run");
            }

        } );
        actions.put(MyInterface.class.getMethod("run", String.class), new Runnable() {

            @Override
            public void run() {
                System.out.println("run string");
            }

        } );
        actions.put(MyInterface.class.getMethod("about"), new Runnable() {

            @Override
            public void run() {
                System.out.println("about");
            }

        } );

        MyInterface face = (MyInterface) Proxy.newProxyInstance(getClass().getClassLoader(),
                new Class<?>[] { MyInterface.class }, new InvocationHandler() {

                    @Override
                    public Object invoke(Object proxy, Method method,
                            Object[] args) throws Throwable {
                        actions.get(method).run();
                        return null;
                    }

                } );

        face.run();
        face.about();
        face.run("Hello");
    }
}

A: What about using the result of Method.toGenericString as the key? The string it returns includes all details of the signature, as far as I can tell.
Another thing that might be useful is: Method m2 = i.getClass().getMethod("compute", String.class).getDeclaringClass().getMethod("compute", String.class);. That might result in m1.equals(m2) returning true.

A: I just had a bug with code doing this, I took name, genericReturnType and genericParameterTypes, and I had problems when working with proxies because I lost the generic information.
I switched to use name, returnType and parameterTypes and it works fine...
I also considered using declaringClass but I removed it and don't remember exactly how I did this...


text:
Q: Is there any way to track all costs for a specific Compute Engine Machine? I find it really hard to control my GCP costs considering the invoice has a lot if items that are not easily linked to a specific machine. Is there any way to do this?
I have tried the billing reports, but I can only get the detail by SKU (XX RAM or YY vCPUs) but its really hard to link this SKU to specific Machines.
For clarity, I wish to know to total cost (sum of all SKUs) of each specific Machine.

A: I would recommend using labels. When you label a resource, such as a VM, the charges for that resource will be marked with your label in the detailed billing export. This export can be configured to write to either BigQuery or GCS.
You can label each machine individually (which sounds like it would cover your case), or groups of resources. One common practice is to put different labels for production and testing, allowing you to track and search the different environments.
Once the labels are configured to your liking and the export is enabled, you'll be able to query and summarize the data based on the labels you've set.
To JJJ's point, you may consider using GCP's billing support chat in the future if you have more billing issues.


text:
Q: How to export a list of intersections of 2 datasets of boundries/polygons I am using the following datasets:

*

*NYC Zip Codes: https://data.cityofnewyork.us/Business/Zip-Code-Boundaries/i8iw-xf4u

*NYC City Council Districts: https://data.cityofnewyork.us/City-Government/City-Council-Districts/yusd-j4xi/data
I want to generate 2 lists, the zip codes in or partially in each council district, and the council districts in or partially in each zip code.
So far I have tried this in Carto but I am open to other solutions.
I have found examples of intersecting a second layer of data with points, but nothing about intersecting 2 layers of data where both data sets are boundaries.
Is this possible?

A: You need to apply a SQL query similar to this one:
SELECT
   d.coun_dist as district,  --- z.zipcode as zipcode
   array_agg(z.zipcode) as zipcodes --- array_agg(d.coun_dist) as districts
FROM
  nyc_zipcodes z, nyc_districts d
WHERE
  st_intersects(z.the_geom, d.the_geom)
GROUP BY 1

Result:
| district |                         zipcodes                   |
|----------|:--------------------------------------------------:|
|    48    |  ["11229","11235","11224","11210","11230","11223"] |
|    18    |  ["10460","10472","10473","10474","10462","10461"] |
|    ...   |                         ...                        |

Do not forget to replace nyc_zipcodes and nyc_districts with your dataset names. Also notice that you will need to run the query twice, replacing the columns selected with the code after the comments ---. You can learn more about PostGIS ST_Intersects operation and PostgreSQL array_agg method reading their documentation.


text:
Q: How to use symmetric key to encrypt and sign SOAP using WSS4J I need to build web-service client application using Axis 1.4 that will access third party system (Web service Producer).
In order to send valid request to third party system I need to encrypt and sign the SOAP request before sending it to them.
I make use of wss4j 1.5 to do this task where I follow the steps in this link:
Calling an OWSM protected service with Axis 1.4 and WSS4J
What I understand that:
1- To encrypt the SOAP I need to use third party public key and they will decrypt it using their own private key.
2- To sign the SOAP I need to use my own private key and they should verify the signature using my public key that I need to share it with them.
I did that but I am receiving the error
  faultString: Did not understand "MustUnderstand" header(s)

From third party end. After checking with third party team they said:
"We use "Username authentication with symmetric key", so we do not maintain any client certificates at our trust store. There is a single shared key used for both signing and encryption. Hence you need to do signing and encryption using our certificate."
This response does not make sense to me. I understand that I need to use third party certificate (i.e. public key) to encrypt the SOAP Request.
But how can I use the same public key - which is the only certificate shared by them - to sign SOAP Request ?
I believe I need a private key in order to do that.
Do I need their private key to do that? Any clarification will be helpful.


text:
Q: Get the selected items inside a List Box and assign them to a SharePoint text field Defult property I have a ListBox inside my Power Apps screen, as follow:

And I have a hidden text box, where I want to define the Default value for the text box to be the selected items (if any) from the ListBox separated by ",".
So from the above screen the Default value for the text box should be "Wireless Mouse/Keyboard", while if the user select all the values inside the List Box, then the Default value for the textbox should be "Docking Station, Wireless Mouse/Keyboard, Monitors ".
Any advice on this please?

A: Use below formula in Default property of text box control:
Left(
    Concat(
        ListBox1.SelectedItems,
        Value & ", "
    ),
    Len(
        Concat(
            ListBox1.SelectedItems,
            Value & ", "
        )
    ) - 1
)

Where ListBox1 is the name of ListBox control.
Output:


text:
Q: How to get data from a variable parameter list? I have following function with only a variable parameter list (Without supporting/fixed  argument). Is it possible to get values passed to this function? I am using ANSI format.
Foo( ... )
{
}

Adding some more points for clarity. In my special case, the number of arguments and their types are stored in a .xml file as configurations which can be accessed from Foo().
Edit:
I am adding some information from my trial and error. I partially succeeded to get data from list as follows.
va_list Arguments;

Arguments = (( va_list ) &Arguments + Offset );

Data = va_arg( Arguments, Type );

Idea I put behind this is directly reading data from stack. Here the problem factor is Offset whose value is varying according to the number of arguments I am passing into Foo(). For example, when I am passing a pointer only, I put its value as 16 to get correct result. I found this values with trial and error. I want to derive Offset from parameter list that my program can run without any runtime failure in all possible cases. Can someone tell me the relation between this Offset and the parameter list.
I am using Visual Studio 2008 for developing this.

A: Variadic functions with no fixed arguments are not supported in modern C.  However, for backwards compatibility purposes, they are supported by varargs.h.  See also this man page, which provides the following example code.  Note the K&R-style function definition required by varargs.
#include <varargs.h>
void foo(va_alist) va_dcl {
    va_list ap;
    va_start(ap);
    while(...) {
        ...
        x = va_arg(ap, type);
        ...
    }
    va_end(ap);
}

A: Variadic functions require fixed arguments in modern C because functions should be able to sort out what to do from the arguments. For instance, printf() knows what arguments to retrieve from the stack based on the format string. If you omit these fixed parameters, there is no checking on the correctness of the arguments.
If Foo() performs a lookup of some kind, then it would make sense to pass either xml reference or the values to look up as a parameter (or better: both).
Going back to K&R style C is quite nasty. Possibly you can change the splitting between parser and interpreter Foo() to use a more clear interface.


text:
Q: Preventing Enter from Submitting form in Safari I have the following code on my page:
$('form.enter-doesnt-submit').submit(function () {
    console.log($(document.activeElement));
    if($(document.activeElement).attr('type') == 'submit') {
        console.log
        return true;
    } else {
        console.log("Prevented enter from submitting the form.");
        return false;
    }
});

Which I'm fairly certain I got from stackoverflow a long time ago.  It works fine, just not in Safari.  The reason being that when I log out document.activeElement it gives me the entire page, so of course the attribute type is not submit and therefore the form doesnt submit even when you are clicking the submit button.
I need to be able to prevent enter submitting on my form because they are online tests, and if the user is writing an answer and accidentally presses enter before the form is complete then they are marked incorrectly as they didn't actually finish the test.
Can anyone help me with some way of preventing enter from being pressed on Safari?

A: Okay I solved this by coming at it in another way, by targeting the inputs in the form instead:
$('form.enter-doesnt-submit input[type=text]').keypress(function (e) {
    if(e.keyCode == 13) {
        e.preventDefault()
    }
});

Pressing enter in a textarea doesnt submit a form by default, so its just the inputs that need preventing.  Now my submit button works in safari and in chrome.


text:
Q: How to show maps in an android app, if google play services is not installed on a phone I have to show google maps v2 in my android app. Is there any way to show the map even if google play services is not installed on device?

A: If the Google Play Services application is not installed on your user's device, you may fall back to other providers, e.g. static maps from Google or osmdroid.

A: No there is not since google maps is part of google play services. the only thing you can do is side-load google play services on the device or if the device has access to the play store you start an intent that takes them to where they can install it

A: Android - Google Map v2 - need update google play service on device
You need google play services to show map, but follow the link for checking and downloading of google play services


text:
Q: Html.ValidationMessageFor not displaying at all I have the following form:
<form action="~/buy-online" method="get" class="buy-online-form clearfix" autocomplete="off" id="buy-online-search">

        @Html.LabelFor(m => m.CustomerPostcode, new { @class = "infield" })
        @Html.TextBoxFor(m => m.CustomerPostcode, new { @class = "textbox" })
        <input type="submit" value="Buy Online" id="find-retailer-button" class="button" />

</form>

@Html.ValidationMessageFor(m => m.CustomerPostcode)

Which works fine and will display an error message when submitted without jQuery, but when I add the jQuery validate scripts (v 1.11.1):

It stops the form submitting but doesn't display the error message
My property is marked like so:
[DisplayName("Enter your full postcode")]
[Required(ErrorMessage = "Please enter your full postcode")]
public string CustomerPostcode { get; set; }

And the html renders like this:
<input class="textbox" data-val="true" data-val-required="Please enter your full postcode" id="CustomerPostcode" name="CustomerPostcode" type="text" value="" />

If I inspect the input when I hit submit it is adding the class input-validation-error to the textbox but just not updating the validation message.
All the posts that I have checked on this problem just say to include the scripts so I'm at a loss as to why the message is not showing.
I've even tried adding the jquery.unobtrusive-ajax.js script but that didn't seem to do anything either.  Any help would be appreciated, thanks.

A: You need to include the @Html.ValidationMessageFor(m => m.CustomerPostcode) within the form tags for jquery.validate.unobtrusive to work.


text:
Q: AttributeError: Can't get attribute 'TunerInternal._validate_overwrite_trainable' on When I am trying to run a Basic Ray Model in our server, Tune Code is breaking. I didnt understand the issue and I didnt find any useful information in internet. Can any one help me with it. FYI, I am able to run them properly when I use local ray cluster which I setup in my local machine.
AttributeError: Can't get attribute 'TunerInternal._validate_overwrite_trainable' on <module 'ray.tune.impl.tuner_internal' from '/home/ray/anaconda3/lib/python3.7/site-packages/ray/tune/impl/tuner_internal.py'>
import ray
from ray.air.config import ScalingConfig
from ray.train.xgboost import XGBoostTrainer

trainer = XGBoostTrainer(
    scaling_config=ScalingConfig(
        # Number of workers to use for data parallelism.
        num_workers=2,
        # Whether to use GPU acceleration.
        use_gpu=False,
    ),
    label_column="y",
    num_boost_round=20,
    params={
        # XGBoost specific params
        "objective": "binary:logistic",
        # "tree_method": "gpu_hist",  # uncomment this to use GPUs.
        "eval_metric": ["logloss", "error"],
    },
    datasets={"train": traindata_ray},
   # preprocessor=preprocessor,
)
result = trainer.fit()
print(result.metrics)

Reference: https://docs.ray.io/en/latest/train/train.html

A: This is likely due to a ray version mismatch.  _validate_overwrite_trainable is available in nightly wheels but not in the latest 2.2.0 release.
Can you verify that you are using the same version of ray across your local machine and cluster?


text:
Q: Custom HQL Function with param and single quote I'm trying to write a custom function in hibernate to use ts_vector (postgres), my code so far:
public class PostgresSQLFTSFunction implements SQLFunction {

    static final Logger LOG = LogManager.getLogger();

    @Override
    public boolean hasArguments() {
        return true;
    }

    @Override
    public boolean hasParenthesesIfNoArguments() {
        return false;
    }

    @Override
    public Type getReturnType(Type firstArgumentType, Mapping mapping) throws QueryException {
        return new BooleanType();
    }

    @Override
    public String render(Type firstArgumentType, List arguments, SessionFactoryImplementor factory) throws QueryException {
        if (arguments == null || arguments.size() < 2) {
            throw new IllegalArgumentException("The function must have at least 2 arguments");
        }

        String fragment, ftsConfig, field, value;

        if (arguments.size() == 3) {
            ftsConfig = (String) arguments.get(0);
            field = (String) arguments.get(1);
            value  = (String) arguments.get(2);
            fragment = "to_tsvector(" + ftsConfig + ", unaccent(" + field + ")) @@ to_tsquery(" + ftsConfig + ", unaccent(" + value + "))";
        } else {
            field = (String) arguments.get(0);
            value = (String) arguments.get(1);
            fragment = "to_tsvector(unaccent(" + field + ")) @@ " + "to_tsquery('" + value + ":*' )";
        }

        LOG.info(fragment);

        return fragment;
    }
}

My repo:
@Query(value = "from City c where fts_partial(c.name, :cityName) = true")
List<City> getPartialByName(@Param("cityName") String cityName);

And registering the function:
public class SqlFunctionsMetadataBuilderContributor implements MetadataBuilderContributor {

    @Override
    public void contribute(MetadataBuilder metadataBuilder) {
        metadataBuilder.applySqlFunction("fts_partial", new PostgresSQLFTSFunction());
    }
}

The output query generated by Hibernate is:
select city0_.id as id1_0_, city0_.created_at as created_2_0_, city0_.updated_at as updated_3_0_, city0_.version as version4_0_, city0_.lat as lat5_0_, city0_.lng as lng6_0_, city0_.name as name7_0_, city0_.state_id as state_id8_0_ from cities city0_ where to_tsvector(unaccent(city0_.name)) @@ to_tsquery('?:*' )=true

The problem here is that to_tsquery('?:*' ) does not translate the question mark to the named param (cityName), because it is included in single quotes, but the single quote here is necessary, otherwise the query does not work.
For instance, the query that works is:
select city0_.id as id1_0_, city0_.created_at as created_2_0_, city0_.updated_at as updated_3_0_, city0_.version as version4_0_, city0_.lat as lat5_0_, city0_.lng as lng6_0_, city0_.name as name7_0_, city0_.state_id as state_id8_0_ from cities city0_ where to_tsvector(unaccent(city0_.name)) @@ to_tsquery('vi:*')=true;

So, the cityName question mark should be translated by HQL to 'vi' in the above example.
How can I achieve that?
Thanks!