iText - OutOfMemory creating more than 1000 PDFs

Question: I want to create a ZipOutputStream filled with PDF-As. I'm using iText (Version 5.5.7). For more than 1000 pdf entries I get an OutOfMemory-exception on doc.close() and can't find the leak.
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(new BufferedOutputStream(baos));
zos.setEncoding("Cp850");
for (MyObject o : objects) {
try {
    String pdfFilename = o.getName() + ".pdf";
    zos.putNextEntry(new ZipEntry(pdfFilename));
    pdfBuilder.buildPdfADocument(zos);
    zos.closeEntry();
} ...

PdfBuilder
public void buildPdfADocument(org.apache.tools.zip.ZipOutputStream zos){
   Document doc = new Document(PageSize.A4);
   PdfAWriter writer = PdfAWriter.getInstance(doc, zos, PdfAConformanceLevel.PDF_A_1B);
   writer.setCloseStream(false); // to not close my zos
   writer.setViewerPreferences(PdfWriter.ALLOW_PRINTING | PdfWriter.PageLayoutSinglePage);
   writer.createXmpMetadata();
   doc.open();
   // adding Element's to doc
   // with flushContent() on PdfPTables
   InputStream sRGBprofile = servletContext.getResourceAsStream("/WEB-INF/conf/AdobeRGB1998.icc");
   ICC_Profile icc = ICC_Profile.getInstance(sRGBprofile);
   writer.setOutputIntents("Custom", "", "http://www.color.org", "sRGB IEC61966-2.1", icc);
   //try to close/flush everything possible
   doc.close();
   writer.setXmpMetadata(null);
   writer.flush();
   writer.close();
   if(sRGBprofile != null){
     sRGBprofile.close();
   }
}

Any suggestions how can I fix it? Am I forgetting something?
I've already tried to use java ZipOutputStream but it makes any difference.

Thx for ur answers! I understand the issue with the ByteOutputStream, but I am not sure what's the best approach in my case. It's a web application and I need to pack the zip in a database blob somehow.
What I am doing now is creating the PDFs directly into the ZipOutputStream with iText and saving byte array of the corresponding ByteArrayOutputSteam to blob. Options that I see are:
Split my data in 500 object packages, save first 500 PDFs to the database and then open the zip and add the next 500 ones and so on... But I assume that this creates me the same situation as I have now, namely too big stream opened in the memory.
Try to save the PDFs on the server (not sure if there's enough space), create temporary zip file and then submit the bytes to the blob...
Any suggestions/ideas?
Comment: Don't use ByteArrayOutputStream because that builds your entire zip file in memory.  Try using FileOutputStream instead.
Comment: If the ZIP is so large it already makes a server-side vm (which usually is given quite a lot of memory) go out-of-memory, then this certainly is a case for either using hard disc space instead or to stream to the DB (if the DB in question provides such a real streaming interface, that is). That been said, does it really make sense to store such a big ZIP in a single BLOB? Wouldn't a DB design with one BLOB per PDF be way more flexible?
Answer: It's because your ZipOutputStream is backed by a ByteArrayOutputStream, so even closing the entries keeps the full ZIP contents in memory.
Answer: You need to use another approach to do it with this number of arguments (1000+ files).
You are loading all the PDF files in memory on your example, you will need to do this in blocks of documents to minimize the effect of this 'memory load'.
Another approach is serialize your PDFs on filesystem, and then create your zip file.


Positioning on top of a input text field?

Question: I want to position .select-delete on top of the <input> text field. I did this once before, but alas I lost the code, and I'm pretty sure the surrounding elements CSS properties were different.
Here's a link to my JS fiddle, so that you can edit/see what I'm talking about: http://jsfiddle.net/gPF8X/
I've tried a negative margin-top but it's sent to the back of and hidden behind the text field. I've also tried to set float which alone with altering margin settings, which had the same effect.
Any edits/answers that have the desired effect would be greatly appreciated!
Answer: http://jsfiddle.net/gPF8X/2/
Like this:
I set the position of the #box to relative.
then set the position of the .select-delete box to absolute
CSS
#box {
    margin: 20px auto 20px;
    background: #fff;
    width: 460px;
    padding: 20px;
    box-shadow: 0px 0px 5px 0px rgba(0,0,0,0.6);
    color: #444;
    position:relative;
}
.select-delete {
    margin-left: 430px;
    margin-top: 0px;
    background: url(http://cdn2.iconfinder.com/data/icons/aspneticons_v1.0_Nov2006/delete_16x16.gif) no-repeat;
    height: 16px;
    width: 16px;
    position:absolute;
    top:40px;

}

Comment: Also if you are going to have multiple instance of this you may want to wrap your inputs in  tags and set those to position:relative and position the "x"'s accordingly. inside of those.


PHP Redis extension is installed and enabled in laravel 6 version

Question: When I am trying To installing redis  in larvel  6 version I can not install redis and it extension it show me the error.
Answer: By default In Laravel 6 'client' => env('REDIS_CLIENT', 'phpredis'), is not working but when i change this 'client' => env('REDIS_CLIENT', 'predis') .
Answer: For ubuntu
sudo apt-get install php7.2-redis //7.2 is php version

then
sudo systemctl restart php7.2-fpm

Answer: Solution in my case was:

download Redis PHP extension (I used version https://pecl.php.net/package/redis/5.2.2/windows but you download a version for your php version from here https://pecl.php.net/package/redis/ )
copy php_redis.dll in your ext folder (in my cas was laragon4\bin\php\php-7.4.0-nts-Win32-vc15-x64\ext)
add to your php.ini extension=redis
restart apache

My problem was that I had installed and working Redis but I hadn't the php extension.


Why does my password keep getting reset?

Question: This is the second time this message has been displayed. I have changed my password and then 24 hours later, Mojang resets my password again. Here is the text:

Due to recent suspicious activity in your account we suspect that your Mojang account email and password may have been compromised. To prevent unauthorized use of your account we've reset your account password. If you use that same password on other sites we strongly recommend that you change your password on those sites as well.
Comment: Did you change your email password? Do you let anyone else use your Mojang account?
Comment: Also, I have a YouTube channel as well. I hope that's not why my account is being targeted, if it is being targeted
Answer: Messages like that are usually relating  to other people trying to or actually accessing your account. I would change your password to a much stronger password, and if you are sharing your account with someone else, don't since that is a serious security issue and may be what is causing your problem.
Answer: You need to change the password of your connected e-mail account as well. Anyone with access to that account can regain access to your Mojang account. Also you should no longer give access to your Mojang account, if you did so in the past.
Of course you should change all passwords of the accounts connected to that e-mail account and all passwords that were equal to your stolen one.


Getting NaN values when multiplying a number by document.getElementById('myid')

Question: I'm learning JavaScript. I want to make subtotal for each product and I don't know why I keep getting NaN? Here is my code. I couldn't find the problem for this. Maybe there's something wrong with the value or something?

    var value;

    var price = document.getElementById("price");

    function priceTotal() {
        var total = value * price;
        document.getElementById("subtotal").innerText = total;
    }

    $('.increment-btn').click(function(e) {
        e.preventDefault();
        var incre_value = $(this).parents('.quantity').find('#qty-input').val();
        var value = parseInt(incre_value, 10);
        value = isNaN(value) ? 0 : value;
        if (value < 100) {
            value++;
            $(this).parents('.quantity').find('#qty-input').val(value);
        }

        priceTotal();
    });

    $('.decrement-btn').click(function(e) {
        e.preventDefault();
        var decre_value = $(this).parents('.quantity').find('#qty-input').val();
        var value = parseInt(decre_value, 10);
        value = isNaN(value) ? 0 : value;
        if (value > 1) {
            value--;
            $(this).parents('.quantity').find('#qty-input').val(value);
        }

        priceTotal();
    });

Rp. {{ number_format($cartlist->product->productprice)}}

                                            -

                                        <input type="text" class="qty-input form-control text-center" maxlength="2" value="1" id="qty-input">

                                            +

                                    Rp. {{ number_format($cartlist->product->productprice)}}

Comment: There may be other issues, but for starters, you have `var price = document.getElementById("price");` and then you attempt to do `var total = value * price;`. The problem here is that `price` isn't the ***value*** of the HTML element, it's a reference to the element itself and you can't do math with an element. So, you'd need: `var total = value * price.textContent;` (assuming that `price` points to the `td` element).
Comment: yes, i change it into `var price = parseInt($("#price").text());` now its working. thanks for the help!
Answer: Two problems:

1 -- You need to pass value from the onClick() handler to the priceTotal() function.  I recommend you take a quick glance at MDN Web Docs: Encapsulation, specifically:

Encapsulation is the packing of data and functions into one component (for example, a class) and then controlling access to that component to make a "blackbox" out of the object.

2 -- You are setting price to var price = document.getElementById("price"); and then using it in multiplication.  You cannot do that, you must use a number in multiplication, not an HTML element.  In addition, the price element is not even an input, so you can't use its val() function either.  I set this statically to just 1 to prove my point.

    var value;

    var price = 1; // you can't use an element as an integer

    function priceTotal(value) {
        var total = value * price;
        document.getElementById("subtotal").innerText = total;
    }

    $('.increment-btn').click(function(e) {
        e.preventDefault();
        var incre_value = $(this).parents('.quantity').find('#qty-input').val();
        var value = parseInt(incre_value, 10);
        value = isNaN(value) ? 0 : value;
        if (value < 100) {
            value++;
            $(this).parents('.quantity').find('#qty-input').val(value);
        }

        priceTotal(value);
    });

    $('.decrement-btn').click(function(e) {
        e.preventDefault();
        var decre_value = $(this).parents('.quantity').find('#qty-input').val();
        var value = parseInt(decre_value, 10);
        value = isNaN(value) ? 0 : value;
        if (value > 1) {
            value--;
            $(this).parents('.quantity').find('#qty-input').val(value);
        }

        priceTotal(value);
    });

Rp. {{ number_format($cartlist->product->productprice)}}

                                            -

                                        <input type="text" class="qty-input form-control text-center" maxlength="2" value="1" id="qty-input">

                                            +

                                    Rp. {{ number_format($cartlist->product->productprice)}}

Comment: Hi, claudia, that sounds like you're having a different problem now.  If my answer helped you with your current problem, can you mark it as correct, and then re-ask a new question, so I can look at it?  This helps people in the future who only have your first problem, etc..


Drilling 1/4" steel plate and concrete?

Question: I need to drill (44) holes in (22) 1/4"-thick stainless steel plates. These are for 3"x3/8" heavy Duty Screw Anchors that will go through the plate and into the concrete.
My question is: if possible, can I use one drill bit that will make the hole through the 1/4"-thick steel plate and the concrete where the screw will be inserted? This is hard reinforced concrete.
If not, what drill bits should I use? And can I use a regular drill?
Comment: note aside to the concrete question, stainless steel is particularly difficult to machine. You'll want good cobalt, carbide, etc bits and a powerful variable speed drill that can turn the bit at a cutting speed while you put quite a lot of force on it.  If feasible id want a drill press for this.  You'll probably want a hammer drill for the concrete.
Comment: Good points. I skimmed right past the stainless part. A person can melt the edge off standard bits in a hurry by spinning them at top speed while dry on stainless.
Comment: FYI a mag drill might be especially helpful here if this is a magnetic stainless steel plate. Also, you could consider something like a thermal lance or a plasma cutter.
Comment: If it were possible to drill through the concrete side first you might avoid some of the issues with ruining your steel-cutting bits when they hit the concrete.
Answer: No.
Steel bits need to be very sharp to do their job. In fact, unless you set a depth gauge just barely through the metal, you'll wreck the cutting edge with every hole when you contact concrete and need to resharpen.
Concrete bits create holes by pounding and disintegrating the material. They have cutting edges, but that's mostly to focus the impact and clear debris. They become dull over time as well, but it doesn't dramatically affect their performance.
Ideally you'll drill your plates in advance, then use them as guides for drilling the concrete. Herb Guy offers some good advice on that note: "Try to find a local welding, ironworks or machine shop. They can punch or drill those holes for faster and cheaper than you ever will and make the S/S plate hole's ø 1/8" larger so the hammer drill tip and anchor shields/wedges pass through."
Otherwise, I suggest having several of each type of bit on hand. The steel bits will need time to cool after several holes (unless you lubricate with oil), so you'll want to rotate them, and the concrete bits occasionally throw their carbide teeth.
Answer: If you mean non-magnetic , eg 304. stainless , you have a problem. I am assuming a limited amount of experience. If the drill turns without cutting , it coldworks the stainless making it even more difficult to cut. I would say get several 1/8" bits and several 3/8" drill bits. The "chisel" at the center of the point scrapes metal away instead of cutting it so you want it as small as possible. You make a small hole first ( and smaller than 1/8 would be good.) Low RPM, high pressure, high sulfur cutting oil, if a bit is not very sharp, change it or sharpen it. If any bit touches the concrete, it is ruined.As isherwood says you need to drill the metal before it is on the concrete. High Speed Steel bits  will keep cutting up to 1000 F , so the big problem is the bit must cut and not slip/spin. Sorry for duplication. If it is magnetic stainless , eg. 410. it will not be quite as bad because the workhardening is not as extreme.

Drilling 1/4" steel plate and concrete?


Tranferring Large Data Between Servers Fast

Question: This is a common question, but Googling this gives a lot of crap.
As data volumes are getting higher and higher, all along with processing power & cloud capabilities, we are witnessing a growing need for fast data transfer technologies capable of unleashing the power of all this available data by spreading / moving / sharing it across different servers/clients.
In our case, we are recording real time binary data (50 Gigs a day) and we need to upload it / download it every day to/from subscribers (yes, all of it is needed locally by each subscriber server, for computing and various data analysis stuff)
So to put is shortly, what are choices available today to transfer many Gigs of Data REALLY FAST between remote windows servers (VPS's, Cloud, with a "fairly" consistent bandwitdth -(optic fiber put aside) )
This is an open question. Every Idea is welcome whatever the protocol.
Comment: As an option see [Sneakernet](https://en.wikipedia.org/wiki/Sneakernet)
Comment: Did you consider using the BitTorrent protocol?
Comment: @JaneDoe no, ServerFault
Comment: i think this might be suited better for programmers?
Comment: How is stored the data ?
Comment: I know CloudOpt, which seems to be an interesting solution (http://www.cloudopt.com/). I am though curious to know what other recent technologies/setups have to offer
Comment: These 'subscriber servers', is there any reason they can't all be on the same LAN, along with your master server? Or are they controlled by the clients?
Comment: @SteveB Large Binary Files (~1Gig)
Comment: @ThomasMueller : This might be possible... but I don't thing there are enough subscribers to create a significant sufficient torrent leverage (in terms of seeders, leeshers)
Comment: a mirroring service that is running all the time will 'hide' a lot of transfer time, as well as giving you multiple points to pull from.
Comment: @lynks : Good question. LAN is the past :-)
Our network is scattered throug different virtual/physical machines We have 10 to 20 different Cloud HPC servers / Dedicated Servers / Local workstations / VPS's. If we had to put this on a LAN it would cost one leg to each developer we have every month. We do not have enought developers/legs for that.
Comment: @MikaJacobi haha xD ahh well, let me live in the past. i have a server cluster (yep; real, metal, boxes) on a gigabit lan, horizontal scaling can bite me :P
Comment: @oleksii LOOOOL XD Actually this is an option that Amazon (AWS) offers to transfer large data files. They literally ask you to send them a portable Hard drive so they can upload your data
Comment: How about real time distribution? A data distribution service (DDS) may be your solution.
Answer: The challenge of sending and receiving the data over the network is multi-fold.

The network bandwidth is the most limiting factor and there is hardly anything you can do for this at application level (except occasional compress the data and even in that case the compression ration determines the gain). So faster network is the first choice.
Certain protocols are more suited for transferring certain type of files/data. For example http is a text based protocol and and not really suited for binary and large contents. But since its the most popular web protocol which needs binary contents to be sent over the wire, techniques like encoding and chunking have evolved. HTTP is really not the choice if your data is in the order of GBs which is your case.
FTP is the most popular protocol used to transfer files over the network and its specifically designed for transferring files. There are several extension of FTP like GridFTP, bbftp which are very specifically designed for large data transfers.
BitTorrents is another option that can be explored. Facebook uses BitTorrents to push the binaries to the servers (tens of thousands in number).

You problem is very open ended and I am limited by my experience :). Here is link I found which deals of large data transfers. Hope this helps you.
Comment: +1 for diverse approach. I would also add [sneakernet](https://en.wikipedia.org/wiki/Sneakernet). Somehow, people at Serverfault [frown upon](http://serverfault.com/a/332612/82856) ftp for this purpose. Also there are [some other](http://serverfault.com/questions/332606/what-is-the-fastest-and-most-reliable-way-of-transferring-a-lot-of-files) solutions discussed, not sure if those can be used programmatically though.
Comment: +1 for use of bit torrent or similar peer to peer protocols as you have to send multiple copies and the network bandwidth is likely to be the limiting factor.


Create a pandas Dataframe based on a dictionary which summarizes hierarchy between categories

Question: I have the following dictionary :
hierarchy = {
'Category1': [],
'Category2': ['Category1'],
'Category3': ['Category1'],
'Category4': ['Category2'],
'Category5': ['Category4'],
'Category6': ['Category4'],
'Category7': ['Category6']}

This dictionary summarizes which category is a sub-category of a parent category. For example, Category2 is a sub-category of Category1. Similarly, Category3 is a sub-category of Category1. Category4 is a sub-category of Category2, Category5 is a sub-category of Category4, and so on.
I'd like a function that could summarize these informations in a dataframe, and link all the sub-categories together. For example, thanks to the previous dictionary, we know that Category5 is a sub-category of Category4, Category4 is a sub-category of Category2, and Category2 is a sub-category of Category1. I'd like to have the information on the same row, where each column contains the categories of the hierarchy in descending order of size.
In the example of the hierarchy dictionary, I'd like to have the following output:
pd.DataFrame(data={
    'Biggest_category' : ['Category1','Category1','Category1'],
    'Second_Biggest_category': ['Category2','Category2','Category3'],
    'Third_Biggest_category': ['Category4','Category4',[]],
    'Fourth_Biggest_category': ['Category5','Category6',[]],
    'Fifth_Biggest_category': [[],'Category7',[]]
})

Can someone helps me please? I have tried many things but nothing really work as I would like.
Comment: Is there a reason you want 3 items in each list?
Comment: No, it's just an example. I want the number of items I need, it doesn't have to be a specific number
Comment: Could you edit your post to show exactly what you want, please?
Answer: First, get parent nodes and their children:
from collections import defaultdict

# Use defauldict to initialize a dictionary with empty lists as values
nodes = defaultdict(list)
for key, value in hierarchy.items():
    if value:
        nodes[value[0]].append(key)
nodes = dict(nodes)

print(nodes)
# Output

{'Category1': ['Category2', 'Category3'],
 'Category2': ['Category4'],
 'Category4': ['Category5', 'Category6'],
 'Category6': ['Category7']}

Then, traverse the nodes in a recursive fashion:
def traverse(start, nodes):
    if start not in nodes:
        return [start]
    paths = []
    for child in nodes[start]:
        for path in traverse(child, nodes):
            paths.append(start + "," + path)
    return paths

categories = pd.DataFrame([path.split(",") for path in traverse("Category1", nodes)])

Finally:
print(categories)
# Output

           0          1          2          3          4
0  Category1  Category2  Category4  Category5       None
1  Category1  Category2  Category4  Category6  Category7
2  Category1  Category3       None       None       None

Comment: Thank you a lot, it works perfectly ! But I have just found another problem on my dictionary hierarchy... Could you help me please? https://stackoverflow.com/questions/76530115/create-a-hierarchy-between-categories


What are all the passive weapon effects in COD: Cold War (Zombies)?

Question: I noticed that some weapons have a passive effect when you Pack-a-Punch them. For instance, the Gallo shotgun has an explosive ammo effect which sometimes triggers on melee.
What are all the weapons that gain an effect besides increased ammo / damage when Pack-a-Punched (and what is that effect?)
I could not find a list on the wiki, and a lot of results returned are for earlier COD titles (at least at this point). There were weapons in other Black Ops titles that changed drastically when you PaP'ed them, most notably the ballistic knife and the crossbow, so I was curious if there was anything along those lines.
Answer: The ballistic knife changes drastically when Pack-a-Punched: if you shoot someone while they're down they will get revived
The starting M1911 handgun will  become duel-wielded and fire rifle grenades - making it similar the game's "Death Machine" - when upgraded
Comment: Welcome to Arqade! This answer is currently very basic and lacking of description and detail. We expect answers to be of quality on our network, so you need to add sources, back up your claims, and talk more about what each thing does, instead of giving an incomplete solution (without explicitly stating it). Show that you're putting effort into giving answers here, that's what we're all about.


I can't redownload Skyrim on my Xbox

Question: So I accidently deleted Skyrim off of it. I originally put the skyrim code for the game on my other account but I deleted the account. The game worked on my new account also but now I deleted it and can't get it back. Looked on download history and searched the game and I have to buy it.
Comment: You probably can't re-download it because you deleted the account it was licensed to, so there isn't anyone who owns the game on your console, so you can't re download it.
Comment: recovering your old gamertag and using that is likely the only option.
Comment: Can't you redownload it from your other account?
Answer: Ownership of a digital game is tied to the account. If there is no account on a console that owns the game, you can't download it- there's essentially no difference between you and someone who has never bought Skyrim in their life.
Your only options at this stage are either recovering the old account or buying a new copy of Skyrim.

I can't redownload Skyrim on my Xbox


Prove that a function is both odd as well as even.

Question: Consider the function
$$f(x) =
\begin{cases}
e^{-\sqrt {\vert ln \{x\}\vert}}- \{x\}^{\sqrt {1/\vert ln \{x\}\vert}},  & \text{wherever it exists} \\
\{x\}, & \text{otherwise}
\end{cases}$$
where $\{x\} $ denotes fractional part of $x$. Prove that $f(x)$ is odd as well as even.
I am not getting any idea over how to start approaching the problem. I tried using $f(-x) +f(-x)$  to see whether odd or not but got messed up badly.  Somebody please help.
Comment: There are no integers that are both odd and even.  The only function that is both odd and even, satisfying $f(x)=f(-x)=-f(x)$ for all $x$, is the zero function.
Comment: $2$ is odd as well as even?
Comment: Just my problem. Is it possible ?
Comment: First, how many functions can be *both* even and odd.  $f (x)=f (-x)=-f (x) $.  Surely that's unusual.  Perhaps the are asking you to prove something much simpler.
Comment: I also guess that the function might reduce to f(x)=0 since it is the only odd and even function
Comment: Do you know any way to relate general exponential functions to exponentials with base $e$?
Comment: Guys I have proved the statement If x is an integer because the first part of the function isn't defined on integers.
Comment: It is true via some slightly tricky algebra. My hint above about exponentials is a good one.
Comment: Since $\ln \{x\}<0$ then $|\ln\{x\}|=\ln  \frac 1 {\{x\}} $.
Comment: To be a little more explicit about my hint, if $a^b = e^c$, then what is $c$?
Comment: The top term exists exempt when x is an integer.  To compare e^stuff to {x}^stuff take the ln of each.  You get -root (|ln {x}|) for one and root (1/|ln {x}|)x ln {x}.  Show those are equal.
Answer: It's not hard to see that for $f$ to both even and odd, $f$ must be identically $0$ on its domain. The first branch of $f$ is undefined whenever $\ln\{x\} = 0$, which occurs when $x$ is an integer; in this case, $f(x) = \{x\} = 0$.
If it is defined, then
$$e^{-\sqrt {\vert ln \{x\}\vert}}- \{x\}^{\sqrt {1/\vert \ln \{x\}\vert}}= e^{-\sqrt {\vert \ln \{x\}\vert}}-e^{ \ln \{x\}\sqrt {1/\vert \ln \{x\}\vert}}$$
$$= e^{-\sqrt {\vert \ln \{x\}\vert}}-e^{-\vert \ln \{x\}\vert\sqrt {1/\vert \ln \{x\}\vert}}=0,$$
since $a^b = e^{b \ln{a}}$ and $\vert \ln \{x\}\vert = - \ln \{x\}$.


Deleting entire data from a particular column in oracle-sql

Question: Recently I have started learning Oracle-sql. I know that with the help of DELETE command we can delete a particular row(s). So, Is it possible to delete entire data from a particular column in a table using only DELETE command. (I know that using UPDATE command by setting null values to entire column we can achieve the functionality of DELETE).
Comment: `UPDATE table SET your_column_name = NULL` DELETE removes rows, alternatively you can get rid of column using `ALTER table DROP COLUMN name` (not recommended)
Comment: @lad2025 Thank you. Now I clearly understood that DELETE removes only rows but not entire data from a particular column.
Answer: DELETE

The DELETE statement removes entire rows of data from a specified
  table or view

If you want to "remove" data from particular column update it:
UPDATE table_name
SET your_column_name = NULL;

or if column is NOT NULL
UPDATE table_name
SET your_column_name = <value_indicating_removed_data>;

You can also remove entire column using DDL:
ALTER TABLE table_name DROP COLUMN column_name;

Comment: @RajeeVVenkaT Yes, because Oracle treats internally empty string as  NULL
Comment: What do you mean by  ?.
Comment: @RajeeVVenkaT For example your column is set to `NOT NULL` and you have column name, you can for example set ` ` empty string
Comment: I observed that a column when set NOT NULL cannot be updated with ' '. So, only by using DROP or UNUSED command we can perform actions.
Comment: Now I understood. Column when set NOT NULL cannot be updated with    ' ' but can be updated with ' '. Small difference, but matters a lot.
Answer: In SQL, delete deletes rows not columns.
You have three options in Oracle:

Set all the values to NULL using update.
Remove the column from the table.
Set the column to unused.

The last two use alter table:
alter table t drop column col;
alter table t set unused (col);

Answer: Use Invisible Type, which is from an oracle 12cR2.
ALTER TABLE LOG1
MODIFY operation  INVISIBLE

It is  a better than drop of a particular column.If you need to visible you can get back by altering with an VISIBLE of a column name.
Answer: update employee set commission=nvl2(commission,'','')
this will remove all the data from the column


Are icons in business software helpful?

Question: My team and I are working on a re-design for an internal software that people within our customer service use to track shipments in real-time.
I am thinking about a way to efficiently show different states of shipment or any kinds of problems with icons.
I've read some articles about the use of icons in interfaces and that they actually work for sure only for universaly understood metaphors like "home" (house icon), "search" (magnifying glasses) "print" (printer).
Iconic Simplicity. The Vital Role of Icons
Do Icons Need Labels?
But in our case our users are expert users and they work with this software the entire day. But anyway, I think that this should not be an excuse for not trying to make intuitive and as easy as possible to understand icons.
I am now looking for some information or studies about the efficiency of icons in expert systems, where it is hard to find an intuitive metaphor for complex situations.
It is said that when you have to think for more than 15 seconds to come up with an icon, you should not use one at all.
Can icons be helpful in expert software and increase efficiency versus text?
Comment: That expert users are human beings in the first place :-] Why not make the interface easier for them?
Comment: And who said *"when you have to think for more than 15 seconds to come up with an icon, you should not use one at all."*?
Answer: Yes, icons are helpful, very helpful, in some situations they are necessary.
In your case, where users are professionals, they can easily learn.
The best practice would be to show a text next to the icon, if the interface dose not allows it, you can use only icons with tooltips.
Screenshot from CorelDraw showing a complex concept with the tooltip.
Answer: I've observed the trend in user interfaces is toward icons + text, sometimes with a user configurable option to hide either the icon or the text.
Two key pieces of context in your question:

"re-design for an internal software"
"our users are expert users"

Given that context, starting with text makes a lot of sense. First, it will reduce the cost of iterating your design as you work with internal stakeholders. Second, expert users are likely to require expert commands. It is unlikely icons will exist that are recognizable enough for the specialized terminology that describes those commands.
As you validate user workflows and iterate on the design of your app, it may turn out that adding icons makes sense. One way icons can help is to allow multiple commands to be shown in a compact area. Application toolbars like the one in the FreeCAD Part Design workbench use icons to represent complex concepts in a compact space. They do show a text label on hover. Icons also work well when they are OS-specific icons used in a consistent way across many applications written for that OS.
Here are some screen shots I took showing examples of icons + text. The last example is the sidebar of GitLab, a web application designed to support relatively complicated tasks related to project management, configuration management, change management, and DevOps. Given that complexity and the large user base, including "enterprise customers", GitLab is a nice benchmark for professional software.
iOS Mail

iOS Photos

iOS WhatsApp

GitLab web app (Safari Mobile)

I'll try to come back and edit this answer to add authoritative references.
Answer: There are also other considerations or reasons why you might want to use icons, for example if the text descriptions are very long and you have limited spaces (or lots of buttons), and also icons can be learnt and a visual language for it developed over time. Not only that, icons can be easier to recognize for some people, so that if you introduce more features over time people can still learn where to go for certain features quickly (e.g. if used in a tile/grid design pattern for display).
As with all questions on UXSE, the context is very important and in your case it would appear that there might not be a need to design icons. However, you should always test these assumptions with actual end users as part of the design process. You will probably still find it suitable to design icons for standard functions like Save (which is slowly being phased out in some applications these days), Log-off/Exit, Edit, etc.
Some examples of the use of icons in expert systems would be those seen in engineering or scientific applications, where there are a lot of acronyms or complex chemical formulas and it is much easier to design and organize the interface if you use icons instead of text. Or there might be cases where you are restricted to using certain interface elements due to the length of text (that you can't or don't want to abbreviate/truncate).
Answer: For "expert" systems, the analogy that I think works best is the car. It is a complex, life-threatening device that takes hours of learning to be operated safely, but that you can eventually drive for hours pretty much without thinking about it.
In my opinion, the situation depends on whether you're talking about controls or displays. A critical aspect of it is also the frequency of expected use.
For controls
A large part of what makes driving a car possible is that it relies on your muscle memory: you don't need to read the label on the switch that turns on the headlights, you just know where it is and turn it on.
The same kind of efficiency can be reached on a computer by allowing keyboard shortcuts, which in my opinion are way faster for expert UIs. Nearly all of the highly proficient experts that I've seen use the same software throughout the day rely heavily on keyboard shortcuts to do their job faster.
Icons can work to increase information density too. What's also important is that they are in reliable locations as well.
Some examples of this that you may be familiar with is Photoshop, Adobe Premiere, or any CAD software — labels are typically scarce in the UIs, which (the field being pretty competitive commercially) show that it's an advantage for expert user bases. But again past a certain point, expert users of these applications tend to switch to keyboard shortcuts.
As an example, below is the Photoshop toolbar — with labels, it would take up about 5x as much screen real estate.
All of this comes at the cost of a longer training curve simply because when you tell someone "use the  tool" they may not understand right away what you are referring to. But if your tool needs significant amounts of learning anyway, it doesn't matter as much.
For displays
In the case of displaying information, we can go back to the car analogy and see that it works at least for very simple cases: people know what a red light means without it being labeled. However, you will see a lot more things labeled on the road signs than in your car.
Europe is an exception to this — being a linguistic patchwork, people have decided there to standardize on road signals, so that a "stop sign" or a "no parking" sign are supposed to look the same across the continent (to the endless puzzlement of American tourists). But for computer UX where the UI can be translated to the viewer, this makes no sense.
Back to UX, one thing to consider is that accessibility requirements will typically force you to find a way to write things out for users with visual impairments, or color blindness. Personally I would be more careful about use of icons in displays than in controls.
The role of frequency
The more your users will rely on a control or display, the more familiar it gets and therefore the more appropriate an icon treatment is. Conversely, the less your users will rely on a control, the less familiar it gets and the more important labels are.
As an example, car warning symbols are notoriously bad, i.e. many people can't tell what they mean, even when the symbol represents important, potentially life-saving advice. This is because these icons are hardly ever seen, so people's memory of what they mean (assuming they ever learned it) decays with time.
Icons and other visual treatments are appropriate for things that people need to do with high frequency. "Red light means stop" is a good example: most drivers encounter it every time they drive. It is risky to use icons for things that happen infrequently, because users may just overlook them completely out of a lack of understanding, and it may lead to bad mistakes.
Illustration: photoshop toolbar
Comment: Car warning symbols may not be self-explanatory, but they still give a good idea of what's wrong with the car by just looking at them. Battery warning, seatbelt reminder, open doors, oil pressure warning and low fuel icons aren't that bad.
Comment: @Shahriar I'm not making a subjective judgment when I say that, just looking at stats it's objectively bad.  https://www.expressandstar.com/news/motors/2018/08/23/more-than-half-of-drivers-too-dim-to-identify-dashboard-warning-lights/

Are icons in business software helpful?


Mapping URL in Maximo Anywhere

Question: I'm looking to deploy mapping functionality in the Work Execution app within the Maximo Anywhere framework. The issue I'm having is the app throws an error when I attempt to go into the "Map of Work Orders" screen. The error that displays on the screen is

"Unable to show map. It is possible that the value for the providerURL property is invalid. Contact your administrator."

When I look into the logging data I get a bunch of lines about OpenLayersMap.js - stating that the providerURL is wrong.
In the app.xml for the WorkExecution app we have this configured in the Map tag (line 3320 in our config)
        <map adjustToTop="true" androidLocalMapUrl="file://mnt/sdcard/basemaps/Manhattan.tpk" id="WorkExecution.MapView_esri_true" iosLocalMapUrl="Manhattan.tpk" iosMapAccessMethod="useDocumentsFolder" layoutInsertAt="map" provider="esri" workOfflineResource="workOrder" providerUrl="http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}"/>

Additionally, we've enabled maps in the app-feature.properties file by setting map.enabled=true
Does anyone have online maps working in a test environment on 7.5.2 in the work execution app? If so, mind sharing their config if it hits a public server, or point out what's wrong with ours?
Answer: This message inform you that the value for providerUrl is invalid or that this connection to the server could not be achieved. I checked here and it seems that this value is correct.
Are you using the adminmode? Because internally, the value for providerUrl from app.xml can be replaced by the value of providerUrl from the server via adminmode (maximo). To check if you are using it, take a look at your worklight.properties file and if the property for si.adminmode is true, you need to confirm if the value put on maximo to providerUrl is a valid one.
Comment: We do have the admin mode enabled within the worklight.properties file. The providerUrl shown in the administrative console is incorrect, but it doesn't look like I can modify it. I'll work to get those permissions and then modify that variable, rebuild, and report back the results.
Comment: Still not showing the mapping. I've reached out to IBM, and will report back what they say.
Comment: Just got this back from IBM :  It appears our KC is not being specific enough on the providerURL value. Please try setting it to the following and test again:

http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}
Comment: As you are using the admin mode, remember that the value from server will replace the value get from app.xml. So, make sure that the value on server is correct. You can change this value for each application that you are using. Remember to save your changes on maximo and re-log on app to get the new values. About the value of providerUrl, the value that you said that is on your app.xml seems good, I mean: http://server.arcgisonline.com/ArcGIS/rest/services/World_Topo_Map/MapServer/tile/{z}/{y}/{x}, so use it on providerUrl from server.

Mapping URL in Maximo Anywhere


How to change the url of numbers in pagination using CakePHP?

Question: By default, when displaying pagination numbers, the url looks like /controller/action/page:number. In my application I have defined a route:
Router::connect('/:categ', array('controller' => 'posts', 'action' => 'index'), array('categ' => '[a-zA-Z]+'));

I want the number link to be something like /:categ/:page.
I've tried with
Router::connectNamed(array('page'));

but has no effect.
Am I missing something?
Answer: You must using pagination options with url params:<?php $this->Paginator->options(array('url' => 'some params')); ?>


Debugging using RealView Debug(RVDebug)

Question: I have some C code for an ARM926 target. I am trying to debug it using "Arm Xtended Debugger" (AXD).  The main() of this code, takes 14 command line arguments which are mentioned in the code warrior project settings at proper place and behavior of the code is as expected.
But when I try to use the same AXF (Arm eXecutable Format file) file and try to do source level debugging using the RVDEBUG by changing the settings of the Codewarrior project, and start debugging, then the argc value is 1.  Then the behavior of the code is unexpected.
When I select RVDEBUG in code warrior settings I give the same options as I used during AXD debug session.
So my question is:
I am using the same AXD for both the debugging sessions(AXD and RVDEBUG), why are they behaving differently?  They should behave the same.
Answer: I don't use CodeWarrior but I know AXD and RVD: I remember Code Warrior can invoke AXD with the suitable arguments for the image, and so on. I don't know if Code Warrior can invoke RVD as well. So I suppose you run RVD yourself, outside any Code Warrior menu, don't you?
Then you just have to add the arguments in the dedicated input box at the bottom of the Load Image menu.
If this still does not work, I suggest you have a look at the semihosting options (they're rather in the connections options of RVD than in Code Warrior's).
Good luck!

Debugging using RealView Debug(RVDebug)


NetBeans plugin fails if nb-javac installed

Question: Using NetBeans 11.1 with Java 11 on Linux (haven't tried on other platforms).
If I install the 'nb-javac' plugin, as recommended by the IDE notifications, the CodenameOne plugin module fails to load and therefore CodenameOne features are unavailable.
Any suggestions or workarounds?
Comment: This is a know bug: https://github.com/codenameone/CodenameOne/issues/2916
Comment: I use Netbeans 10 + Oracle Java 8 + CN1 plugin on Linux and they work fine. So a simple workaroud is the use of a previous version of Netbeans, if it's not a problem for you. However, for a proper solution, you can try to add a comment to https://github.com/codenameone/CodenameOne/issues/2916
Comment: @FrancescoGalgani I just downloaded the [11.0 Codename One plugin](http://plugins.netbeans.org/plugin/42406/codename-one) and installed it in NetBeans 11.1 with no problems at all. I am running on Windows 10. As noted in the bug report, the error is not necessarily reproducible.
Comment: Thanks @JoseHeitor I think this is the key we need to reproduce that issue. I've added a link to this post and moved it to the closer milestone release
Answer: I am using Windows 10, NetBeans 12 and had the same problem.
I solved it by removing

org-netbeans-modules-nbjavac.jar
org-netbeans-modules-nbjavac-api.jar
org-netbeans-modules-nbjavac-impl.jar
files from directory C:\Users[USERNAME]\AppData\Roaming\NetBeans\12.0\modules.
After staring NB, it notifies that some modules are missing. You can click the link to install the lastest version. It worked for me.

I hope this will help someone.
Comment: Removing the files under  made the installation work for me with Netbeans 12.1.  Thanks!
Answer: I had a similar problem with Netbeans 12.0 on Windows. I installed the nb-javac plugin as suggested in the notifications, and then immediately after was unable to run my application. I use Java FX and Netbeans said it couldn't find the javafx.controls module. Deleting the three files from C:\Users[USERNAME]\AppData\Roaming\NetBeans\12.1\module worked for me too.


Alpha value not persisting while saving Bitmap

Question: Good morning all,
I am making an Image Steganography project for college.
While hiding data in image. I am writing the "Text Length" which is an Int32 in a pixel. As Int32 is of 4 bytes. I thought I could write it in the 4 bytes of Alpha,Red,Green,Blue, as each color is of 1 byte.
Then I save the image in bmp format.
I used single stepping and data get properly distributed and set in the pixel.
The problem arise when I read back the pixel. R,G,B have their value as i had set them. But the alpha is always 255 no matter what it was set.
Code that I am using for distributing Int32 into 4 bytes are
byte R, G, B, A;
int colorValue = messageLength;
int first = colorValue & 255;
//R contains bit 0-7 means the least significant 8 bits
R = (byte)first;
colorValue = colorValue - first;
int second = colorValue & 65535;
colorValue = colorValue - second;
second = second >> 8;
//G contains 8-15
G = (byte)second;
int third = colorValue & 16777215;
colorValue = colorValue - third;
third = third >> 16;
//B contains 16-23
B = (byte)third;
colorValue = colorValue >> 24;
//A contains 24-31
A = (byte)colorValue;
pixelColor = Color.FromArgb(A, R, G, B);
bitmap.SetPixel(location.X, location.Y, pixelColor);

Code for getting the values back is
byte R, G, B, A;
R = pixelColor.R;
G = pixelColor.G;
B = pixelColor.B;
A = pixelColor.A;

messageLength = A;
messageLength = messageLength << 8;
messageLength += B;
messageLength = messageLength << 8;
messageLength += G;
messageLength = messageLength << 8;
messageLength += R;

Is there something I am missing. Is it that BMP does not allow alpha value to persist???
Please help.
Thanks.
Comment: It's difficult to diagnose the problem without seeing the code that you're using to write and read the bitmap. Can you post that?
Comment: Not sure, hence the comment, but wouldn't you need something such as a `PNG` to hold alpha values?
Comment: Seems it's not possible. Perhaps [use PNG](http://msdn.microsoft.com/en-us/library/aa970062(v=vs.100).aspx)?
Comment: I just want to confirm that using Bitmap.MakeTransparent() and Bitmap.Save(sFilePath, ImageFormat.Png) can preserve alpha values.
Answer: Sorry to say that Bitmap doesn't support an alpha value.
Comment: If you click around a bit to where you link, you'll find [_"The high byte in each DWORD is not used"_](http://msdn.microsoft.com/en-us/library/dd183376%28VS.85%29.aspx) and [_"The Windows API is not capable of generating BMP images with alpha information and very few graphics editing programs are able to preserve transparency when saving images as BMP files."_](https://github.com/thomerow/png2bmp32). So while it technically may be possible to utilize all four bytes in order to store an alpha channel, it cannot be done using .NET's mechanism to save bitmaps.
Comment: Thanks for clarifying. The BMP format technically can, but the Bitmap class actually can't. Mistook Bitmap for BMP. My apologies. I've always used PNG in the past when I needed to use alpha values.
Comment: @ChrisMantle but the libraries you linked in in your (now removed) comment **do** allow the user to write the otherwise unused byte. Perfect for hiding information, like OP wants. Unless those files have to be openable and savable by other editors, because those will wipe the hidden data.


Return JSON from self-hosted WCF 4.5 service?

Question: How do I get JSON from a self-hosted WCF 4.5 service?
I'm using Fiddler2 to send requests with "Content-Type: application/json" (also tried "Content-Type: application/javascript") but I keep getting XML.
In combination with setting "AutomaticFormatSelectionEnabled = true" on my WebHttpBehavior I still get XML and when using "Content-Type: application/json" the server won't respond at all (Then I get error 103)
I have enabled CrossDomainScriptAccessEnabled on my WebHttpBinding and I'm using a WebServiceHost in a console host.
The service is very simple:
<code>[ServiceContract]
public interface IWebApp
{
  [OperationContract, WebGet(UriTemplate = "/notes/{id}")]
  Note GetNoteById(string id);
}
</code>
I've also tried setting AutomaticFormatSelectionEnabled to false and using ResponseFormat = WebMessageFormat.Json in my service-contract but that also result in "error 103" with no further info.
I've turned of customErrors and set FaultExceptionEnabled, HelpEnabled to true (not sure if that would do anything about this but just to make sure I've tried it all)
Am I missing a dll or something else?
Comment: Have you tried setting the `ResponseFormat = WebMessageFormat.Json` property in your `WebGet` attribute?
Comment: Yes and the result is: "Error 103 (net::ERR_CONNECTION_ABORTED): Unknown error"
Comment: Another thing to try would be to enable tracing (http://msdn.microsoft.com/en-us/library/ms733025.aspx) and see if there is anything that could explain the problem.
Answer: Try to start simple, as in the code below (which works on 4.5). From there, you can start adding the features your code uses one at a time, until you find the moment it breaks. That will give you a better idea what is going wrong.
<code>using System;
using System.Net;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace ConsoleApplication5
{
    class Program
    {
        static void Main(string[] args)
        {
            string baseAddress = "http://localhost:8000/Service";
            WebServiceHost host = new WebServiceHost(typeof(Service), new Uri(baseAddress));
            host.Open();
            Console.WriteLine("Host opened");

            WebClient c = new WebClient();
            Console.WriteLine(c.DownloadString(baseAddress + "/notes/a1b2"));

            Console.WriteLine("Press ENTER to close");
            Console.ReadLine();
            host.Close();
        }
    }

    public class Note
    {
        public string Id { get; set; }
        public string Title { get; set; }
        public string Contents { get; set; }
    }

    [ServiceContract]
    public interface IWebApp
    {
        [OperationContract, WebGet(UriTemplate = "/notes/{id}", ResponseFormat = WebMessageFormat.Json)]
        Note GetNoteById(string id);
    }

    public class Service : IWebApp
    {
        public Note GetNoteById(string id)
        {
            return new Note
            {
                Id = id,
                Title = "Shopping list",
                Contents = "Buy milk, bread, eggs, fruits"
            };
        }
    }
}
</code>
Comment: Thanks for the push. Your example worked fine so I tried to make it more and more like my own to see where it broke. And I found out that the problem was a DateTime-property in my Note-class that was set to DateTime.MinValue and this was "obviously" not supported by the serializer. What a headake to debug! Finally got it =)
Comment: I have same problems with DateTime. Thanks a lot, this post save my tyme!


How to drag shapes (like rect,circle,other polygons,etc) around the canvas using native javascript

Question: Am simulating a shape click and trying to do drag/drop inside canvas using Sahi framework.I have found some references that by looping through an array containing that shapes position/sizes , we get whether shape is clicked.While testing other website using sahi framework/native jaascript , how can it be achieved ? I wanted to select that shape inside canvas and do drag and drop inside canvas.This is my goal.
Comment: Please post an example image that you are attempting to analyze.
Comment: Am trying to achieve the same in the link - simonsarris.com/blog/140-canvas-moving-selectable-shapes..In this link , there's a canvas with 2 rectangles placed.am trying to do a click in this site and drag the rectangle.Though it already have a source code ,am trying to apply the logic which you have quoted--to scan all the pixels from imagedata.But Data array from imagedata is coming with zero values.I am trying to use the logic you have mentioned because i wont be knowing shape's position or size when testing customer applications.
Comment: To discover the position of unknown rectangles, you will have to use the `getImageData` script in my answer. If the rects are not black (as in my example) you will have to adjust the test to find your desired rectangles. You could test for non-zero alpha pixels if you don't know the color of the rects.
Comment: Actual customer application is having a satellite map in canvas and on top of it it has a rectangle shape.So when user do the drag/drop of that shape to another position in canvas,we should be able to record that and playback.Hope if user clicks somewhere other than this shape (means in the satellite map) , then also i will get the non zero alpha values based on opacity.So i cannot determine whether user clicked on a rectangle or the satellite map.I can get the rgba values at the point when user clicks.So based on that data how can i determine that its a rectangle in which they clicked ?
Comment: Your explanations of the images are difficult to understand. **Please take a screenshot and post it for us to look at.**
Comment: Sorry am new to posting here.could you please tell me how to post a screenshot?
Comment: Sure. Click the "edit" link under your question. Then add an image by clicking the [image button](https://dl.dropboxusercontent.com/u/139992952/multple/temp-1.png). Then drag your screenshot onto the add-image dialog.
Comment: Thanks Mark.Have added the screenshot..User can drag and drop the rectangle to anywhere inside canvas.So we have to record that useraction.For this i need to find out the element means the rectangle here and simulate the drag drop over canvas.Am not ableto identify that rectangle.
Comment: You will need to develop a plan to identify the rectangle. Will it always be a red stroke containing a white cross with the same number of blue rectangles? How will you identify the rectangle -- not in code, but rather what characteristics make the rectangle unique?
Comment: As of now, i have seen with same red stroke with same number of blue rectangles with white cross..But am not sure it might get change..Its with one of the customer application.I dont have access to this data actually.So i have to devise the generic strategy to identify it so that it could work for n number of applications and not specific to this one .
Answer: In html5 canvas, A "Shape" is defined and drawn using a Path.
You define a shape by:

Declaring that you a beginning a new path: context.beginPath
Using one or more of the path definition commands: moveTo, lineTo, arc, etc.
// define a triangle path
context.beginPath();
context.moveTo(x+50,y+50);
context.lineTo(x+100,y+100);
context.lineTo(x+0,y+100);
// see not below about .closePath()
context.closePath();

Note: context.closePath is NOT used to close a context.beginPath command --  it is NOT like a closing parenthesis! Instead, it is used to draw a line from the last coordinate to the starting coordinate -- to "enclose" the path. In our example, it draws an "enclosing" line from [x+0,y+100] to [x+50,y+50].
Just defining a path will not cause it to be drawn onto the canvas. To actually draw the shape onto the canvas you can:

Stroke the outline of the path, and / or
Fill the inside of the path.
context.stroke();
context.fill();

For example, here's how to define and draw a triangle. You can also use offset variables ([x,y] in the example) to reposition the triangle anywhere on the canvas.
// set the offset of the triangle
var x=30;
var y=40;

// define the path
context.beginPath();
context.moveTo(x+50,y+50);
context.lineTo(x+100,y+100);
context.lineTo(x+0,y+100);
context.closePath();

// stroke the path
context.stroke();

// if desired, you can also fill the inside of the path
context.fill();

To drag a shape, you must test whether the mouse is over that shape. You can "hit-test" the most recently defined shape using context.isPointInPath.
Be sure you read that carefully!
You can hit-test the most recently "defined" path. If you define and draw multiple paths then isPointInPath will only hit-test the last defined path.
if(context.isPointInPath(mouseX,mouseY)){
    console.log('Yes, the mouse is in the triangle.');
}

Also note that you don't have to re-stroke the path being tested so your drawings won't be altered by the hit-testing process. So you hit-test multiple paths by:

Define one of the paths
Hit test with isPointInPath(mouseX,mouseY)
Repeat step#1 for the next path (path==shape)

Nothing drawn to the canvas can be moved -- everything is as permanent as dried paint. So to "move" a shape on canvas you clear the entire canvas and redraw the shape in its moved position:
// clear the canvas
context.clearRect(canvas.width,canvas.height);

// move the canvas by changing it's offsets
x+=20;
y+=30;

// redefine and restroke the shape
context.beginPath();
context.moveTo(x+50,y+50);
context.lineTo(x+100,y+100);
context.lineTo(x+0,y+100);
context.closePath();
context.stroke();

To make redefining and re-stroking the shape more reusable you can put the code in a function:
function myTriangle(alsoStroke){
    context.beginPath();
    context.moveTo(x+50,y+50);
    context.lineTo(x+100,y+100);
    context.lineTo(x+0,y+100);
    context.closePath();
    if(alsoStroke){
        context.stroke();
    }
}

You can read more about dragging a shape in this previous post. Since you can't move a shape you can't "drag" a shape either. You must again clear the canvas and redraw it in its newly dragged position.
To drag a shape you need to listen to 4 mouse events.
In mousedown: Check if the mouse is over the shape, and, if yes, set a flag indicating a drag has begun. To check if the mouse is over the shape, you can use canvas context's isPointInPath method which tests if an [x,y] point is inside the most recently drawn path.
In mousemove: If the dragging flag is set (indicating a drag is in process), change the position of the selected text by the distance the user has dragged and redraw the shape in its new position
In mouseup or in mouseout: The drag is over so clear the dragging flag.
Here's example code and a Demo:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;
function reOffset(){
  var BB=canvas.getBoundingClientRect();
  offsetX=BB.left;
  offsetY=BB.top;
}
var offsetX,offsetY;
reOffset();
window.onscroll=function(e){ reOffset(); }
window.onresize=function(e){ reOffset(); }

var isDown=false;
var startX,startY;

var poly={
  x:0,
  y:0,
  points:[{x:50,y:50},{x:75,y:25},{x:100,y:50},{x:75,y:125},{x:50,y:50}],
}

ctx.fillStyle='skyblue';
ctx.strokeStyle='gray';
ctx.lineWidth=3;

draw();

// listen to mouse events
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});

function draw(){
  ctx.clearRect(0,0,cw,ch);
  define();
  ctx.fill();
  ctx.stroke()
}

function define(){
  ctx.beginPath();
  ctx.moveTo(poly.points[0].x+poly.x,poly.points[0].y+poly.y);
  for(var i=0;i<poly.points.length;i++){
    ctx.lineTo(poly.points[i].x+poly.x,poly.points[i].y+poly.y);
  }
  ctx.closePath();
}

function handleMouseDown(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  startX=parseInt(e.clientX-offsetX);
  startY=parseInt(e.clientY-offsetY);

  // Put your mousedown stuff here
  define();
  if(ctx.isPointInPath(startX,startY)){
    isDown=true;
  }
}

function handleMouseUp(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  // Put your mouseup stuff here
  isDown=false;
}

function handleMouseOut(e){
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  // Put your mouseOut stuff here
  isDown=false;
}

function handleMouseMove(e){
  if(!isDown){return;}
  // tell the browser we're handling this event
  e.preventDefault();
  e.stopPropagation();

  mouseX=parseInt(e.clientX-offsetX);
  mouseY=parseInt(e.clientY-offsetY);

  // Put your mousemove stuff here
  var dx=mouseX-startX;
  var dy=mouseY-startY;
  startX=mouseX;
  startY=mouseY;

  poly.x+=dx;
  poly.y+=dy;
  draw();

}
body{ background-color: ivory; }
#canvas{border:1px solid red; }

Drag the polygon

<canvas id="canvas" width=300 height=300></canvas>

[ Addition: Discovering Rectangles using context.getImageData ]
If you don't have the shape's position/size and you instead have an image of a shape then you must get the position/size by searching the pixels. Here's an example showing how to isolate rectangles by searching pixels:

var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var cw, ch;

// background definition
// OPTION: look at the top-left pixel and assume == background
//         then set these vars automatically
var isTransparent = false;
var bkColor = {
    r: 255,
    g: 255,
    b: 255
};
var bkFillColor = "rgb(" + bkColor.r + "," + bkColor.g + "," + bkColor.b + ")";

cw = canvas.width;
ch = canvas.height;
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
drawTestRect(30, 30, 50, 50, "1");
drawTestRect(100, 30, 50, 30, "2");
drawTestRect(170, 30, 30, 50, "3");

function drawTestRect(x, y, w, h, label) {
    ctx.fillStyle = "black";
    ctx.fillRect(x, y, w, h);
    ctx.fillStyle = "white";
    ctx.font = "24px verdana";
    ctx.fillText(label, x + 10, y + 25);
}

function clipBox(data) {
    var pos = findEdge(data);
    if (!pos.valid) {
        return;
    }
    var bb = findBoundary(pos, data);
    alert("Found target at "+bb.x+"/"+bb.y+", size: "+bb.width+"/"+bb.height);

    clipToImage(bb.x, bb.y, bb.width, bb.height);
    if (isTransparent) {
        // clear the clipped area
        // plus a few pixels to clear any anti-aliasing
        ctx.clearRect(bb.x - 2, bb.y - 2, bb.width + 4, bb.height + 4);
    } else {
        // fill the clipped area with the bkColor
        // plus a few pixels to clear any anti-aliasing
        ctx.fillStyle = bkFillColor;
        ctx.fillRect(bb.x - 2, bb.y - 2, bb.width + 4, bb.height + 4);
    }
}

function xyIsInImage(data, x, y) {
    // find the starting index of the r,g,b,a of pixel x,y
    var start = (y * cw + x) * 4;
    if (isTransparent) {
        return (data[start + 3] > 25);
    } else {
        var r = data[start + 0];
        var g = data[start + 1];
        var b = data[start + 2];
        var a = data[start + 3]; // pixel alpha (opacity)
        var deltaR = Math.abs(bkColor.r - r);
        var deltaG = Math.abs(bkColor.g - g);
        var deltaB = Math.abs(bkColor.b - b);
        return (!(deltaR < 5 && deltaG < 5 && deltaB < 5 && a > 25));
    }
}

function findEdge(data) {
    for (var y = 0; y < ch; y++) {
        for (var x = 0; x < cw; x++) {
            if (xyIsInImage(data, x, y)) {
                return ({
                    x: x,
                    y: y,
                    valid: true
                });
            }
        }
    }
    return ({
        x: -100,
        y: -100,
        valid: false
    });
}

function findBoundary(pos, data) {
    var x0 = x1 = pos.x;
    var y0 = y1 = pos.y;
    while (y1 <= ch && xyIsInImage(data, x1, y1)) {
        y1++;
    }
    var x2 = x1;
    var y2 = y1 - 1;
    while (x2 <= cw && xyIsInImage(data, x2, y2)) {
        x2++;
    }
    return ({
        x: x0,
        y: y0,
        width: x2 - x0,
        height: y2 - y0 + 1
    });
}

function drawLine(x1, y1, x2, y2) {
    ctx.beginPath();
    ctx.moveTo(x1, y1);
    ctx.lineTo(x2, y2);
    ctx.strokeStyle = "red";
    ctx.lineWidth = 0.50;
    ctx.stroke();
}

function clipToImage(x, y, w, h) {
    // don't save anti-alias slivers
    if (w < 3 || h < 3) {
        return;
    }
    // save clipped area to an img element
    var tempCanvas = document.createElement("canvas");
    var tempCtx = tempCanvas.getContext("2d");
    tempCanvas.width = w;
    tempCanvas.height = h;
    tempCtx.drawImage(canvas, x, y, w, h, 0, 0, w, h);
    var image = new Image();
    image.width = w;
    image.height = h;
    image.src = tempCanvas.toDataURL();
    $("#clips").append(image);
}

$("#unbox").click(function () {
    var imgData = ctx.getImageData(0, 0, cw, ch);
    var data = imgData.data;
    clipBox(data);
});
body {
    background-color: ivory;
}
canvas {
    border:1px solid red;
}
#clips {
    border:1px solid blue;
    padding:5px;
}
img {
    margin:3px;
}

<button id="unbox">Clip next sub-image</button>

<canvas id="canvas" width=300 height=150></canvas>

Below are images clipped from the canvas above.

[Addition: discovering the bounds of a reddishness stroked rectangle]
You can test for "reddishness" by checking if the red component value of a pixel is much larger than the green & blue component values.
function xyIsInImage(data, x, y) {
    // find the starting index of the r,g,b,a of pixel x,y
    var n = (y * cw + x) * 4;
    return(data[n+3]>240 &&        // this pixel is mostly opaque
        data[n]-data[n+1]>180 &&   // this pixel is more reddish than green
        data[n]-data[n+2]>180      // this pixel is more reddish then blue
    );

Then use this reddishness test to find the bounds of the reddish stroked rectangle:

Find the theoretical top-left pixel of the red rect. The discovered pixel is probably on the top of the rect. It might not be on the left of the rect because your image shows the rect's corner pixels are much less reddish. So declare the y value as the top of the rect.
Move towards the center of the rect by a few pixels.
Test each vertical pixel downward until you find the bottom reddish border of the stroked rect.
Test each horizontal pixel rightward until you find the right reddish border of the stroked rect.
Test each horizontal pixel leftward until you find the left reddish border of the stroked rect.

Now you have found the top-left and bottom-right bounds of the rect.

Here's example code and a demo using your image:

var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var cw=canvas.width;
var ch=canvas.height;

var img=new Image();
img.crossOrigin='anonymous';
img.onload=start;
img.src="https://dl.dropboxusercontent.com/u/139992952/multple/raw.png";
function start(){
  cw=canvas.width=img.width;
  ch=canvas.height=img.height;
  ctx.drawImage(img,0,0);
  var data=ctx.getImageData(0,0,cw,ch).data;
  var edge=findEdge(data);
  var top=edge.y;
  var x,y,left,bottom,right;
  var off=25;
  for(var y=edge.y+off;y<ch;y++){if(xyIsInImage(data,edge.x+off,y)){bottom=y; break;}}
  for(var x=edge.x+off;x<cw;x++){if(xyIsInImage(data,x,edge.y+off)){right=x;break;}}
  for(var x=edge.x+off;x>=0;x--){if(xyIsInImage(data,x,edge.y+off)){left=x;break;}}
  dot({x:left,y:top});
  dot({x:right,y:bottom});
}

//
function dot(pt){
  ctx.beginPath();
  ctx.arc(pt.x,pt.y,4,0,Math.PI*2);
  ctx.closePath();
  ctx.fillStyle='red';
  ctx.fill();
  ctx.strokeStyle='gold';
  ctx.lineWidth=2;
  ctx.stroke();
}

function xyIsInImage(data, x, y) {
  // find the starting index of the r,g,b,a of pixel x,y
  var n = (y * cw + x) * 4;
  return(data[n+3]>240 &&
         data[n]-data[n+1]>180 &&
         data[n]-data[n+2]>180
        );
}

function findEdge(data) {
  for (var y = 0; y < ch; y++) {
    for (var x = 0; x < cw; x++) {
      if(xyIsInImage(data, x, y)){ return ({x:x,y:y,valid:true}); }
    }
  }
  return ({x:-100,y:-100,valid:false});
}
body{ background-color: ivory; }
#canvas{border:1px solid red; margin:0 auto; }

Red-gold dots are on top-left & bottom-right of target rect.

<canvas id="canvas" width=300 height=300></canvas>
Comment: you can also add a mouseLeave/mouseEnter event on the canvas, so if you drag the object and your mousecursor moves out of the canvas nothing will break.
Comment: Thanks for the detailed explanation with code.In this code snippet , you know the sizes like height,width and shapes's position x,y to process futher while repainting canvas.But while testing other website,i will have access to the canvas as a whole and event(mouse position where the user has clicked).So in this case,i don know the sizes/position of already drawn rectangle inside canvas.So how to find that its a rectangle which is clicked and how to redraw it without knowing its size ?
Comment: If you don't have the shape's position/size and you instead have an image of a shape then you must get the position/size by searching the pixels. Here's an example showing how to isolate rectangles by searching pixels: http://jsfiddle.net/m1erickson/3m0dL368/
Comment: Thanks Mark.I am trying to use the same as reference.I am getting data from imagedata and passing the same to find whether imageisinXY function.but am keep on getting the values as zero in imagedata.Am trying to simulate the click/drag using the same with the demo in this link --http://simonsarris.com/blog/140-canvas-moving-selectable-shapes.
Comment: I've added to my answer showing how to find the bounds of a reddish stroked rectangle


How to fix type names conflicts in Dynamic Data

Question: We're working in a Dynamic Data project that will handle entities coming from two different namespaces: myModel.Abby and myModel.Ben.
whose classes are:

Abby
myModel.Abby.Car

myModel.Abby.Lollipop

Ben
myModel.Ben.Car

myModel.Ben.Apple

So myModel.Abby.Car and myModel.Ben.Car are homonym.
when I try to register both ObjectContext's, an exception is thrown telling us that there are type name conflicts between the mentioned classes (although the types belong to different namespaces).
How can we overcome type-name conflicts, caused by repeated type names among different namespaces?
Answer: I don't think there is a way around this.
DynamicData routes to the correct forms based on type names. Look in the URL, the type name is always up there someplace.  How can DD know which type you mean to interact with?
Comment: Hi Jfar!
I was thinking in something like Areas or Routing by last part of namespace. +1 : )
Answer: Here is a workaround from MSDN

The problem is a naming conflict
  between types in 2 different contexts.
  To get around this you can rename one
  of the classes specifying the
  TableNameAttribute on your entity.

Hope it helps others. : )


What happens in IIS/C# when a request is aborted

Question: So I'm thinking about a functionality where the user pastes a link and the server-side code crawls the provided link and responds with the contents of that link (such as page title, description, thumbnail, etc).
The user can meanwhile change the link, and in doing that, the ajax-request should be aborted client-side.
I'm wondering what exactly happens in the IIS server and specifically to my C# code.

Is the response thread terminated?
Does the Response object now return null, or Response.Write throw exceptions?
Is an exception thrown in the response thread just whereaver it is? (that one doesn't even make sense, but whatever)
Answer: If the server code checks the state of Response.IsClientConnected, it can stop the work and produce an empty response when the client aborts the request, otherwise it will just complete the request as usual.
The request handling will not be aborted automatically just because there is noone waiting for it any more. The server code has to actively check the state of the request.
Answer: Your web server doesn't know that the client cancelled the request.  The request will still be fulfilled and a response will be sent back.  The client-side script that you write will need to be able to handle what the current state of your page should be.
If you are certain that you don't care about the response, I would recommend aborting the request client-side:
xhr.abort()

Comment: So my web server's code is executed to completion? what would be the point in aborting a request, then?
Comment: So there are usually two steps (simplified) to an Ajax request.  1. Kick off the request.  2. Do something with the response (a success or failure callback).  If you abort the request, then your callback methods won't have to handle the response.
Answer: If you close the connection client side before the response is written an error stating as much is thrown. You could just choose not to handle the response when it comes back from the server.
Answer: Once a request is posted to server the IIS will start executing the server side code. Now the server can decide upon whether the code needs to be executed or not.
In the entire page cycle you can check Request.IsClientConnected  as mentioned by Guffa and terminate the execution.
But yes it totally depends on the scenario you have.
Hope it helps.


How can I get the enum class from a variable?

Question: Best explained in code.
I have something like this
public enum MyEnum implements MyEnumInterface {
   A,
   B,
   C
}

public enum MyOtherEnum implements MyEnumInterface {
   AA,
   BB,
   CC
}

and somewhere else
public void doSomething(MyEnumInterface anEnum, ... ) {
   ...
   // doSomething
   ...
}

I would like to find out what class anEnum comes from (e.g. MyEnum or MyOtherEnum).
How can I do that? (without doing an instanceof check for all possible implementations :) )
Comment: Why would you want to do that?
Comment: Use polymorphism. Whatever it is you are needing to do, put it on the interface.
Answer: You need to call .getDeclaringClass() on the enum value to get the class. But I think you are in search of the Visitor Pattern:
public class Example implements Visitor {

    public static void main(String[] args) {
        Example example = new Example();
        example.doSomething(MyEnum.A);
        example.doSomething(MyOtherEnum.BB);
    }

    public void doSomething(MyEnumInterface anEnum) {
        anEnum.visit(this);
    }

    @Override public void visit(MyEnum my) {
        System.out.println("MyEnum: " + my);
    }

    @Override public void visit(MyOtherEnum my) {
        System.out.println("MyOtherEnum: " + my);
    }
}

interface Visitor {

    public void visit(MyEnum my);

    public void visit(MyOtherEnum my);
}

interface MyEnumInterface {
    public void visit(Visitor visitor);
}

enum MyEnum implements MyEnumInterface {
    A,
    B,
    C;

    @Override public void visit(Visitor visitor) {
        visitor.visit(this);
    }
 }

 enum MyOtherEnum implements MyEnumInterface {
    AA,
    BB,
    CC;

    @Override public void visit(Visitor visitor) {
        visitor.visit(this);
    }
}

This is the answer to your comment:
public static void main(String[] args) {
    System.out.println(MyEnum.A.getDeclaringClass());
}

OUTPUT:
class MyEnum

Comment: I can't do anEnum.getDeclaringClass(); I can do anEnum.getClass().getDeclaringClass(), but that does not ( necessarily) return MyEnum etc. If your enum declaration is itself in another class, it will return that.
Comment: And now you may copy-paste the whole Example, which shows you how and that it works, as described.
Answer: You can do it by accessing its class object:
System.out.println(anEnum.getDeclaringClass().getName());

Note that getDeclaringClass() is critically different from getClass() when each value has a custom class body. More information
Comment: That works, thanks for confirming! I had tried this before and for some reason it didn't work out, but I think I just did something stupid that time.
Comment: You're welcome. I'm glad it helped. And thank you for big green checkmark and up-vote!  :)
Comment: -1 for using getClass and not getDeclaringClass, which will break in weird ways on enums that declare constant specific methods.
Answer: Enums are also classes so use
if(anEnum instanceof MyEnum) {...}

