How to perform multiple HTTP requests with unique IP addresses from my local

Question: I am trying to call our homepage www.123.com 10 times simultaneously with unique IP addresses.
We are having issues with GTag Analytics and I am trying to confirm if I can call our homepage 10 times and it will register on GTAG, or not.
I have found 2 posts on load balancing testing with unique IP addresses, which would allow me to do this
One using K6 and the other using JMeter.
k6 -> https://stackoverflow.com/questions/72016444/websites-load-testing-using-k6-from-multiple-ip-addresses
but the comment suggests it wont work on a laptop you need more Network cards (which aligns with my findings below)
I tried using JMeter and selecting 'Number of Threads (users) and increasing this to 10, these tests passed, but it only showed as one user on GTag, because of the same IP im assuming.
I found this post which talks about this and suggests Spoofing(adding multiple IP addresses to your IP4) and running with JMeter which should make a call for each IP address,
https://stackoverflow.com/questions/41049686/how-to-create-a-load-test-with-unique-ip-addresses

But this didnt work. The article states 'In the case of a DHCP-assigned address, the IP alias feature won't work and you won't be able to add extra IP addresses to your network adapter.'
As I am running through my home router which would be using DHCP, this would not work
Any replies very much appreciated thank you
(I tagged C# and JS also incase theres anything thats available that I am unaware of thank yoU)
Comment: Your home router is likely using NAT, which would translate all requests to use your public IP address.
Comment: Yea, in other words its still not going to let me assign multiple IP addresses?? any advice?
Answer: For JMeter it's possible to bind the request to the IP address of your choice via "Source address" field of the HTTP Request sampler:

The IP address (or its alias) needs to be present in the system.
If you're behind NAT the system under test will see only one IP address which is assigned to your by your ISP or your organization or whatever.
So if you need to hit an application residing in the Internet from 10 different IP addresses - these IPs need to be global so you need to reach out to your ISP and ask for them or kick off 10 machines somewhere in cloud like Oracle or Azure and run your JMeter test in distributed mode
And last but not the least, I don't know what "GTag Analytics" is, but I suppose that it's some form of an anal probe which adds an invisible pixel to your web page and it runs tons of JavaScript to track you. As per JMeter project main page:

JMeter is not a browser, it works at protocol level. As far as web-services and remote services are concerned, JMeter looks like a browser (or rather, multiple browsers); however JMeter does not perform all the actions supported by browsers. In particular, JMeter does not execute the Javascript found in HTML pages. Nor does it render the HTML pages as a browser does (it's possible to view the response as HTML etc., but the timings are not included in any samples, and only one sample in one thread is ever displayed at a time).

So in order to "see" 10 users in analytics you need to either mimic the JavaScript XHR calls the GTag is doing or use other monitoring options.


How to open Treasure Pods

Question: I've placed made and placed over 35 gadgets and I got the thing saying that I unlocked the treasure cracker but it's not in my store or in my blueprints. I can't open the treasure pods either. I've tried restarting my game but it still doesn't work. Any thoughts?
Answer: A check of the wiki reveals the answer:

To open Treasure Pods, you must obtain Treasure Crackers from the Vacpack upgrade terminal. There are three tiers, each opening more advanced Pods:
The Treasure Cracker MKI allows you to open Green Pods; it will become available once The Lab is unlocked and your first gadget has been crafted. It costs 4,500Newbucks.
The Treasure Cracker MKII allows you to open Blue Pods and will become available after the MKI Upgrade is bought and a total of 35 Gadgets have been crafted in The Lab. It costs 9,000Newbucks
The Treasure Cracker MKIII allows you to open Purple Pods and becomes available after the MKII Upgrade is bought and a total of 100 Gadgets have been crafted in The Lab. It costs 25,000Newbucks.
It is not necessary to use the gadgets you create to unlock the Treasure Crackers.

Make sure that you have unlocked the Lab in order to gain access to the Treasure Crackers.

How to open Treasure Pods


Why put staff on bridge/engine room instead of dodge/gun rooms?

Question: What's the purpose of having red shirts on the bridge other than a better response to boarding parties? Would you ever staff them in the bridge instead of one of the gun rooms?
Likewise, is there ever a reason to put extra engineers in the engine room instead of the dodge room?
Comment: Thanks for the edit and the proper tag Yi Jiang's Evil Clone
Answer: Bridge and engine rooms boost all the other rooms.
For example, a weapon room with no people in the bridge will function at 50% its maximum capacity, which I assume means that the weapon recharges half as fast as it otherwise would. The bridge contributes 25%, the engine room contributes 25%. Thus one person contributes about 6.25% to each room.
This adds up to quite a lot when you have a lot of rooms. The small boost is also cheaper than getting most room upgrades. However, make sure that you have at least one staff in the small rooms first, because the rooms would not function without staff.
One tactic is to constantly keep your bridge and engine room staffed, so that the dodge and shield generator constantly regenerate the shields fast enough to prevent invaders from teleporting in.
Answer: Not sure about the bridge. My assumption was that having crew in the bridge would boost command recharge times, though I've yet to confirm this. As for the engine room, having engineers in there speeds up the shield recharge rate. Further, I also noticed during the final battles that having multiple engineers in the engine room (along with a fully upgraded ship that includes a shield booster room) gave a small, but significant boost to shield threshold. Having this basically stopped boarding parties from teleporting to my ship following an enemy attack. I would cycle between dodge and shield boost to ensure that my shields were always fully intact prior to an incoming attack. This made the end game battles extremely easy (on normal difficulty).
Answer: After playing for a few more hours, the answer is clear to me now:

Always put staff in your rooms first
Each room has a limit of 2 staff, and you'll hit this limit very quickly
Personally, I prefer to keep the Dodge room fully staffed at all times and have 1 extra engy who can roam the ship making repairs. AFAIK you do not need staff to stay in the engine room or bridge for any reason.


NodeJS package.json dependency from github

Question: I have a nodejs project, and a dependency:

https://github.com/MrRio/jsPDF

Usually i used package.json for manage my dependencies, but jsPDF isnt in npm, can i download it from github directly in package.json?
Answer: You sure can.
You can specify the repository as username/repo or use a full URL such as
git://github.com/user/project.git

So in your case it'd be
"dependencies": {
  "jsPDF": "MrRio/jsPDF"
}

Also jsPDF is a client-side dependency. Meaning it won't work in Node.js and will only work in the browser, which is why it isn't in NPM, because it's not a Node.js module.
Comment: I have this error:

npm ERR! Error: ENOENT, open '/var/folders/pg/c27d18sn72x0kj3w7xm7hzlw0000gp/T/npm-62590-LzdWVmxm/1400669796361-0.9027906500268728/package/package.json'
Comment: I will use in angularjs client. I was think it was server-side library. Thanks you.


URL styling: Why should I use ids+slug names ("/products/[id]-[product-name]") over slug names only ("/products/[product-name]")?

Question: Some details about my product list first:

Static, contains about 400 items.
It will not grow any further. Trust me on this one.
No duplicate item names.
Properties of products will not change.

Basically think of my product list as the periodic table. I do not see any point of adding the id to the URL with the "slug name" (or whatever it's called). I'd rather have a clean SEO friendly URL. Is there something I'm overlooking here?
Comment: Who is telling you to use the first option?
Comment: Nobody. I'm just looking for an opinion :) I want to use good practice from the very start.
Answer: Here's the thing about IDs and slug names:
Using "product-id":
Usually, URLs are designed using the ID:
"/products/[product-id]"
example: /products/213

But they are too little descriptive about what's exactly in that URL (I mean, different URLs will have different IDs, but this alone - just by looking at it - will not give you any information about that specific URL.)
Botoom line: ID-only is bad because it is little descriptive.
Using "product-name":
Using:
"/products/[product-name]"
example: /products/three-legged-walking-oven

Is actually pretty good, the caveats are:

How are you going to map a [product-name] into a [product-id]?
Titles (or [product-name]) change a lot, what if someone bookmarks an old title?

Using "[product-id]/[product-name]":
Using:
"/products/[product-id]/[product-name]"
example: /products/213/three-legged-walking-oven
or
"/products/[product-id]-[product-name]"
example: /products/213-three-legged-walking-oven

In this approach, you get the product by the id part of the URL.
Gives you the best of both worlds: descriptive urls AND easy to map urls AND titles (names) can change without making old URLs useless.
Your scenario:
So, if you are 100% certain you'll never change your products' name, you can go on and use "product-name". Just find a way to map that "product-name" into a "product-id" in an efficient way.
Bonus: Make sure you check out this nice article about the importance of using slug names and search engines.
Answer: Since whatever is at the end of the url is what your app will use to look up the product in the database, this turns into a database question. Keeping the id in the url lets your app look things up by id.
If your product names will never ever change, and you can actually use the product name as a primary key (or at least have a unique index on the colum) in your database, then you might get away with using just the product name in your URL as well.
Usually, it's better practice to have a unique, meaningless field as your primary key, because things like product names tend to change in most cases, even if only to fix typos.
Answer: The only reason i can think of is that to use /products/[id]-[name], you need to know both the id and the [name], to use the second option you only need to know the name.
A more common choice here would be to use : /products/[id]
I would only consider /products/[name] if you are confident if name is: short, unique, does not contain any special characters (&, ? #, / , ...)


No executable code found at line inside Observer - Android Studio gradle breakpoint

Question: I am trying to debug inside of a LiveData Observer but the debugger says that there is

No executable code found at line ...

The following screenshot shows what it looks like after I have removed and replaced the breakpoints at the offending lines.

I have already tried the following:

The answers on this question: Android studio gradle breakpoint No
   executable code found at line
removing .gradle, .iml, app/build and .idea and restarting
invalidating caches and restarting
adb kill-server and adb start-server
cleaning project and resyncing gradle
attaching the debugger to the running process again
uninstalling the app from the device and reinstalling

I am using Android Studio 3.2.1
Any other ideas?
Comment: Did you found solution? I've similar problem, breakpoint at run() method inside Runnable class shows error "No executable code found at line (...) Suspend: thread". And i tried the same ideas as you, without success as well.
Answer: In my case, I was using the observer inside the fragment onActivityCreated Method.
After moving code to onCreate method activity, it is started working.


Sampling vector across image

Question: This might seem a bit strange, but I really feel like there should be a relatively straightforward solution to it. Basically I've got an image in the form of a 3D numpy array (x, y, color). I was following along with this tutorial for a slightly different product area, and found that these methods did not extend well.
As a result, I'm making a modified edge detection algorithm for my use case. As of now this is just some basic signal processing on top of a 1d array. This works great if I only want to sample in the x and y directions, as I can just use the existing rows and columns of the array.
However, to determine orientation of these edges, I would like to be able to sample any arbitrary vector across the image below is an image to help illustrate:

I tried hacking together something that would just append pixels as it crossed them, but it was inefficient, inelegant, and non-ideal in a number of ways. I feel like there must be some relatively elegant way of doing this.
Any ideas? The size of the sample across the vector doesn't really matter to me if that makes things any easier.
Comment: Additional, slightly unrelated question, does anybody know why my image isn't showing up?
Comment: Image shows up for me just fine.
Comment: @askewchan huh, weird.
Answer: I would make an equation for the line you want to cut along, then make a mask around it and keep all pixels that come within some width of it.  For example, say you want a cut along i = 2*j + 34, where i and j are measured in pixels:
h, w = im.shape[:2]
width = 2 # width of slice in pixels, too narrow and it will have gaps
i, j = np.ogrid[:h, :w]
mask = np.abs(2*j + 34 - i) < width
im[mask]

Note that im[mask] will be a 2d array, since it should still have the colors.  It will be ordered so that the uppermost pixels are first, and the bottom pixels are last, opposite of that shown in your arrow, unless of course you have origin=lower in your plotting :)  And if several pixels are selected in each row (if width > 1), then they'll go left to right, so the shape for a slice like your drawing would be a tiny sequence of z's, and for the other direction, backwards z's (s's?).
Keep in mind that for an array there doesn't exist a diagonal slice without some weird zigzag (or alternatively, interpolation) no matter how elegant your implementation is.  You could rotate the image (by some algorithm) and take a horizontal slice.
Comment: So... I was thinking much more along the lines of interpolation here. Mostly because that zigzagging means disaster on edge boundaries, which is mostly what I'm working with here.
Answer: Using the equation
 x2 = x1 + length * cos(θ)
 y2 = y1 + length * sin(θ)

where
θ = angle * 3.14 / 180.0

You can iterate through the pixel using angle and length like
int angle =45; //angle of iteration
int length = 0; //Alternately you can skip the pixel by giving value other than 0
Point P1(starX,startY); //Your starting point.
Point P2;//??

while(1){

  length++;
  P2.x =  (int)round(P1.x + length * cos(angle * CV_PI / 180.0));
  P2.y =  (int)round(P1.y + length * sin(angle * CV_PI / 180.0));

  if(P2_exceed_boundary()) break;
  do_Whatever_with_P2();

}

Comment: Umm... I don't think you mean to be incrementing angle?
Comment: @Slater Tyranus You are right it should be length, thanks for noticing me the mistake. I will edit it.

Sampling vector across image


JSONcpp iterate through a list within the object

Question: My json object has a list in it and I would like to iterate through the elements of the list
I saw the following post Iterating through objects in JsonCpp , but this did not work for me
My json object:
{
         "name": ["str1",str2" ... ]
}

The code that I have and is not working
Json::Value names= (*json)["name"];
for( Json::ValueIterator itr = names.begin() ; itr != names.end() ; itr++ ) {
    string name =  *itr.asString();}

I am getting the following error
cannot convert from 'Json::Value' to 'std::basic_string<_Elem,_Traits,_Ax>

I am sure the elements are string because calling string name = names= (*json)["name"][0].asString() is working
Answer: In c++11 its even simpler now:
for (auto itr : json["name"]) {
    string name = itr.asString();
    // ...
}

Answer: I don't see how you can get a cannot convert error from your code, but I do think I see the problem.
Json::ValueIterator is an iterator; in other words, similar to a pointer, it needs to be dereferenced to access the value it points to.

itr.asString() tries to access the asString method of the iterator, and the iterator doesn't have an asString method.
*itr.asString() tries to access the asString method of the iterator then dereference the result (because of order of operations; . has a higher precedence than *), and the iterator doesn't have an asString method.
(*itr).asString() (using parentheses to clarify precedence) or itr->asString() (using the -> operator, the preferred approach) should work.
Comment: You're welcome.  However, you should use `itr->` instead of `(*itr).`; they mean the same thing, but `->` is cleaner and is the universally accepted style.
Comment: Are you sure about itr->asString()? I am getting type 'Json::ValueIterator' does not have an overloaded member 'operator ->'
Comment: You're right. I'm sorry; I hadn't tested it myself. So `->` is cleaner and is the almost universally accepted style, and I'd consider it a mistake or bug in JsonCpp to not support it, but since it doesn't, use `(*itr).`.


Unexpected = in coffeescript class definition

Question: I'm new to coffee script, and there is likely more things wrong with this definition than this problem itself.
Given
class window.SlideManager
  constructor: (@$contentDiv, @analyticsCanvas) ->
    @iterator = Iterator(@slides)
    @slides = @$contentDiv.data('slides')

  nextSlide: ->
    try {
      url = @iterator.next()
    } catch {
      @iterator = Iterator(@slides)
      url = @iterator.next()
    }

    this.renderSlide(url)

  renderSlide: (slide) ->
    $.get(slide, {nolayout: 'true'}, (data) ->
      @$contentDiv.contents().replaceWith(data)
      window.setupCanvas($(@analyticsCanvas), window.createChartData(window.getVisitCounts($(@analyticsCanvas))))
    )

I get a unexpected = syntax error on line 8 (url = @iterator.next())
Does anyone know what I might be missing?
Answer: You shouldn't be using braces:
nextSlide: ->
  try
    url = @iterator.next()
  catch
    @iterator = Iterator(@slides)
    url = @iterator.next()

First, the basics: CoffeeScript uses significant whitespace to delimit blocks of code. You don't need to use semicolons ; to terminate expressions, ending the line will do just as well (although semicolons can still be used to fit multiple expressions onto a single line). Instead of using curly braces  { } to surround blocks of code in functions, if-statements, switch, and try/catch, use indentation.

See: http://coffeescript.org/
Comment: To explain a bit further: Braces in CoffeeScript are used to denote object literals. So it things that `{ url = @iterator.next() }` is meant to be an object, which is obviously not the right syntax for that.
Answer: You may try to use this without brackets{}:
nextSlide: ->
  try
    url = @iterator.next()
  catch
    @iterator = Iterator(@slides)
    url = @iterator.next()

instead of this:
nextSlide: ->
    try {
      url = @iterator.next()
    } catch {
      @iterator = Iterator(@slides)
      url = @iterator.next()


Converting from Pressure Assisted to Gravity

Question: I have an American Standard 4086 toilet with a Sloan Flushmate pressure assisted unit in it. Is this toilet compatible with a regular gravity flush/fill valve set up if I wanted to remove the flushmate unit?
Thank you
Answer: Hmmm... interesting proposal and probably a question best answered by the American Standard designs engineers, although good luck getting anything out of them.
You could test the physics of your idea by removing the pressure flush mechanism and rigging a stopper in the tank/cistern that you could manually pull up/off. Fill the tank and pull the stopper, this would tell you if the tank size and bowl/trap design will actually flush by gravity. Then it would be a matter of whether or not a traditional flush valve and fill valve will fit in the holes provided.


How to change files permissions from a different hard drive?

Question: I installed yesterday ubuntu 11.10 on my 80GB hard drive and i can't change files permissions on my second hard drive.
How to fix this?
ps: i have dual-boot with win7
mount:
/dev/sda5 on / type ext4 (rw,errors=remount-ro,commit=0)
proc on /proc type proc (rw,noexec,nosuid,nodev)
sysfs on /sys type sysfs (rw,noexec,nosuid,nodev)
fusectl on /sys/fs/fuse/connections type fusectl (rw)
none on /sys/kernel/debug type debugfs (rw)
none on /sys/kernel/security type securityfs (rw)
udev on /dev type devtmpfs (rw,mode=0755)
devpts on /dev/pts type devpts (rw,noexec,nosuid,gid=5,mode=0620)
tmpfs on /run type tmpfs (rw,noexec,nosuid,size=10%,mode=0755)
none on /run/lock type tmpfs (rw,noexec,nosuid,nodev,size=5242880)
none on /run/shm type tmpfs (rw,nosuid,nodev)
binfmt_misc on /proc/sys/fs/binfmt_misc type binfmt_misc (rw,noexec,nosuid,nodev)
gvfs-fuse-daemon on /root/.gvfs type fuse.gvfs-fuse-daemon (rw,nosuid,nodev)
dev/sdb1 on /media/600CA8AD0CA88020 type fuseblk (rw,nosuid,nodev,allow_other,blksize=4096,default_permissions)

Comment: Can you provide some more information?  When you say you installed Ubuntu on your 80GB hard drive, is this the first hard drive or are you referring to the second hard drive again?  What file system is in use on the second hard drive?  The line of output from `mount` corresponding to the second hard drive would be useful here.
Comment: in my first hard drive i have installed ubuntu and win7, on my second i don't have any system, i don't know how to use the command mount.
Comment: ...and why change file permissions on the second HDD? What's wrong with them? What file system is there?
Comment: may be you mean change owner? chown is what you need then!
Comment: @derekk_m: open up the terminal and run the command `mount`.  Partitions from your second hard drive will probably turn up as `/dev/sdb1`, `sdb2`, etc.  If you could provide those lines of output, it should help answer the question.
Comment: I think i know what is the problem, usually after i install win7/xp, some weird file system are created in the the second hard drive'  http://img831.imageshack.us/content_round.php?page=done&l=img831/2567/screenshotat20111208123.png
Answer: Based on the mount output, it looks like your second hard drive is formatted with the NTFS file system.  This isn't a bad choice if you want to be able to access the files from both Ubuntu and Windows, but has slightly different semantics to native file systems.
The NTFS driver does have support for mapping Windows user IDs to equivalent UNIX user IDs though, which might help.  There is a tool called ntfs-3g.usermap that can help you build up the user mapping:

First unmount the NTFS partition by running sudo umount /dev/sdb1 from a terminal.
Build up the user map by running sudo ntfs-3g.usermap /dev/sdb1 in the terminal.  Provide the Ubuntu user account names for each Windows account you want to map.  The program will create a file called UserMap in the current directory.
Remount the file system and copy the UserMap file to the special .NTFS-3G directory:
sudo mount -t ntfs-3g /dev/sdb1 /mnt
sudo mkdir /mnt/.NTFS-3G
sudo mv UserMap /mnt/.NTFS-3g/
You may need to unmount and remount the file system again to make this user mapping take effect.

Once this user mapping file is in place, your Ubuntu user account should have access to any files or folders owned by your Windows account, and any files you create in Ubuntu should look like they were created by your Windows account when you boot Windows.
Comment: Is there a way to reset this "mount" to default?
Comment: Default in what way?  The NTFS file system supports permissions, so that is what is the default behaviour.  The file system driver does support squashing all files down to the same user/group ownership, but that is not a default option.


Entering text into a textarea

Question: I have a form:
function show_welcome()
{
        print_r($_REQUEST);
        global $error_flag , $date_error_flag;

        $first_name = isset($_REQUEST['Fname']) ? $_REQUEST['Fname'] : "";
        $last_name = isset($_REQUEST["Lname"]) ? $_REQUEST["Lname"] : "";
        $phone = isset($_REQUEST["Phone"]) ? $_REQUEST["Phone"] : "";
        $height = isset($_REQUEST["Height"]) ? $_REQUEST["Height"] : "";
        $birthday = isset($_REQUEST["Bday"]) ? $_REQUEST["Bday"] : "";
        $sex = isset($_REQUEST["Sex"]) ? $_REQUEST["Sex"] : "";
        $history = isset($_REQUEST["Hx"]) ? $_REQUEST["Hx"] : "";
        $age = isset($_REQUEST["Age"]) ? $_REQUEST["Age"] : "";
?>
        <form method='post' action=""  >

            First Name: <input type='text' name='Fname' maxlength = '10' value = <?php echo $first_name ?> ></input>
            Last  Name: <input type='text' name='Lname' maxlength = '20' size = '25' value = <?php echo $last_name ?> ></input>

Ten Characters

 Twenty Characters

        Phone: <input type="text" name="Phone" value = <?php echo $phone ?> ></input>
        Height: <input type="text" name="Height" value = <?php echo $height ?> ></input>

XXX-XXX-XXXX

  Inches

        Birthday: <input type='text' name='Bday'  value = <?php echo $birthday  ?> ></input>

<?php
        printf(" \t\t\t\t YYYY-MM-DD   \n\n");
?>

<input type="radio" name="Sex" value = <?php echo $sex ?> value = "0"/>Male
        <input type="radio" name="Sex" value = <?php echo $sex ?> value = "1"/>Female

        Hx:

        <textarea style="overflow: scroll" cols="60" rows="10" wrap="hard" name="Hx" value = <?php echo $history ?>   ></textarea>

        <input type="text" hidden="true" name="Age" ></input>

<input type="submit" />

<input type = "reset" value="Clear Form"/>
        <input type=hidden name='welcome_already_seen'   value='already_seen'>
        </form>
<?php

}

The form is filled out by the user and then checked for valid format.  Invalid format triggers an error message and the script returns to the form.  I wish to show all the data entered, so that the user can more easily make corrections.  Everything is re-entered into the form except the history (Hx).
The $_REQUEST contains the history:
Array ( [Fname] => 44444444 [Lname] => Jones [Phone] => 123-123-4656 [Height] => 62 [Bday] => 1989-03-05 [Sex] => 0 [Hx] => good pt [Age] => [welcome_already_seen] => already_seen )
As an side issue, how can I ensure that the correct radio buttons are re-checked at data re-entry.
Advice and help, please.
Thanks
Answer: Contents of a <textarea> are placed within the start and end tags - There is no value attribute of a <textarea>.
<textarea style="overflow: scroll" cols="60" rows="10" wrap="hard" name="Hx"><?php echo $history ?></textarea>

You should also be careful, as $history can contain HTML that would open your site up to security vulnerabilities.
Radio buttons require the `checked="checked" attribute in order to be checked by default. You'd achieve this like so:
<input type="radio" name="Sex" value="1" <?php echo ($sex == 1 ) ? 'checked="checked" : ''; ?> />

Comment: This works beautifully:
Comment: This  in the textarea string does not work.  Inserted as     and it works.

Entering text into a textarea


What is the frequency of the Sponsor Eagle?

Question: Is there a set frequency for the Sponsor eagle or is the time between 2 sponsor eagles random?
Answer: If you click the sponsor eagle, it will be something around 1 minute before it returns. If you miss it, it will come back after a minute or so.
Comment: @Auro ah, ok, then you have just answered your own question. Do some testing instead of just asking first, alright?
Comment: @Auro also, whoops, I thought you asked the question for a second
Comment: So yes, in a way, it is
Comment: I have done some testing, and when I claim the reward from the Eagle, I actually got the next one within a minute or two.
Comment: I wasn't the one asking the question, though. Yet I didn't want to steal your thunder.


Whether the series converges or diverges

Question: The series is given as
$$\sum_1^\infty\left(\frac{1}{n^2}+\frac{1}{n}\right)$$
In the answer the given series diverges. But I don't know how.
Also tell me how $\sum_1^\infty\frac{1}{n}$ diverges.
Comment: The series diverges because it is $\ge \sum \frac{1}{n}$, which diverges. For the latter, see [this](https://en.wikipedia.org/wiki/Harmonic_series_(mathematics))
Answer: Since general term $$\dfrac{1}{n^2}+\dfrac{1}{n}=\dfrac{1+n}{n^2}\sim \dfrac{1}{n}$$ but $$\sum\limits_{n\leqslant N} \dfrac{1}{n}\sim \ln N$$ so initial series diverges


python too many values to unpack xlsxwriter

Question: I am having a difficult time finding out what the issue could be here. I understand the error and am following the tutorial here, https://xlsxwriter.readthedocs.io/tutorial01.html, for writing to an excel workbook but I still keep getting the error for first, last in accounts:
ValueError: too many values to unpack (expected 2) If anyone could assist then that would be great. I have tried removing the methods for first and last name as well in the accounts tuple for create_accounts() method and replacing with string's but that hasn't helped either.
import xlsxwriter
from account import Acc

class FillExcel(object):
def __init__(self):
    self.obj = Acc()

def create_accounts(self):
    workbook = xlsxwriter.Workbook('accounts05.xlsx')
    worksheet = workbook.add_worksheet()

    accounts = ([self.obj.first_name(), self.obj.last_name()])

    # Start from the first cell. Rows and columns are zero indexed.
    row = 0
    col = 0
    print(accounts)
    for first, last in accounts:
        worksheet.write(row, col, first)
        worksheet.write(row, col + 1, last)
        row += 1

    workbook.close()

test = FillExcel()
test.create_accounts()

Here is the class that contains my methods first_name and last_name for the account object.
import random
import string

# create an account array object that will be used
# in xlsxwriter literal

name=["Beck","Glenn","Becker","Carl","Beckett","Samuel","Beddoes","Mick","Beecher"]

class Acc(object):

    def first_name(self):
        f_name = random.choice(name)
        return f_name

    def last_name(self):
        l_name = random.choice(name)
        return l_name

    def addy_line1(self, address):
        chars1 = string.ascii_uppercase
        chars2 = ''.join(random.choice(chars1) for i in range(4))
        return chars2 + address

    def phone_number(self, area_code):
        rand_num = random.sample(range(10), 7)
        number = str((''.join(map(str, rand_num))))
        return area_code + number

if __name__ == "__main__":
    accObj = Acc()
    accObj.first_name()
    accObj.last_name()
    accObj.addy_line1('123 West St.')
    accObj.phone_number('212')

Here is the full exception that I am getting. (edited)
['Blanchet', 'Ingmar']
Traceback (most recent call last):
  File "C:/Users/Carsten/PycharmProjects/Dna_Nike/Obj_Creator.py", line 29, in <module>
test.create_accounts()
  File "C:/Users/Carsten/PycharmProjects/Dna_Nike/Obj_Creator.py", line 21, in create_accounts
    for first, last in accounts:
ValueError: too many values to unpack (expected 2)

Comment: Please post the full exception, not just the description, so we can verify that it really is coming from `for first, last in accounts:`. But assuming it is that line, you have a `print(accounts)` right before it. What does it print?
Answer: The problem is here:
accounts = ([self.obj.first_name(), self.obj.last_name()])

At first glance, this looks like a tuple of lists, and the only list in the tuple has two values. So, for first, last in accounts: ought to work, right?
But it's not actually a tuple.
Commas create tuples in Python; parentheses are just for disambiguation. The value (2+3) is not a tuple of the single element 5, it's just the number 5. You need 2+3, (or (2+3,)) if you want a tuple with that one element.
And that's exactly what's happening in your code. Without the comma, you're just creating the list [self.obj.first_name(), self.obj.last_name()]. When you iterate over that, you don't get a 2-element list, you get a name (presumably a string), so you're effectively doing first, last = first_name, which is nonsense.1
To fix it, just add the comma:
accounts = ([self.obj.first_name(), self.obj.last_name()],)

Or you could just use a list. You're not really looking for immutability here (otherwise you'd have a tuple of tuples, not a tuple of lists), or for a fixed-size collection where position is meaningful, or for a micro-optimization (a tuple should shave ~6% of the <100 bytes…), and those are the main reasons to use tuples in place of lists:
accounts = [[self.obj.first_name(), self.obj.last_name()]]

1. Actually, it's a perfectly legal statement, because strings are iterable—they iterate their individual characters. But a first name like, say, 'Balla' has 5 characters, and you're trying to unpack those 5 elements into 2 variables. Hence the error ValueError: too many values to unpack (expected 2).
Comment: thank you so much. that was indeed the issue. I actually thought to add the comma in too and after I looked, I now see that I put the comma inside the square brackets of the list and not outside the list, thus making me think this was not the issue. bonehead mistake. Thanks!
Comment: @BallaBaby In Python, lists, unlike tuples, _are_ made by the brackets, so `[2+3]` is a 1-element list. Because you're usually dealing with things like `(1, 2, 3)` vs. `[1, 2, 3]`, you don't notice the difference until the first time you run into this bug, which everyone does at some point…
Comment: one other question. How would you suggest I go about creating more of these list elements and putting them in a tuple? I can't loop through a tuple and append since tuples are immutable. Is there any way to take a list of lists and turn that into a tuple of lists? I'm sorry if the question is vague. Just thought I'd ask
Comment: @BallaBaby Right, you can't `append` to a tuple. You can write `accounts = accounts + (account,)`, but this creates a whole new copy for each "append", which can be a bad idea if the thing is going to get large. (It takes quadratic rather than amortized-linear time, if that means anything to you.) So, creating a list, and then converting to a tuple at the end (with `accounts = tuple(accounts)`), as you suggest, is usually the best answer. (Unless… do you know how to write generators? Create a generator that produces the accounts lazily, then do `accounts = tuple(lazy_accounts)`.)
Comment: @BallaBaby But meanwhile, is there a reason this needs to be a tuple rather than a list? This really does seem like a paradigm use case for a list.
Comment: thanks for the response. My assumption is that writing to an excel workbook needs data in form of a tuple (though I could be wrong). I was just following along with the docs. I do plan on having the data get large and I realize it probably wouldn't be best to constantly be creating new tuples. I do not know how to do generators but it is on my bucket list of things to learn so no better time like the present I guess. I will start there. Thank you.


Get Search Location from Index Page & Zoom to Location on Map Page

Question: I'm trying to setup a redirect from the index page to the map page, so if a user searches for an address using the Places Autocomplete library, they get redirected to the map page with the location that they searched for. The index page does not include a map, but just the search bar with Places Autocomplete library.
The function I've setup on the index page is as follows:
var place;
function indexSearch() {
    // Get Address Field and Attach Places Autocomplete
    var input = document.getElementById('autocomplete');
    var autocomplete = new google.maps.places.Autocomplete(input);

    // Get Place When Place_Changed Event if Fired
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        place = autocomplete.getPlace();
        if (typeof place !== 'undefined') {
            window.location.href = 'map';
            // Don't know what to do here
            // as I can't use map.panTo(place.geometry.location) because
            // map does not exist on index page.
        }
    });

    // Erase Previous Address if Search Bar is Clicked
    inputIndex.onclick = function () {
        inputIndex.value = '';
    }
}

Do I need to include something in the initialize() function which is responsible for setting up the map?
function initialize() {
    var mapOptions = {
        zoom: 17,
        center: {
            lat: -33.8666,
            lng: 151.1958
        },
        disableDefaultUI: true
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
    // Catch place and pan map to its location
}

Edit: At least provide a reason for downvote.
I'm looking into using localStorage or sessionStorage. Pass the lat and lng to either of those, and retrieve the location when the map page is loading. Is this an optimal solution? Will update with answer once I have the solution.
Comment: I had used solution with `localStorage` or `sessionStorage` before with your situation, and I think that's the best way, bro. Try this ^^
Comment: Thank you. I posted my solution below.
Answer: Here's what I ended up doing. It's working for me. Hope it helps someone in future.
In indexSearch() function, set a key in sessionStorage to store lat and lng of place that is searched. Capture this information when the place_event is fired.
var place;
function indexSearch() {
    // Get Address Field and Attach Places Autocomplete
    var input = document.getElementById('autocomplete');
    var autocomplete = new google.maps.places.Autocomplete(input);

    // Get Place When Place_Changed Event if Fired
    google.maps.event.addListener(autocomplete, 'place_changed', function () {
        place = autocomplete.getPlace();
        if (typeof place !== 'undefined') {
            window.location.href = 'map';
            // Set key in sessionStorage
            sessionStorage.myLat = place.geometry.location.lat();
            sessionStorage.myLat = place.geometry.location.lng();
        }
    });

    // Erase Previous Address if Search Bar is Clicked
    inputIndex.onclick = function () {
        inputIndex.value = '';
    }
}

Then in initialize() function, check to see if the key exists. If it does, take the user to that location.
function initialize() {
    var mapOptions = {
        zoom: 17,
        center: {
            lat: -33.8666,
            lng: 151.1958
        },
        disableDefaultUI: true
    };
    var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);

    // Get place from sessionStorage if its exists & pan map to its location
    var placeLat = sessionStorage.getItem('myLat');
    var placeLng = sessionStorage.getItem('myLng');
    if (placeLat && placeLng) {
         var searchedPlace = new google.maps.LatLng(placeLat, placeLng);
         map.setCenter(searchedPlace);
         map.setZoom(15);
    }
}


Calendar in MS Teams not synced with Outlook

Question: The office 365 email account is email@example.com, and the office 365 account is firstname.lastname@example.com. I signed in MS Teams via the account email@example.com. But its calendar (opened by the calendar button on the left sidebar) is completely empty and does not sync with the Outlook Calendar. I am able to schedule a meeting in Teams calendar. But it does not appear in my Outlook Calendar.
I went to https://teams.microsoft.com, and the Calendar button is not on the left sidebar. Actually, the Calendar button on the Teams Desktop just showed up or disappear, after a restart of the desktop app, for no reason.
Also, the workstation is not in the Azure Active Directory of xyz.com. The windows user testuser is a windows local account
Answer: I realized that xyz.com and xyz.onmicrosoft.com are two different platforms. They are hosted by different hosting companies and there is no sync between the two platforms.


Angular Dragdrop Programatic pick up

Question: On my page I'm handling the drag and drop of widgets using your angular-dragdrop. The behavior I'm striving for is the same as rearranging apps on iOS, press-and-hold to enter drag mode, once you've entered the mode, the widgets become draggable.
To do this I have created a custom ng-mousedown which uses $timeout to trigger the rest of the widgets to become draggable. The $timeout callback should also attach the current object to the cursor, programmatically, but I can't seem to initiate the dragging from inside this method. I've tried the standard jQuery UI draggable invocation: $("#widget" + id ).trigger("mousedown.draggable")
How would I do this using angular-dragdrop?
Answer: I solved this with $("#widgetDraggable" + index).trigger(event); as in:

 --Widget Template--

and
$scope.mouseDown = function (event, item, index, element) {
  $scope.dragTimeout = $timeout(function () {
    $scope.pickUpWidget(event,item, index, element);
  }, 1000);
};

$scope.pickUpWidget = function (event, item, index, element){
  item.floating = true;
  setAllWidgetsToDrag(true);
  // The line that threw me, seems easy enough:
  $("#widgetDraggable"+index).trigger(event);
}

But I'd still be interested in a less jQuery heavy solution. Just out of curiosity. I'm even offering a $25 bounty: http://www.codersclan.net/ticket/127
Comment: I'm interested in how you implemented setAllWidgetsToDrag as well. I found that when I trigger the event, it never hits the angular-dragdrop "onStart" library again, causing weird behavior.

Angular Dragdrop Programatic pick up


drag mouse and select in react

Question: I have this react code:
import React, { useState } from 'react';

const App = () => {
  const [selectedSquare, setSelectedSquare] = useState(null);

  const handleSquareClick = (squareIndex) => {
    setSelectedSquare(squareIndex);
  };

  return (

        <div
          className={`square ${selectedSquare === 1 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(1)}
        >

        <div
          className={`square ${selectedSquare === 2 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(2)}
        >

        <div
          className={`square ${selectedSquare === 3 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(3)}
        >

        <div
          className={`square ${selectedSquare === 4 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(4)}
        >

        <div
          className={`square ${selectedSquare === 5 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(5)}
        >

        <div
          className={`square ${selectedSquare === 6 ? 'selected' : ''}`}
          onClick={() => handleSquareClick(6)}
        >

  );
};

export default App;

This simulates 6 squares if I click one of them the color changes. I want to know if there's a way I could drag my mouse throughout the area and select multiple of them at the same time, like selecting a bunch of files from the file explorer, but in react.
Answer: This is a complex feature to create from scratch, I recommend a library like https://dragselect.com.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Answer: If you want to do it from scratch, you basically need to do the following:

Listen for the onMouseMove event on the document and start tracking the mouse coordinates
Listen for the onMouseDown event on the body or container element
When the onMouseDown event fires, create a div at the mouse location (position fixed)
When the onMouseMove event fires, change the width/height of the div to create the "selecting" effect. Also, here you check for "collision" with your divs to decide whether or not they should be marked as selected. This on its own can be a bit tricky to implement from scratch.

Alternatively, just use an existing lib like this one https://github.com/unclecheese/react-selectable
Comment: Okay, it sounds tricky and I don't have that much of experience so I will stick with the available libraries. Thank you.

drag mouse and select in react


Does $\tan(1/z)$ has a Laurent series convergent?

Question: Well, I have no idea: Does $\tan(1/z)$ have a Laurent series convergent on $0<|z|<R$?
Comment: Where does it have poles?
Comment: It is preferable to use `\tan`, `\sin`, `\log`, `\cos`, `\exp` etc in math mode instead of `tan`, `sin`, `log`, `cos`, `exp` etc
Comment: ok, thank you, i did not know that.
Answer: In short, the answer is no. The function $\tan(1/z)$ has poles at $z=\frac{1}{\pi/2+n\pi}$, which means that it is not analytic on the annulas you mentioned for any $R$.


iphone ISO-8859-1 encoder. how?

Question: The app sends uitextfield.text to a php file using POST.
php file has
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />  (Norwegian/Swedish Letters.ÄÖÅ)
How to encode UITextField.text so that is readable online?
I have tried several options. with no luck. Strange chars appear online.
     NSString* mess = [message.text stringByAddingPercentEscapesUsingEncoding:NSISOLatin1StringEncoding];
    NSData *postData = [post dataUsingEncoding:NSISOLatin1StringEncoding  allowLossyConversion:YES];
 [request setHTTPBody:postData];

Answer: Try using NSWindowsCP1252StringEncoding, and I won't be so sure about page conforming to encoding it specifies.

iphone ISO-8859-1 encoder. how?


Why is this unit randomly invulnerable?

Question: I have never seen this unit be invulnerable before, but now my sword goes right through this enemy without doing any damage. Question mark symbols float above the unit after my attack.

What's going on?

Edit: It happened again, this time with a different unit. I also noticed that it doesn't damage me:
Comment: You are seeing things. You should check what your doctor diagnosed you with :)
Comment: And the map's not working either!
Answer: This is an effect of the Dementia trait. Occasionally you will encounter an enemy that is only in your head.
See my answer here for a full list of traits.
Comment: @Codemonkey Would you mind accepting this, if it helped you? It's been bugging me that one of my highest voted answers remains unaccepted :P
Answer: You probably had the dementia trait which makes you insane so you see fake enemies which dont harm you neither can you kill them
Comment: This answer doesn't add anything to the existing answer. Please don't add a new answer unless you have something significant to add.

Why is this unit randomly invulnerable?


Half the power in my house goes out randomly and comes back on

Question: Like the title says, half the power in my house will randomly go out.
And it's random rooms. No power in 1 upstairs room, but power in the other two. No power in main room of basement, but power in laundry room and bathroom of basement.
No power to 240v in kitchen, but power to lights and outlets in kitchen.
No power to living room or outdoor lights.
No breakers are tripped. No GFIs tripped.
The power will go out for a random period of time, and then come back on for a random period of time.
Has been happening for 2 days.
Any ideas what on earth is going on?
No outages or problems reported in my area. Asked a neighbor and they have no issues.
Comment: Probably a lose hot feed. Where the house loses power always the same?
Comment: Is there any pattern to which 120V circuits in your breaker panel lose power?
Comment: Try re-seating the circuit breakers in your panel.  And look for loose connections there (carefully).
Comment: Yes, always the same part of the house that loses power.  Turned off main power and checked for loose wires in panel, none that I can see.
Comment: I can contacted the electrical company in case I am intermittently losing one hot leg coming into the house. Although I am hoping that it is not somewhere between my house and the pole, as I think I am reaponsible for that.
Comment: Does the power availability change with running a 240v load (like a dryer, furnace or electric oven)? If so, that sounds like a lost neutral which is probably a PoCo issue at the pole or weatherhead. Calling the PoCo is your best bet.
Comment: your responsibility stops at the weatherhead.  You do not own the crimps on the weatherhead.  You also don't own the meter itself but you do own the meter pan.
Comment: You might need an electrician.... or an exorcist!
Answer: Lost hot wire from the utility
Call the utility emergency number and report an outage.  They'll have a truck out in an hour on a Sunday.

And it's random rooms. No power in 1 upstairs room, but power in the other two. No power in main room of basement, but power in laundry room and bathroom of basement.

Not random at all!  I bet if you identified the breakers of the circuits that are out, they would be on every other row of the panel, like described here.

The power will go out for a random period of time, and then come back on for a random period of time.

Not random either.  That is your tanked electric water heater, or other 240V load, cycling on and off.
A water heater and any large heat load is just a giant resistor between the two hot phases.
If one phase is dead, then it connects the dead  phase to the live phase through the resistor, causing it to re-energize.  Like borrowing electricity from your neighbor through way too many extension cords lol.    So modest 120V loads on that phase will now power up normally.  Greater loads on that phase will make the voltage sag considerably.
But here's the weird part, the current moving through that resistor is heating the resistor.  Modern water heaters are so well-insulated that they have very little loss.  Even this limited current is enough for them to "get ahead" and eventually reach their target temperature.  And then, they turn off!  Cutting power to those appliances.  So this (or another similar heater) would explain the random power-ups.
Turn off the breakers on all your 240V appliances (which you should do anyway, as this isn't good for them).  If the sporadic appliances are now dead as a doornail, that was it.
Answer: Although you haven't said where in the world you live, it sounds like you have an intermittent connection to half of your incoming electrical service.  This is very serious, and suggest you contact your electrical provider ASAP and have them check out the lines going to your house and meter.  If they don't find anything amiss, call an electrician and have them check for a loose feeder connection in your breaker box.


What does glUseProgram(0) do?

Question: The OpenGL docs for glUseProgram claim that calling it with an argument of zero will cause the results of shader execution to be undefined.
However, after a little searching I've seen a couple examples of people using glUseProgram to uninstall the current shader program.
Is this behavior reliable? If not, then what exactly does glUseProgram(0) do?
Answer: glUseProgram means that the given program object is the current program that will be used for things that use programs (glUniform, rendering commands, etc). 0 is a lot like NULL for OpenGL objects. It represents not an object (for most objects). Therefore, glUseProgram(0) means that no program is current, and therefore no program will be used for things that use programs.
If you attempt to call the glUniform functions when no program is current, they will fail with an error. If you attempt to render when no program is current, one of two things will happen. In OpenGL 3.1+, core profile, you will get undefined behavior, because core OpenGL must render with a program. In compatibility profiles or version 3.0 or less, you will get fixed-function rendering.
Comment: @user11171: No. You should call it when you want to not have a program bound. By doing so, you prevent accidentally rendering with a program that wasn't intended (ie: you forgot to call `glUseProgram` with the actual program you want). You would usually call it when you're finished rendering.
Comment: So in other words I should just not call `glUseProgram(0)`?
Comment: Interestingly enough, on a Jetson AGX, I forgot to put the `glUseProgram()` before attaching/binding a texture & calling the `glDrawArrays()` and yet I did not get any errors. Yet I thought that the `glDrawArrays()` only worked with programs/shaders. Instead I was getting some really weird results ("random" rendering of whatever).
Comment: I wonder why they wouldn't revert to fixed function pipeline rendering, or just have `glUseProgram(0)` generate an error. It really is a bad program state to have a NULL shader bound after having bound one, since you cannot render anything then
Comment: @bobobobo: 0 does revert to fixed-function, if you're using a compatibility context where fixed-function is a thing. Otherwise, it's just like any other reason to set a pointer to null: to represent that it cannot be used.
Answer: Contrary to a lot of answers here and elsewhere, glUseProgram(0) does not revert to fixed-function mode. It is not safe to use it this way. You can use it to set the rendering state to an invalid program object, but if it's still bound to this when rendering occurs, the behaviour is undefined.
From the doc:

"If program is zero, then the current rendering state refers to an
invalid program object and the results of shader execution are
undefined"

Therefore the results are entirely specific to OS, driver and graphics card. In many cases it appears to revert to fixed-function mode, but this is not defined by the spec and should not be relied upon. It could just as easily keep the last shader, render garbage, or cause a segfault (I've seen this happen).
Comment: glUseProgram(0) is perfectly safe.  As that page says, it's not an error to call glUseProgram(0); only to render anything without a program bound.  And this only applies to the core profile.
Comment: @SystemParadox: I see. Altough your answer makes it sound like "glUseProgram(0)" is dangerous by itself.
Comment: This answer is wrong. rdp is right. Calling "glUseProgram(0)" is not a shader execution. If you perform rendering after calling "glUseProgram(0)", THAT is a shader execution!
Comment: @Dudeson, you are correct. glUseProgram() does not cause shader execution, but as the spec says, it changes the rendering state so that the results of any shader execution (when you later do something to cause it) are undefined
Comment: @SystemParadox: You just repeated what I said.
Comment: @Dudeson, I was trying to show that we are in agreement, and that my answer is not wrong. Calling "glUseProgram(0)" will not result in an immediate error, but it is not safe to do because it results in undefined behaviour when rendering occurs.
Comment: By this logic calling `free(ptr)` is not safe: You can use it to delete a pointer, but if the pointer is still deleted (not reallocated) when another use occurs it is undefined behavior ...
Comment: I have edited my answer to avoid the arguments about whether glUseProgram(0) itself is technically safe or not. I respectfully request that people who have downvoted based on this semantic argument please review my changes and reconsider. The fact that you can safely call glUseProgram(0) itself or not is irrelevant - it is unsafe to render in this state, yet the majority of information out there claims that glUseProgram(0) reverts to fixed function mode. This is simply untrue and should not be relied upon.
Comment: @SystemParadox: "*it is unsafe to render in this state*" It is in a compatibility profile. The compatibility profile allows for fixed-function OpenGL stuff. The documentation you link to is for core OpenGL, where there is no fixed-function stuff.
Answer: Once you are using glUseProgram(myShader)    all subsequent rendering will be done using the shader ID myShader.
If you are calling this each time you have a material change in a modern openGL 3.1+, there is little use of glUseProgram(0).
However, if you are planning to integrate some fixed-function rendering in there, like glVertex3f(..), then glUseProgram(0)  will make sure that the last used shader is not active anymore, and it will use the fixed-function pipeline, like glColor3f(...)
Comment: No, no, no. glUseProgram(0) DOES NOT revert to fixed-function mode. In many systems it does, but this is not defined by the spec and should not be relied upon.
Answer: It tells OpenGL to use the fixed-function pipeline.
Comment: Note that in the core profile, there is no fixed-function pipeline, so you'll just get an OpenGL error (`GL_INVALID_OPERATION`)
Comment: Or on some machines, a segfault.

What does glUseProgram(0) do?


How to download a website where javascript code lookup results are included?

Question: How to download a copy of a website in linux?
I have tried using wget --recursive --level=inf https://example.com however it also downloaded links from different domains.
Also is there a way to download a copy of the website where the javascript has run and resulted in output on the page. For example if downloading a weather website, there might be javascript which looks up the current temperature in the database and then renders the output. How to capture the temperature/final output?
Answer: Phantom.js?
http://phantomjs.org/quick-start.html

I think this will do what you like!
The best thing to do is install from here:
http://phantomjs.org/
Basically you run it by creating javascript scripts and passing as a command line arg, e.g.
phantomjs.exe someScript.js

There are loads of examples, you can render a website as an image,
for example you can do:
phantomjs.exe github.js

Where github.js looks like
var page = require('webpage').create();
page.open('http://github.com/', function() {
  page.render('github.png');
  phantom.exit();
});

This demo is at
    http://phantomjs.org/screen-capture.html
You can also show the webpage content as text.
For example, let's take a simple webpage, demo_page.html:

Static content

And then create a test script, test.js:
var page = require('webpage').create();

page.open("demo_page.html", function(status) {
    console.log("Status: " + status);
    if(status === "success") {
        console.log('Page text' + page.plainText);
        console.log('All done');
    }
phantom.exit();
});

Then in the console write:
> phantomjs.exe test.js
Status: success
Page text: 42 is the answer.
All done

You can also inspect the page DOM and even update it:
var page = require('webpage').create();

page.open("demo_page.html", function(status) {
    console.log("Status: " + status);
    if(status === "success") {
        page.evaluate(function(){
            document.getElementById("1").innerHTML = "I updated the value myself";
        });

        console.log('Page text: ' + page.plainText);
        console.log('All done');
    }
    phantom.exit();
});

Comment: Looks great! Is there a way to get the javascript rendered html source code? And download the whole website?


How does notch's new graphics engine work?

Question: @notch has recently been posting on an engine he is developing. He claims that it is voxel-based and supports deformable terrain, with a render distance of almost 1000 000 voxels and real-time reflections, running at 99fps in WebGL. Even with heavy LOD reduction, such a thing sounds too good to be true. He has not published any source code as of now, so does anyone have an idea how this is done? Is it just many small optimizations or could this be a new approach to real time 3D?
EDIT: He also mentions a "signed density field". What does that mean exactly?
Comment: Notch deleted his old tweets, so we'll probably never know...
Comment: Deve Strawn has compiled [a pretty good summary](https://www.devonstrawn.com/articles/Notchs-rendering-experiments.html) though.
Answer: Notch's engine most likely works using volume raymarching in a volume field. This means that you shoot rays that move a certain distance and check whether they are inside and object or not. Once they are, they return the position of the colission and some other data.
You can either advance rays by a set amount per step until you hit something or refine the final collision position by doing a binary search along the last walked ray segment once you hit something. Both of these aproaches have the problem that they can overshoot, missing small geometry, or take a large amount of steps to traverse empty space where there is no geometry to hit.
Binary search can add precision and reduce overshoots somewhat but comes at an extra runtime cost for doing a binary search per ray.
Signed distance fields are essentially 3d arrays  tell you how far away from any surface you are. This allows you to do raymarching with ray step sizes equal to that number and being sure that you wont overshoot, as well as stepping through large empty spaces quite quickly. This greatly enhances performance and reduces overshoots from a regular step size or binary search based approach.
This last technique trades off runtime speed for precompute time and extra memory. So it is not always adequate for rendering exteriors or large scenes. Its memory usage an runtime speed can be further improved by using a hierachical data structure that gets re built every so often with more detail and data density near the camera and less further away from it.
EDIT: Oh it seems i misread density for distance
I really have no idea what a signed density field is. I've never heardthe term before. A quick goolge search throws results that talk about signed distance fields. I would guess it was either a mistake to write that, some obscure tech or something that Notch made up himself.


how to create search form with into codeigniter uri format?

Question: dear all, i'm a noob in codeigniter,
i would like to ask for advise, on how to create a search form that would result to url as:

http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val

the form would be like
<form action="http://domain/class/index">
   <input name="searchvar1" value="searchvar1val">
   <input name="searchvar2" value="searchvar2val">
   <input type="submit">
</form>

what is the best practice for this?
i've googled around including stackoverflow posts, still can't find any solution.
thanks :)
~thisismyfirstposthere
update ::
i would like to emphasize that my objective is to process search variables from the uri string (above), not from post vars; so i think setting the form search to POST is not an option? :)
update (2)
i don't think this can be done out of the box in codeigniter, i'm thinking of client-processing the form vars/vals into the form action in URI format using jQuery.
will post an update here later when done.
Comment: http://stackoverflow.com/questions/712340/codeigniter-uris-and-forms take a look at NexusRex's answer, that might probably work for this
Comment: Saw your update. You absolutely don't need jQuery for this, I can't imagine how it could even help. I am doing a advanced search form right now for a real estate lookup in Codeigniter and having no issues whatsoever. Maybe your goal is just unclear to me...
Comment: thanks @littlechad; NexusRex's answer i think is more to the process in the Controller (after request); while my issue is more on the pre-request, in the View itself, how to create the search form action parsing the search input vars&values into uri string.
Answer: taking a look at the user_guide :
$this->uri->assoc_to_uri()

Takes an associative array as input
  and generates a URI string from it.
  The array keys will be included in the
  string. Example:

$array = array('product' => 'shoes', 'size' => 'large', 'color' => 'red');

$str = $this->uri->assoc_to_uri($array);

// Produces: product/shoes/size/large/color/red

and i think if your form is this:
<form action="http://domain/class/index/search">
   <input name="product" value="shoes">
   <input name="size" value="large">
   <input name="color" value="red">
   <input type="submit">
</form>

then somewhere in the search controller do this $this->uri->assoc_to_uri($data); IMHO will produce  product/shoes/size/large/color/red
Answer: hey guys, thanks for replying and discussing, I think imma go with flow:
View --> form --> jquery, on form submit: replace action attribute with form params --> controller with uri string --> rest of the process
the jquery part would be something like this
$("#searchFormID").submit(function(){

    // $(this).serialize() outputs param1=value1&param2=value2 string
    // var.replace(regex, string) outputs param1/value1/param2/value2 string
    // newact would be http://localhost/class/index/param1/value1/param2/value2
    var newact = $(this).attr("action") + "/" + $(this).serialize().replace(/&|=/g,"/");

    $(this).attr("action", newact); // or $(this).attr("target", newact);

    return true;
});

notes:

add an id attribute to the form -> for the form selector in jquery
use post method in the form (this is default in codeigniter) -> so action url will not be populated with the GET string
Answer: You may want to enable query strings and use $_GET. IMO, this is a perfect example what the query string is intended for.
Make sure to change your form to <form method="get" action="http://domain/class/index">
You will then have a query string in your URL like ?searchvar1=value1&searchvar2=value2
You can access parts of the string like this: $this->input->get('searchvar1')
With the method you are currently using, if a user searches for any characters that are not allowed in your $config['permitted_uri_chars'], you will have to do a lot of encoding and decoding yourself to make sure the string is safe/readable in your URL. The CI Input class takes care of this for you, so it is my recommendation.
Another disadvantage to URI segment based search params is that there is no proper way to express an array like ?values[]=one&values[]=two&values[]=three.  There are hacks to work around this, but they are all exactly that: hacks. you will eventually run into trouble.
Using $_POST is very tedious and forces the use of form submits for paginated results and links, and also ensures that you cannot link to the search results or use the back button properly.
If you must use this method, simply have the form post to your controller, read the input, and then redirect() to the url that you construct from it. littlechad has the right idea for this method in his answer
// This URL:
http://domain/class/index/searchvar1/searcvar1val/searchvar2/searchvar2val

// With this:
$search = $this->uri->uri_to_assoc();

// Produces this:
array(
    'searchvar1'    =>    'searchvarval1',
    'searchvar2'    =>    'searchvarval2',
);

// And you can use it like this:
$arg1 = $search['searchvar1'];
$arg2 = $search['searchvar2'];

To get TO this url, you can do something like this with your form post (in the controller after post):
$var1 = $this->input->post('searchvar1');
$var2 = $this->input->post('searchvar2');
redirect('searchvar1/'.urlencode($var1).'/searchvar2/'.urlencode($var2));

I'm sure you can see how much more work this is than just using the tried-and-true query string...
Comment: Thanks @Madmartigan, you explanation above is exactly what i'm doing right now, but i have an intention to parse the `?searchvar1=value1&searchvar2=value2` into `/searchvar1/value1/searchvar2/value2` instead from the View itself. agree with the rest of your comment.
Comment: @Seno I added the redirect part, let me know if it is unclear.
Comment: yes it's true this require more effort to redirect again. but hey right, this is one way to do it, thanks :)


Does a cable lift have any advantages over a chain lift?

Question: I noticed that giga coasters in RollerCoaster Tycoon 3 can have cable lift hills.  Instead of a chain running the length of the hill, a train-length cable travels from the top of the hill, picks up the train from the station, carries it back up, and drops it off the other side.
What's the point to this, though?  Does it have any advantages over traditional chain lifts?
Comment: perhaps it would be better stated as: "Created a tag for you. - ♪ "
Comment: Fixed the tag for you. - ♪
Comment: @Raven Thanks.  I wonder why that didn't show up in the list.
Answer: As Maxpm hinted at in his comment, it's mostly an issue of speed.  A cable lift is faster than a chain lift, so the coaster gets to the top faster.  I don't think there's any major gameplay reason to have one over the other, though a cable lift would likely shorten the ride time and thus might effect ratings.  One would have to build two coasters that are otherwise the same to test the effects.
In terms of gameplay: It's been a while since I've messed around with Rollercoaster Tycoon 3, but if I remember right, cable lifts require a special start and end piece, and requires a completely straight lift hill.  This means you need a certain amount of horizontal space to be able to use it successfully, and ideally, it should be used for the main starting hill.  I'm not 100%, but you might be limited to only one cable lift start/end point.  Chain lifts also only work on straight inclines, but you can add tight turns between them to break up the lift hill and make it spiral (though you need a certain train length to be able to do this).  So chain lifts work well in areas with space limitations.
Outside of the game: Cable lifts are used in a variety of coasters and (according to wikipedia) they require less maintenance, and are fairly quiet compared to the loud, clanking chain lift.  The earliest coaster to use a cable lift  (at least, per the wikipedia article) was built in 2001, though the method was likely used prior to that.  Rollercoaster Tycoon 3 came out in 2004 (with RCT2 coming out in 2002, and RCT1 coming out in 1999).  Likely, the cable lift in RCT3 was included for realism and ride variety as opposed to any major gameplay reason.
Comment: The first coaster to use a cable lift was Millennium Force, which opened in 2000.
Answer: You can use it with the higher degree angle! So you can climb 200 feet in almost no time at all.
Comment: You can do this with some chain lifts, too, albeit slightly slower.
Answer: There is not a huge difference between a chain lifts and a cable lifts in RCT3. The main differences seem to be that cable lifts are faster (just like in real life) however they need to be at the start of the ride otherwise if the cable lifting section has not reached the bottom by the time the train has reached the lift hill, the train will roll back. Basically if you use a cable lift hill, it probably won't work if you have a pre-lift section. Chain lifts on the other hand can pick the train up at any time, however they are slower (and much louder in real life).
Comment: I know it's an old post but I just wanted to answer it xD
Comment: There's nothing wrong with answering an old question, as long as your answer improves upon previous answers, or is a better answer (like an update changing the mechanics.)


Concatenate two pandas dataframes for analysis

Question: I'm trying to solve a problem about customer preferences on restaurants. I have two different CSVs, one which has the customer information:

And the other one has restaurant ratings:

So I want to try out supervised training based on customer preferences in order to determine what the restaurant rating will be. In order for this to happen I think I have to append the customer information for each rating (so I will have variables to analyze).
Im trying this using python & pandas.
I have tried this:
import pandas as pd
from pandas.plotting import scatter_matrix
import matplotlib.pyplot as plt
from sklearn import model_selection
from sklearn.metrics import classification_report
from sklearn.metrics import confusion_matrix
from sklearn.metrics import accuracy_score
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
from sklearn.naive_bayes import GaussianNB
from sklearn.svm import SVC
from pandas.plotting import scatter_matrix
import numpy as np

df1 = pd.read_csv('/2_user_profile.csv', index_col = [0])
df2 = pd.read_csv('/3_Ratings.csv')

#Create empty dataframe with named columns
df = pd.DataFrame(columns=(np.concatenate((df2.columns.values, df1.columns.values), axis=0)))

#Joining the tables
for index, row in df2.iterrows():
    userID= row['userID']
    frame=[row, df1.loc[userID]]
    print(frame)
    df = pd.concat([df, pd.DataFrame(frame)], axis=0)

print(df)

The print(frame) will give me this result:

And that makes sense but when I print df it gives me this:

Which means that each frame I create makes a double record on the dataframe, one with the information from df1 and all values that correspond to data on df2 are empty and another register for all values on df2 and empty values that correspond to df1.
This is my first go at python+machine learning so let me know if you also have a comment on my approach.
Comment: so you just want to join the columns?
Answer: Looks like you want to join on the userID in both dataframes, right?
You can do this using merge. Here is a short example:
import pandas as pd

data_1 = pd.DataFrame({'id': ['A', 'B'] * 5, 'value_1': [0, 1] * 5})
data_2 = pd.DataFrame({'id': ['A', 'B'], 'value_2': [3, 4]})

data_1.merge(data_2, how = 'inner', left_on = 'id', right_on = 'id')

Gives:
Comment: Oh man I really need to go through documentation. Thanks a lot!


NodeJS - Given a full path of a directory, how to get a list of all subdirectories and check if a file exists here asynchronously?

Question: For example given: '/Users/John/Desktop/FooApp',
I would like to get a list such as:
['/Users/John/Desktop/FooApp',
 '/Users/John/Desktop/FooApp/Folder1',
 '/Users/John/Desktop/FooApp/Folder2',
 '/Users/John/Desktop/FooApp/Folder2/folderA',
 '/Users/John/Desktop/FooApp/Folder3',
 '/Users/John/Desktop/FooApp/Folder3/folderX',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY/folderZ',
 '/Users/John/Desktop/FooApp/Folder3/folderX/folderY2'
]

I require this list to search through all directories to check the existence of a file. The user inputs a folder, and I basically will perform a check similar to finders in OS. I am planning to check fs.exists(subdir + '/mylib.dll') on all the subdirectories.  Is there any neat way to do that?
Answer: I have converted an answer to a similar question in here, where search was performed for files instead of directories. I also used async to check if file exists. I also found out that fs.exists was about to be deprecated and decided to go on with fs.open.
Anyway, Here is the snippet:
var fs = require('fs');

var getDirs = function(dir, cb){
    var dirs = [dir];
    fs.readdir(dir, function(err, list){
        if(err) return cb(err);
        var pending = list.length;
        if(!pending) return cb(null, dirs);

        list.forEach(function(subpath){
            var subdir = dir + '/' + subpath;
            fs.stat(subdir, function(err, stat){
                if(err) return cb(err);

                if(stat && stat.isDirectory()){
                    dirs.push(subdir);
                    getDirs(subdir, function(err, res){
                        dirs = dirs.concat(res);
                        if(!--pending) cb(null, dirs);
                    });
                } else {
                    if(!--pending) cb(null, dirs);
                }
            });
        });
    });
};

One can then use it as:
var async = require('async');

getDirs('/Users/John/Desktop/FooApp', function(err, list){
    if(err) return 'Error retrieving sub-directories';

    async.detect(list, function(dir, cb){
            fs.open(dir + '/mylib.dll', 'r', function(err, file){
                if(err) cb(false);
                else cb(true);
            });
        },
        function(dir) {
            if(!dir) return 'File Not Found';
            /* Do something with the found file ... */
        }
    );
});


How to escape a Java swing window in fullscreen?

Question: I've built a swing window in eclipse that goes to fullscreen when opened, however it becomes impossible to toggle the fullscreen off.
I've tried researching online (I am aware of similar threads) but I've come across issues when attempting solutions.
Here is my JFrame
    private void initialize()
    {
    frmCpStats = new JFrame();
    frmCpStats.setTitle("CP Stats");
    Toolkit tk = Toolkit.getDefaultToolkit();
    int x =((int) tk.getScreenSize().getWidth());
    int y =((int) tk.getScreenSize().getHeight());
    frmCpStats.setExtendedState(JFrame.MAXIMIZED_BOTH);
    frmCpStats.setSize(x, y);
    frmCpStats.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frmCpStats.setUndecorated(true);
     KeyStroke k = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);
     int w = frmCpStats.WHEN_IN_FOCUSED_WINDOW;
     dialog.getRootPane().registerKeyboardAction(e -> window.dispose(), k, w);
    }

    public static void main(String[] args) {

    EventQueue.invokeLater(new Runnable() {
        public void run() {
            try {
                StatsDisplay window = new StatsDisplay();
                window.frmCpStats.setVisible(true);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    });

    }
    public StatsDisplay() {
        initialize();
    }

Eclipse identifies errors Cannot be resolved or is not a field with VK_ESCAPE and WHEN_IN_FOCUSED_WINDOW, and dialog cannot be resolved with dialog. I'm quite unfamiliar with how swing actually works, so I haven't the foggiest idea why these errors are occurring.
Comment: Don't blindly copy code. This is not how you learn to code and not how you ask questions on this site.
Comment: Please post a valid [mcve] with your question, code we can compile, run and test. Question: are you importing the correct KeyEvent class, specifically `java.awt.event.KeyEvent`?
Comment: Also, `JFrame` does not inherit from `JComponent`, and so it does not have `JComponent` constants such as `WHEN_IN_FOCUSED_WINDOW`. But you should be checking the API for stuff like this before coming here, no?
Comment: I was using `org.eclipse.swt.events.KeyEvent`, using awt seems to have cleared up whatever was wrong with the `VK_ESCAPE` bit. I'm not hugely knowledgeable on Java, I've had to work on this a little blindly.
Comment: The API is your friend -- you will want to use it to exhaustion.
Comment: Again, please post a valid [mcve], a complete small program. You're still only posting snippets. Please be sure to read the link.
Comment: I think what's up there should be a simplified program, not sure what else it needs
Comment: You're missing imports, class structure, ... we should be able to copy, paste it into our ide's and run without modification. Please note my code posted below to see what I mean. Remember that you're asking *volunteers* to help you, and we request, no expect, that you make it as easy as possible to help. That's certainly not asking too much.
Comment: Why `window.dispose()`? What is "window"?
Comment: I'm not sure, the solution was from [this](https://stackoverflow.com/questions/38802417/how-to-escape-from-full-screen-mode-in-java) thread. I think it closes the window instead of just exiting fullscreen. Sorry about the confusion.
Answer: You're almost there. Key Bindings works in this situation. Please note my MCVE:
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;

import javax.swing.*;

public class StatsDisplay {
    private JFrame frmCpStats;

    private void initialize() {
        frmCpStats = new JFrame();

        JPanel contentPane = (JPanel) frmCpStats.getContentPane();
        int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
        InputMap inputMap = contentPane.getInputMap(condition);
        ActionMap actionMap = contentPane.getActionMap();

        KeyStroke escapeStroke = KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0);

        inputMap.put(escapeStroke, escapeStroke.toString());
        actionMap.put(escapeStroke.toString(), new AbstractAction() {

            @Override
            public void actionPerformed(ActionEvent arg0) {
                frmCpStats.dispose();
            }
        });

        frmCpStats.setTitle("CP Stats");
        Toolkit tk = Toolkit.getDefaultToolkit();
        int x = ((int) tk.getScreenSize().getWidth());
        int y = ((int) tk.getScreenSize().getHeight());
        frmCpStats.setExtendedState(JFrame.MAXIMIZED_BOTH);
        frmCpStats.setSize(x, y);
        frmCpStats.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frmCpStats.setUndecorated(true);
    }

    public static void main(String[] args) {

        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    StatsDisplay window = new StatsDisplay();
                    window.frmCpStats.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

    }

    public StatsDisplay() {
        initialize();
    }
}

Curious as to why you're calling window.dispose() when its the frmCpStats JFrame that you're actually trying to dispose of??
Comment: Thanks, this is almost what I need, however when I press escape the window closes as opposed to simply exiting fullscreen.
Comment: @R.McGuigan: but your code is calling `dispose()` within its action???
Comment: @R.McGuigan: then change that code so it changes the window's state. You're using variables that have never been declared, making calls that you don't want to do ....  I think I see what's going on -- you're trying to copy found code and use it without thinking what it does. Please don't do that, and certainly never ask a question with this type of code. Instead copy ideas but write your own code that makes sense.
Comment: Sorry, my knowledge of how Java functions is quite rudimentary, apologies for wasting your time with my unprofessional responses/question
Answer: Remove these code lines
frmCpStats.setExtendedState(JFrame.MAXIMIZED_BOTH);
frmCpStats.setUndecorated(true);

Comment: Doesn't answer the main question at all


Making a timber frame cupboard door using an MDF insert to hold its shape

Question: I have been working on a design for some cupboard doors. The requirements are:
 - Simple to build so that an low-skilled wood-worker (myself) can put it together.
 - Be strong enough that the door does not "sag" over time.
My frame is basically a rectangle of 80mm x 20mm oak.
In-side the frame I will have an MDF board (with oak laminate) that is either 4mm or 6mm (I have not yet decided) that will be attached within a 4/6mm groved channel inside the frame.
I have made an attempt at a diagram below for the MDF board grove that I will cut into the oak frame, it shows how the MDF will slot inside.
<code>   | |     <-- 4/6mm MDF board sitting within the groved channel
   | |
+--+ +---+
|  |_|   |
|        | <-- Oak 20mm frame cross-section view
|        |
</code>
The frame is constructed with dowelled and glued joints (three large dowels per join to stop twisting). And the MDF board will slot snug into the groves and will be glued.
The idea is that the MDF will keep the doors in shape.
Do people have suggestions / or confirm this is a good/poor design? / alternatives? (please not hammer and mortice joins... too difficult for me!)
Comment: Your plan sounds fine to me, except I'd go with two dowels per corner. Also, since you're new to woodworking, doweling can be devilish if you don't have special doweling tools. So, if you don't, and you end up with some angular holes, or misaligned holes, I suggest you just drill the holes a little oversize, fill the holes with wood filler, insert the dowels, clamp, and scrape off the excess filler. Good luck.
Comment: @getterdun Thanks for that, I have obtained a pillar drill for the dowels, so I think I can get the holes quite straight, but I don't suppose I need 3 dowels, maybe two is enough! Thanks for helping to confirm the design :)
Answer: Although MDF is more stable than solid wood, I won't claim that it will not swell enough with enough humidity to break the joints at the corners as solid wood will if there is no room for expansion, did that my self with a single panel in a 24" cabinet door 20 years ago never again...
The strength of the door needs to be in the joinery, not the panel. There really needs to be room for movement, maybe not as much as a wood panel, but something.
Dowels will suffice for the joinery, keep it to 2 per corner.
If you are going to cut the groove (dado) with a router or table saw, I presume you will stop the dado from the ends so it is not visible. It need not be exact where, as long as it is behind the joint and long enough to not foul the panel.
Take this a step farther and run the dados all the way through and a little deeper to 1/2 inch, and you have the basis for a simple joint that will be strong enough to hold without dowels. The trick is to use a smaller bit or blade than the panel get it roughly centered on the set up and run the stock (wood) the turn it the other way and pass it through again. With a little patience the dado will finish exactly in the center, and the proper width for the panel.
With that done, you can use the same bit to cut the ends of the stock for the top and bottom pieces (rails) they need to be 1 inch longer than the dimension between the horizontal pieces (stiles) so when the ends are reduced to fit in the dados it will give your finish size you need.
If the notion I pass by intrigues you, the next step is actually pretty simple too, but it depends in what tool you are using to machine your wood.
Edit 1/28/13
If you wish to use dowels, and don't mind seeing the holes at the outside corners of your doors, I would suggest this. Lay your corner out on a flat surface just as you would like it after it is assembled. Clamp it in place so it is square and near the edge of your support table, and drill in from the edge into the wood through one piece and into the other, gauging your depth to allow the dowel to be centered in both pieces. Use fluted dowels, the fluting allows excess glue to escape from the drilled hole. then plug the holes on the outside corners with an oak plug to blend in. You will need bar clamps for this, though a jig can be made to do the same with blocks screwed to a flat surface and a wedge of wood to draw it all tight. lay plastic under your joints or better yet, tape at the joint locations to keep the glue that will ooze out from gluing your frame to the workbench. Bar clamps will allow you to maneuver the frame after assembly to clean the glue on all sides, just be sure when you are done tidying up the frame is absolutely flat (no twist) and square, while the glue is drying. If it is a little out of square, a bar clamp diagonally across corner to corner will pull it back the little it may need. Have all this ready before you start, even make a dry run without dowels if possible, you will not want to try to find stuff while the glue is making its first "grab", it all needs to be at hand.
I say without dowels because if they get inserted without glue, they will still be more than very contrary to remove. Since the holes are all the way through, use metal drill bits that are smaller than your holes to line everything up temporarily.
I have used the turret style doweling jigs before, definitely not accurate. You can spend a lot of money on other doweling jigs, but the same money can be used on a matched router bit set too, the trick is, you need a router table and the router should have a 1/2" collet to hold up under the strain of cutting these joints.  Back at the doweling. The clamping of the material will insure you can control how the drill is going, a piece of tape, making a "flag" on the drill bit can act as a depth gauge. All this will make certain the faces will match on assembly and the holes are in plane with each other on each part. This alone is most critical. The slightest misalignment in the way the holes line up to each other will create a twist in the door frame and the door will not meet the cabinet box (carcass) on all corners, one corner on the door will set away from the carcass. In a matched set of doors, this can really look bad....
Comment: thanks for your answer. I guess you are suggesting that mdf can expand?, but I was sort of under the impression MDF was the most stable marterial (of the "woody" materials). Anyway, your other idea sounds interesting, but I can't quite understand what you mean. Are you saying cut a larger groove in one side of a join (with a router) and then cut two grooves (either side of the middle) on the other side and slot the two together?
Comment: Yes MDF is the most stable, but with humidity changes, any material that can take on moisture will expand, it is paper, more or less bonded together with glue and heat under extreme pressure. Do not let it get wet, it will swell back to its uncompressed size, usually double of what it was
Comment: The groove will be larger in depth, not wider than 1/4", but a 1/2" deep. Now I know you will use a router, I will post more in a detailed part regarding the groove making. Another question, do you have access to a table saw at all? The suggestion I can make will tremendously reduce the strain on your router if you do. There is a technique with the table saw that does this simply too. There may already be a post that does so on this site, but if you don't the router will work too. You will need to feed the material slowly to not overheat the cutting bit, when you start your milling.
Comment: I just realized a few more questions are in order. Do you have a router table? maybe better to ask what is in your tool selection? Table saw, router with table, router with 2 or 3 wing cutter, straight cutter, etc. Sorry to ask so much, when you are asking about doweling it all together. I will add more to the answer on that too.
Comment: I have a "chop-saw" I think its called (circular saw that pulls down from above), I have a hand-circular saw (you push it along by hand), not sure if either of those is a table saw? - I don't have a router table, but I have work benches and clamps etc...
Comment: Without re-tooling, it sounds like the dowels may be the best route. I built my first cabinet with dowels about 30 years ago, it turned out nice, but it had its difficulties as I mention above. The owner still has it, it is a cabinet to hold his record collection and stereo equipment. I have used the same technique mentioned above to resize doors for homes too.
Comment: Thanks for your detailed explanation, plenty for me to think about here. I will endevour to get the right clamps before I start. There are some nice guidances in your comments :)


Access Denied to "Documents" in C# (and pretty much any other folder)

Question: I've already read a lot about this and after several hours I still cant fix it. This is the fragment of the code that matters:
    void CopiarMover(string file)
    {
        File.Copy(@"C:\\Users\\Daniel\\Documents", "../../contenidos/" + file);
    }

I've already configured my app manifest to:
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />

And it keeps returning errors (permission denied).
I'm using Win7. Any ideas on how to fix this?
Comment: Are you sure that the 'access denied' refers to Documents folder? Could it be that it refers to 'contenidos'?. You are using relative paths. Relative to which folder? And why don't you use the backslashes in the destination path?
Comment: Never use relative paths in your code.  You cannot rely on Environment.CurrentDirectory being predictable and stable.
Answer: Any reason why you didn't specify the filename for the source?
Like this:
void CopiarMover(string file)
{
    File.Copy(@"C:\\Users\\Daniel\\Documents\\" + file, "..\\..\\contenidos\\" + file);
}


Mvc 4 CodeFirst ModelBuilder ForeignKey

Question: I have trying to write this section in MVC 4 for a bit now and I just cant get the syntax right. I have a user class in my entities and every user has messages. On my messages the will be linked to the user via either sender or receiver. So this will have back and forth access methods. That way i can pull messages and either access through code first who the sender and receiver is, or access the the message they sent or received through the user.
I removed the modelBuilder info fromt he script and im back to fresh, If you need me to post any other info, plz let me know.
<code>public class User
    {
            [Key]
            public Guid UserId { get; set; }

            public String Username { get; set; }
            public String Email { get; set; }
            public String Password { get; set; }
            public DateTime? BirthDate { get; set; }
            public String SecurityAnswer { get; set; }
            public String SecurityQuestion { get; set; }

            public ICollection<Message> PrivateMessages { get; set; }
            public ICollection<Message> SentMessages { get; set; }

    }

public class Message
    {
        [Key]
        public long Id { get; set; }

        public User Reciever { get; set; }
        public User Sender { get; set; }

        public string Title { get; set; }
        public string Message { get; set; }
        public DateTime PostDate { get; set; }
    }
</code>
Answer: I think what you are looking for is the 'InverseProperty' data annotation.
Check out this SO question:
Navigation Property without Declaring Foreign Key
Comment: Thank you so much, I'm a little new to CodeFirst and this was a huge help. I was not aware of that attribute

Mvc 4 CodeFirst ModelBuilder ForeignKey


Open GZIP with classic ASP

Question: Is there any way or code sample to open GZIP stream with classic asp?
Answer: This COM object will do the job.
http://www.xstandard.com/en/documentation/xzip/

Open GZIP with classic ASP


How to trouble shoot arbitrary Linux programs

Question: Currently I am trying to become better at using Linux and therefore I would like to know how Linux experts troubleshoot arbitrary programs.
On my new laptop I could not burn a cd via k3b. It just got stuck during the burning process and did not do anything any more... It created the isofile but did not start burning at all.
I did the following:

redo everything to check if the error is reproducible
see the logs via journalctl – nothing found
looked out for specific k3b logs – did not find own log files
checked if necessary cmd-line tools are installed and if the permissions are set correctly
run k3b as root
use another program (brasero) – worked – burned the discs

Then I tried many different things and found the bug coincidentally. I created a much bigger iso file from the original that was only 50 kb and then it worked.
My questions to the experts:

Are there more sophisticated tools I could use?
Could I have done something better?
What would you have done?
Comment: Is the error reproducible? If so, did you report the bug?
Comment: @user535733 yes on my machine. But I did not report it yet.
Comment: Which distro and version of Linux are you using?
Comment: I am currently using fedora and ubuntu but I noticed the bug on my fedora machine
Answer: Step 1: Determine the minimum number of steps required to reproduce the behavior from a stock new-install of Ubuntu.
Step 2: Spin up a Virtual Machine (unless your issue is hardware-related). See if you can reproduce the behavior in the latest release of Ubuntu. Or, better yet, in a pre-release daily build of Ubuntu.

If the issue is hardware-related, boot from a new-release or daily .iso instead of using a VM.

If you cannot reproduce the behavior in a new build, then the bug has likely already been fixed. Stop here.

Step 3: Review the bug reports for that software. If the issue has already been reported, help provide any additional information or testing that the developers need. If the issue is unreported, then report it. Monitor the bug report for information requests and testing requests from the developers.

Similar bug reports and requests from the developers will inform you what kind of troubleshooting information is needed for your bug. There is no universal rule -- every bug is different. Some bugs require lots of trace information, others require almost none.

There may be multiple Bub Trackers. Ubuntu has one, Debian has another, and the upstream project usually has it's own. Check them all!

DON'T add "me too" and other irrelevant comments to a bug report. Keep it clean and on-topic. It's a working notesheet for developers to track and and fix bugs. I've seen progress on bugs slow (even stop) when the report became unreadable.

Step 4. Be patient. Some bugs get fixed in hours. Some take years.
OPTIONAL: If you want to dive into the codebase and fix the bug yourself, you certainly can. Create a patch or merge request, and add it to the bug report. Again, be patient: Other folks must test your patch before agreeing to include your code in their project.
Comment: Thanks for your effort and comment. What I initially was asking was do you use any more sophisticated tools in such a case except log files?
Comment: Depends upon what you are troubleshooting. The question title says "arbitrary." If others have reported a similar problem, and the developers have asked for specific information, then you follow that guidance.