Sine-based Tiled Procedural Bump

Question: I am trying to implement this formula to generate bump but I am facing some issue. The result doesn't look the same it's much darker.

Here is my result (without same parameters) but it is much darker and I don't get why.

And here is the associated code.
// randx, randy and frequencies are array with some random values for each sin wave.
for (int x = 0; x < _width; ++x)
{
    for (int y = 0; y < _height; ++y)
    {
        float color = 0.0f;
        for (int i = 0; i < _iterations; ++i)
        {
            val += Mathf.Sin(Mathf.Sqrt(Mathf.Pow(x - randx[i], 2.0f) + Mathf.Pow(y - randy[i], 2.0f)) * 1.0f / (2.08f + 5.0f * frequencies[i]));
        }
        color /= (float)_iterations;
    }
}

Any idea why I am getting this result ?
Thanks a lot !
EDIT: Thanks to @trichoplax it works by doing this.
float tmp = Mathf.Sin(Mathf.Sqrt(Mathf.Pow(x - randx[i], 2.0f) + Mathf.Pow(y - randy[i], 2.0f)) * 1.0f / (2.08f + 5.0f * frequencies[i]));
tmp = tmp * 0.5f + 0.5f;
val += tmp;

Comment: Pro tips, unrelated to your question: you can expect `(foo * foo)` to be a lot faster than `pow(foo, 2.0f)`; if your data is organized row by row (as opposed to column by column), you should swap the for loops to traverse data in a more coherent order.
Answer: As you are taking the mean of a number of sine waves, your colour values will range from -1 to 1. From your example image, it looks like only the top half of this range of values (from 0 to 1) is resulting in colour, with everywhere else remaining black.
If whatever you are using to display the result can only handle positive values, then you will need to convert the result to the correct range of values. For example, to convert from the range [-1 to 1] into the range [0 to 1], you would add 1 and divide by 2.
In the context of your example code, this could be by following the line
color /= (float)_iterations;

with
color += 1;
color /= 2;

Sine-based Tiled Procedural Bump


Why js text to speech not taking more charachters?

Question: Here i am using js text to speech with SpeechSynthesis and its working fine with limited amount of words/sentences, but the time i add all my blog paragraph which is more then 2-3k words its not working, its converting till some part and automatically being stop. So how can i add unlimited no of words or total page content converted to speech.
NOTE: I tried js speak() also, which worked fine but i want a pause/stop option so i used this. So if there any other working way then please suggest.

const msg = new SpeechSynthesisUtterance();
let voices = [];
const voicesDropdown = document.querySelector('[name="voice"]');
const options = document.querySelectorAll('[type="range"],[name="text"]');
const speakButton = document.querySelector('#speak');
const stopButton = document.querySelector('#stop');

msg.text = document.querySelector('[name="text"]').value;

function populateVoices() {
  voices = this.getVoices();
  voicesDropdown.innerHTML = voices.map(voice => `<option value="${voice.name}">${voice.name}(${voice.lang})</option>`).join('');
}

function setVoice() {
  msg.voice = voices.find(voice => voice.name === this.value);
  toggle();
}

function toggle(startOver = true) { //true is for it will not stop if language changes
  speechSynthesis.cancel();
  if (startOver) {
    speechSynthesis.speak(msg);
  }
}

function setOption() {
  //                console.log(this.name, this.value);
  msg[this.name] = this.value;
  toggle();
}

speechSynthesis.addEventListener('voiceschanged', populateVoices);
voicesDropdown.addEventListener('change', setVoice);
options.forEach(option => option.addEventListener('change', setOption));
speakButton.addEventListener('click', toggle);

  <select name="voice" id="voices">
    <option value="">Select a voice</option>
  </select>
  Rate:
  <input type="range" name="rate" min="0" max="3" value="1" step="0.1">

  Pitch:
  <input type="range" name="pitch" min="0" max="2" value="1" step="0.1">

  <textarea name="text"></textarea>
  <button id="stop">Stop!</button>
  <button id="speak">Speak</button>

Comment: Have you thought about splitting your text and passing smaller chunks to `speak()`
Answer: It's a known bug. The workaround is to issue a resume every 14 seconds.
You can add this immediately after the line speechSynthesis.speak(msg):
let r = setInterval(() => {
  console.log(speechSynthesis.speaking);
  if (!speechSynthesis.speaking) {
    clearInterval(r);
  } else {
    speechSynthesis.resume();
  }
}, 14000);

Comment: @Rk.Sahoo Thanks for accepting. If you haven't already please upvote the question I've linked to under 'workaround', cheers.


How to remove many HTML divs + closing tags efficiently in visual studio code?

Question: After noticing an unnecessary parent container in my HTML, I want to remove all of it in a headache-free and fast way. Below is a sample of what my code looks like. I want to remove the div with class="remove-this-container" and the children within are varied (I want to keep the children).
I understand I can highlight and use ctrl+d to select all the same divs, but how would I remove the closing tag with it as well?

Comment: @konekoya OP points out that each occurrence has a variable number of children which would make positioning multiple selection cursors unworkable.
Comment: I thought "and the children within are varied" refers to the `.remove-this-container` div, not the `.container` div?
Comment: Use the element navigation bar at the bottom of the editor to select entire elements, including their outer tags.
Comment: If that `.container` div is always there, you can select it first with `cmd + shift + L` and move all cursors to where you want to delete and simply delete them.
Answer: Emmet has a command called Remove Tag
As you mentioned, you can use Ctrl + D to select all the occurrences of the tag you are looking for.
Using the command palette Ctrl + Shift + P, search Emmet: Remove Tag and select it.
That should delete the opening tag, as well as each closing tag for each of your cursors


Settings xorg.conf to be used with VESA driver?

Question: I have an brand new installation of Ubuntu 9.10 (karmic version) where everything is fine except the video resolution. In Ubuntu 9.10, the file xorg.conf is empty by default.
I'm using an onboard video card, and Ubuntu can not find the right resolution for me. It always uses 800x600, but I need at least 1024x768. Also, my monitor is listed as Unknown Type.
Ubuntu did find the right resolution when I changed the monitor to a Samsung monitor.
By the way what are the generic settings to put inside xorg.conf?
What is the settings for Refresh Rate, for example, I got a resolution of 1280x800, but the Refresh Rate generally between 60 ~ 80 htz is ZERO on my resolution..
In 1024 resolution my Refresh Rate is 75 htz..
What is going on with my resolution and how to modify the Refresh Rate??
Many Thanks!
Answer: First, I would not install 9.10 (karmic) especially not as "brand new  installation" since its support ends within about two months: http://en.wikipedia.org/wiki/List_of_Ubuntu_releases#Release_history
Second: modern Xorg releases have the goal to work without any configuration file, just run-time detection is enough in most cases. Sure, if there is /etc/X11/xorg.conf it will be used still. You can generate one with Xorg -configure command (as root, of course from a text VT, not from running X), and you may modify it a bit later then, if you need to customize it. As far as I remember that command will generate the config file in your home with name like xorg.conf.new, so you need to move it to the right place too.
Comment: sorry about "brand new installation" hahaha ... but  I just picked up the first linux I saw in my case and did the installation.. and Unfortunattley the ubuntu do not recognize my video monitor, then I gave a command sudo gedit /etc/X11/xorg.conf and Added some lines in there, and everything okay, but the Refresh rate shows to me as 0 (ZERO) in a resolution of 1280x800, when I get back to 1024x768 all is fine, Refresh rate change to 75 hzt.. Do you have any idea why is it happening?
Comment: What is odd for me: why do you want to use the VESA driver? Isn't your card supported at all just with vesa? What kind of hardware it, exactly? (you can use `lspci` command to get information about devices on the PCI & related bus)
Comment: it is an onboard driver, a generic driver VESA. It is an old PC with intel celeron Processor and onboard drivers. I still have the problem with the Refresh Rate of my monitor.. it should be something between 40 - 60 Hz and never up to 75 Hz ... and can not solve this issue.. any idea?


What is this pipe called, and how does it work?

Question: I recently saw a plumbing setup where a 2" pipe was run from a bend in the 4" toilet return.  The 2" pipe bent upwards to meet the floor next to the toilet, where it was capped off with a removable cover.
In case of a clog, apparently the plumber uncaps and pushes air (or water?) through this pipe (or vent? valve?) to purge the clog.
First of all, what is the correct terminology for this apparatus?
And I hope it's not outside of the scope of the question to also ask does this thing function as a vent?
Will it have a one-way valve to prevent the elevated water in the toilet from rushing out when it's uncapped?  (cap is level with the floor next to the toilet)
Here's an ugly sketch of the thing:
Answer: A capped opening in a sewer line is called a clean-out, usually they are a 4" long bend wye with a cap on one branch so you can pull the cover and run a snake down the whole length of the main sewer line.
In this case, a 2" pipe would be a good size to run a snake down to clear any clogs downstream from the toilet. I'd guess that somebody didn't allow enough drop in the sewer line and added the pipe to allow shoving the solids out of a long, level area.
Sewer Auger (Snake) or a Water Bladder Clog Buster just in case you ever have to use it.
No, it's not a vent.

Comment: The water in the toilet is contained in a trap. The pond of water in the bottom has to flow uphill. If you look at the side of the toilet, you can trace the tube cast into the porcelain and see the "S" shape. You can take the cap off and nothing but sewer gas will come out, unless the line is blocked so badly that water above normal level in the toilet is caused by it and not a clog in the toilet trap. Now when you flush, expect water to come up out of that uncapped hole whether the line is clogged or not. And to reiterate @Monso, it's not a vent. Sewer Gas is explosive and causes suffocation.
Comment: OK thanks.  What's preventing the water in the toilet from overflowing when the cleanout is uncapped?
Comment: A Mop LOL (not so funny when its me with the mop tho)
Comment: You should never leave it uncapped because you'll be letting the sewer vapors constantly enter the house and it can cause you sickness. Water (and the sewage with it) will take the path of least resistance, so it happily travel further down a larger pipe (your drain) than try to go up a narrow pipe (your cleanout).
Comment: Thanks for the info fellas, I didn't mean *leave* it uncapped, I meant "at the time it is uncapped" for cleanout.  The trap example answers the question though.  Cheers!
Comment: Just a note I came across when researching the water bladder solution, which apparently inflates a bladder to block the pipe and then injects more water to pressurize the clog clear.  If the clog is not cleared when you deflate, all the pressurized water downstream comes back up past the deflated bladder and can come out of the pipe at the point you're servicing (and all over your floor).  Guess I'll go snake.
Comment: @Steve those bladders are an easy and quick way to remove a clog, but you have to be sure there's no where else for the water to go between the bladder and clog (up the vent, out another drain, etc). Otherwise, you're right, big mess.
Comment: Rule is always snake it first to mechanically break up the blockage and then use the bladder to wash it out.
Answer: That would be an odd location for a cleanout, since a plumber would likely pull the toilet and run a large auger directly down the toilet drain if you had a clog. It looks like a vent line that was installed but not attached to the vent stack (either in error or because you're looking at something while it's still under construction). When the toilet is at the end of a drain line, rather than installed after the sink/shower in a bathroom, you don't have a wet vent for the toilet so you need to install a dry vent.


Better keyboard shortcuts