and
if(anEnum instanceof MyOtherEnum) {...}
Answer: You can use the instanceof operator to decide what type the object is


Accessing acrylic dome skylight from inside

Question: I have an old fashioned dome skylight that looks like this:

My roof is leaking. Roofer was not able to
pinpoint the exact cause of the leak on my roof but suggested that the skylight might be the issue. I am planning to apply some henry patch around the skylight to see if that is really the cause.
Here is the problem. I am fearful of ladders and I am not able to climb the roof. This may sound crazy, but would it be possible to open up the skylight from the inside? That way I can access the roof. Kind of like this guy:
Answer: "This guy" isn't exiting from a skylight, that's a roof access hatch specifically designed to give roof access. Also, there is often (but not always) a ladder to climb to get access to that kind of roof hatch.
Unless your skylights are hinged (a pic from the inside of your skylight, zoomed in close enough for us to see if there are any latches might help), then no, the only way to access the roof through the skylight would be to break the plastic/glass. Doing so would guarantee that's the source of the majority of your leak.
If you're that fearful of ladders/heights that you're not willing to climb onto the roof (is your roof flat, by the way, like the stock image you shared, or is it pitched), then I'd strongly suggest that you get someone else to climb up there to do the work. Being on a roof, for someone who is afraid of heights, is just a bad idea. You're likely to be so focused on not falling that you may fall anyway, and even if you don't, you may not do a good job of patching since you're not thinking about that, but about falling.
It doesn't have to be a contractor, maybe a family member or friend who is willing to help you out.
Comment: If it's _just_ climbing a ladder, then rent/buy a ladder that you feel comfortable with. Do be aware, though, that working on a pitched roof can be quite... sketchy. Even when I was young & foolish, climbing to the top of my 12:12 pitch roof on my 2-story house was a _very_ uncomfortable endeavor. Climbing back _down_ that roof was even worse!
Comment: Thanks. I am more afraid of ladders than the heights. I could climb the roof if I had a safety ladder with rails
Comment: Pitch is less than 4:12. It is a midcentury house similar to this: https://static.dezeen.com/uploads/2017/08/ocotea-street-in-situ-studio-architecture_dezeen_hero-1-1704x959.jpg . The pitch of my house is a little bit more.
Comment: Also, wouldn't you have to climb a ladder (even though it's inside the house) to get up to the ceiling to get out through the skylight?
Comment: It is true that I have to climb a ladder inside as well. But that ladder is a sturdy step ladder that doesn't shake. Also bathroom ceiling where the skylight is not very high.
Answer: Most skylights like shown are just held on by screws installed from the outside, say 3 or 4 per side. Otherwise, they just sit on top of the curb, perhaps with a gasket in between. So you will just have to find a daring person to go up there and undo those screws and lift off the dome.
Comment: Not sure I follow you. How does this help the OP? Also, wouldn't all those screws likely be covered in some sort of waterproofing goop (roofing tar, silicone sealant, something)? That would all have to be scraped off to get access to the screws then have to be reapplied, thus _increasing_ the likelihood of future leaks.


What purpose does Ancient Watcher serve?

Question: Ancient Watcher is a 2 mana 4/5 minion that can't attack.
I recently faced one in an Arena game and just let him sitting there until he randomly died to accumulated AoE damage. He seems to be a totally useless card.
Yet I heard of a deck (Watcher Druid) that actually uses him competitively and have seen him being talked about a lot. That got me wondering how people make use of him.
I could only think of 2 things that might make sense, namely Silencing him (but why would you "waste" a precious and rare silence on him?) and giving him Taunt.
Is there any other use to Ancient Watcher or is he really only useful as a cheap and valuable target for a Taunt buff?
Comment: Sunfury protector on Turn 3 after turn 2 watcher is good. Defender of Argus makes him a 5/6 taunt on turn 3 with coin or Turn 4 (best with turn 3 harvest golem). Also, either neutral taunt turns him into a 4/5 minion for 2. Priest has a few extra silences and Druids have a few extra taunts to boot.
Comment: cheap Shadowflame combo
Comment: Or Void Terror fuel... nom.
Answer: He's mostly a situational card.
As you mentioned you can silence him, Most notably for me I typically use it in my priest deck (as priests have mass dispel and a 0 cost silence) to troll and get a monster on the field. Since it does not attack and doesn't have taunt 90% of the time players let me keep it on the field. Then the next turn I Silence, Divine Spirit, Inner Fire, and boom they've lost 10HP or more if I use multiple Divines or Power word: Shield.
Additionally, I like having Defender of Argus in my decks so I don't have to run as many taunt cards and he's not a bad addition, as sometimes when your enemy has board control you can place it down without the enemy killing it as they don't see it as a threat. If they do kill it then you've re-directed 5 Damage that could have went towards you.
I use it as an underdog-card in most situations. It has it's uses but by no means is an amazing card. I mostly keep it around for the laughs, as I play to troll not play to win :D
Uses:

Rush: If you get him early with a (0) cost silence in a priest deck it can catch your enemy off-guard
Board-Control: If you're losing it can be difficult to gain board control back. This card is commonly left alone as it has no immediate threat. Even if it is killed before you can silence or give it taunt it is a cheap card so it is at little loss to you (other than maybe card advantage)
Buff: Typical usage of Silence or Taunt.
Full-Field: This one is a long-shot, but you can use it as simply another card on the field. Some cards such as Frostwolf Warlord could benefit from having another minion on the field. Hell, you could throw him in before a Brawl just to have a slightly higher chance at killing all of your enemy's minions.
Silence Counter: If you give it taunt it can act as a deterent for your enemy to silence away your taunt since he'll then be able to attack (As mentioned by "z -" below).
Answer: Its mostly for cheap early defense in control/stall decks.  Dropping an ancient watcher or two then putting down either a Sunfury Protector or Defender of Argus (or in the case of the druid, Mark of the Wild) gives you a really cheap and effective defense.  Because he also has high attack, he will be able to kill many things that tries to take him down.
Because the ancient watcher is so cheap and tough, it will often force the enemy to expend way more mana to remove it if you do manage to put taunt on him.
It also works great againts priests as insurance against mass dispel.
Comment: also, as an added bonus, if they dispel the taunt now he can freely attack.
Comment: Great answers, thank you! I'm accepting Shelby's just because it also lists a few more obscure use cases.