Question: I'd like to press, for example, the Menu key and the output be as if I pressed Ctrl+R or another combination of keys. In other words, I'd like to set aliases for combos using the same graphical user interface (System Settings/Keyboard menu) provided by Ubuntu 16.04 to set/change keyboard shortcuts. Thanks in advance!
LE: I do not want to install Autokey, I want a builtin functionality as I already mentioned above. In plus, Ctrl+R does one thing inside a browser window and another thing inside a terminal window. I just want, for example, to press Menu key and Ubuntu to think I pressed Ctrl+R. That's all. I hope I was clear enough. Just a suggestion.
Answer: If you like to change the keyboard shortcuts of various operations then you can do it through settings.
Please follow the following steps.

Go to the system settings.
Click on "text entry."
Now go to the bottom right corner of the dialogue box and click on "keyboard settings."
There you will find the list of various shortcuts and what they do.
You can change the shortcuts from here.

Better keyboard shortcuts


PHP bad mail headers

Question: I want to send an email via the mail() function.
mail($to,$subject,$message) works fine.
But using mail($to,$subject,$message,$header) doesn't work.
The header is:
Date: Tue, 2 Jul 2013 15:01:49 +0200 +0200
Return-Path: firstname.lastname@example.com
From: "email@example.com"
Message-ID:
X-Priority: 3
X-Mailer: PHPMailer 5.2.4 (http://code.google.com/a/apache-extras.org/p/phpmailer/)
MIME-Version: 1.0
Content-Transfer-Encoding: 8bit
Content-Type: text/html; charset=UTF-8

What is wrong with my headers?
FYI, the headers are generated by PHPMailer.
The code I use to send it is:
$mail = new PHPMailer();
$mail->IsMail();
$mail->From = $from;
$mail->FromName = $from;
$mail->AddAddress($to);
$mail->IsHTML(true);
$mail->CharSet = 'UTF-8';
$mail->Subject = $subject;
$mail->Body = $message;
$mail->Send();

Comment: Why doesn't it work?  Error message? Nothing sent? Help us to help you.
Comment: Everything seems to work fine, except I don't receive an email. Thats the weird thing.
Comment: have you got access to the mailserver and logs?`have a look in the logs if mail is reveived at all
Answer: Have you tried to use another header?
I use
$header = "From: firstname.lastname@example.com \n";
$header .= "MIME-Version: 1.0 \n";
$header .= "Content-Type: text/html; charset=iso-8859-1; type=\"text/html\" \n";
mail($email,$betreff,$mailbody,$header)

and it works fine.
Comment: This fixed it for me using XAMPP PHP to "Test Mail Server Tool".
Answer: You need a mail server, that you may not have on your dev environment.
mail() and PHPMailer simply hand over your e-mail to a mail server, which will then proceed to actually send it to it's destination.
If you don't have a mail server available, no matter how good your code is, it simply won't do anything. Check for any return codes or exceptions that you may be missing (I'm not sure how PHPMailer indicates something went wrong, mail() does it by return code),
I never really used PHPMailer, but it seems to me that you're not setting an external server to relay the message, which means PHPMailer will default to the local machine.
A mail server isn't something you just install and configure in a couple of minutes, which I believe your local machine doesn't have.
So, here's what I think is happening:
1) You didn't set an external server, PHPMailer defaults to the local server.
2) You don't have a local mail server, which makes PHPMailer fail.
3) You're missing/ignoring $mail->Send()'s return code / thrown exception, which should tell you something went wrong.
Comment: Hi, as I told in the description, just `mail()` without headers works fine because I do have a local mail server. And for the return code of the Send() function: it doesn't show an error.

PHP bad mail headers


Scope of a callback function

Question: I want to implement a function which performs ajax requests (response is json) until there will be no "next" property in response. After that i need to perform some callback function. What is the best way for this? My code below doesn't work because of the wrong callback's scope, and i cannot imagine how to pass it correctly.

_requestPhotos = function(url, callback) {
  getYFContent(url, function(data) {
    // some actions

    if (!!data.next) {
      _requestPhotos(data.next, callback);
    } else {
      callback(smth);
    }
  });
};
Answer: There are no obvious errors from the script you've posted. For example, an equivalent test could look like this:
alertResult = function(text) {
   console.log("Result is: " + text);
}

doRecursive = function(data, callback) {
   if(!!data.next) {
      doRecursive(data.next, callback);
   } else {
      callback(data.value);
   }
}

var d = { value: 1, next: { value: 2, next: { value: 3 }}};

doRecursive(d, alertResult);

The log result is "Result is: 3", which is what you'd expect.
The error is elsewhere. How are you calling this the first time, what is the callback you're passing to it (and how is it defined) and what exactly does getYFContent do?
Comment: This is not just a recursive function. The problem is that "getYFContent" is ajax request function and all the actions are described in its second argument which is a callback function (like in $.get).
Comment: (cont) ...I want to fill "photos" array with proper values. To get them i should make requests consistently one after another. And this is the problem - getYFContent() calls recursively and callback (function which must perform after all requests are sent and we've got all the photoes) fn's scope is only first iteration.
Comment: Ah right - well can you add another argument to `getYFContent`? that way you can keep passing the callback around.

Scope of a callback function


Draw lines in openGL ES 1.0 with Xcode

Question: I am trying to draw some lines in my GLView, but it just doesn't do anything.
I'm using Xcode 4.5 for iOS 6.0 application.
This is my code:
<code>//Draw Axes
{

    const GLfloat lineX[] = {
        -100.0f, 0.0f, 0.0f, //point A
        100.0f, 0.0f, 0.0f //point B
    };
    const GLfloat lineY[] = {
        0.0f, -100.0f, 0.0f, //point A
        0.0f, 100.0f, 0.0f //point B
    };
    const GLfloat lineZ[] = {
        0.0f, 0.0f, -100.0f, //point A
        0.0f, 0.0f, 100.0f //point B
    };

    glEnableClientState(GL_VERTEX_ARRAY);
    glColor4f(1.0f, 0.0f, 0.0f, 1.0f); // opaque red
    glVertexPointer(3, GL_FLOAT, 0, lineX);
    glDrawArrays(GL_LINES, 0, 2);

    glColor4f(0.0f, 1.0f, 0.0f, 1.0f); // opaque green

    glVertexPointer(3, GL_FLOAT, 0, lineY);
    glDrawArrays(GL_LINES, 0, 2);

    glColor4f(0.0f, 0.0f, 1.0f, 1.0f); // opaque blue

    glVertexPointer(3, GL_FLOAT, 0, lineZ);
    glDrawArrays(GL_LINES, 0, 2);

    glDisableClientState(GL_VERTEX_ARRAY);
}
</code>
I'm new to openGL and I'm just trying to do some basic stuff.
I can use glClear:
<code>glClearColor(1, 0, 1, 1);
glClear(GL_COLOR_BUFFER_BIT);
</code>
so it seems that the context is right but I can't draw the lines.
any help...
Thank you.
Answer: Why don't you try having a look at the GLPaint sample code.
It draws lines (based on touch input) using OpenGL ES 1.0
Comment: Thanks but it doesn't draw lines. It draws points based on touch input.
Comment: Hmm. What are "lines" but filled pixels connecting two points? I don't think I see the distinction you're making. This sample does draw lines (based on touch input, but the source of the points is completely arbitrary). Within the sample, see PaintingView -renderLineFromPoint:toPoint: ... ?
Comment: I understand this but I don't want to draw my lines as a set of pointes like they do in that sample I would like to use GL_LINES to do so. I don't see any point in drawing my lines as sets of points if I just need linear line and openGL has a separate function for that. Thank you but I prefer a solution using the function I want to use.
Comment: Got ya. I haven't used GL_LINES yet, so anyone else who can chime in here?

Draw lines in openGL ES 1.0 with Xcode


Model Constructor In Laravel 5

Question: Good Day, I've tried using a constructor for my model and it flashes an error...

Type error: Too few arguments to function App\DV::__construct(), 0 passed in

E:\Apps\SRAWeb\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Concerns\HasEvents.php
  on line 35 & exactly 2 expected.

This is my code:
protected $date;

public function __construct($attributes = array(), Request $request){
    parent::__construct($attributes);
    $this->date = Carbon::parse($request->toDate)->format('Y-m-d');
}

I've tested it and come up with is that if I try to inject Request Class to my constructor. The errors flash.. but if I remove the Request class it runs smoothly. Whats the problem here?
Answer: The thing is that you can't inject a Request class neither in your Model constructors nor in your Controller constructor, because they don't have to do anything with Http calls and they are not being "hit" by any kind of Request so injecting them into constructors won't work. You can only inject Request in any valid method that actually receives an Http hit, to better put it, you can use Request in all methods/actions you have defined are being used inside of your routes. With an exception of some other layers in Laravel which provide the access to Request like middlewares but they are not inside of a constructor as you can see, but rather in a separate method.

Model Constructor In Laravel 5


UIScrollView Zooming & contentInset

Question: Simliar to iOS Photos App where the user is zooming in and out of an image by pinching:
UIView > UIScrollView > UIImageView > UIImage
Initially, I had the issue of zooming below scale 1: image being off centered.  I got it fixed by doing this:
func scrollViewDidZoom(scrollView: UIScrollView) {
        let offsetX = max((scrollView.bounds.width - scrollView.contentSize.width) * 0.5, 0)
        let offsetY = max((scrollView.bounds.height - scrollView.contentSize.height) * 0.5, 0)
        scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
}

This works well when zooming out.
UIImage content mode is aspectFit
Issue
When I ZOOM IN, when zoomScale is above 1, scroll view insets need to hug the surroundings of the UIImage that the scroll view contains.  This takes away the dead-space that was surrounding the UIImage. IE, Photos app when zooming-in by pinching or double tapping.
Tried
    func scrollViewDidZoom(scrollView: UIScrollView) {
    if scrollView.zoomScale > 1 {
        let imageScale = (self.imageView.bounds.width/self.imageView.image!.size.width)
        let imageWidth = self.imageView.image!.size.width * imageScale
        let imageHeight = self.imageView.image!.size.height * imageScale
        scrollView.contentInset = UIEdgeInsetsMake(((scrollView.frame.height - imageHeight) * 0.5), (scrollView.frame.width - imageWidth) * 0.5 , 0, 0)
        print (scrollView.contentInset.top)
    }
    else {

        let offsetX = max((scrollView.bounds.width - scrollView.contentSize.width) * 0.5, 0)
        let offsetY = max((scrollView.bounds.height - scrollView.contentSize.height) * 0.5, 0)
        scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, 0, 0)
    }
}

Above addition seems to vary the inset amount still.
Update (images added)
First image shows the default layout.  Rest shows when zoomed in.....
Comment: So, you want to stop before the dead-space will appear?
Comment: Updated the question with graphical illustrations.
Comment: Only difference in 2nd & 3rd picture is scrollview is only scaled on x-axis in 3rd one. But what difference does it make to image ? Scaling of image is same in 2nd & 3rd pictures. Do you just want it exactly like photos app ?
Comment: @Gurdeep : 3rd image has trimmed Scroll View Insets.
Answer: Your approach looks correct. You need to update your code as below.
    func scrollViewDidZoom(scrollView: UIScrollView) {

    if scrollView.zoomScale > 1 {

        if let image = imageView.image {

            let ratioW = imageView.frame.width / image.size.width
            let ratioH = imageView.frame.height / image.size.height

            let ratio = ratioW < ratioH ? ratioW:ratioH

            let newWidth = image.size.width*ratio
            let newHeight = image.size.height*ratio

            let left = 0.5 * (newWidth * scrollView.zoomScale > imageView.frame.width ? (newWidth - imageView.frame.width) : (scrollView.frame.width - scrollView.contentSize.width))
            let top = 0.5 * (newHeight * scrollView.zoomScale > imageView.frame.height ? (newHeight - imageView.frame.height) : (scrollView.frame.height - scrollView.contentSize.height))

            scrollView.contentInset = UIEdgeInsetsMake(top, left, top, left)
        }
    } else {
        scrollView.contentInset = UIEdgeInsetsZero
    }
}

Swift 5
    func scrollViewDidZoom(scrollView: UIScrollView) {

    if scrollView.zoomScale > 1 {

        if let image = imageView.image {

            let ratioW = imageView.frame.width / image.size.width
            let ratioH = imageView.frame.height / image.size.height

            let ratio = ratioW < ratioH ? ratioW:ratioH

            let newWidth = image.size.width*ratio
            let newHeight = image.size.height*ratio

            let left = 0.5 * (newWidth * scrollView.zoomScale > imageView.frame.width ? (newWidth - imageView.frame.width) : (scrollView.frame.width - scrollView.contentSize.width))
            let top = 0.5 * (newHeight * scrollView.zoomScale > imageView.frame.height ? (newHeight - imageView.frame.height) : (scrollView.frame.height - scrollView.contentSize.height))

            scrollView.contentInset = UIEdgeInsets(top: top, left: left, bottom: top, right: left)
        }
    } else {
        scrollView.contentInset = .zero
    }
}

Comment: Works like a charm. Thank you so much!
Answer: Swift 5
func scrollViewDidZoom(_ scrollView: UIScrollView) {
    if scrollView.zoomScale > 1 {
        if let image = imageView.image {

            let ratioW = imageView.frame.width / image.size.width
            let ratioH = imageView.frame.height / image.size.height

            let ratio = ratioW < ratioH ? ratioW : ratioH

            let newWidth = image.size.width * ratio
            let newHeight = image.size.height * ratio

            let left = 0.5 * (newWidth * scrollView.zoomScale > imageView.frame.width ? (newWidth - imageView.frame.width) : (scrollView.frame.width - scrollView.contentSize.width))
            let top = 0.5 * (newHeight * scrollView.zoomScale > imageView.frame.height ? (newHeight - imageView.frame.height) : (scrollView.frame.height - scrollView.contentSize.height))

            scrollView.contentInset = UIEdgeInsets(top: top, left: left, bottom: top, right: left)
        }
    } else {
        scrollView.contentInset = UIEdgeInsets.zero
    }
}

Answer: for swift 4
func scrollViewDidZoom(_ scrollView: UIScrollView) {

        if scrollView.zoomScale > 1 {

            if let image = self.imageViewZoom.image {

                let ratioW = self.imageViewZoom.frame.width / image.size.width
                let ratioH = self.imageViewZoom.frame.height / image.size.height

                let ratio = ratioW < ratioH ? ratioW:ratioH

                let newWidth = image.size.width*ratio
                let newHeight = image.size.height*ratio

                let left = 0.5 * (newWidth * scrollView.zoomScale > self.imageViewZoom.frame.width ? (newWidth - self.imageViewZoom.frame.width) : (scrollView.frame.width - scrollView.contentSize.width))
                let top = 0.5 * (newHeight * scrollView.zoomScale > self.imageViewZoom.frame.height ? (newHeight - self.imageViewZoom.frame.height) : (scrollView.frame.height - scrollView.contentSize.height))

                scrollView.contentInset = UIEdgeInsetsMake(top, left, top, left)
            }
        } else {
            scrollView.contentInset = UIEdgeInsets.zero
        }
    }

UIScrollView Zooming & contentInset


BCP out Error in SQL2000: SQLState = 37000, NativeError = 4060

Question: I have created a proc that grabs all the user tables in a local DB on my machine. I want to be able to create a flat file of all my tables using BCP and SQL. Its a dummy database in SQL 2000 connecting through windows authentication. I have set my enviroment path variable in WinXP SP2. I have created new users to access the db, switched off my firewall, using trusted connection. I have tried dozens of forums, no luck.
In dos command prompt I get the same error.
SQLState = 37000, NativeError = 4060
Error = [Microsoft][ODBC SQL Server Driver][SQL Server]Cannot open database requested in login '[HelpDesk-EasyPay'. Login fails.
Here is my SP:
@Path VARCHAR(100),
    @UserName VARCHAR(15),
    @PassWord VARCHAR(15),
    @ServerName VARCHAR(15)
AS

set quoted_identifier off
set nocount on

declare @n int
declare @db varchar(40)
set @db=DB_NAME()
declare @TableName varchar(15)
declare @bcp varchar(200)
select identity(int,1,1) as tblNo,name tblname into #T from Sysobjects where xtype='u'
select @n=COUNT(*) from #T

WHILE (@n>0)
BEGIN
    SELECT @TableName=tblname FROM #T WHERE tblno=@n
    PRINT 'Now BCP out for table: ' + @TableName
    SET @bcp = "master..xp_cmdshell 'BCP " + "[" + @db + ".." + @TableName + "]" + " OUT" + @Path + "" + @TableName+".txt -c -U" + @UserName + " -P" + @PassWord + " -S" + @ServerName + " -T" + "'"
    EXEC(@bcp)
    SET @n=@n-1
END

DROP TABLE #T

Can anyone advise. This seems to be a connection problem or BCP ? Not sure.
edit: I am running this from query analyzer because I have 118 tables to output to flat file. I seem to agree that its an authentication issue because I tried connecting to master db with username sa password root. which is what its set to and I get the same error: SQLState = 37000, NativeError = 4060
Comment: What is the command line string you are using to run this? This looks like an authentication issue.
Comment: I am running this from query analyzer because I have 118 tables to output to flat file. I seem to agree that its an authentication issue because I tried connecting to master db with username sa password root. which is what its set to and I get the same error: SQLState = 37000, NativeError = 4060 If I run it from the command line, same error. It must be something small that I am missing ?
Comment: Also I believe you want "queryout" not "out"
Answer: Your brackets are extending over the entire qualified table name - only the individual components should be bracketed:
bcp [HelpDesk-EasyPay].dbo.[customer] out d:\MSSQL\Data\customer.bcp -N -Utest -Ptest -T

should work, so you want:
SET @bcp = "master..xp_cmdshell 'BCP " + "[" + @db + "]..[" + @TableName + "]" + " OUT" + @Path + "" + @TableName+".txt -c -U" + @UserName + " -P" + @PassWord + " -S" + @ServerName + " -T" + "'"

in your code.  It looks like the error message you gave was truncated, otherwise you would have been able to see that it was attempting to open database "[HelpDesk-EasyPay.dbo.customer]" which, of course, does not exist, and even if it did, you would then get an error that no table was specified.
Answer: I have the same issue for the OUT (the minus character kills everything event the ^ don't work)
I avoid it with the QUERYOUT. Like this :
SET  @s = 'BCP "SELECT * FROM [HelpDesk-EasyPay].dbo.customers" QUERYOUT myfile.txt ...'

Answer: Maybe someone will come in handy: I have the same issue with SQL Server 2017. The reason was the square brackets around the database name.


Xamarin Linker stipping out static class properties?

Question: In VS 2013, Xamarin Forms.
Our Android & IOS app has a static class:
<code>public static class CacheKeys
{
    public static string RememberMeEmail = "RememberMeEmail";
    public static string RememberMeSwitch = "RememberMeSwitch";
}
</code>
This class is stripped by the linker in the iOS device debug build, but not in the
simulator or Android.
See attached screenshot.
I have set the Debug Linker for iPhone to Do Not Link, yet this static class is
removed.
??????
Answer: You can set a preserve attribute to your class: http://developer.xamarin.com/guides/ios/advanced_topics/linker/
See the section: Preserving Code
Example:
<code>[Preserve]
    public static class LinkerPreserve
    {
        static LinkerPreserve()
        {
            throw new Exception(typeof(SQLitePersistentBlobCache).FullName);
        }
    }

    public class PreserveAttribute : Attribute
    {
    }
</code>
Answer: I also found that I had to check the "Enable generic value type sharing" in the Advanced tab of "iOS Build"


How long and how much can I benefit from praying?

Question: When you pray on a shrine you get a temporary buff, how long does this buff last?
Also, how many of this buffs can I have simultaneously?
Comment: I've had at least 2 up simultaneously. Haven't timed them to see how long though.
Answer: I had over 25 buffs on myself, so if there is a limit, it's pretty darn high.
To test this out, I bought a bunch of buff potions and drank them all. Twenty in total. Then I touched the 5 shrines that are right next to each other in Ysa. Only 15 buffs displayed on the screen at once, so at first maybe I thought there was a cap of 15.

However, when I went to the Status->Effects screen, it listed all 25 buffs as active. My guess is that the 15 that displayed on the screen were all it had room for.

Potion buffs seem to have variable durations depending on the potion type. I am not prepared to make a list of every single potion type and their individual durations, but of the 20 I tested, all seemed to fall into two categories... 30 seconds or 60 seconds. I didn't detect any sort of pattern about why some lasted 30 seconds and other lasted 60.

All shrine buffs appear to have a duration of 5 minutes.
Potion buffs seem to be either 30 seconds or 60 seconds.
Comment: It's worth noting that the "Minor Phasewalk" potion lasts much less than 30 seconds. I didn't time it, but it seemed to be in the 10-15 second range.


why this happen in sql

Question: i have the following Statements in sql
 declare @date varchar(20)
 declare @query  NVARCHAR(MAX)

 set @date= '2013-1-1'
 set @query= 'print '+@date+''
 execute (@query)

iam getting the answer as 2011 not as 2013-1-1..
why this is happening. what to do to get the answer as 2013-1-1 instead of 2011 using
execute(@query) statement
Comment: It is getting subtracted.. 2013-1-1=2011
Comment: @asifsid88 it's correct. but i need to get 2013-1-1 in this way(using execute(@query))
Answer: Your query is effectively:
print 2013-1-1

Caused by:
'print '+@date+''

If you rewrote your SQL to be:
print @data

You would get the value printed: 2013-1-1
If you updated your original query:
declare @date varchar(20)
declare @query  NVARCHAR(MAX)

set @date= '2013-1-1'
set @query= 'print '''+@date+''''
execute (@query)

This would be the same as writing:
print '2013-1-1'

Comment: i have a complex problem i simplied the problem and asked the question. i need to get 2013-1-1 using 'print '+@date+''
Comment: @user1925921 I think you should try the code provided in the answer before you comment. Another option would be to assign the value to `@date` with quotes. Like this: `set @date= '''2013-1-1'''`.
Comment: @user1925921 your query is nothing more than a bit of math when you execute it, and I'm unsure how we can help solve your complex problem since I think to most people this would be considered a rather silly question. No offense.
Answer: u can try like this also....this will also give u the answer
declare @date varchar(20)
 declare @query  NVARCHAR(MAX)
set @date= '2013-1-1'
 set @query= 'print '''+@date+''''
 execute (@query)

why this happen in sql


Invalid XML: Error on line 6: The element type "hr" must be terminated by the matching end-tag ""

Question: When I am using rome to parse a xml link:
package com.dolphin.soa.post;

import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.ParsingFeedException;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import lombok.extern.slf4j.Slf4j;

import java.net.ConnectException;
import java.net.URL;

/**
 * @author dolphin
 */
@Slf4j
public class MiniExample {

    public static void main(String[] args) {
        try {
            SyndFeed feed = new SyndFeedInput().build(new XmlReader(new URL("http://yechengfu.com/feed.xml")));
        } catch (ConnectException connectException) {
            log.error("rss parse error", connectException);
        } catch (ParsingFeedException e){
            log.error("rss parse error", e);
        }catch (Exception e) {
            log.error("rss parse error", e);
        }
    }

}

shows the error Invalid XML: Error on line 6: The element type "hr" must be terminated by the matching end-tag "
". I check the xml link, and did not find any non-standard format. why would this happend and is it possbile to fix it? This is my dependencies:
api "com.rometools:rome:1.15.0"

Comment: That URL yields a 308 (a redirect) to https://yechengfu.com/feed.xml (instead of HTTP). A redirect isn't followed but it tries to parse the HTML. Switch to https to get the actual feed.
Comment: The file parsed is not valid XML even if the URL says so.
Answer: The file that is returned from calling "http://yechengfu.com/feed.xml" is a small html file (with a single
 tag):

<title>308 Permanent Redirect</title>

308 Permanent Redirect

nginx/1.19.2

You can see this if you run a command like curl:
curl http://yechengfu.com/feed.xml

The page is redirected in a normal browser, but curl and XmlReader will not follow redirects automatically. If you give curl the "-L" argument it will follow to you feed.xml file.
I guess that you will have to read up on how to configure nginx and use it as a reverse proxy instead of rewrite the URL.


Java and ALSA problems

Question: I'm trying to use a Java-based application that requires sound in Ubuntu 10.04 using sun-java from partner repos . However, the sound is way too fast. It seems like a chipmunk got into my speakers. :)
Is this happening to anyone else? Any ideas on how to fix it?
Answer: As "nhnb" says: it seems like this bug is fixed in OpenJDK.  OpenJDK is based on the open source parts from Sun Java, with the parts that are not open source replaced by alternative code, and which apparently also fixes some bugs...
Answer: I have similar problems using pulse audio and Java applications, except for me I get no sound for my entire system once JVM starts... but if I have an application running before JVM starts, it's sound still works.
I run my java programs with aoss javaws /program/to/run
That fixes my sound, but makes the java programs crash a lot... so it's a trade off. In my opinion, Java's "cross platform" talk doesn't include Linux.
Comment: I can confirm this issue in Sun Java on Ubuntu 10.04. It does not exist in OpenJDK.
Comment: @nhnb: One more reason why open source > closed source, and people should just use OpenJDK instead of Sun Java...   ;-)

Java and ALSA problems


Assigned id with auto-increment

Question: In Grails I would like to have an id that has a prefix and is autoincremented.
I would have these prefixes: A and B.
Then I would have a following sequence:
new MyObject('A').save() ---> id = A-1
new MyObject('A').save() ---> id = A-2
new MyObject('B').save() ---> id = A-3
and so on... Is it possible to combine assigned generator with auto-increment?
Comment: Do you have the notion of sequences in MySQL like Oracle? https://docs.oracle.com/cd/B28359_01/server.111/b28310/views002.htm#ADMIN11792 You could set the domain strategy to assigned, pull the value from the sequence before saving and prefix the letter then save
Comment: What's the underlying DB?
Comment: @mikew, it is MySQL.
Comment: Interesting idea. Have ever done it in Grails. (Of course, I'll have a look but to hear about an experience would be nice. )
Answer: Answer is Oracle specific but gives general idea.
Create a sequence in DB:
create sequence MY_SEQ minvalue 1 maxvalue 9999999 start with 1 increment by 1;

Then in Grails:
class MyService {

    def dataSource

    def save( params ) {
        def myDom = new MyDomain( params )
        myDom.id = generateId()
        myDom.save()
    }

    def generateId() {
        def db
        try {
            db = Sql.newInstance( dataSource )
        "A-${db.firstRow( 'SELECT MY_SEQ.NEXTVAL NEXT_ID FROM DUAL' ).NEXT_ID}"
        }
        finally {
            db?.close()
        }
    }
}

Answer: Just leave the primary key as an integer and add a getter method to derive the A1, B1 value. It's not a good idea to mess with primary keys like you're proposing.
Comment: thx but we need a descriptive id. Currently we have `{A|B}-{randomlyGeneratedLong()}`.
Comment: That's not the job of a primary key.  A primary key is used to uniquely identify a database row.  If anything, what you want is a composite key, but GORM discourages them.

More [here](http://stackoverflow.com/a/7383118/511250).

Assigned id with auto-increment


Relationship between euclidean metric in sphere of radius $r$ and the unit sphere.

Question: I want to show $g_r=r^2g_1$ where $g_1$ is the (Riemannian) metric in the unit sphere induced by its inclusion in  $\mathbb{R}^n$ and $g_r$ is the metric in the sphere of radius $r$ also induced by its inclusion in $\mathbb{R}^n$. I gave the following argument but it seems rather unelegant (maybe wrong?):
$$ g_r = \sum_{i=1}^n \left.dx^i \otimes dx^i \right|_{\lVert x \rVert = r} = \sum_{i=1}^n r^2 \left. (x^i/r) \otimes (dx^i/r) \right|_{\lVert x \rVert = r} = \sum_{i=1}^nr^2 \left. dy_i\otimes dy_i \right|_{\lVert y \rVert=1} =r^2g_1$$
Is this an acceptable answer? What would be a more elegant way?
Note: the equality $g_r=r^2g_1$ is taken in the sense that an element of the sphere of radius $r$ and of radius 1 is determined only by its polar coordinates (by a direction coming from the origin). So a vector orthogonal to radial unit vector in $\mathbb{R}^n$ defines  a vector in every tangent space of every sphere. That is, if we use polar coordinates and we write a vector field in $\mathbb{R}^n\setminus \{0\}$ as $v=v_r\partial_r + v_{\bar{\theta}} \partial _\bar{\theta}$ the quantity $v_{\bar{\theta}} \partial _\bar{\theta}$ defines a vector field in every sphere.
Answer: Technically, $g_{1}$ is a metric on the unit sphere $S^{n-1}(1)$ and $g_{r}$ is a metric on the sphere $S^{n-1}(r)$ of radius $r$, so they're not immediately comparable.
What you're proven is: If $\phi:S^{n-1}(1) \to S^{n-1}(r)$ is radial scaling by a factor of $r$ (i.e., $\phi(x) = rx$), and if $g_{r}$ is the metric induced on $S^{n-1}(r)$ by the ambient Euclidean metric, then $\phi^{*}g_{r} = r^{2} g_{1}$. (Note that both of these metrics "live" on the unit sphere.)
Comment: If I understand your explanation, then under the same logic, $g_r=(\phi^{-1})^*g_1$ right?  Is there a better way to prove this fact?
Comment: 1. Yes, $g_{r} = r^{2} (\phi^{-1})^{*}g_{1}$. 2. It may be easier to avoid using a coframe field, and simply to note (using angle brackets for the ambient metric and putting $\psi = \phi^{-1}$) that if $x$, $y$ are tangent vectors to $S^{n-1}(r)$, then$$\psi^{*}g_{1}(x, y) = g_{1}(\psi_{*}x, \psi_{*}y) = \langle x/r, y/r\rangle = \tfrac{1}{r^{2}}\langle x, y\rangle = \tfrac{1}{r^{2}} g_{r}(x, y).$$


Why different array length output in concurrent golang programming?

Question: I'm writing a simple program in golang for concurrency test and don't understand different output of capitalized array size every time!
data := []rune{'a', 'b', 'c', 'd'}
var capitalized []rune

capIt := func(r rune) {
    capitalized = append(capitalized, unicode.ToUpper(r))
    fmt.Printf("%c done!\n", r)
}

fmt.Printf("Before: %c\n", capitalized)
for i := 0; i < len(data); i++ {
    go capIt(data[i])
}
time.Sleep(100 * time.Millisecond)
fmt.Printf("After: %c\n", capitalized)

Outputs:

b done! a done! d done! c done! After: [D B C A]

a done! d done! c done! b done! After: [D B A]

d done! a done! c done! b done! After: [B]

d done! a done! c done! b done! After: [A B C]

d done! b done! a done! c done! After: [B C]
Comment: In the code, `capitalized` slice is shared among multiple goroutines. Concurrent access to shared data without proper synchronization can lead to data races. This can result in different output sequences
Comment: Concurrency means (more or less) that things run in parallel. In your case you are running goroutines that run in parallel and modify the same data at the same time. Without some kind of synchronization they will overwrite and corrupt the result of each other. So you have just discovered how NOT to do it.
Comment: @jurez But all convertin is done. `d done! a done! c done! b done!`
Answer: Go: Data Race Detector

You have data races.
$ go run -race racer.go
Before: []
==================
WARNING: DATA RACE
Write at 0x00c000012018 by goroutine 8:
  main.main.func1()
      racer.go:14 +0xc4
  main.main.func2()
      racer.go:20 +0x3e

Previous read at 0x00c000012018 by goroutine 7:
  main.main.func1()
      racer.go:14 +0x44
  main.main.func2()
      racer.go:20 +0x3e

Goroutine 8 (running) created at:
  main.main()
      racer.go:20 +0x199

Goroutine 7 (running) created at:
  main.main()
      racer.go:20 +0x199
==================
a done!
==================
WARNING: DATA RACE
Write at 0x00c000012018 by goroutine 9:
  main.main.func1()
      racer.go:14 +0xc4
  main.main.func2()
      racer.go:20 +0x3e

Previous write at 0x00c000012018 by goroutine 10:
  main.main.func1()
      racer.go:14 +0xc4
  main.main.func2()
      racer.go:20 +0x3e

Goroutine 9 (running) created at:
  main.main()
      racer.go:20 +0x199

Goroutine 10 (running) created at:
  main.main()
      racer.go:20 +0x199
==================
d done!
b done!
c done!
After: [B C]
Found 2 data race(s)
exit status 66
$

racer.go:
package main

import (
    "fmt"
    "time"
    "unicode"
)

func main() {
    data := []rune{'a', 'b', 'c', 'd'}
    var capitalized []rune

    capIt := func(r rune) {
        capitalized = append(capitalized, unicode.ToUpper(r))
        fmt.Printf("%c done!\n", r)
    }

    fmt.Printf("Before: %c\n", capitalized)
    for i := 0; i < len(data); i++ {
        go capIt(data[i])
    }
    time.Sleep(100 * time.Millisecond)
    fmt.Printf("After: %c\n", capitalized)
}


How to specify form parameter when using webclient to upload file

Question: As title, how to specify additional form parameters when uploading file using webclient?
Answer: You can't do this with a WebClient. You will need to manually generate the multipart/form-data request. Here's an example which could be easily adapted. You will just need to insert the file contents at the parameter you like. In this example I used a StreamWriter but if your file is binary you would probably want to directly write to the request stream.
The idea is to achieve RFC 1867.
If you don't want to go this route and those values are not very big you could probably pass the additional parameters at the request string and continue using UploadFile method. Of course the target url must be capable of reading those values from the query string.
Comment: too bad to hear that weblcient's limitation on this. Is there any thrid party library to get this done?
Comment: @user496949, I've blogged about a sample implementation: http://www.bratched.com/en/component/content/article/69-uploading-multiple-files-with-c.html
Comment: @DarinDimitrov Can you see this please? https://stackoverflow.com/questions/48295877/webclient-too-many-automatic-redirections-were-attempted


How to install cmake 3.7 in Ubuntu 16.04 using its binary archive file?

Question: I'm on Ubuntu 16.04. I installed cmake with the command
sudo apt install cmake

It installed cmake 3.5.1. Now I want to use cmake 3.7 - I downloaded an archive with binaries (i.e cmake-3.7.0-Linux-x86_64.tar.gz) and extracted it, but how do I run it using the cmake command? My current attempt to run
cmake --version

returns the "old" 3.5.1 version.
Comment: Which version you downloaded? source or binary?
Comment: @SuB Binary version.
Comment: @DavidFoerster: That problem cause is unavailability of cmake's server, but here is installing an version of cmake that does not exist in Ubuntu Repositoroes.
Comment: @SuB: Let's continue this discussion [in chat](https://chat.stackexchange.com/rooms/48782).
Answer: Remove old version using:
apt-get purge cmake

You can use new version of cmake by adding its bin directory path to $PATH. An alternative solution is to extract tar.gz package and go to the directory made after extracting and run following commands:
cp -r bin /usr/
cp -r doc /usr/share/
cp -r man /usr/share/
cp -r share /usr/

The second method is the same as installation process which .deb package does!
Comment: With the difference that you can remove a deb package easily. How do you plan to remove this when not needed?
Comment: I agree - how to remove it if we just copied folders?
Comment: @muru: It is drawback of installing a package using this method. Compiling from source code has the same problem in some packages! In this case this package could be removed by deleting any file which is copied. Another solution is to make a `.deb` package and installing it.
Comment: There is a package for cmake 3.7 [here](http://packages.ubuntu.com/zesty/cmake) in Ubuntu repository for `zesty` version, but i recommend you not using this package. Installing this package need to force `dpkg` to ignore package version check and may cause broken package database.


Do I need to complete AC3 to understand AC4?

Question: I just bought Assassins Creed Revelations, 3 & 4.
I already played 1, 2 & Brotherhood, so I started to end the Ezio story with finishing Revelations.
I just watched some trailers for AC 4 and i'm excited and just want to start to play it. But I don't know if there are some relations to AC3...? When I google about it, there are too many spoilers because they talk too much about the story. SO PLEASE DO NOT SPOILER! I just want to know if I need to play Assassins Creed 3 first, before I start with the 4.
Answer: No - as far as I can tell, the stories are almost entirely unrelated.
Comment: I agree. You might not understand a few goings on between Abstergo and Desmonds crew, but that is about it.
Comment: @Lyrical: Thank you for your feedback. Is this important to understand?
Comment: @DarkDecipio I wouldn't say it is vital. Personally I prefer the individual stories in each AC game. Is there any reason you don't want to play AC3 other than AC4 looking good? AC3 for me was a pretty enjoyable game, it does start off very slow though.
Comment: I only have 1 AC game, AC4, and I havnt needed to know anything from AC3 and I have completed the game.
Comment: @Lyrical: Nah, AC 3 also looks good but I'm too excited about the pirate atmosphere. So I want to AC 4 now :). As you said about the individual stories, AC Brotherhood and Revelations should both be played successively. Because Brotherhood continuous the story of Brotherhood.
After AC4, I would play AC3. If I wouln't it was a bad bought :)

Okay thank you. `+1` & accepted.
Comment: It's probably worth mentioning that the whole ship sailing / fighting mechanic in AC4 is also in AC3 - you get to do ship to ship battles in that too.
Comment: The ending of AC 3 was shoved into a final cinematic. There was next to no exposition of any real merit then all of a sudden they tried to tie it all up. I, personally (and this is just opinion), got the feeling / impression they ran out of time / money and just finished it out of the blue. You could watch it on Youtube and just play the fourth one. AC 3 was the weakest of them so far. It pushed plausibility too far, and the historical setting was tedious. I'm finding 4 better, but god the tutorials give you false information at times, and the grinding for the ship is, to me, beyond boring!
Comment: In story elements AC3 is seen as the weakest, in gameplay and launch ac unity is seen as the weakest, the overall best series is the Ezio Saga
Answer: There are absolutely no references to AC3 in the main (Edward Kenway) section of the game. In the Abstergo Research Assistant position, there are one or two videos about the ending of AC3, but it is not related to the story.
Some characters from the present-day section of past AC games make a small appearance in ACIV, but they directly don't play a major role in the story, and the parts they do play have nothing to do with any previous game.
You will be able to fully understand the game's plot without playing AC3
Answer: There is a relation between AC4 and AC3 where in AC4, you will play as Edward Kenway who is the father of Haytham Kenway and grandfather of Connor Kenway in AC3.
Answer: It's not necessary although if you do not play AC3  you won't understand or be able to appreciate the surprise "didn't see that coming" ending.
Answer: thats true there is not a big deal if u have not played ac3  but there is a small connection between ac3 and ac4
ac3 was set in 1775 in the american revelutionary war  and ac4 takes place in the 1716 in ac4's ending   nathan kenway  the chacracter who makes an apperance in ac3 was edward kenways son (i think so) so yeah :)


URL Rewriting in PHP / Apache

Question: So I am making an website using php to show  users and there post for other site using API .
So I have URL likes mysite.com/user.php?username=demo .
So is there any way I can make it mysite.com/user/demo.
I made searches here I came to know that Its call URL_rewriting . But as I am newbie to php / apache Can any one will help me in making my .htaccess
my site url now is > site.com/user.php?name=namehere.
any small help will be appreciated thanks .
Comment: possible duplicate of: http://stackoverflow.com/questions/10595556/facebook-like-custom-profile-url-php
Comment: simply the rule is

`RewriteRule ^page/([a-zA-Z0-9]+) index.php?page=$1 [L,NC]`
Answer: I learned from this
You can do
<code>RewriteRule ^user/([A-Za-z0-9-]+)/?$  user.php?username=$1    [NC,L]
</code>
Comment: Thanks ! This worked . But I am having Error with my CSS Codes ?
Comment: try adding `` inside `` tag of your html file

URL Rewriting in PHP / Apache


Rails count of distinct values of a column of associated model in SQL

Question: I have in my Rails (4.1.8) app the following models: Event, User, Box, EventBoxMapping and following associations relevant to the question among them:
User has_many events; Event belogs_to User
Event has_many boxes through event_box_mappings

I'm trying to achieve faster (and hopefully more memory efficient) CSV generation through ActiveAdmin by using PostgreSQL's COPY functionality to stream output of a raw SQL directly into a CSV export. To achieve this, however, I need to pass a raw SQL string, which I'm having some trouble creating for all bits of information generated to populate columns of our Events CSV. In particular, I'd like to pick out counts of distinct values of box_property_id column of the boxes of events.
Now, so far, I have the following SQL that runs perfectly to maps some values of Event and User models:
SELECT
    events.id,
    events.user_id,
    events.event_type,
    events.promo_code,
    events.created_at,
    events.transport_fee,
    events.boxes_count,
    users.email,
    users.gender,
    users.first_name,
    users.last_name
FROM events
LEFT JOIN users ON users.id = events.user_id`

I'm stuck at the part I mentioned above - to include counts of "each kind of box" represented by the box_property_id field in boxes of an Event in the table returned by the above SQL.
I come from a NoSQL background from past experience and fairly new to this field, and so I apologise if my query is ambiguous/incomplete in some form.
Comment: Fast question, I didn't understand, do you need to count box_property_id from the above statement or? Since I can't see the box_property_id anywhere in the statement you wrote, if this is the case I can write you simple SQL to count the field. Also, where is box_property_id field ? Which table has that value and how is it connected to the others?
Comment: I would suggest you leave out unnecessary information. You talk about wanting to COPY it to CSV. But that's irrelevant because you're asking for help with a query. Don't give background that's unnecessary in order to understand the question. (I'm saying this because I spent some time wondering what about it was incompatible with COPY... then realised it had nothing to do with it.)
Comment: Quick question. Is `EventBoxMapping` belongs_to `Event` and `Box`?
Answer: As understood, you need you wanna get distinct count of box_property_id with other columns.
Event.joins(:user, event_box_mappings: :box)
     .select("events.id, events.user_id, events.event_type, events.promo_code,
             events.created_at, events.transport_fee, events.boxes_count,
             users.email, users.gender, users.first_name, users.last_name,
             COUNT(distinct boxes.box_property_id) AS total")

total will return the count of distinct box_property_id.
Hope this would be helpful


Unity ARKit SetWorldOrigin - Wrong Rotation

Question: I try to set a new position and orientation as origin with SetWorldOrigin
I'm using Unity 2018.3.0f2 and ARKit 2.0
My start alignment is: "Unity AR Alignment Gravity And Heading"
In my outdoor test environment I have a known point with a visualized north direction. I can place a Gameobject (newOriginGO) on this point and rotate it towards the visualized north direction. The problem is, the virtual objets are rotated to a wrong position. I tested with only translations, this worked.
Here is a code snippet:
GameObject translationToLastPosition = new GameObject();
GameObject rotateToNewRotation = new GameObject();
GameObject translationToNewPosition = new GameObject();

translationToLastPosition.transform.position = -lastOriginP;
rotateToNewRotation.transform.eulerAngles = lastOriginR - newOriginGO.transform.eulerAngles;
translationToNewPosition.transform.position = lastOriginP - newOriginGO.transform.position;

UnityARSessionNativeInterface.GetARSessionNativeInterface().SetWorldOrigin(translationToLastPosition.transform);
UnityARSessionNativeInterface.GetARSessionNativeInterface().SetWorldOrigin(rotateToNewRotation.transform);
UnityARSessionNativeInterface.GetARSessionNativeInterface().SetWorldOrigin(translationToNewPosition.transform);

lastOriginP = newOriginGO.transform.position;
lastOriginR = newOriginGO.transform.eulerAngles;

Because the SetWorldOrigin  needs a relative transform and I'm rotating my Gameobject around the last Origin, with transform.RotateAround(lastOriginP, Vector3.up, angle), I tried to translate the WorldOrigin back to the last Origin, rotate the WorldOrigin and then translate back to the actual position. Do I have a thinking error or do I not understand exactly how the method SetWorldOrigin works? How does the ARKit SetWorldOrigin affects the Unity World Space coordinate system?
Answer: Okay, finally I found another solution. Instead of changing the WorldOrigin with ARKit, I made all my 3D objects as child objects of an empty GameObject. Then I changed this GameObject with my correction values (translation and rotation).


Check date interval with SQL Server

Question: Hi in a stored procedure I want to select rows that are in an interval of a month where
@Anno is the year of the start and @Mese is the month of the date start. I try this:
WHERE FinePeriodo >= CAST((@Anno + '-' + @Mese + '-01 00:00:00') as datetime)
    AND FinePeriodo <
           DATEADD(month, 10, CAST(
               (@Anno + '-' + @Mese + '-01 00:00:00') as datetime))

But it doesn't work.
How can I do?
thanks
Answer: First of all, in order to make sure your date arithmetic works regardless of the language and regional settings on your server, use the ISO-8601 format YYYYMMDD for your dates.
In that case, you should be able to do something like:
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME

-- this assume @Anno and @Mese are already VARCHAR variables!
SET @StartDate = CAST(@Anno + RIGHT('00'+@Mese, 2) + '01' AS DATETIME)
SET @EndDate = DATEADD(MONTH, 1, @StartDate)

and then in your WHERE clause, use:
WHERE FinePeriodo BETWEEN @StartDate AND @EndDate

Could that work for you?
Answer: The code below works:
declare @anno VARCHAR(4)
declare @mese VARCHAR(2)

SET @Anno = '2006'
SET @mese = '6'

SELECT CAST((@Anno + '-' + @Mese + '-01 00:00:00') as datetime) as BeginMOnth,
    DATEADD(month,10,CAST((@Anno + '-' + @Mese + '-01 00:00:00') as datetime)) as EndMonth

select [name],crDate from sysobjects
WHERE crDate >= CAST((@Anno + '-' + @Mese + '-01 00:00:00') as datetime)
          AND crDate < DATEADD(month,10,CAST((@Anno + '-' + @Mese + '-01 00:00:00') as datetime))

Using sysobjects table for test.

Is your search field an actual date (not a character type instead)
Is it possible you've got extra spaces, etc in your variables
Do you get an error or just the wrong records back
Answer: Try this: (make @Anno and @Mese integers)
  Where FinePeriodo Between DateAdd(month, 12*(@Anno-1900) + @Mese, 0)
                       And  DateAdd(month, 12*(@Anno-1900) + @Mese + 1, 0)

Check date interval with SQL Server


Error while compiling a GTK application on ubuntu 13.04 - missing headers

Question: I am developing a GTK application using the ECLIPSE IDE.
I am unable to build the application cause when I include file from gtk/gtk-2.0/gtk.h then it gives me a error that
`gdk/gdk.h` no such file or directory found ..
I tried to add the include directory path also but it is of no use.
Is there is any way to solve this.
Answer: The gdk header file is part of the libgtk2.0-dev package, so you will need to install that before you can compile GTK applications. You can install it using apt.
sudo apt-get install libgtk2.0-dev

While you're at it, you'll probably need the build-essential package too. It contains applications like g++, gcc and other standard headers.


How to update Ubuntu 14.04 from BIOS to UEFI?

Question: I'm getting a new motherboard which uses UEFI instead of BIOS, so I was wondering what I would need to do in order to make sure that my Ubuntu partition will run smoothly once I plug into the new motherboard.
Comment: There is a way to convert an MBR partition layout to GTP, but it is very advanced, and has a huge data loss risk. Unless your OS was installed using UEFI, I don't believe you can convert it post-installation.
Comment: Converting from MBR to GPT using `gdisk` is trivially easy in most cases: Run `gdisk` on the disk and type `w` to save the changes. The risk of data loss is low, but not non-existent. The biggest problem is that this will wipe out the BIOS-mode boot loader, making it impossible to boot in BIOS mode after the conversion. See [here](http://www.rodsbooks.com/gdisk/mbr2gpt.html) for more details.
Comment: If you have room for another primary partition on an MBR table or you are already using GPT try adding an EFI system partition as described [here](http://askubuntu.com/q/559007/40581).
Answer: Your mother board very likely supports a "Legacy" (BIOS) mode.  When you get the new motherboard, configure it to use Legacy boot instead of EFI.  It should then 'just work'.  (There are many motherboards that support both, and you can tell them which to use primarily)
Comment: If you've got Windows on the disk now, then either your current computer is EFI-based and you can continue to boot in that way (although you may need to add a boot manager entry) or the computer boots both Windows and Ubuntu in BIOS mode, in which case you can keep booting that way. You should update your question to clarify your current configuration. Including the output of `sudo parted -l` would be helpful.
Comment: Will this allow me to use my windows partition on efi mode?
Comment: @Isaac_E If your Windows is in EFI and your Linux is on BIOS, there may be conflicts.  It may be simpler to just reinstall things.  (In 99% of all cases, I do NOT run things in 'both' - not all mobos can support both modes, AFAIK)


Anchoring aluminum pergola to 4" slab

Question: I just purchased a 11'x23'x8' aluminum pergola from Wayfair that will arrive in a couple weeks. It weighs roughly 750lb. In some reviews, it says the concrete screws that come in the kit are kind of weak so I'm looking at beefing them up a bit.
The pergola has 6 posts and each post has 4 pre-drilled holes on baseplate. The predrilled screw holes are about 5" apart. Research tells me I should have at least 10x distance of fastener diameter between holes so 3/8" sounds like the widest I can go. I plan to get a rotary hammer and drill some of the holes 5" from concrete edges.
I have a concrete slab that is 4" thick. No footers.
Been searching the internet for past few hours trying to find proper guidance on recommended drill depth and cant seem to find anything.
There are a total of 24 concrete anchors/screws to support the 750lb pergola. I live in md and we do get gusts up to 45-50mph. I'm leaning towards Tapcon+ 3/8" diameter concrete screws to not put too much outward pressure near concrete ends(I hear wedge anchors do this).
Now after providing backstory and details of my project, here are my big question I'm hoping someone can help with...

What is the recommended depth to drill into my 4" slab? (For 3/8" fastener)? I was thinking drilling a 3 1/4" hole and using these 3" Tapcons.

Or should I go with the 2.25" depth fastener and drill only 2.5" into the slab?

I know there is reinforcement near center of slab, (chicken wire and some rebar) so some spots my not be able to go deeper than others.
Comment: Yes sorry i call it chicken wire because thats what it looks like but it is re-mesh
Comment: I hope that was re-mesh, not chicken wire in your slab. I suppose chicken wire would work, but...
Answer: You need to drill at least 1/2" deeper than the screw. Concrete debris accumulates in the hole quickly and would prevent full penetration of the screw. All that's in the instructions, though:

Your overall strategy seems sound. If you weren't using four per post I'd consider something with more grab, but I can't see these pulling out if they're installed properly. You could also consider adding epoxy to enhance hold.
Comment: Only the screw holes. Flat joints like under the bases don't usually perform well as they're in tension rather than shear. I suppose it can't hurt, and may reduce moisture penetration.
Comment: +1. For clarity, are you suggesting epoxy in the holes to help hold the screws, between the post bases & concrete, or both? I could see any/all of those as valid options. (I tend toward overkill, so my reading of the epoxy suggestion would lead me to the "both" option.)
Comment: So if i use the 3" screws i would need to drill 3.5" into 4" slab. Is that too close to bottom? Wondering if i should go with the 3" screws or the 2.25". If i go with the 2.25" i would only need to drill 2.75". Thanks again for all your advise.
Comment: What do you think happens if you drill all the way through? (Nothing.)
Answer: Replace the shipped concrete screws with screws of equal or greater diameter and equal or greater length.
How big of a deal the anchors are depends on what they're doing. If your pergola uses moment resisting connections or bracing like knee braces, then the column anchors are there just to prevent the structure from sliding as a rigid body. The toppling of columns is handled by a lateral system like moment resisting connections or bracing.
Alternatively, each of your pergola's columns could be designed as fixed against the concrete base at 90°, where the strength of your slab provides the lateral system to the pergola. In this scenario, obsessing over the column's base anchorage is warranted.
My intuition is that a company distributing pergolas isn't going to design it so that the bending strength of your concrete is relevant to the design strength of the pergola. Such a pergola would impose difficult design constraints for a supporting wooden deck, for instance. And if people are pointing out how weak the shipped fasteners are, then that's pretty strong supporting evidence that your pergola has a lateral system independent of your concrete.
I suppose wind could cause some significant uplift if plants fill the gaps of the pergola, so that uplift would be a good reason to worry about the anchorage quality.

Anchoring aluminum pergola to 4" slab


Question about Lie derivative

Question: $(M,w)$ is symplectic manifold.
$f_t : M\to M$ is a symplectic isotopy between $f_0=id$ and $f_1$.
Let X_t be the vector field on M satisfying $d(f_t)/dt=X_t(f_t)$
Now I differentiate $(f_t)^*w$. Here goes the problem.
If $X_t$ is time(t) independent, I know that the result is the Lie derivative of w with respect to the vector field $X(write L(X)w)$, simply by definition. But for general $X_t$, Why is the result same as $L(X_t)w$?
The question arose while reading "Dusa McDuff, Dietmar Salamon Introduction to symplectic topology  1999". It appears at p83-84, proof of propostion 3.2. I also found someone's note on the internet but neither the book nor the note explains this. So I suspect that this is trivial problem but still not figured it out. Thanks for the help.
Answer: http://www.math.jussieu.fr/~ma/M2_14/Chap1.2-1.3.pdf
P.27-28, it's the exercise 1.2.26.
It's not trivial, but really makable, as you'll see.

Question about Lie derivative


Windows 10 - vagrant plugin install vagrant-aws - The "libxml2" package isn't available. (RuntimeError)

Question: Trying to install aws plugin for vagrant. Getting a dependency error.
Logs show...
find_executable: checking for xml2-config... -------------------- no

--------------------

"pkg-config --exists libxml2"
package configuration for libxml2 is not found

Console output:
C:\Users\jkittell\Documents\Schedule3> vagrant plugin install vagrant-aws
Installing the 'vagrant-aws' plugin. This can take a few minutes...
Building native extensions.  This could take a while...
Bundler, the underlying system Vagrant uses to install plugins,
reported an error. The error is shown below. These errors are usually
caused by misconfigured plugin installations or transient network
issues. The error from Bundler is:

ERROR: Failed to build gem native extension.

    current directory: C:/Users/jkittell/.vagrant.d/gems/2.4.4/gems/ovirt-engine-sdk-4.2.4/ext/ovirtsdk4c
C:/HashiCorp/Vagrant/embedded/mingw64/bin/ruby.exe -r ./siteconf20181002-19764-xj4q7a.rb extconf.rb
checking for xml2-config... no
*** extconf.rb failed ***
Could not create Makefile due to some reason, probably lack of necessary
libraries and/or headers.  Check the mkmf.log file for more details.  You may
need configuration options.

Provided configuration options:
        --with-opt-dir
        --without-opt-dir
        --with-opt-include
        --without-opt-include=${opt-dir}/include
        --with-opt-lib
        --without-opt-lib=${opt-dir}/lib
        --with-make-prog
        --without-make-prog
        --srcdir=.
        --curdir
        --ruby=C:/HashiCorp/Vagrant/embedded/mingw64/bin/$(RUBY_BASE_NAME)
        --with-libxml2-config
        --without-libxml2-config
        --with-pkg-config
        --without-pkg-config
extconf.rb:29:in `': The "libxml2" package isn't available. (RuntimeError)

To see why this extension failed to compile, please check the mkmf.log which can be found here:

  C:/Users/jkittell/.vagrant.d/gems/2.4.4/extensions/x64-mingw32/2.4.0/ovirt-engine-sdk-4.2.4/mkmf.log

extconf failed, exit code 1

Gem files will remain installed in C:/Users/jkittell/.vagrant.d/gems/2.4.4/gems/ovirt-engine-sdk-4.2.4 for inspection.
Results logged to C:/Users/jkittell/.vagrant.d/gems/2.4.4/extensions/x64-mingw32/2.4.0/ovirt-engine-sdk-4.2.4/gem_make.out
PS C:\Users\jkittell\Documents\Schedule3>

Answer: I did a google search and found a hotfix for this.
Gem file available here.
Just do a vagrant plugin install ~/PATH/TO/vagrant-aws-0.8.0.gem
I had to install fog-aws plugin first and then it worked.
vagrant plugin install fog-aws
Console output:
PS C:\Users\jkittell\Documents\Schedule3> vagrant plugin install ..\..\Downloads\vagrant-aws-0.8.0.gem
Installing the '..\..\Downloads\vagrant-aws-0.8.0.gem' plugin. This can take a few minutes...
Fetching: iniparse-1.4.4.gem (100%)
Fetching: fog-core-2.1.2.gem (100%)
Fetching: fog-aws-3.3.0.gem (100%)
Bundler, the underlying system Vagrant uses to install plugins,
reported an error. The error is shown below. These errors are usually
caused by misconfigured plugin installations or transient network
issues. The error from Bundler is:

conflicting dependencies fog-aws (= 2.0.1) and fog-aws (~> 3.0)
  Activated fog-aws-3.3.0
  which does not match conflicting dependency (= 2.0.1)

  Conflicting dependency chains:
    vagrant-aws (= 0.8.0), 0.8.0 activated, depends on
    fog-aws (~> 3.0), 3.3.0 activated

  versus:
    fog-aws (= 2.0.1)

PS C:\Users\jkittell\Documents\Schedule3> vagrant plugin install fog-aws
Installing the 'fog-aws' plugin. This can take a few minutes...
Successfully uninstalled dry-inflector-0.1.2
Successfully uninstalled fog-aliyun-0.3.2
Successfully uninstalled fog-atmos-0.1.0
Successfully uninstalled fog-aws-2.0.1
Successfully uninstalled fog-brightbox-0.16.1
Successfully uninstalled fog-cloudatcost-0.1.2
Successfully uninstalled fog-core-1.45.0
Successfully uninstalled fog-digitalocean-0.4.0
Removing console
Removing setup
Successfully uninstalled fog-dnsimple-1.0.0
Successfully uninstalled fog-dynect-0.0.3
Successfully uninstalled fog-ecloud-0.3.0
Successfully uninstalled fog-google-0.1.0
Successfully uninstalled fog-internet-archive-0.0.1
Successfully uninstalled fog-joyent-0.0.1
Successfully uninstalled fog-local-0.6.0
Successfully uninstalled fog-openstack-0.3.6
Successfully uninstalled xml-simple-1.1.5
Installed the plugin 'fog-aws (3.3.0)'!
PS C:\Users\jkittell\Documents\Schedule3> vagrant plugin install ..\..\Downloads\vagrant-aws-0.8.0.gem
Installing the '..\..\Downloads\vagrant-aws-0.8.0.gem' plugin. This can take a few minutes...
Installed the plugin 'vagrant-aws (0.8.0)'!
PS C:\Users\jkittell\Documents\Schedule3> vagrant plugin install vagrant-aws
Installing the 'vagrant-aws' plugin. This can take a few minutes...
Installed the plugin 'vagrant-aws (0.8.0)'!
PS C:\Users\jkittell\Documents\Schedule3>

Answer: Try using:
vagrant plugin install fog-aws
vagrant plugin update
vagrant plugin install vagrant-aws

This should upgrade fog to a version 3.5 or greater


I ran a .exe setup file for MS Office 07

Question: I right clicked the setup.exe for word 2007 and ran it by wine 1.2.3 after installation i clicked ok but where do i find my new office software, not in dash home, can't find by terminal, i just installed ubuntu 12.4 lts today so please explain and answer this please
Comment: I would recommend installing MS Office via PlayOnLinux. Here is a useful link: http://www.makeuseof.com/tag/easily-install-microsoft-office-2007-linux/
Comment: Unless you absolutely need MS Office, I'd like to recommend KingSoft office as a "clone" or alternative. It's quite alike to MS Office and I've personally had success using it in a business context with limited compatibility issues. You can download it here: http://wps-community.org/download.html
Comment: ++1 for PlayOnLinux... I had been using Crossover Office, but I find that PlayOnLinux works best and it's free... (and easy to setup).
Answer: It should appear when looking for "Word" or "Excel" on the dash if it still doesn't, then go to the dash and look for Explore C unit that will prompt the "Wine space" on your computer, then look for the executable files.
The MS Office executable files are usually located at %ProgramFiles%\Microsoft Office\Office12\WinWord.exe (within the C unit and changing "WinWord.exe" by the office application desired). If you have any other questions, please let us know.
Note: The "C folder" is usually located at Home/.wine/dosdevices/c:.
Answer: There are some problems installing Office 07 under Wine 1.2.3.  See Wine App Database.
I would recommend that you upgrade your Wine installation to a later release, and try installing Office again.
Installed properly, you should be able to run the Installed office by typing Microsoft Office in Dash.


Autoscale range 16-bit grayscale image in Java

Question: I have an 12-bit grayscale image. I want to display it in Java with BufferedImage, and I find BufferedImage.TYPE_USHORT_GRAY is the most suitable. However, it makes my display image almost black (my pixels are in 0 ~ 4095 range).
How can I autoscale it to clearly display it?
Thanks so much.
Comment: How are your data represented? As 16 bit samples with the upper 4 bits zeroed, or as continuous 12 bit data (two samples will occupy 3 bytes)?
Comment: It is 16-bit allocated. T tried to multiply to 16. It seems good.
Answer: You need to scale from 12 bit to 16bit. Multiply your values by 16
Answer: If your data is stored as 16 bit samples (as indicated in the comments), then you can either:

Multiply the samples (by 16) to the full 16 bit range, and create a BufferedImage.TYPE_USHORT_GRAY image. Straight forward, but requires massaging and copying the data.
Or, you could also create a custom BufferedImage with a 12 bit ColorModel, and just use the data as is. Probably faster, but more verbose/complicated code.

Here's the code to create an image using a 12 bit gray color model:
WritableRaster raster = Raster.createInterleavedRaster(new DataBufferUShort(twelveBitData, twelveBitData.length), w, h, w, 1, new int[]{0}, null);

ColorSpace gray = ColorSpace.getInstance(ColorSpace.CS_GRAY);
ColorModel twelveBitModel = new ComponentColorModel(gray, new int[]{12}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
BufferedImage image = new BufferedImage(twelveBitModel, raster, twelveBitModel.isAlphaPremultiplied(), null);

Full, runnable demo program below.
Alternatively, if your data had been stored as "one and a half byte" packed 12 bit samples, the simplest solution would be to first pad the data to full 16 bit samples.

Demo program:
public class TwelveBit {

    public static void main(String[] args) {
        int w = 320;
        int h = 200;
        short[] twelveBitData = new short[w * h];

        createRandomData(twelveBitData);

        WritableRaster raster = Raster.createInterleavedRaster(new DataBufferUShort(twelveBitData, twelveBitData.length), w, h, w, 1, new int[]{0}, null);

        ColorSpace gray = ColorSpace.getInstance(ColorSpace.CS_GRAY);
        ColorModel twelveBitModel = new ComponentColorModel(gray, new int[]{12}, false, false, Transparency.OPAQUE, DataBuffer.TYPE_USHORT);
        BufferedImage image = new BufferedImage(twelveBitModel, raster, twelveBitModel.isAlphaPremultiplied(), null);

        showIt(image);

    }

    private static void createRandomData(short[] twelveBitData) {
        Random random = new Random();
        for (int i = 0; i < twelveBitData.length; i++) {
            twelveBitData[i] = (short) random.nextInt(1 << 12);
        }
    }

    private static void showIt(final BufferedImage image) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("test");
                frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);

                frame.add(new JLabel(new ImageIcon(image)));

                frame.pack();
                frame.setLocationRelativeTo(null);
                frame.setVisible(true);
            }
        });
    }
}

Comment: Got it! Thank you so much!


Ruby/Rails updating existing records with duplicate's data

Question: I have an app that has monitors the development of skills, it has many training_programs and each training_program has many participants.
The user every month can add either participants individually or by upload through excel. I have a situation now where people are uploading a spreadsheet that is amended each week, this is duplicating the participants within the system.
One of the fields is times_trained, and what they are expecting is each time a participant is added if it exists then just sum all the attributes together.
Training_program.participants.first
  => { id: 33, name: "rob", id: 123456789, times_trained: 3, amount_spent: 65000 }

So if we want to add
Participant.new(name: "rob", id: 123456789, times_trained: 2, amount_spent: 25)

Rather than adding a new participant, it should update the existing one. so if we want to find rob again we can say
Participant.find(33)
  => { id: 33, name: "rob", id: 123456789, times_trained: 5, amount_spent: 65025}

We use the ID as the unique optional identifier, so if they don't have an id then we assume that they are always new. Is there anything baked into rails that i can use to do this?
What i am planning on doing is before saving it i'll find if there is a participant with the id provided, if so then pull that record and sum the two of them together and save the record. ill have to test how efficient that will be, but i don't see it being very efficient.
Any help or reading would be great. I have found a few queries on SO about finding duplicate records but its on a global scale and it can take up to 60seconds just to locate a duplicate never mind updating it. we have close to 25 million participants within the Participant table and 650 thousand are duplicates.
Answer: you can use find_or_initialize_by and write something like this:
excel_row =  { id: 33, name: "rob", id: 123456789, times_trained: 3, amount_spent: 65000 }
participant = Participant.find_or_initialize_by(id: excel_row[:id])
participant.name = excel_row[:name] #Set this row default 0 in your db
participant. amount_spent += excel_row[:name]) #Set this row default 0 in your db
participant.save

So, if a participant is found, the data is updated, in the other case it update the row


validating numbers only and letters only in my textbox

Question: Pleasant day everyone.. i have this java script code in my php file wherein i used this as my validator..for the inputs in different fields in my textbox... my only problem is i don't know how to create a validation that only accepts letters... in my first name and last name field ...looking forward for any assistance thanks have a nice day... i also wanted to know how about accepting numbers only in my field super thanks ^^,
Here's the code:

Answer: only letters : /^[a-zA-Z]+$/ or /^[a-z]+$/i
only numbers: /^[0-9]+$/
Comment: thanks for answering ^^, i'll just try this one.. check if it works .. thanks again
Comment: Or just `/^\d+$/` for the digits


Takes 30 mins to respawn in ark

Question: Whenever my friend joins my ark world on the island on the Xbox one, the respawn time can take up to 39 minutes. What could be causing this and how can I fix it?
Answer: It could be because of your world settings, there are options for respawn times. I found these:
Increase PvP Respawn Interval - Enabling will allow for setting changes in repeat deaths from PvP.
Inc PvP Respawn Interval Check Period - The time in which repeat deaths will still count towards a higher respawn timer. !
Inc PvP Respawn Interval Multiplier - The higher the number the longer respawn timers for each death within the "Check Period" interval.
Inc PvP Respawn Interval Base - The base amount of time for one death from PvP. Each death after within the "Check Period" will use the "Multiplier" setting above.
Found this at https://www.reddit.com/r/ARKone/comments/49jwsw/xbox_one_server_settings_explained_to_my_best/
Comment: care to expand on your answer as to what settings could be causing this?
Comment: Fixed my answer, added much more info
Comment: *Much* better than your original answer.  Please take our tour to learn what we're all about, as your previous answers are very low quality, and liable to deletion.
Answer: When you're making the game, scroll down to Enable PvE and check it. Start the server and that should make it work.

Takes 30 mins to respawn in ark


How to stop XDM performing automatic downloads

Question: I am using XDM (Xtreme Download Manager) as Download manager in Ubuntu 14.04 LTS. It works well but sometimes it shows pop-ups to download some mp3 or wav files from different sites, sometimes even when I open Google.
Today while using WebHTTrack, it opened such pop-ups for like 1000+ times and my laptops went to halt. Here's a snapshot of what it looks like.

I need some idea to stop such automatic downloads. I went through its settings, but could not find any settings to change or work with.
Answer: Try the latest version.
This problem is fixed in version 4.7 for Linux
There is a checkbox added in the new download dialog, which can add the unwanted link to download ignore list.
Answer: I tried to do it by going through settings. In Exceptions I added Soundcloud but it still opened 100% of downloaded pop ups.
What worked was to disable it while using Soundcloud.
Comment: Please edit your answer and add some more details how to disable it. The answer must be useful in general (not only for the person asking, notice that the question is two years old).


How best way in JavaScript to do return promise in object?

Question: In this part of my code that is to try to identify if it is CPF or CNPJ before and already returns whether it is valid or not, I needed the result of the Validate () function to return to the {valid: true} object but it only returns {valid : Promise {}}, I tried to put async and await but the same result. :-(
He does not expect the promise. I tried promise.resolve(Valid (number, type)), but the return is <promise>.
Any suggestion?
function cpfcnpj (doc){
    let valid = false,
        number = doc.toString().replace(/\D/g, ''),
        masked = false,
                type = number.length === 11 ?
            'CPF' : number.length === 14 ?
                'CNPJ' : false

    if (type === 'CPF') {
        masked = number.replace(
            /(\d{3})(\d{3})(\d{3})(\d{2})/,
            "$1.$2.$3-$4"
        )
    }
    if (type === 'CNPJ') {
        masked = number.replace(
            /^(\d{2})(\d{3})(\d{3})(\d{4})(\d{2})/,
            "$1.$2.$3/$4-$5"
        )

    }

    function Valida(number, type)
        valid = true;

        let Soma = 0, Resto;

        if (number == "00000000000") valid = false;

        for (i = 1; i <= 9; i++) Soma = Soma + parseInt(number.substring(i - 1, i)) * (11 - i);
        Resto = (Soma * 10) % 11;

        if ((Resto == 10) || (Resto == 11)) Resto = 0;
        if (Resto != parseInt(number.substring(9, 10))) valid = false;

        Soma = 0;
        for (i = 1; i <= 10; i++) Soma = Soma + parseInt(number.substring(i - 1, i)) * (12 - i);
        Resto = (Soma * 10) % 11;

        if ((Resto == 10) || (Resto == 11)) Resto = 0;
        if (Resto != parseInt(number.substring(10, 11))) valid = false;

        return valid
    }

    return {
        type: type,
        valid: Promise.resolve(Valida(number, type))
                    .then(valid => { return valid }),
        number: number,
        masked: masked
    }
}

console.log(cpfcnpj('123.456.789-01'));
console.log(cpfcnpj('123 456 789@12'));
console.log(cpfcnpj('11.911.119/0001-9'));
console.log(cpfcnpj('11.9s11.1d19%0001&9'));

RETORNO:

{
  type: 'CPF',
  valid: Promise { <pending> },
  number: '12345678901',
  masked: '123.456.789-01'
}
{
  type: 'CPF',
  valid: Promise { <pending> },
  number: '12345678912',
  masked: '123.456.789-12'
}
{
  type: false,
  valid: Promise { <pending> },
  number: '1191111900019',
  masked: false
}
{
  type: false,
  valid: Promise { <pending> },
  number: '1191111900019',
  masked: false
}

Comment: Why are you using a `Promise` at all?  Why not just `valid: Valida(number, type)` ?
Comment: I would like put Valida() in a external module if is possible to structure a multi files codes
Comment: And what's stopping you from doing that?  Have you attempted that and encountered a different problem?
Answer: This looks like a case of overengineering gone awry.  There's no reason to use a Promise here, because there's no asynchronous operation taking place.  Just set the value in your return object with the result of your function:
return {
    type: type,
    valid: Valida(number, type),
    number: number,
    masked: masked
}


I want to set automatic selected file in input type if file exist in path

Question: I want to set file automatically loaded if exist file in local defined default path.
here is the code
<form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="hard_file" >
<input type="submit" name="submit" class="submit">

Comment: It is not possible. Only the user can select a file.
Comment: Make sure to actually ask a question at least in your title, since this is a Q&A website. Just saying what you want does not make it easy to formulate an answer.
Comment: Possible duplicate of [How to set a value to a file input in HTML?](https://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html)
Comment: your question is not clear. Can you clarify you question in detail? I think you want to know that the file selected by user already exists on your server?
Answer: all you have to do is follow this post
How to set a value to a file input in HTML?
In there is a reazon for what that is not permitted:

You cannot due to security reasons.

Imagine:
<form name="foo" method="post" enctype="multipart/form-data">
    <input type="file" value="c:/passwords.txt">
</form>

You don't want the websites you visit to be able to do this, do you? =)


Select all rows having specific value assigned only once

Question: I am confused that how i can query this from table below. I have to get only those categories which is assigned to a single group.
**Id**          **Category**   **PracticeGroup**
1               Category-1     Practice Group-1
2               Category-1     Practice Group-1
3               Category-2     Practice Group-2
4               Category-1     Practice Group-1
5               Category-2     Practice Group-1

As in above scenario Category-1 will be the result set which has only one assigned practice group "Practice Group-1".
Comment: Use an aggregate query : group by category, add COUNT(group), then add a filter such that COUNT(group) = 1
Answer: Just can do this :-
select [category] from (select distinct [category] ,[Practice Group] from tbl) as temp
group by [category]
having count([category]) = 1

Answer: You can use the same query what @potasin mentioned, with the min of Practice Group
select [Category],min([Practice Group])
from tbl
group by [Category]
having count(distinct [Practice Group]) = 1

Answer: I like to approach this type of question by comparing the minimum and maximum values:
select cateogry
from t
group by category
having min(practicegroup) = max(practicegroup);

Although count(distinct) can also be used, count(distinct) is much more expensive than simpler aggregation functions.  Also note that this ignores null values.  If you want to ensure that null values do not affect the results:
select cateogry
from t
group by category
having min(practicegroup) = max(practicegroup) and
       count(practicegroup) = count(*);


How to toggle geojson layer visibility in openlayers 3 on click of a button?

Question: I have several geojson layers added via:
    var layer1 = new ol.layer.Vector({
        title: 'Geojson 1',
        source: new ol.source.Vector({
            url: 'geojson1.json',
            format: new ol.format.GeoJSON()
        })
    });

    map.addLayer(layer1);
    var layer1 = new ol.layer.Vector({
        title: 'Geojson 2',
        source: new ol.source.Vector({
            url: 'geojson2.json',
            format: new ol.format.GeoJSON()
        })
    });

    map.addLayer(layer2);

How can I create a button "Toggle Layer 1" and another button for "Toggle Layer 2" outside of my map that has an onclick event so that the corresponding layer will show and hide on click?
Answer: You can bind it to button element like this (using layer1 as an example, similar for layer2 as well):
document.getElementById("myBtn").onclick = function() {
    layer1.setVisible(!layer1.getVisible());
};

If you have a lot of these layers/buttons, a helper function could generalize the step and make it cleaner:
var bindLayerButtonToggle = function (btnId, layer) {
    document.getElementById(btnId).onclick = function() {
        layer.setVisible(!layer.getVisible());
    };
}

Then you can just do:
bindLayerButtonToggle("myBtn", layer1);
bindLayerButtonToggle("myBtn2", layer2);


Multiple dataframes column re-arranging using for loop

Question: I have a list of dataframes with these columns
Color Date     Fruit     Num

all have same columns.
I need to re-arrange columns. However, for loop doesn't seem to work.
for i in [df1,df2,df3,df4,df5,df6]:
    i = i[['Date','Fruit','Num','Color']]

this way
df1 = df1[['Date','Fruit','Num','Color']]

it changes columns order but why not in loop. Isn't i every time looping through each dataframe and assigning reorder of column names.
Any advice?
Comment: The reason the loop does not work is because you assign to `i`, not to `df1`, etc.
Comment: I'd use a dictionary of DFs instead of list of DFs.
Comment: yeah I realized what was going wrong, python noobie I am
Answer: Consider using dictionary of DFs instead of list of DFs:
Given data sets:
In [470]: df1
Out[470]:
    c   b   a
0  63  85  49
1  51  20  43
2  92  67  93
3  58  11  96
4  19  70  82

In [471]: df2
Out[471]:
    b   c   a
0  83  53   0
1  45  23  43
2  49  64  93
3  76  34  38
4  98  78  88

In [472]: dfs = {'df1':df1, 'df2':df2}

Solution:
In [473]: for k in dfs.keys():
     ...:     dfs[k] = dfs[k][['a','b','c']]
     ...:

In [474]: dfs
Out[474]:
{'df1':     a   b   c
 0  49  85  63
 1  43  20  51
 2  93  67  92
 3  96  11  58
 4  82  70  19, 'df2':     a   b   c
 0   0  83  53
 1  43  45  23
 2  93  49  64
 3  38  76  34
 4  88  98  78}

In [475]: dfs['df1']
Out[475]:
    a   b   c
0  49  85  63
1  43  20  51
2  93  67  92
3  96  11  58
4  82  70  19

In [476]: dfs['df2']
Out[476]:
    a   b   c
0   0  83  53
1  43  45  23
2  93  49  64
3  38  76  34


How to obtain debug information (symbols) for gcc OpenMP library?

Question: I have a GCC OpenMp library (libgomp.so) that doesn't contain any symbol, and I need to either install/compile a new library with symbols or obtain debug information for the library. I found something (lib64gomp1-dbg) in the gcc-5 package, but I'm not sure if this is what I want and I don't know how to install it either (I've tried sudo apt-get lib64gompl-dbg, but it didn't work, it threw the error: E: Invalid operation lib64gompl-dbg). So how can I get debug symbols for the library? I'm fresh new to Linux, can somebody give me a hint on how to do that? Thanks a lot!
Comment: I think you need `apt-get install`, not just `apt-get`.
Comment: I think the above comment solves your problem. Also please ask [\[ mcve \]](http://stackoverflow.com/help/mcve)s here.
Answer: You need to use
sudo apt install lib64gompl-dbg

(Note the inclusion of the word install.)


I am trying to understand step 6 in https://help.ubuntu.com/community/MovingLinuxPartition

Question: I am trying to copy a partition and make the copy bootable (the original is bootable).  Step 6 of MovingLinuxPartition refers to something called [instance].  What is that?
Given that one of the consequences of guessing what this means incorrectly is that my computer will become entirely unbootable, I am reluctant to just go blindly guessing.
The "disks" application is actually gnome-disks.  Is there a CLI equivalent for if you are working on a server?
Comment: Note that those older instructions are for MBR (msdos) partitioning which uses MBR for BIOS boot. Newer systems use gpt for UEFI and can use gpt for BIOS boot. But gpt has GUID in partition, primary partition table & backup partition table and GUIDs must all match. So you should not use dd on a partition as duplicate GUIDs not allowed. You may be able to repair with gdisk. http://www.rodsbooks.com/gdisk/ Better to just do new install & restore data, configuration & apps from your normal backup. Also good way to confirm backup has everything as you still have install to recover missing info.
Comment: Have you been satisfied with my answer? Then please give me an upvote (▲). If I could solve your problem, it would be nice if you [accepted](https://meta.stackexchange.com/q/5234/217657) my answer (✓). In the opposite case, please clarify your needs by [edit]ing or comments. See also [What should I do when someone answers my question?](https://askubuntu.com/help/someone-answers)
Answer:
Step 6 of MovingLinuxPartition refers to something called [instance]. What is that?

The sentence below the command line with [instance] tells you:

Where [instance] is the version you want to make bootable

When I do ls -l /usr/lib/grub, I get just one folder called i386-pc which is likely the "instance" you are looking for.

The "disks" application is actually gnome-disks. Is there a CLI equivalent for if you are working on a server?

Yes but there are multiple CLI tools and ways used to do the tasks integrated into Disks. The page you are referring to speaks about modifying mount options. This can be done by editing the /etc/fstab file manually. If you don't know how to do it, refer to similar questions or ask a new one describing your specific situation.