'Handle' on rear guard of fan

Question: I just bought an oscillating standing electric fan, and I have noticed a little wire 'handle' thing on the rear wire mesh guard. Can anyone tell me what it is for? I wondered whether it was to aid changing the direction it was pointing in, when not in oscillating mode, but grasping the motor housing is very easy.
Answer: Generally speaking, it's a handle for lifting. It could be used as a bracket to hang the fan onto a hook - but better make sure the oscillating switch is off.
Comment: @Tetsujin - not unknown to have it hanging on a bracket sticking out from the wall, when there's no room left on the desk it's intended for! Maybe better than the floor. Last night's gig had mine on top of the amp on top of the speaker. Could maybe have put it *in front* to give a Leslie sound?
Comment: Thanks for the answer. I did wonder about that, but it looks kind of puny for the weight of the thing. The picture in my post is of a desk fan, and the feature in question is at the top (at twelve o'clock), but on mine, which is on a floor stand, it is at nine o'clock, and there are lugs when fitting the guard to the motor so I haven't put in on a quarter circle displaced. I guess the maker will use the same fan guards for both types.
Comment: You can leave the oscillating function on, just be prepared for the "thump thump" of the rest of the fan banging against the wall. :)
Comment: It should be movable, just release the clips and turn round. Obviously the weight of any fan will dictate whether it's a good idea to hang or not.
Comment: It's got a little hole in the rim, with nut and bolt, which, if fitted as per the instructions, mean you can't rotate the guard.
Comment: To clarify, the back half of the guard is in a fixed position, determined by two protruding lugs on the motor housing, which engage in holes in the rear guard at 12  and six o'clock only. Then the front half is attached, and the instructions specify that it is fixed in position using a single nut & bolt through holes in the rim.
Comment: Plus the clips of course.
Comment: Of course, the ruddy gert motor sticking out the back of the fan housing, plus having to keep it wired to the stand, would probably put paid to any idea of hanging it. ;)

'Handle' on rear guard of fan


Using forcats with data that has possible levels not present in data

Question: My data has levels that are theoretically possible but not present in the data. I can easily represent this in base R:
factor(c("test","test1","test2"), levels = c("test","test1","test2","test3"))

If I table it, I see that test3 is 0. This is great and allows for the possibility that I can write functions assuming these levels include all possible outcomes in case data is eventually added that includes this level.
I can not replicate this in forcats. First off, the as_factor function does not accept any additional arguments:
forcats::as_factor(c("test","test1","test2"), levels = c("test","test1","test2","test3"))

The above produces an error.
The following works with a warning (which I would prefer to accomplish my goal without warnings, if possible):
forcats::as_factor(c("test","test1","test2")) %>% forcats::fct_recode(`test` = "test", `tests` = "test1", `tests` = "test2", `tests` = "test3")

Warning message:
Unknown levels in `f`: test3

Is there any way in forcats to play with levels that theoretically exist but are not necessarily in the data at that moment?
Answer: If we want to replicate the same behavior with factor, may be use fct_expand
c("test","test1","test2") %>%
       forcats::fct_expand(c("test","test1","test2","test3"))
#[1] test  test1 test2
#Levels: test test1 test2 test3

Regarding the use of ... (other arguments in as_factor), it is not actually used
library(forcats)
methods(as_factor)
#[1] as_factor.character* as_factor.factor*    as_factor.logical*   as_factor.numeric*

Now, we check the code of as_factor.character
getAnywhere(as_factor.character)
function (x, ...)
{
    structure(fct_inorder(x), label = attr(x, "label", exact = TRUE))
}

The fct_inorder takes only the 'x' and not any other arguments passed in with ...
Here, we can use fct_expand directly to expand the levels of the factor or character (converts to factor)
Comment: Works great! see my solution below where I have implemented your suggestion. Let me konw if you have any additional improvements . Thanks!
Answer: Per the advice of @Akrun, I have accomplished what I was seeking to do. See an example below:
test <- c("fruit","fruit","apple","drink","meat")
levels <- c(
  `Fruit` = "fruit",
  `Fruit` = "apple",
  `Drink` = "drink",
  `Vegetable` = "vegetable",
  `Meat` = "meat"
)

factor(test) %>% table()
factor(test) %>% forcats::fct_expand(levels) %>% table()
factor(test) %>% forcats::fct_expand(levels) %>% forcats::fct_recode(!!!levels) %>% table()


Should I have multiple cable runs for a room, or just one?

Question: My girlfriend is finishing up her basement and has set up a good layout for electrical outlets throughout the rooms (family room, bedroom, and office), but she's only accounted for a single coaxial cable run to each room for her ideal furniture arrangement.  I talked her into at least running a phone line along with the cable to match the rest of her house (and at least an ethernet connection as well for when I move in to accommodate my geek projects), but I'm trying to talk her into more than one run per room.  I've rented for several years and most apartments have at least 2 cable/telephone outlets on opposite walls/corners of the room to widen the options for furniture arrangements.  Since she's looking at putting her place on the market in a few years I'm trying to convince her it will be a helpful selling point, but my Google-fu is failing me at finding supporting or negating evidence.  Is there any evidence one way or the other, or are my geeky more-is-better ideas influencing me?
Comment: While you're at it, just run Cat5e/Cat6 for the telephone/network. A standard phone connector (RJ11 or RJ14) can plug into the network (RJ45) connector and is pin-compatible. The nice thing is if you ever need network instead of phones, it's already there. Think VoIP phones..
Comment: @Gregmac: That's what I was planning.  Running 2 Cat5e cables to each drop and installing a small punch down panel for one end for all the cables. I did that type of wiring at a former company so I'm pretty familiar with it.
Comment: It's probably one of those things you won't notice when you buy, but wish you had when you come to rearrange your furniture 6 months after you've moved in.
Comment: Exactly what I have in my house, which works great. http://gregmaclellan.com/blog/wp-content/uploads//imgp4280.jpg. Almost everything is VoIP, but you can see one phone line plugged in for an analog cordless phone.
Answer: I doubt most buyers will even notice or care if it was pointed out to them.  Today, everyone uses a cordless telephone, wifi for networking, and any cables are just run around the baseboard.  And I say this as a geek that ran conduit through the walls when I redid my basement.  Speaking of which, if you ever remodel (or build) something you plan to stay in, run conduit through the walls.
The key point you need to keep in mind is that it should be possible to get to a majority of the walls along the baseboard from your wall jacks without passing a door or closet.  If a large wall could be used for a TV but requires running the wire over the door, then I'd put a second jack on that side.
My guess for apartment owners is that two jacks results in less wires over carpets or nails holding wires everywhere, so they do this more to reduce damage than to make your life easier.
Comment: Not everybody uses wifi.
Comment: "Everyone" is an exaggeration, but no one is going to drop the price because they expected a network connection to be on the same wall as their home computer.  They'll find 100 other reasons first.
Answer: If you're going through the trouble of running cables, go all out. The difference of 3 cat5 versus 1 cat5 is minimal, but can make a huge difference in usefulness in the future. If later you find you need them in a room, it is much more work to add them then. I would personally allow for the possibility of at least 3 internet enabled devices in every room. It doesn't mean that there will be that many in every room, but it allows that any given room should be able to accommodate most needs that way. You might look at pulling 4-5 in the main room of the house. You can get faceplates that can mix and match connections so you can have up to 4 RJ45, 1 RJ14 and 1 coaxial all in the same spot on a wall.
Comment: Considering you can't buy cat5 anymore, cat5e was assumed. In most home environments people will run cables in such a way that gigabit speeds will never be reached. Even if they are, they will design their network in such a way that it won't matter. Cat5e will almost never produce desired speed results in a gigabit environment regardless of what the standards say. I'm a firm believer in only using a switch when no other cabling solution exists. You always want a full drop for every connection, more switches mean more points of failure and more money in unnecessary equipment.
Comment: Cat5e/Cat6 is more appropriate with Gigabit networking becoming standard.  And two lines are appropriate with one used for phone and second for networking (use different colors of cable if possible).  Once the connection is in the room, you can use a switch to split the network cable to multiple devices, no need to run multiple network cables to a room.
Comment: Yeah, the main cost is the labor, not the wires.  Run extras.
Answer: I finished my basement a few years ago and ran two coax, two ethernet, speaker and phone lines to each room.
How many of them have I used since then? 0.
Ethernet/phone = nice to have but, really, everything is wireless now.
Coax = likely useful for a few more years, but that, too, will eventually be wireless (we're close already as most of our watching is done via Amazon Streaming or Hulu now).
Speaker = well...this could be useful. I had dreams of a massive surround sound system. But then I got my new TV and realized the sound quality of the TV was great. So didn't need the surround sound.
So...I'd suggest that rather than running all that cable, she run smurf tube with a fish line to blank outlets in each room. It's cheap, and makes it easy for any future cable pulling without having to invest in it all now.
Comment: You just need the smurf tube. Smurfs can then travel via the tubes. You can also run wires through them too.
Comment: Is it necessary to pipe smurfs to each room? Probably convenient but how many of them do you need?
Comment: If you're going to the effort of running smurf tube, just run the cables and be done with it.
Comment: @aphoria...the purpose of the smurf tube is to avoid the reality that home A/V/Networking technology changes fairly often. The Smurf tube helps future proof things a bit.
Comment: what the hell is a smurf tube?
Comment: 0a0d: it's a flexible plastic tube used to allow easy pulling of cables through. It happens to be blue, hence the term 'smurf tube'. It looks like this:  http://www.google.com/search?gcx=c&q=smurf+tube&um=1&ie=UTF-8&hl=en&tbm=isch&source=og&sa=N&tab=wi&biw=1100&bih=609
Answer: I wouldn't worry about the resale value of running the extra lines. Just do it for your own convenience. Yes, you probably will not ever use many of the extra runs, but you'll be happy for the ones you do use.
Comment: +1 Except every little bit counts. You can tell the difference between someone who really cared for a home by the tiniest details applied. If extra lines are installed, hopefully they make sense. My in-laws have radio wires all over their house that they bought in 2004 and have no idea how to hook them up.
Answer: I recently did my house, and only put a single port in each room thinking, "I can just use an ethernet switch." I have found from experience though that when you have a TV, Wii, XBox, Cable Box, Media PC, Audio Receiver, and a Subwoofer, adding an extra A/C plug, extra device and all of the RJ-45 cable running to that device just adds to the clutter.
You might just have to say that networked devices are going to become more and more prevalent in the future, and just as people want plenty of A/C outlets, they will also want plenty of RJ-45 jacks.
Comment: I work at a networking company, and hard wiring gives faster speeds, does not receive interference, and it was cheap for me to do. It's generally better for XBox and other devices that stream data.
Comment: why not wifi? Seems less instrusive and you can always buy a repeater.
Comment: Hmm.. seems to work fine playing Call of Duty on my Wii.