stuck while uploading an image file in sql server 2008 from vb.net code

Question: ok so this is the code i used from this site. everything works fine, but i need a little different code to upload image, and i dont know what to do -
here's the code -
Private Sub btnAttach_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnAttach.Click
    Dim iLength As Integer = CType(File1.PostedFile.InputStream.Length, Integer)
    If iLength = 0 Then Exit Sub 'not a valid file
    Dim sContentType As String = File1.PostedFile.ContentType
    Dim sFileName As String, i As Integer
    Dim bytContent As Byte()
    ReDim bytContent(iLength) 'byte array, set to file size

    'strip the path off the filename
    i = InStrRev(File1.PostedFile.FileName.Trim, "\")
    If i = 0 Then
        sFileName = File1.PostedFile.FileName.Trim
    Else
        sFileName = Right(File1.PostedFile.FileName.Trim, Len(File1.PostedFile.FileName.Trim) - i)
    End If

    Try
        File1.PostedFile.InputStream.Read(bytContent, 0, iLength)
        With cmdInsertAttachment
            .Parameters("@FileName").Value = sFileName
            .Parameters("@FileSize").Value = iLength
            .Parameters("@FileData").Value = bytContent
            .Parameters("@ContentType").Value = sContentType
            .ExecuteNonQuery()
        End With
    Catch ex As Exception
        'Handle your database error here
        dbConn.Close()
    End Try
    Response.Redirect(Request.Url.ToString) 'Refresh page

End Sub

everything works fine except when it comes to this part -
    With cmdInsertAttachment
        .Parameters("@FileName").Value = sFileName
        .Parameters("@FileSize").Value = iLength
        .Parameters("@FileData").Value = bytContent
        .Parameters("@ContentType").Value = sContentType
        .ExecuteNonQuery()
    End With

i dont have these parameters. i only have 1 field in sql server table that says Img and has image datatype. how do i use this code to get my image in db using this insert statement?
insert into table1 (img) values (???)
Comment: If you post the actual table structure, it will be much easier for us to answer
Answer: Consider changing your table to be have the FileName, FileSize, FileData and ContentType fields.
If you really don't want the name, size and content type stored in the database, then you can change
With cmdInsertAttachment
    .Parameters("@FileName").Value = sFileName
    .Parameters("@FileSize").Value = iLength
    .Parameters("@FileData").Value = bytContent
    .Parameters("@ContentType").Value = sContentType
    .ExecuteNonQuery()
End With

to
With cmdInsertAttachment
    .Parameters("@Img").Value = bytContent
    .ExecuteNonQuery()
End With

And after the appropriate edit to the cmdInsertAttachment stored procedure that should get the data in the table. WHat you can do with it afterwards is anyone's guess though.


Reset jquery tab

Question: I'm using jquery ui tab version 1.9.1 and I do have content with scroller in second tab. What I'm trying to do is whenever I come back on second tab, tab should be reset(Should display content from top).
I've tried to find solution but what I got is to reset form fields on tabs and indexes not for this particular issue.
Answer: Given you haven't provided any of your code it is difficult to guess, but if you are loading your tab content via. ajax, at the bottom of your HTML for your second tab, you could add a script like:
$(document).ready(function() {

    $('#secondTabID').animate({scrollTop:$('#secondTabID').offset().top}, 'slow');
});

If your HTML is static, then you can probably do something with the activate function.
Something like:
$("#tabs").tabs({

    activate: function(event, ui) {

       ui.newTab.animate({scrollTop:ui.newTab.offset().top}, 'slow');
    }
});

Comment: Hi Daren, Thanks for your response. At which event I should set this function? I mean is there any default property / event to define tab change?
Comment: Hi Dhaval - I have updated my post so that you can see I take care of both cases - remote tab load via. ajax and static HTML tab load.
Comment: Hi Daren, Thanks for updating your code to give me more clear idea. In your code tab will scroll up to the top but is there any way to reset that tab completely as I do have video on second tab so I need to reset that video too. I'm using videojs plugin to play the video, you can find that plugin here http://videojs.com/
Comment: If you loaded the tab remotely it would automatically "reset".  Here's an example on the jqueryui site:
http://jqueryui.com/tabs/#ajax

Reset jquery tab


How to get before first &nbsp

Question: I get a text from a div but I  need to get before first &nbsp.How can I do.
Image.html

63951_1417323055238082_7899260806224854935_n.jpg
59.4 KB

I need to "63951_1417323055238082_7899260806224854935_n.jpg"
getImage.js
aracResimYolu=template.$(".progress-label").text();

Answer: try with this:
var text = $(".progress-label").text();
aracResimYolu= text.substring(0, text.length-6);

or as @tibzon stated in his answer, you can do this too:
aracResimYolu= $(".progress-label").html().split("&nbsp")[0];

Comment: But Text is change every upload image not static
Comment: It doesn't matter, it will work as long as you have a structure like `yourUrl `
Answer: This will extract out the image name,
var img_name = $(".progress-label").html().split("&nbsp")[0];
alert(img_name);

JsFiddle - http://jsfiddle.net/ydzzhb0r/
Answer: An alternative to the split(...)[0] approach is to use indexOf and substring:
const html = $(".progress-label").html();
const index = html.indexOf("&nbsp");
const string = index === -1 ? html : html.substring(0, index);

This avoids unnecessarily creating arrays (not that it matters 99.999999% of the time).

How to get before first &nbsp


Is a decimal comma used in data entry?

Question: Historically, I know that in most parts of the world decimals have been represented with a comma.

3.14 (US and Canada mostly)
3,14 (most other places)

In software development, normally a period (3.14) is used. This is true throughout the world. Programming languages provide facilities to display numbers in the UI with the right format, per the user's locale settings.
However, I don't recall ever seeing code that recognizes a comma decimal in input. If a user types 3,14 it's typically either rejected or interpreted as "three hundred and fourteen".
Should software attempt to interpret input such as 3,14 correctly? Or is it not necessary -- perhaps because users are accustomed to adopting "computer" conventions?
Comment: The culture setting in most programming environment handles both display and parse.    It this a programming question or a UX question?
Answer: Good question, but the Wolfram reference is terribly incorrect.
The use of the period . in user interfaces is almost universal nowadays, and I would advise against trying to overload the comma.
The spread of the decimal point is a pretty interesting case on the effects of globalization and technology.  In this case, the broad standardization of global financial statements on the decimal point (because commas are used in financial statements to denote thousands, millions, etc) combined with the promulgation of tech user interfaces using decimal points (e.g. mobile phone calculator) has pretty much eradicated the use of commas as decimal separators in user interfaces.
I've been doing business in Europe, Asia and Australia for decades and I have never seen the comma used as a decimal separator in any user interface.
Trying to restore support for the comma as a decimal separator not only bucks a sensible UI trend, but also (and this is IMO) reverses an informal standardization process that has been beneficial for the global community.
On a related note, for financial and scientific applications it's good UI practice to recognize commas and exponents (e.g. 299,792,456 or 3e8) as valid numerical inputs (e.g. when pasted into a calculator or spreadsheet).
Comment: I come from europe (rather than just doing business with it), so I don't know how you got this idea that no user interface uses a comma as a decimal separator. Every properly localized application does that. Also [wikipedia](http://en.wikipedia.org/wiki/Decimal_mark#Influence_of_calculators_and_computers) pretty much confirms what wolfram says. If you don't attempt to localize your application by all means stick with the dot though. Don't make it ambiguous by interpreting comma and dot as the same thing.
Comment: @PatrickMcElhaney I don't think it was your understanding.  It seems you did the right research but what should be an authoritative source (Wolfram) was way outdated!  I do remember that their old *Mathematica* software in the 80's allowed commas to be used via user settings.  Maybe their documentation dates back to that decade!
Comment: Either way, this is a great answer. I owe you a pint.
Comment: Thanks a ton, this is exactly what I wanted to know. My understanding was off by a mile. Glad to hear the world is inching toward standardization.
Comment: Here is UI that uses comma as a decimal separator out of the box: http://imgur.com/5VthbLW It's a localized Excel, for Finnish. Numbers with dots are treated as text. Strangely though, calculator understands both dot and comma as decimal separator.
Comment: @locationunknown Nice example. I believe there are quite a few products (include Excel and Windows) which still have optional support for comma decimals. However, it's notable that the default regional settings for Windows in almost all countries use the period ```.``` rather than the comma. Users today have to go into settings and deliberately change the delimiter to the comma to get support.
Comment: @tohster I recall that during the installation Windows asks about the way numbers, time and such are to be presented and makes a suggestion based on something. For me the suggestion was comma as decimal separator. So I haven't changed any settings after installation.
Comment: @locationunknown interesting...what version of Windows is that?  I don't recall seeing the option on Windows Vista, Windows 7 or Windows 8 and as a designer I tend to pay attention to the wizard design.  I believe the install wizard asks for your location and language/keyboard, then sets everything else automatically without confirming.  Where are you located?
Comment: @tohster The last Windows that I have installed is 7. And yes installation wizard asks for location and language but I do remember seeing the confirmation for the time/number formats. Though I may be wrong because its been a while since I last installed Windows. But I checked that system default formating is the one that uses comma as a decimal separator. So even if the installation wizard doesn't confirm the format, it sets them, probably based on location. I think it's bad design not to confirm the selection that will set system defaults. And I'm in Finland.
Comment: @locationunknown interesting. I think this is the screen I remembered:  http://www.buildeasypc.com/pics/windows_7/windows7_2.jpg
Comment: @DavidOngaro Thanks. I've un-accepted the answer. Why don't you post an answer yourself? Can you provide some examples of applications which can be localized so that `3,14` is parsed correctly?
Comment: @locationunknown I'm open to being corrected but I grew up in Europe and have worked in global finance there for over a decade in London, Geneva, Amsterdam and Milan and I haven't seen the use of commas as a decimal in financial statements or spreadsheets for any of the >100 companies I've worked with or looked at as investments. Perhaps I've had the wrong sample set though, because I've worked primarily with multinationals.
Comment: Maybe London is not a good example, because I think they are using a dot as a decimal separator in UK as well? Anyway maybe it's just common in your industry. What I was talking about was about common everyday applications, like office suites, calculators or websites . I'm not sure if I would be comfortable in writing in answer though, since I'm no UX expert.
Comment: @DavidOngaro you may very well be right because my experience is heavily biased towards financial statements and technical documents where I have only seen the decimal point used.  I may have just missed the comma for other applications.
Comment: @DavidOngaro Just share your experience. There are very few true "experts" on UX. I won't accept either answer until a consensus is reached.
Comment: @PatrickMcElhaney I agree with waiting for consensus, but would respectfully disagree that there are few experts in UX as there are quite a lot of users here who are UX professionals and are pretty good at it (at least, good enough that we have many top web and agency organizations represented on bios!)
Comment: @DavidOngaro Yes, indeed. Poor choice of words.
Comment: I have seen the comma used on a German system.
Answer: Ok, I try to provide an answer in hope that it will encourage an expert to jump in, in case I tell nonsense.
First of all I think the answer to your general question

Should software attempt to interpret input such as 3,14 correctly?

can only be unambiguously answered with a firm "it depends".
I think the keyword in my above comment "every properly localized application does that" is "properly localized". If you have an application which attempts to interpret the decimal according to the locale settings but doesn't bother to get the language or date formats right it would be very confusing. On the other hand if you adhere the language, currency, date settings etc. one would just expect that also the corresponding decimal separator is adhered.
To localize an application for several locales is not a small task though. In general it's split into two projects:

The internationalization (i18n) of the application. That means all locale specific parts (like string content, text direction, collation, date formats, number and currency formats...) are abstracted and made configurable
The localization of the application, which has to be done for each supported locale

You shouldn't attempt to localize your application without properly internationalize it first. You may make yourself a maintenance hell.
When the application is changed both these aspects also have to be continuously maintained. Considering these implications the decision to provide a proper localization is oftentimes an all or nothing consideration. You have to decide if its worth it, which in turn might depend on many factors, like the type of application, the customer base your resources etc. But if you decide to do it, you should do it properly and it's hardly just a matter of getting the decimal separator right.
That all being said there a still exceptions though. E.g. for a calculator application a complete localization probably doesn't matter too much, but its just convenient to be able to use either a comma or a dot as a decimal separator. E.g. in the Apple "Calculator" I can use a dot instead of a comma, but its always displayed as a comma. If I use spotlight to do calculations the comma and dot are displayed literally but interpreted interchangeability (it only gets confused if I mix thousand separators in, eg 1,234.56 gets interpreted as 1.23456 but 1.234,56 gets correctly interpreted as 1234.56).
But exceptions not only apply for simple applications. If you look at a german keyboard layout you can see that there is a comma at the numeric keypad where there is a dot at the english layout. So if you have an application which requires lots of numeric inputs, users expect to be able to use the comma as a decimal separator. It's simply an ergonomic matter.
In my opinion the localization effort is oftentimes done too far, which can lead to surprising results. E.g. if I ex- or import CSV files from Excel or LibreOffice Calc it depends on my locale setting in how dots and commas in fields are interpreted. Sure, it should be adhered in display and input, but should that affect the file format!? I even had to change my locale system setting in order to be able to import certain CSV files. Of course one could argue that CSV is not a real standard and just and ad-hoc format, but its still confusing and counterintuitive.
Also POSIX defines locale settings, which are stored in environment variables. But the results with certain shell builtins can be surprising:
$ export LC_NUMERIC="en_US.UTF-8"
$ printf "%'f\n" 1234.5678
1,234.567800
$ export LC_NUMERIC="de_DE.UTF-8"
$ printf "%'f\n" 1234.5678
bash: printf: 1234.5678: invalid number
0,000000
$ printf "%'f\n" 1234,5678
1234,567800

What does that mean? Ok, I have to provide the right input format when I change the locale. But what's the use of a format function if I have to provide the right format myself? And isn't "shell" also a scripting language? That means changing the locale changes the semantic of the language itself!? I guess it's not always so clear cut, what is interactive and non interactive input...
Even though your question is specifically addressing input, I want to provide least one practical tip (and that should apply whether or not you decide for the localisation of your program): if you have to display numbers between 1 and 999 don't use 3 decimal digits if you have the choice. A number like 1,234 might be interpreted as 1234 or 1.234 because by looking into the number itself its not clear if the ',' is a thousand separator or a decimal separator. Whereas for a number like 1,23 it' unambiguous. But that's just my own "private" rule. I'm actually curious if there is an "official" usability guideline for that. Maybe one of the experts could comment on that?
Of course there is no such tip if you have integers between 1000 and 999999 and have to use a thousand separator. But normally its clear from the context if the number has to be an integer, so its less of a problem.
Comment: There _is_ an unambiguous digit grouping symbol: thin space. Wikipedia [says](https://en.wikipedia.org/wiki/Decimal_separator#Digit_grouping) that it is officially endorsed by SI/ISO 31-0 standard, as well as BIPM and IUPAC, and a couple of other bodies.
Comment: Yes, resorting to a thin space was what we even did in an application. But it felt like cheating since it doesn't solve the localization issue as a whole. Also, the harder problem is how to interpret input. Over output one has usually complete control.

Is a decimal comma used in data entry?


Why did matrix multiplication using python's numpy become so slow after upgrading ubuntu from 12.04 to 14.04?

Question: I used to have Ubuntu 12.04 and recently did a fresh installation of Ubuntu 14.04.  The stuff I'm working on involves multiplications of big matrices (~2000 X 2000), for which I'm using numpy.  The problem I'm having is that now the calculations are taking 10-15 times longer.
Going from Ubuntu 12.04 to 14.04 implied going from Python 2.7.3 to 2.7.6 and from numpy 1.6.1 to 1.8.1.  However, I think that the issue might have to do with the linear algebra libraries that numpy is linked to.  Instead of libblas.so.3gf and liblapack.so.3gf, I can only find libblas.so.3 and liblapack.so.3.
I also installed libopenblas and libatlas:
$ sudo apt-get install libopenblas-base libatlas3-base

and tried them, but the slowdown doesn't change.  So, my questions are:

What's the difference between the packages with and without the "gf"?
Is this possibly causing the slowdown in the matrix multiplications?
If so, how can I go back to libblas.so.3gf and liblapack.so.3gf?  They seem to be discontinued in Ubuntu 14.04.

Thanks much!
Answer: wim is correct, in that the problem is probably caused by numpy linking to a slower BLAS library (e.g. the reference CBLAS library rather than ATLAS).
You can check which BLAS library is being linked at runtime by calling the ldd utility on one of numpy's compiled shared libraries.
For example, if you installed numpy in the standard location using apt-get:
~$ ldd /usr/lib/python2.7/dist-packages/numpy/core/_dotblas.so
        ...
        libblas.so.3 => /usr/lib/libblas.so.3 (0x00007f01f0188000)
        ...

This output tells me that numpy is linked against /usr/lib/libblas.so.3. This is usually a symlink to the reference CBLAS library, which is pretty slow.
You could, as wim suggests, remove the version of numpy installed via apt-get and build it yourself, either using pip or by downloading the source directly. However, I would strongly discourage you from using sudo pip install ... to install Python modules system-wide. This is a bad habit to get into, since you run the risk of breaking dependencies in your system-wide Python environment.
It is much safer to either install into your ~/.local/ directory using pip install --user ... or even better, to install into a completely self-contained virtualenv.
Another option would be to use update-alternatives to force your system-wide numpy to link against a different BLAS library. I've written a previous answer here that shows how to do this.
Answer: Are you installing numpy through package manager?
If so, I recommend to go through pip instead so you can clearly see in the build process what is being successfully linked during setup.

Remove the apt version (sudo apt-get purge python-numpy)
Install build-deps headers and static libraries (sudo apt-get install libblas-dev liblapack-dev gfortran), maybe there are some others but these are the ones I remember.
pip install numpy


gpg: --sign, --clear-sign, --detach-sign

Question: I am making this question because I didn't find a clear explanation about the difference between these 3 gpg options:
gpg --sign file        # produces file.gpg
gpg --clear-sign file  # produces file.asc
gpg --detach-sign file # produces file.sig

file.gpg and file.sig seem to be binary files, while file.asc seems to be a text file. What is the relationship between these 3 files?
Answer: Here you go: https://www.gnupg.org/gph/en/manual/x135.html
Basically when signing with --detach-sign the resulting .sig won't contain the signed file only the signature.
--sign compresses, signs and outputs the signed text in a binary format.
--clearsign wraps the text in an ASCII-armored signature
Comment: `--sign` does not encrypt files!
Comment: Is `--clearsign` any different from `--armor --sign`?
Comment: Yes. With `--sign --armor` the cleartext isn't show, and the ascii will be different because the armor includes both the message and the signature. `--clearsign` is more similar to `--detach-sign --armor`, which is exactly the ascii that shows up after the cleartext.


Concrete floor/slab sealing

Question: I would like to have someone seal my concrete floor without grinding or etching. Can this be done?
Comment: Depends on what you mean by sealing.  Most people would just clean the floor good, dump a paint can on it and rolled it out and call it a day.  Grinding/etching are done when other work needs doing.
Answer: Depends how filthy it is.
If it's more-or-less clean and not contaminated (oil, etc.) you can clean it well and expect success painting. Whether or not the sealant has pigment it's essentially painting, and floor paint is my "sealer" of choice, though your choice may vary.
If it has stuff that won't come off with soap and water and scrubbing, you may need to etch it to get a good bond for painting/sealing. Otherwise the paint/sealer may peel off, wasting the money spent on doing that job.
The only reason to grind is to change the shape or texture of the surface. So if you don't want to do those things, grinding should not be needed.
If it's new, virtually all products suggest waiting until it's a month old before coating. Check the label on the product you choose, and if need be, wait.

Concrete floor/slab sealing


can i install Ubuntu14.04 in my ideapad?

Question: i'm using ubuntu 12.04  64 bit version in my Lenovo S100 ideapad.
my ideapad is having 2GB RAM and Atom processor.Is there any performance and speed problems will occur if i change my OS to 14.04?
Answer: These are the official system requirements:
700 MHz processor (about Intel Celeron or better)
512 MiB RAM (system memory)
5 GB of hard-drive space (or USB stick, memory card or external drive but see LiveCD for an alternative approach)
VGA capable of 1024x768 screen resolution
Either a CD/DVD drive or a USB port for the installer media
Internet access is helpful
I'd say you are good to go, but really try xubuntu, it's also supported by Canonical but it's more light, or Lubuntu (but it's not Canonical supported) that is even more light.They are both Ubuntu compatible.


Using a heater and toaster oven trips the breaker. Can an electrician fix this?

Question: Using a heater and a toaster oven together, both about 1500w each, trips the breaker. It seems both are on the same circuit. Moving either appliance to a different location is not really an option.
Can an electrician do something so that this load can be handled? I want to get an idea of his work.. what will he do?
Comment: This could use a location tag, since all of the answers seem to assume North America (120V)
Comment: Pictures on older questions indicate he is in the US.  That and 1500w is the typical max heater size sold in the US.  In fact almost all space heaters sold are 1500w because of our typical 15A@120v circuits (15 * 120 * 80% ~= 1500).
Comment: What country are you in?  This is important information.  Everyone is assuming you live in North America.  Is this the case?
Comment: @EdBeal Most people don't know it is a **valid** solution... The alternative is 1) do something stupid and burn your house down 2) hire an electrician, and spend thousands or even tens of thousands to re-wire your house. This involves ripping out the wires out of the walls and putting in higher gauge wires. Most people don't know the circuit breaker is to prevent your house from burning down.
Comment: Well the op said they wanted both heat and toaster oven, but I guess it accepted an answer to not turn them on at the same time makes me think the question was a joke!
Comment: @nelson Well no wires need to be removed and a single circuit would normally be hundreds , can't use larger gauge as 20a is the max, as I mentioned.
Comment: @JPhi1618 1500W is a common size for heaters all over the world.  It happens to be the largest that fits on a 15A 120V circuit, but it is nevertheless common in other regions as well.
Comment: Does your electric stove have an outlet in it? If you plug the toaster into that you should be fine. I suspect this may be specific to Canada - there have generally been a couple of outlets on our electric stoves, usually at or near the top of the control panel, and a set of fuses or breakers in the panel. So you're using the dedicated 40A (or 50A) 240V circuit of the stove, and the outlet is protected to 15A. But this may be less common in more recent models.
Answer: There is something you can do:  Do not turn on both appliances at the same time!
This is relatively straightforward for the combination of a heater and toaster.  Unless you are a toast making factory, the toaster runs like 3 minutes per day.  During that time, turn off the heater.
Comment: ...but if operating in oven mode, it throws heat, so still a perfectly good answer, IMHO.
Comment: Not a terrible solution on a budget, but it does say "toaster oven", so it could be running for much longer than a sliced toast maker.
Comment: We'll just say that it might help someone else in a _similar_ situation ;)
Comment: @JPhi1618:  Oops!  I overlooked the toaster *oven* part.  Perhaps the answer isn't as useful as intended.
Comment: Actually it's much simpler than doing what seems to be a costly job. Will turn off the heater. It's just a matter of remembering to do it every time.
Comment: A toaster *oven* is not a toaster, so will be on for longer than three minutes.
Comment: @Bort OP is pretty shifty about expected answers.
Comment: Those of us used to running caravans/campervans have to be familiar with what we can run at the same time for a given current limit. In general the idea is to warm the living space, cook, then turn the heater back on if needed.  If your toaster oven is fairly well insulated and you're cooking for a long period with it closed, you should be able to turn it off for a few minutes to run the heater. I've only used toaster ovens a couple of times, and only basic ones with simple controls that would make this easy. They're not really a thing here.
Comment: The op knows the problem and asked if it could be fixed and info around a fix. If you turn the power off to the house it won't trip either.
Comment: You can get a switch that instead of "one position is on, the other is off", it's "one position is the heater has power, the other the toaster has power".
Comment: This isn't even an answer to the question. It is no way attempts to answer if it can be fixed by an electrician. It only aims to tell the user to use different behavior.
Comment: I asked myself *When I express a problem in terms of my imagined solution, would I appreciate challenges to the scope of my question?*  The answer is decidedly **yes**!  Often the best solutions come from such a reexamination.  Especially if my expected solution got bogged down in unimaginative solutions and failed to focus on the essential core problem.
Answer: Yes an electrician can fix this.
I would suggest a second 20a circuit be pulled in. Since you said toaster oven (in a kitchen) there should be 2 20 amp circuits for the small appliances already. 3000w / 120v= 25 amps so you really don't have many options as you are limited to 20 amp circuits.
 Depending on the type of service panel and if it has space may really affect the cost ( and access to an attic or crawl space to pull the new circuit).
You should be able to get a quote on the job that explains the scope of work , new circuit, number of boxes and outlets ect.
Comment: And permits, if your jurisdiction requires them.
Comment: Most importantly from a safety perspective, you have to have wiring that supports higher amperage for that circuit. You cannot just put a higher amperage circuit breaker in and call it good unless the wiring is a low enough gauge.
Answer: Why run the heater if the toaster oven is on?
When the toaster oven is on, it also is putting 1500W of heat (about 4000 BTU) into the room.  Therefore it is redundant to the heater, and you don't need the heater at those times. You can turn it off.
Someone raised an issue about toaster oven heat being delayed heat. Since  your other heater is a radiator type, it is also delayed about the same.  So shutting off the heater while toasting is a good plan that will yield about the same heat in the room.
Improving service means running new cables to the service panel.
The electrician will cheerfully take your money to run 1 circuit on 1 cable.
However, the lion's share of cost will be labor of fishing cables through the walls. That labor is unaffected by whether 1 cable is run, or 4.  So there's big economical savings in running as many as 4 additional circuits on 4 cables (provided you have the circuit breaker space) for barely more than the cost of cables and outlets.
There is also a way to run 2 circuits per cable, however it is largely obsolete and requires compromises.
If this is a kitchen, there is no such thing as too many circuits in a kitchen.  Code now requires 2 complete 20A circuits merely for kitchen countertop receptacles. Practicality calls for a dedicated non-GFCI circuit for the fridge.  You can't have too many.
Think about a circuit dedicated to heating
If  you're running a new circuit anyway, you'll get far more heat capacity by running a 240V circuit. This allows up to 3840 watts of heating per circuit instead of 1500.  Further, it allows (requires) you to use installed heaters actually made for, and safe for, permanent/continuous service.  Cost for the heaters is very minimal, at $50 for a 2000W Cadet, and that's comparable to a radiator style heater and cheaper-by-the-year than those cheapie 1500W heater-fans.  And worlds safer!
And you can run two of them on a 20A/240V circuit.  Resistive heating is cheap. To buy.
Comment: @n0rd No, the heat still ends up in the room; insulation just puts a time delay on it.  Not that much of one either. So if you ran it from 1:00 to 2:00, the full 1500 watt-hours would indeed end in the room, just from 1:15 to 2:15.
Comment: *When the toaster oven is on, it also is putting 1500W of heat ... into the room.* Not really.  When the **element** is on that's true, but the element is likely to be switched by a thermostat.  Once it's warmed up it probably only averages something like 1/10 of that, which may not be enough to keep the room warm.  So you turn the heater on, then when the thermostat on the oven comes back on, the breaker trips.
Comment: @Tony_Henrich The radiator/oil heaters are safer than cheapie heater-fans, but still not as safe as properly installed heaters like a Cadet.  Also, radiator/oil heaters have about as much thermal delay or inertia as a toaster oven; rendering n0rd's point above entirely moot.  When both are running, you are putting 3000W of heat into the room. *Do you really need that?*
Comment: @harper Your answers are full of how things operate. My question is NOT why the breaker trips. My question is about finding a solution. For heaven's sake, stop asking why I am using a toaster oven to heat a room. I am not. I am heating FOOD for a few minutes. I bought a radiator heater. I am using it because I bought it and I like it. I don't care if a cadet is better more efficient or whatever. You're comments go into different directions. Anyways, I already accepted an answer.
Comment: That's not even true when the element is on. Any decent oven would be insulated so the majority of the heat is kept in the oven. In order for an oven to heat the room one has to run it with its door open.
Comment: @Harper I am using the toaster oven for food for a few minutes. Certainly you must know that I am not using it to heat a room! I am using a radiator type of heater. Heater fans are noisy.
Comment: @n0rd the reason running the oven with the door open heats the room a lot more is that with the door open the heat escapes, so the thermostat turns the element on a lot more
Comment: It never ceases to amaze me that people get befuddled why running 2 or more heating elements on any given circuit overdraws the circuit and trips the breaker. Electric heaters are some of the highest amp devices around!
Comment: My point was that ovens make a very lousy replacement for a space heater as they are designed to keep the heat inside of it instead of heating the room. Yes, *eventually* the heat will end up in the room, but it will never release the heat at the same rate as it is produced during the normal use. Insulation is not just delaying the heat release, it slows it down:if you run oven for 1 hour, it then will then take many hours to release the heat it accumulated into the room.
Comment: @Tony_Henrich **You should accept my answer instead!**  I make a point of covering every point you *and others who follow* are likely to need.  I am not accusing you of using it for space heating, but *some people do that* so it deserved a mentsch, regardless I didn't mention it but once. I do note that  you have now complained about it twice, do you wish me to edit it out of the answer? Alright.  I'm sorry if you took it personally but it was not meant that way, so "let it go" :)  Anyway like I say, it's the most helpful answer for everyone who comes after you, so by all means pick it!
Comment: @n0rd Not true. I have a toaster oven. Ten minutes after I turn it off, it's cool enough to touch the elements. (Note that I would never recommend that you touch the elements of an oven. If you do, you do so at your own risk.) So, where does it store the heat to be released an hour later?
Comment: "To buy". That is a critical little throw away statement there at the end.
Comment: @Harper-ReinstateMonica The hover text on the check mark reads, `Click to accept this answer because it solved _your_ problem or was the most helpful in finding _your_ solution` (my emphasis). It says nothing whatsoever about being a useful answer for others. Your answers are _always_ thorough, complete and very useful to the poster and future generations, but the OP is under no obligation whatsoever to select an answer that's useful to others (or any answer at all, though it's highly recommended, appreciated, and a courtesy).
Answer: Kitchen circuits have been required to be 20A for a long time, your capacity then is 120 Volts x 20 Amps = 2400 Watts. If you reduce the heater to 900 or 600 watts then it should not trip. If it does then your breaker is likely failing and replacing it may help. However you may actually find more devices on the same circuit, even the fridge is allowed to be on the same circuit as countertop receptacles.
Sometimes people state that a circuit should not be loaded more than 80%, this is generally conservative and safe advice, but the NEC only restricts 80% on motors and circuits that operate at full current for 3 hours or longer, which both the toaster and heater should be cycling loads.
Otherwise routing another cable or two from the panel is the only option, this could take 2 hours, it could take 22.
Bear in mind your general purpose receptacle circuits were not designed to replace an engineered heating system.  Constantly using general purpose in that manner will certainly result in shortened lifespan of some of electrical system components.
Comment: Just want to point out that while you're right and the portable space-heater types are not considered continuous load, a fixed heater (like electric baseboard heaters) is.
Answer: The only thing that can be done will involve running a new wire, which is typically a more expensive job (compared to just switching out some light switches or an outlet).  There might be a shortcut that can be taken depending on how nearby circuits are run, but figuring that out would take an on-site electrician anyway.
Go into the bid process assuming that a new wire will need to be run.  If there are not any blank spots in your current breaker panel, that will make the job a little more expensive if you can use "double" breakers, or a lot more expensive if you need a second electrical panel.
What you can't do is just replace the breaker, because the breaker is limited by the wire size.  Even if you happened to have wire rated for a 20A circuit, that still is not enough to power two 1500w appliances.
Answer: I had a similar problem with a toaster and microwave.  The breaker was old (circa 1975).  I replaced it.  Problem solved.
Comment: That's poor advice. Two 1500W devices means 3000W total. If this is in North America, 3000W/120V means 25A, and the circuits are limited to 20A. While it's possible that a new breaker could help in specific scenarios, you should at least explain that, especially since it likely won't help in this case.
Comment: One benefit to the implied (rather than stated) approach of putting in a breaker that's rated too high for the wiring is: The wires in the wall will soon help in warming the room, as well.
Comment: Toaster and toaster oven are  two different problems.  A toaster oven runs for longer time.  Thermal magnetic breakers trip based on an inverse time curve. NEMA standards have a trip window that by spec should not trip for 90 seconds at 125% overload. After that you are in a trip window, the longer it remains overloaded the more likely it will trip.
Comment: What make and model was the old breaker, and what did you replace it with?
Comment: This is certainly better reading than the comment threads on this page. It's not going to solve the OP's problem but a crappy old breaker *will* exacerbate similar situations. All the other answers here are obvious to the contractor in me; not of-the-mind of a repairman like this one is.


Spivak's 'Calculus', 5-21(b): Is there an easier/shorter way?

Question: Some personal background: I'll be going into my second year as a maths undergraduate in September of this year, and I'm currently working my way through Spivak's Calculus. While $\epsilon$-$\delta$ arguments have been introduced in the course, certainly nothing like this question has been thrown at me yet, but I enjoy the challenge. In the Supplement, Spivak merely says the result is obvious, and gives no working; while it is intuitive, I wouldn't say this answer occurred to me immediately.
The problem is as follows:
Prove that if $\lim_{x\rightarrow0}|f(x)|=\infty$ and $\lim_{x\rightarrow0}g(x)$ does not exist, then $\lim_{x\rightarrow0}f(x)g(x)$ also does not exist.
Prior to this, in Problem 21-5(a), it is proved that the same result holds if instead we assume $\lim_{x\rightarrow0}f(x)$ exists and is nonzero, but I don't think this result is immediately relevant.
Please note that 'the limit exists' is taken to mean that function tends to some finite limit.
My answer is as follows:
Suppose $\lim_{x\rightarrow0}|f(x)|=\infty$ and $\lim_{x\rightarrow0}f(x)g(x)=l$, for some $l\in\mathbb{R}$. Let $\epsilon>0$.
By hypotheses, we can find $\delta_{1},\delta_{2}>0$ such that $|f(x)|>(\epsilon + |l|)/\epsilon$ whenever $0<|x|<\delta_{1}$, and $|f(x)g(x)-l|<\epsilon$ whenever $0<|x|<\delta_{2}$. Note that $(\epsilon + |l|)/\epsilon\geq1>0$.
By the Triangle Inequality, we have $|f(x)g(x)| \leq |f(x)g(x)-l|+|l|$ always, so that $|f(x)g(x)|-|l| \leq |f(x)g(x)-l|$ always.
Also, when $0<|x|<\delta_{1}$, we have $|g(x)|(\epsilon+|l|)/\epsilon < |f(x)g(x)|$.
Hence, if we take $\delta = \mathrm{min}\{\delta_{1},\delta_{2}\}$, then:
\begin{eqnarray*}
0 < |x| < \delta & \Rightarrow & |f(x)g(x)-l| < \epsilon \\
& \Rightarrow & |f(x)g(x)| - |l| < \epsilon \\
& \Rightarrow & |f(x)g(x)| < \epsilon + |l| \\
& \Rightarrow & |g(x)|\cdot\frac{\epsilon+|l|}{\epsilon} < \epsilon + |l| \\
& \Rightarrow & |g(x)| < \epsilon.
\end{eqnarray*}
Hence, $\lim_{x\rightarrow0}g(x)=0$.
Thus, if $\lim_{x\rightarrow0}|f(x)|=\infty$, then $\lim_{x\rightarrow0}g(x)=0$ if $\lim_{x\rightarrow0}f(x)g(x)$ exists. Therefore, if $\lim_{x\rightarrow0}g(x)$ does not exist, then $\lim_{x\rightarrow0}f(x)g(x)$ also does not exist, provided $\lim_{x\rightarrow0}|f(x)|=\infty$.
My questions to you: is there any shorter way of proving this, given the tools available (knowledge of definitions and inequalities, mostly)? More importantly, is my solution correct? Any feedback at all would be appreciated.
Answer: Yes:
$$
g(x) = \frac{f(x)g(x)}{f(x)}.
$$
The denominator tends to infinity,${}^1$ and if the numerator tends to a limit, then...
${}^1$Take absolute values if you really want to be precise.
Comment: I accepted this answer previously, but taking a look again I'm no longer convinced that this is enough. "Taking absolute values" seems to entail trying to prove that $g(x)$ tends to a limit whenever $\text{sgn}(f(x))g(x)$ does. This does not look pleasant (and I'm not sure it's even true), because we have to account for pathological choices of $f$, and we don't have much to work with when it comes to $g$ either.

I will keep this answer as "accepted", because, to be honest, I would be surprised if Spivak was expecting students to consider the problem so thoroughly when he put it in the book.
Comment: @WillR I am not sure if I have understood your comment. First of all, that exercise is marked with two stars. However, it seems to me that I gave you all the ingredients to write down a complete proof, assuming that 'having a limit' means 'having a finite limit'. Indeed, if you assume that the numerator converges to some $\ell \in \mathbf{R}$, then $|g(x)| \to |\ell|/\infty =0$. By a previous exercise in Spivak's book, this is equivalent to $g(x) \to 0$.
Comment: My sincerest apologies, you are entirely correct. I had not checked StackExchange until it occurred to me just now that I had missed the obvious way of doing things - perhaps I even saw this at the time and simply forgot it!
Answer: I'm going to claim the result is false, since the author is allowing $\infty$ as a limit in the statement of the problem. A countexample is
$$f(x) = \frac{1}{x^2}, x\ne 0, g(x) = 1, x > 0, g(x) = 2, x< 0.$$
Then $\lim_{x\to 0} f(x) = \infty,\lim_{x\to 0} g(x)$ doesn't exist, but $\lim_{x\to 0} f(x)g(x) = \infty.$
Comment: I thought about this too, but I think the limit being infinity is considered to "not exist" in this context. So the limit of $|f|$ doesn't exist either, but it doesn't exist in a very specific way. The problem should have been stated more clearly such that the limit of $fg$ either doesn't exist or diverges.
Comment: Yes, perhaps I should have been more specific. In the text, $\infty$ is not taken to be a limit that 'exists'. I have edited my question to avoid any further confusion.


Is it possible to deploy a jdk 6 (or 7) war in a container instance running in jre 5 environment?

Question: I would compile a company legacy java web project, currently compiled with jdk 5, with jdk 6, in order to upgrade version of some libraries in use, like Struts, Axis etc...
Since this application need to be deployed in a Tomcat 5.5 instance, running in jre 5 environment, shared with multiple other project, neither Tomcat nor jre version can be upgraded.
I wonder if is it possible, to deploy a war containing code compiled with a java version (version 6 or 7) newer than the jre (version 5) running the container?
Answer: Short Answer: No
Long Answer:
It may be possible to compile your code with '-target 1.5'. However in this case all code including any bundled dependencies also need to be compiled with '-target 1.5' defeating the whole purpose of upgrading the JDK. You also need to be careful not to use any API that was introduced in Java 6 (or 7), not in your code nor in bundled dependencies.
In other words there is no point in trying to do this as any potential benefit can not be utilized anyway.
Answer: Each JDK version has some changes, you need to understand whether the code in your project uses these changed functions,If it has nothing to do with your code, you can upgrade


Solving a limit with L'hospital rule or without it

Question: So I have a limit that I want to solve:
$$\lim_{x\to0}\bigg(\frac{1+\ln(1-x^2)}{2x+1-\sin(x)}\bigg)^{\frac{1}{x^2}}$$
So I thought of using L'Hospital's rule, but it's not the $\displaystyle\frac{0}{0}$ situation.
Or Can it go for a different L'Hospital's rule situation, like it's $\displaystyle\frac{\infty}{\infty}$ but i get $1$ at the numerator?
Can I still use it or should I first manipulate the fraction somehow that it's plausible for using that rule, or is there another trick to use?
Any help would be appreciated.
Comment: If you like to use L'Hospital's rule then take the logarithm of your term because you will get $0/0$. But it becomes complicate.
Comment: I have done as I have said above. With the first step I get $-\frac{1}{0}$. Therefore perhaps your task is written wrong.
Answer: You may do an expansion in power series (use $\log(1+z)=z-O(z^2)$ and $\sin(x)=x+O(x^3)$):
$$ \frac{1+\log(1-x^2)}{2x+1-\sin x} = \frac{1-x^2+O(x^4)}{1+x+O(x^3)} =1-x+O(x^3)$$
Now, taking log of your expression we may write it as
$$ \frac{\log(1-x+O(x^3))}{x^2}=\frac{-1}{x}+O(1)$$
which goes to $\mp \infty$ as $x\rightarrow \pm 0$.
So the limit is zero or infinity depending on how $x$ goes to zero.
Answer: Hint it's of the form $1^{\infty}$ so write we can write it as $e^{g(x)(f(x)-1)}$ (which can be proved using basic results of limits ) where $f(x)=base ,G(x)=index)$ then you have a form where both numerator,denominator tend to $0$ and thus you can use Lhospital or Taylor expansions for $ln,sin$
Answer: First of all, notice that a two-sided limit does not exist.

Use Taylor series (at $x=0$):
$$\left(\frac{1+\ln(1-x^2)}{2x+1-\sin(x)}\right)^{\frac{1}{x^2}}=\exp\left[-\frac{1}{x}-\frac{1}{2}-\frac{x}{2}-\frac{7x^2}{12}-\frac{43x^3}{120}-\frac{149x^4}{180}+O(x^5)\right]$$
Using l'Hôpital's rule:
$$\lim_{x\to0^-}\left(\frac{1+\ln(1-x^2)}{2x+1-\sin(x)}\right)^{\frac{1}{x^2}}=\exp\left[\lim_{x\to0^-}\frac{\ln\left(\frac{1+\ln(1-x^2)}{2x+1-\sin(x)}\right)}{x^2}\right]=\exp\left[-\frac{\lim_{x\to0^-}\frac{1}{x}}{2}\right]\to\infty$$
Using l'Hôpital's rule:
$$\lim_{x\to0^+}\left(\frac{1+\ln(1-x^2)}{2x+1-\sin(x)}\right)^{\frac{1}{x^2}}=\exp\left[\lim_{x\to0^+}\frac{\ln\left(\frac{1+\ln(1-x^2)}{2x+1-\sin(x)}\right)}{x^2}\right]=\exp\left[-\frac{\lim_{x\to0^+}\frac{1}{x}}{2}\right]=0$$
Answer: As others have said, find the limit of the log of your expression.  But take advantage of the log:
$$\lim_{x\rightarrow 0} \frac{\ln(1+\ln(1-x^2)) - \ln(2x+1-\sin x)}{x^2}.$$
Apply L'hospital once to get
$$\lim_{x\rightarrow 0} \frac{ \frac{1}{1+\ln(1-x^2)}\frac{1}{1-x^2}(-2x) - \frac{1}{2x+1-\sin x}(2-\cos x)}{2x}.$$
Then  the numerator goes to $-1$ and the denominator goes to $0.$  So the left hand limit is $+\infty$ and the right hand limit is $-\infty$.  So for your original expression, the left hand limit is $e^{+\infty} = +\infty$ and the right hand limit is $e^{-\infty} = 0$.


Should I merge identity server database with application database?

Question: I recently started from scratch to implement a new application, so I have created a new application with its own database and I used Identity Server 4 with ASP.NET Identity which has a separate persistence database and I named it Identity_Server.
The plan is that in near future I will start developing another applications which will be clients in the central Identity service provider (Identity Server 4).
The problem which I'm facing right now, in the application I'm developing I have auditing columns like CreatedById & LastUpdatedById which will capture the user id. As will as I will have a logs table where I will store the user id as a foreign key.
Storing user ids is not a problem because I can capture it once user logged into the application but the problem that in UI I wanted to present more meaningful claim like username or full name.
how I can make the relation between application entities and identity server user entity where both are in separate db context and separate physical databases.
Shall I change the architecture and keep all my applications entities in same database with identity server?
Answer: The problem is that the information of the user is not part of the context.
Mixing the two contexts is not going to help you and querying both contexts is not the solution. The solution is to make sure that the information becomes part of the context.
This is in fact how Identity works. When you login with an external provider, like Google, a local copy of the user is created in the AspNetUsers table. Redundant? No, because that is another context, which you don't have access to.
In case you want to show user info on a report, you'll need to create a local copy of the user including the relevant information.
Please note that there may be information of the current user available in the claims. But as you need information from other users as well, you'll need to store it in the business context.
You can either choose some strategy to read information from claims when the user logs in, calling a UserInfo endpoint (if consent is given) or add functionality to maintain the user information in the business context.
Bottom line is that you'll need to create a User table in the business context that contains the information you need for reports.
Comment: I'm totally convinced with your answer, I was thinking about this as well.. it's only I have to think in how to came up with a strategy on how to keep users info table in sync in business databases.
Comment: Thank you for your answer. If I want to start developing using a single database, and at the same time, I want it to be friendly with future database concerns-based separation. Should I follow the exact approach when databases are separated ?? e.g., creating two users table, one for identity and another for application (without identity info)?


do I need to use exit after header("Location: http://localhost/...");?

Question: I'm creating a script to validate a form and I was asking myself a question. When I use a header (see example below), do I need to use exit right after? I mean, does using header also means that it is exiting by default therefore I don't need to use the command exit?
// cancel button clicked
if (isset($_POST['cancel'])) {
  header("Location: http://localhost/admin/tracks.php");
  exit;
}

echo '
$name
'

Comment: @EmCo Not exactly true. See the example in my answer.
Comment: I think you don't need to. When the header is sent, you will be redirected and the script will stop the execution.
Comment: possible duplicate of [Why I have to call 'exit' after redirection through header('Location..') in PHP?](http://stackoverflow.com/questions/2747791/why-i-have-to-call-exit-after-redirection-through-headerlocation-in-php)
Answer: You should call exit() because a header() won't automatically stop the script from executing - or if it does (I'm honestly not 100% on that), it definitely doesn't stop the script instantly.
For example, try this code:
<?php

  header("Location: http://www.google.com");
  unlink(__FILE__);

?>

This little script uses header() to redirect you to Google, and then deletes itself. If you run it, you'll notice that after you were redirected, the file was still deleted. This means that the unlink() call was still executed even though the header() call redirected you.
Comment: I've had the same concern and it does continue executing! Best to exit;
Answer: I use exit after the header->location call because I want to be able to rely ABSOLUTELY on the fact that the script won't get past the header->location call.
If there's a bug somewhere and your script starts generating output BEFORE the header->location call, the call will fail, and script execution will continue normally (unless you call exit)
Comment: Good point about the failed call. I hadn't even considered that possibility.
Comment: Your bug example is irrelevant. No bugs required for script to continue
Comment: @Shrapnel I didn't say one was _required_, I offered an example. Script execution does _not_ continue normally after a successful header->location call
Comment: @Shad: Actually, it does. See my answer for an example. Your first "Location" header doesn't even need to be the first one you send. You can set a Location header, do some processing, then send another one, and the user will be redirected to the last Location you specify.
Comment: @Shad oh, really? any reason for that?
Comment: @Agent that's not so true. Depends on time of that activity.
Comment: @Col. Shrapnel: I assume you're referring to the double-location headers? If so, you're absolutely right. You can only replace the header until the headers are sent. If you did location->echo->location, without any sort of output buffering, then the first location would be used because the Location header, along with all other headers, would automatically be sent before the echoed contents could be sent. Presumably the second one would also throw a "headers already sent" error as well, but nobody would see it since the browser would have already redirected away from your page.
Comment: Not knowing exactly _when_ your script will stop executing is not what I call _normal_ execution.
Answer: Although the answers above sound great, if you're unsure of your code path, this could lead to unexpected results. For example, if you're using a framework that relies on the fact that code execution will run from beginning to end, you may inadvertently interrupt it.
This might be okay from a user perspective as they will still be redirected and will be none the wiser, but consider the following:
You're using a framework (OS or custom) that is expecting to log redirects, or set additional headers (or any number of other items). By calling exit, you're circumventing that logic and therefore may get unexpected results.
So in short, yes the above methods will work, just a word of caution to know what you're expecting to happen before short circuiting it.
Answer: Output is generally not sent (depending on output buffering and so on) if you redirect like that, but as shown by the unlink() example the script does not die with header().
So the exit() or die() calls are necessary if you want to prevent the script from continuing after the redirect.
Answer: It does NOT stop your script from running, your script will keep on running and sometimes all a person (could be with bad intentions) needs is your script to reach a certain point where he could do X. Header() will just redirect, exit(); however will stop the script right on the spot (where exit(); is). or as someone else stated under the username:
Cody. A. Ray: Yes, the script continues to process after the call to header('Location: http://google.com') if you don't explicitly terminate it! I just tried this locally. I added test.php to a site in apache with these contents
<?php

 header('Location: http://google.com');
 error_log("WE MADE IT HERE SOMEHOW");

?>

And checked my /var/log/apache2/error_log for this entry:
 [Tue Feb 12 23:39:23 2013] [error] [client 127.0.0.1] WE MADE IT HERE SOMEHOW

so end conclusion: Header doesn't stop the script from running.
Answer:
does using header also means that it is exiting by default

How so?
What if your header is not Location: one but Content-type: or Cache-control or whatever else?


How to install Bad Piggies on ubuntu 12.04?

Question: I am completely new with Wine. I haven't installed any games through Wine. What are the steps to install Bad piggies on Ubuntu 12.04?
Comment: @Danatela for Wine related questions, please point them to http://askubuntu.com/questions/316025/installing-and-configuring-wine which is a complete guide about Wine.
Answer: You could try PlayOnLinux. It's available in the software center and has nice GUI menus to assist you in installing games like this. If your game is not listed, just choose the option to install a game that isn't listed.
Comment: Why not playing the game online: http://www.puffgames.com/games/bad-piggies-2/
Answer: Using wine is not complicated but some games or Applications might not work as expected since Wine is NOT an emulator :)
To install normally you do
sudo apt-get install wine
to install application:
wine Setup.exe
then if everything went ok you should have the Application/Game installed on your wine directory which as a similar layout as in Windows.
cd ~/.wine/drive_c/
then go to the path of the Application/Game
cd Program\ Files\ApplicationXYZ

and run wine *Executable.exe*
For more instructions and help on Bad Piggies with Wine, follow this page which the Wine community maintain.
EDIT
Also as an alternative, since Bad Piggies should not have a big 3D and CPU requirements you could also try to run it on a Virtual Machine. This is usually more easy and if you have a powerful machine you should get also a good performance.


Set Text to be Underline without Selection

Question: I am trying to allow users the ability to set text they will type as underline, without having text currently selected. This is for an iOS 6 app, entering text in a UITextView. It will be saved as an NSAttributedString. Bold and italic work fine. Something about underline is keeping it from working.
UITextView *textView = [self noteTextView];
NSMutableDictionary *typingAttributes = [[textView typingAttributes] mutableCopy];
[typingAttributes setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
NSLog(@"attributes after: %@", typingAttributes);
[textView setTypingAttributes:typingAttributes];
NSLog(@"text view attributes after: %@", [textView typingAttributes]);

My initial log statement indicates it is set to underline:
attributes after: {
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0xa9c5e30> font-family: \"Verdana\"; font-weight: normal; font-style: normal; font-size: 17px";
    NSKern = 0;
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
    NSUnderline = 1;
}

But the log statement immediately after doesn't show an nsunderline attribute. Removing the textView setTypingAttributes line has no affect.
text view attributes after: {
    NSColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSFont = "<UICFFont: 0xa9c5e30> font-family: \"Verdana\"; font-weight: normal; font-style: normal; font-size: 17px";
    NSKern = 0;
    NSStrokeColor = "UIDeviceRGBColorSpace 0 0 0 1";
    NSStrokeWidth = 0;
}

I'm stumped why I have it working for bold and italic, but not underline. Also why it seems to initially get the attribute, then forget it. Please share any insight you may have. Thanks.
Comment: Try using the System Font. Not sure if the underline is drawn or its a glyph in the font.
Comment: Have the exact same problem, it retains all attributes I've tried except underline (I tried font, background color, fore-color, text alignment, etc they all work fine). Did you find a workaround?
Answer: I think you've found a bug, or at least some undocumented behavior. If I set the typing attributes to red, I can do it:
-(BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range
        replacementString:(NSString *)string {
    NSDictionary* d = textField.typingAttributes;
    NSLog(@"%@", d);
    NSMutableDictionary* md = [NSMutableDictionary dictionaryWithDictionary:d];
    // md[NSUnderlineStyleAttributeName] = @(NSUnderlineStyleSingle);
    md[NSForegroundColorAttributeName] = [UIColor redColor];
    textField.typingAttributes = md;
    return YES;
}

With that code, all the user's new typing comes out red. But if I uncomment the commented line, trying to add underlining to the typing attributes, it breaks the whole thing - I don't get underlining, and I don't get red coloring either!
The answer to the other part of your question, though, is documented. You have to do it the way I'm doing it, reasserting the typing attributes as the user types, because, as the documentation clearly states, "When the text field's selection changes, the contents of the dictionary are cleared automatically" (that's the "forgetting" you asked about).
Comment: Thanks for the reply Matt. I thought it was just me! Having read your post, I've done quite a bit of testing. As you mention, Underline doesn't work as a preformatting option using typingAttributes. Neither does strikethrough. Everything else I've tried (foreground & background colors) seem to work.
Comment: Thanks, DenVog - I filed a bug on this, and I suggest you do so too.
Comment: I filed a bug as well. Though given that I have some still open from June, I won't hold my breath of getting a fix any time soon.
Comment: Many of my bugs have been open for years. The important thing is numbers of reports. Apple has explicitly said that they pay more attention to bugs that have been reported more times.
Comment: I had the same issue, tried reporting the bug, but there is a bug in the bug-reporting page and gives me this error "An error has occurred". How can I report this bug related to their bug-reporter? :)
Comment: In my testing, in iOS 7.1 you can use strikethrough with `typingAttributes`, but you need to set `typingAttributes` after you set any attributed text.
Comment: @phatmann Yes, what you've found here is a discussion of an iOS 6 bug. It was fixed in iOS 7.
Comment: @matt, the point I was trying to make was that `typingAttributes` needs to be set after `attributedText` for "preformatting" to work, even in iOS 7. I did not see that mentioned anywhere else.
Comment: @phatmann See the docs on `typingAttributes`: it's pretty clear there. Changing the `attributedText` changes the selection. But changing the selection clears the `typingAttributes`.
Answer: As of iOS 6, UITextView now declares property attributedText which allows you to underline text by creating an NSAttributedString.  Here is the modified code:
UITextView *textView = [self noteTextView];
NSMutableDictionary *typingAttributes = [[textView typingAttributes] mutableCopy];
[typingAttributes setObject:[NSNumber numberWithInt:NSUnderlineStyleSingle] forKey:NSUnderlineStyleAttributeName];
NSLog(@"attributes after: %@", typingAttributes);
textView.attributedText = [[NSAttributedString alloc] initWithString:[textView text] attributes:typingAttributes];
NSLog(@"text view attributes after: %@", [textView typingAttributes]);

By using this code, any further text that is typed will also conform to the format set out in your NSAttributedString e.g. underlining
Hope this helps!
Comment: You are correct about the use of typingAttributes for selection length of zero. But I do not find this works for underline or strikethrough.


Correct way to transform python request parameters

Question: I'm using Pyramid web framework to build a web app.  There are many times that I find myself doing this:
result = request.params.get('abc', None)
if result:
  result = simplejson.loads(result)
else:
  result = {}

The thing is, sometimes, 'abc' request parameter is not present and the value of  "result" would be None.  Hence I always have to check if it's None before I perform a simplejson.loads operation or else I would get a TypeError: expected string or buffer exception.
Is there a better/more "pythonic" way of doing this?
Answer: Try this:
result = simplejson.loads(request.params.get('abc', '{}'))

Comment: Brilliant! Thanks.  Sorry I can only accept the answer in another 7 minutes.


Some advice needed on working as a UI designer in a app dev company

Question: A week ago, I managed to get a job in a app dev company. They create apps based on clients' needs.
Before that, I'm a general graphics designer who also does some app UI mockup but it's for in-house purposes, not for clients.
As for my background, I mainly use photoshop / illustrator / balsamiq mockups and I have basic understanding of HTML/CSS/JQuery and basic programming principles.
1) I'll start work at the new company in 1+ months time. What books or website should I read or practice now during this period so that when I start work, I won't be lost? The first few months of joining a new company is the most painful due to zero comfort zone. Do I need to memorize the Android Material design encyclopedia by heart and the iOS too?
2) I've a huge issue which I never understood. When meeting clients to discuss the app and requirements, what questions do u ask the client? How do you develop the app based on their needs? Do you guys refer to similar existing apps on the market and create the app mockups based on that?
Trying to convert "users' needs" and that sort of thing into UI feels really abstract to me.
3) In agencies like this sort, there's usually a project manager to manage the project and in my case, my boss is the project manager (no senior designer or art director there). Is the project manager usually responsible for dealing with the client and collecting the design brief and data etc.?
4) In most app dev companies, what's the speed of work like? How long do u guys (UI designers) usually take to finish the mockups for the average app?
Tks!
Answer: The answers to your questions vary greatly depending on the company you work for, their style of work and other business factors. But I'll advise as best I can, based on my experience.
1) I would recommend basic readings of:

Donald Norman, Design of Everyday Things
Steve Krug - Don't Make Me Think
Jesse Garrett - The Elements of User Experience
If you love to read, you can find many more in a UX book collection, such as this.
It'd also be useful to become familiar with the Android and iOS guidelines, but don't worry about memorising them, that'll come with time and practice.
2) Understanding a clients needs is all about asking the right questions. Obviously, I can't give you a set of questions because all clients differ, but the key thing to understand is you are there to analyse what it is clients need, and why they need that. You need to analyse what they say, and translate that into effective solutions. Referring to existing apps can be useful - eg. if your client is working with a lot of file/data management, check out the heavy hitters like Dropbox etc. - but don't rely on other apps for your inspiration. Try to get away from your computer screen, using a pen and paper to deeply understand the user's needs. Have faith in yourself, with a good understanding of UX principles you will be able to apply these to the user's needs. Knowing a good set of 'patterns' can be useful here, you could read more about those here: Theresa Neil - Mobile Design Pattern Gallery
3) Yes, a project manager is usually responsible for communicating with a client, ensuring the project stays on track and leading the direction. But be prepared to take responsibility for your own work, and don't be afraid to 'own' a part of the project.
4) This question is too subjective to answer, it depends on too many factors. If you're unsure, ask your coworkers or your project manager. Being honest here is key, there's no need to pretend to be something you're not!
Do remember to have faith in yourself and your abilities. Read a lot, practice daily and most important of all, I think, practice being a good listener.
Best of luck.
Comment: Tks a lot! I've rented some of the books above today.
Answer: It's an app development company. Get both an Android device and an iOS device. And start downloading and using apps. Every single app you can find recommended for every single app usage activity.
You have one month. If you download and use 10 apps per day, each for an hour per day, and note their 'on boarding' experience, the level of discoverability, familiarity, conventional-ness of the UI (or otherwise) and fitness for its stated purpose, etc.
Become an expert on apps. 30 days, 300 apps.
Try the top ten in each of these categories:

Mail
Text Editors / Word Processors
Code Editors
Illustrative Drawing
Video Editors
Photo Editors
Painting
Todo Lists
Calendars
Download/Storage/Cloud Management
Mapping/Navigation
Fitness
Expenditure Management
And any and all categories of apps pertinent to the company you're going to work at. Become a virtual library of the UI paradigms and UX processes in the market.

Keep notes, take screenshots, record videos/voiceovers of yourself commenting and thinking about the experience in each app. Review them all.
Do a category of apps per day, more if you can. Pick the best features, functionality and UI elements and UX processes from each, and imagine the perfect app for each category.
Now you're a UX designer.
All the books, websites, videos and tutoring in the world can't beat out the above done with diligence, discipline and dedication.
Comment: Tks, I will do that!


ModuleNotFoundError: No module named 'register'

Question: I am working on a Django project. I am working on the register page. When I try to import my register/views.py to my mysite/urls.py file I get an error message. ModuleNotFoundError: No Module named 'register'. Both files are are in the same directory.
from django.contrib import admin
from django.urls import path, include
from register import views as v

Adding full exception message
Comment: If you're importing to a file thats within the register directory, try `from .views import *`
Comment: Thanks that did not work.
Answer: Please add a blank __init__.py file in the register folder.
Only then python will understand that register is an importable package
Edit:
After seeing the exception, it looks like a working directory issue in pycharms. Please try the fix mentioned in this link
Comment: Can you share the full exception traceback?
Comment: Just added the full exception
Answer: Try the following:-
from . import views

Comment: any other suggestions?


www RewriteRule not applying to subdirectories with other RewriteRules

Question: I have an .htaccess file in my root folder to redirect non-www accesses to www
RewriteEngine On
RewriteCond %{HTTP_HOST} ^example.com$
RewriteRule .* https://www.example.com/$0 [L,R=301]

The rule works fine, but in a subdirectory (call it /sub) where I have another .htaccess file with rewrite rules - the www rule is not applied.
Of course I can copy paste it - but that is obviously not the best solution.
I've tries adding RewriteOptions Inherit to the subdirectory's .htacces - and the rule works, but the rules works in relation to the sub folder and not the sub folder so http://example.com/sub/something.html is redirected to https://www.example.com/something.html (removing the sub folder from the path)
Setting RewriteBase / in the subdirectory's htaccess isn't good as well - since it interferes the other rules I have in the file
I'd really appreciate your help
Comment: Did you have `RewriteBase /` at the beginning of the root `.htaccess`?
Comment: @johnwait No I didn't. I tried adding it now but still `http://example.com/sub/something.html` is redirected to `https://www.example.com/something.html`
Comment: I asked because without it it should have worked. Does the `RewriteRule` work better with subfolders (having `RewriteOptions Inherit` in their `.htaccess`) when using in the root `.htaccess` the part `%{REQUEST_URI}` instead of `/$0`, as in `RewriteRule .* https://www.example.com%{REQUEST_URI} [L,R=301]`? Or else, maybe the child `.htaccess` is faulty. You might want to take a look at that related question: http://stackoverflow.com/questions/18980710/htaccess-wont-add-www-to-only-one-subdirectory
Answer: By default sub directory's .htaccess doesn't inherit rules defined in parent .htaccess. To enforce this behavior you need to insert this line in /sub/.htaccess:
RewriteOptions Inherit

before RewriteEngine On line.
Read more about RewriteOptions
Though keep in mind that parent .htaccess rules are only applied after your current .htaccess rules and there is no way to change this behavior in Apache 2.2 at least. If this is affecting you then you will need to copy www rule and place it above your other rules in /sub/.htaccess.
EDIT: Also change your root https rule to this:
RewriteEngine On

RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^example\.com$
RewriteRule ^ https://www.example.com%{REQUEST_URI} [L,R=301,NE]

Comment: Also, docs state the following: `Rules inherited from the parent scope are applied **after** rules specified in the child scope.`, if it can be related to your case.
Comment: @johnwait: Thanks, very valid point that I should have mentioned earlier. (Its added in answer now)
Comment: TNX for your reply, but this still doesn't work... ='


React useEffect to obtain Autocomplete options (material UI) from Cloud Firestore

Question: I'm trying to use react useEffect hook to get data from firestore and give it to the options attribute on a Material UI autocomplete select menu.
I have a collection in my firestore called "organisations". That document has an attribute called "shortName".
I'm trying to get the data from the collection and then use it to set the state on a property called orgList, which I can then use in the in the select menu.
This is what I'm trying.
import React, { useState, useEffect } from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import CheckBoxOutlineBlankIcon from '@material-ui/icons/CheckBoxOutlineBlank';
import CheckBoxIcon from '@material-ui/icons/CheckBox';
import firebase from "../../../../../firebase";

const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;

export default function CheckboxesTags() {
  const [orgList, setOrgList] = useState();
  const [selectedOrgList, setSelectedOrgList] = useState();

  useEffect(() => {
    firebase
      .firestore()
      .collection("organisations")
      .onSnapshot(snapshot => {
        const orgList = snapshot.docs.map(doc => ({
          id: doc.id,
          ...doc.data(),
        }))
        setOrgList(orgList)
      })
  }, [orgList])

  return (

        <Autocomplete
        multiple
        id="checkboxes-tags-demo"
        options={orgList}
        disableCloseOnSelect
        getOptionLabel={(option) => option.shortName}
        renderOption={(option, { selected }) => (
            <React.Fragment>
            <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
            />
            {option.shortName}
            </React.Fragment>
        )}
        style={{ width: 500 }}
        renderInput={(params) => (
            <TextField {...params}
            variant="outlined"
            label="Select Organisation"
            placeholder="Acme Inc"
          />
        )}
        />

  );
}

The error message I'm getting says:

TypeError: Cannot read property 'shortName' of undefined

NEXT ATTEMPT
Using the suggestion from gdh below, this is the next attempt.
import React, { useState, useEffect } from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import CheckBoxOutlineBlankIcon from '@material-ui/icons/CheckBoxOutlineBlank';
import CheckBoxIcon from '@material-ui/icons/CheckBox';
import firebase from "../../../../../firebase";

const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;

export default function CheckboxesTags() {
  const [orgList, setOrgList] = useState([]);
  const [selectedOrgList, setSelectedOrgList] = useState();
  const [loading, setLoading ] = useState(true);
  const [ error, setError ] = useState(false);

  useEffect(() => {
    const unsubscribe = firebase
      .firestore()
      .collection("organisations")
      .onSnapshot((snapshot) => {
        const orgList = snapshot.docs.map((doc) => ({
          id: doc.id,
          shortName: doc.shortName
        }));
console.log(orgList)

        setOrgList(orgList);
      }, () => {
          setError(true)
        });
        setLoading(false);
        return() => unsubscribe();

  }, [orgList]);

  useEffect(() => {
    firebase
      .firestore()
      .collection("organisations")
      .get()
      .then((snapshot) => {
        const orgList = snapshot.docs.map((doc) => ({
          id: doc.id,
          shortName: doc.shortName
        }));
        setOrgList(orgList);
      });
  }, []);

  return (

        <Autocomplete
        multiple
        id="checkboxes-tags-demo"
        options={orgList}
        disableCloseOnSelect
        getOptionLabel={(orgList) => orgList.shortName}
        renderOption={(orgList, { selected }) => (
            <React.Fragment>
            <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
            />
            {orgList.shortName}

            </React.Fragment>
        )}
        style={{ width: 500 }}
        renderInput={(params) => (
            <TextField {...params}
            variant="outlined"
            label="Select Organisation"
            placeholder="Acme Inc."
          />
        )}
        />

  );
}

The console log prints both orgList ids, but the shortName is undefined.
I get an error that says:

TypeError: Cannot read property 'toLowerCase' of undefined .

In an attempt to solve this error, I added:
    ignoreCase = {false}

to the Autocomplete head tag, but the same error persists. The console logs an error that says:

Warning: React does not recognize the ignoreCase prop on a DOM
element. If you intentionally want it to appear in the DOM as a custom
attribute, spell it as lowercase ignorecase instead. If you
accidentally passed it from a parent component, remove it from the DOM
element

I tried renaming shortName in firestore to 'short' to see if I could avoid the case sensitivity issue, but the same error persists (console logs short as undefined when it has a value in the firestore console).
I know the form is reading from firestore because when I try setting the option as the id of the document, the form loads and the id prints as the value.
Answer:
you don't have initial values for orgList. Provide a blank array.
you are only registering onSnapshot callback which only executes when organisations collection is changed but you are not fetching any data on mount. This means that your autocomplete will only have values when someone make change in organisation collection. So maintain another useEffect and fetch the data.

refactored code
export default function CheckboxesTags() {
  const [orgList, setOrgList] = useState([]);
  const [selectedOrgList, setSelectedOrgList] = useState();

  useEffect(() => {
    firebase
      .firestore()
      .collection("organisations")
      .onSnapshot((snapshot) => {
        const orgList = snapshot.docs.map((doc) => ({
          id: doc.id,
          ...doc.data(),
        }));
        setOrgList(orgList);
      });
  }, []);

  useEffect(() => {
    firebase
      .firestore()
      .collection("organisations")
      .get()
      .then((snapshot) => {
        const orgList = snapshot.docs.map((doc) => ({
          id: doc.id,
          ...doc.data(),
        }));
        setOrgList(orgList);
      });
  }, []);
//.... rest of code...

Comment: hmmm - no errors - but the options don't render either. I have a series of warnings that are triggered by using Material UI Typography: validateDOMNesting(...):  cannot appear as a descendant of . I'll try resolving those and testing again before I look further into this. Thank you for the help so far.
Comment: I have removed all Typography warnings and am still producing a form without any options (there are 2 in the console).
Comment: I added the next attempt above - along with the error message
Comment: I also tried making a new 3rd organisation to test whether the update might force the form to use the options - but it doesn't
Comment: i see ... as mentioned in the answer, there is no need of dependency `orgList` in the useEffect. It will register new callback whenever data in `organisations` collection changes
Comment: I tried it both with and without the dependency. The same lowerCase error results in both use cases.
Comment: when I console log the snapshot, I can see both org shortNames, but shortName is undefined. I get an error that says: Material-UI: The `getOptionLabel` method of Autocomplete returned undefined instead of a string for {"id":"7zKsfdfdfeSDEx7"}.  Thanks anyway for trying to help
Comment: As for the second useEffect you suggested, this seems to be inconsistent with the firestore docs, which say: You can listen to a document with the onSnapshot() method. An initial call using the callback you provide creates a document snapshot immediately with the current contents of the single document. Then, each time the contents change, another call updates the document snapshot.
Comment: and FYI: the reason to add the dependency is  to optimise the hook by only re-running when there is a change in firebase.
Answer: I found what worked - eventually. There seems to be an issue limiting reading single attribute from the firebase document. In my snapshot, I was trying to read: doc.shortName / doc.short. It needs to be:
 shortName: doc.data().shortName,

I didn't end up needing the second .get useEffect as proposed by gdh.
Here is what worked for me:
import React, { useState, useEffect } from 'react';
import Checkbox from '@material-ui/core/Checkbox';
import TextField from '@material-ui/core/TextField';
import Autocomplete from '@material-ui/lab/Autocomplete';
import CheckBoxOutlineBlankIcon from '@material-ui/icons/CheckBoxOutlineBlank';
import CheckBoxIcon from '@material-ui/icons/CheckBox';
import firebase from "../../../../../firebase";

const icon = <CheckBoxOutlineBlankIcon fontSize="small" />;
const checkedIcon = <CheckBoxIcon fontSize="small" />;

export default function CheckboxesTags() {
  const [orgList, setOrgList] = useState([]);
  const [selectedOrgList, setSelectedOrgList] = useState();
  const [loading, setLoading ] = useState(true);
  const [ error, setError ] = useState(false);

  useEffect(() => {
    // if (doc.exists) {
      const unsubscribe = firebase
        .firestore()
        .collection("organisations")
        .onSnapshot((snapshot) => {
          const orgList = snapshot.docs.map((doc) => ({
            id: doc.id,
            shortName: doc.data().shortName

          }));
          console.log(orgList)
          setOrgList(orgList);
        }, () => {
          setError(true)
        });
        setLoading(false);
        return() => unsubscribe();

  }, [orgList]);

  // useEffect(() => {
  //   firebase
  //     .firestore()
  //     .collection("organisations")
  //     .get()
  //     .then((snapshot) => {
  //       const orgList = snapshot.docs.map((doc) => ({
  //         id: doc.id,
  //         ...doc.data()
  //       }));
  //       setOrgList(orgList);
  //     });
  // }, []);

  return (

        <Autocomplete
        multiple
        id="checkboxes-tags-demo"
        options={orgList}
        disableCloseOnSelect
        getOptionLabel={(option) => option.shortName}
        renderOption={(orgList, { selected }) => (
            <React.Fragment>
            <Checkbox
                icon={icon}
                checkedIcon={checkedIcon}
                style={{ marginRight: 8 }}
                checked={selected}
            />
            {orgList.shortName}
            </React.Fragment>
        )}
        style={{ width: 500 }}
        renderInput={(params) => (
            <TextField {...params}
            variant="outlined"
            label="Select Organisation"
            placeholder="Acme Inc."
          />
        )}
        />

  );
}

As for the toLowerCase error - there is a filterOptions attribute that can be used on Autocomplete. I couldn't figure out how to get that working - but for now, that's a problem for another day.


Use a checkbox or radio button to save search term in jQuery DataTables

Question: I have a jQuery DataTable in a rails app where I am using the built in stateSave so that a user's choices of visible columns, column order, and search terms. I would like to have some way to force the user to choose to save the search term. So the desired function would be saving state like it does automatically, but null the search value unless the checkbox is checked. I've run into a few issues.

If I add a checkbox that sets the search term to the current search value, I have to either force the user to only check it AFTER they have modified the search term, or check it every time they type something into the search box.
I have only figured out how to turn sateSave on or off with the checkbox, not just the search function. Which will mess with their other settings that I always want saved.

I think the way to go is to have a checkbox that when checked or unchecked it fires a function that changes the jQuery stateSave param but JUST for the search function. I've spend literally many hours reading through the DataTables docs and forums but can't figure it out. It seems like it should be an easy thing to just turn one of the stateSave params on or off. Here is the javascript I have so far:
$('#some_table').dataTable( {
        stateSave: true,
        stateDuration: 0,
        dom: '<"toolbar">Bfrtip',
        colReorder: true,
        buttons: [
            { extend: 'colvis', position: 'dropdown', columns: ':not(.noVis)',
                className: "btn btn-xs btn-brand dropdown-toggle", dataToggle: "dropdown", ariaExpanded: "false"},
            { extend: 'copy', className: 'btn btn-xs btn-brand' },
            { extend: 'print', className: 'btn btn-xs btn-brand' },
            { extend: 'csv', className: 'btn btn-xs btn-brand' },
            { extend: 'excel', className: 'btn btn-xs btn-brand' }
        ],
        inputType: 'search',
        name: 'search',
        "oLanguage": {
            "sSearch": "Filter: "
        },
        search: {
            search: '<%= raw(@filter) %>'
        },
        "order": [[ 1, "asc" ]],
        "columnDefs": [
            {"targets": [0], "orderDataType": "dom-checkbox"},
            {"targets": [0], "className": "noVis"}
        ],
        scrollY:        550,
        scrollX:        true,
        scrollCollapse: true,
        paging:         false,
        fixedHeader:           {
            header: true,
            footer: true
        },
        "initComplete": function(settings, json) {
            if (getParam() !== 'undefined') {this.api().search(getParam()).draw();}
        }
    } );

The getParams is a function that just grabs part of the url and applies it to the search box. This is for when people click on a tag link from another page to populate the search with that term. When they navigate away it will save that search term since I have stateSave set to true. If a user enters a new search filter term in the search box and then checks a checkbox, it should update the saved state with the new term automatically. I think if I can come up with a way to turn search term saving on or off through the API it should do that automatically.
I tried adding this to my table definition above:
        data.search.search = "";
        data.search.smart = $('#saveSearchCheckbox').prop('checked');
    },

and a checkbox like:
<input type="checkbox" id="saveSearchCheckbox">Save Search

but it doesn't actually do anything.
Comment: ***I have to either force the user to only check it AFTER they have modified the search term, or check it every time they type something into the search box*** <-- The `input` event is triggered from either of these situations.
Comment: Thank you for the reply. JS is really a weak point for me. Can you elaborate with some example of how to leverage that event?
Answer: As you have said that you have written code for enabling/disabling the stateSave of datatable but probably you have done wrong as you have just given the datatable configuration code. so let me explain with coding example
var dataTableConfiguration = {
// here you can add your datatable configuration that you already mentioned above.
};

var dataTable = $('#some_table').DataTable(dataTableConfiguration);

$('#yourCheckbox').change(function() {

  if ($(this).is(':checked')) {
    dataTable.destroy();
    dataTableOptions.stateSave = true;
    dataTable = $('#some_table').DataTable(dataTableOptions);
  } else {
    dataTable.destroy();
    dataTableOptions.stateSave = false;
    dataTable = $('#some_table').DataTable(dataTableOptions);
  }

});

The above example is for enabling/disabling the stateSave according to checkbox selection. but if you want to enable the stateSave just for search term you can modify the above code into change event of checkbox
if ($(this).is(':checked')) {
  dataTable.destroy();
  dataTableOptions.stateSave = true;
  // Save only the search term
  dataTableOptions.stateSaveParams = function(settings, data) {
    data.search.search = settings.oPreviousSearch.sSearch;
  };
  dataTable = $('#some_table').DataTable(dataTableOptions);
} else {
  dataTable.destroy();
  // Disable stateSave
  // Reset the stateSaveParams
  dataTableOptions.stateSave = false;
  dataTableOptions.stateSaveParams = null;
  dataTable = $('#some_table').DataTable(dataTableOptions);
}

Hope this will help.
Ref: stateSaveParams
Updated:
You can now add this configuration in your datatable configuration to capture the search input keyup event to save the search terms
var dataTableOptions = {
  // DataTables options
  "initComplete": function() {
    var searchInput = $('.dataTables_filter input');

    // Attach keyup event listener to the search input
    searchInput.on('keyup', function() {
      var searchTerm = searchInput.val();
      // Save search term to localStorage
      localStorage.setItem('searchTerm', searchTerm);
    });
  }
};

var dataTable = $('#some_table').DataTable(dataTableOptions);

// Retrieve search term from localStorage on page load
var storedSearchTerm = localStorage.getItem('searchTerm');
if (storedSearchTerm) {
  // Apply the stored search term to the DataTable search input
  $('.dataTables_filter input').val(storedSearchTerm);
  dataTable.search(storedSearchTerm).draw();
}

Comment: I gave the example of what I wrote in my question, the configuration is all there. Your answer does not work. I get  `uncaught TypeError: dataTable.destroy is not a function` when I click on the checkbox.

  Also I don't want to RESET the data table state, I want to save the search term if the box is checked and null it out if it is not. But I still want the other state params like visible columns and column order.
Comment: by the way above code is working fine, as you can check here on my codepen link -> https://codepen.io/mbt/pen/BaGpEZG

anyhow you just want to save the search term if the checkbox is enabled, so where you want to save that user searched terms on browser localStorage or in db.
Comment: You are missing the part where a requirement is to be able to use the other facets of state saving i.e. column order and column visibility. Thank you though.


Number Theory - Decimal Representation Question. Difficulty understanding a given solution.

Question: This question is from the 1995 Hungarian Mathematical Olympiad.
Let $k, n$ be positive integers such that $(n+2)^{n+2}, (n+4)^{n+4}, (n+6)^{n+6}, ..., (n+2k)^{n+2k}$ end in the same digit in decimal representation. At most how large is $k$?
A solution given in the book uses this crux argument:
Since $x^5 \equiv x\pmod {10}$, $x^x \pmod {10}$ depends only on $x \pmod{20}$.
Then, the author proceeds to tabulate the last digit of $x^x$ for $x=1, 2, \ldots , 19$ and looks for the longest run of same digits.
My confusion:
I understand that $x^5 \equiv x\pmod {10}$, but I cannot understand the inference that this must imply that $x^x \pmod {10}$ must depend only on $x \pmod {20}$.
Can someone help me understand the second part of the crux argument. Thank you.
Answer: The period of $x^n\pmod{10}$ with respect to $n$ is $4$. Also, $n^x\pmod{10}$ has a period of $10$ with respect to $n$. Thus $x^x\pmod{10}$ has a period $\operatorname{lcm}(4,10)=20$.


Guild experience math

Question: What are the formulas to calculate the levels and the experience gain of a Guild?

Meaning is how much XP the guild earns when completing a quest a % of what that quest gives you or is it a flat rate.
How much do you earn per kill...
etc.

Full answers are appreciated I am working on a calculator. Thank you for your time and responses.
Answer: How guild experience works
There are many methods of gaining guild experience;

Raiding in a guild group
Dungeons in a guild group
Arena in a guild group
Completing quests that give experience
Completing daily quests
Completing guild challenges

Experience in raid and dungeon groups is granted provided you meet the requirement for the number of people in the party. For example, with dungeons you will get get scaling experience based on the number of people from the guild that are in the party as follows;
3 guild members                50%
4 guild members                100%
5 guild members                125%

For raids, the number of people required in the group from the guild is a set threshold, and simply exceeding this threshold will provide the bonus;
25 man raiding                 20 guild members required
10 man raiding                 8 guild members required
Pre-WotLK 25/40 man raids      10 guild members required

For arena, the whole arena group must consist of members of the guild to qualify for guild experience.
Completing quests will provide experience to your guild for each quest completed, the amount of guild experience gained is approximately 60k experience per quest handed in since the release of Mists of Pandaria. This means that you can get a guild to level 25 by completing around 14100 quests.
Guild experience required for each level
level    reputation needed     daily quests needed
1        N/A                   N/A
2        16,580,000            277
3        18,240,000            288
4        19,900,000            332
5        21,550,000            360
6        32,220,000            387
7        24,880,000            415
8        26,530,000            443
9        28,190,000            470
10       29,850,000            498
11       31,510,000            526
12       33,170,000            553
13       34,820,000            581
14       36,490,000            609
15       38,140,000            636
16       39,800,000            664
17       41,450,000            691
18       43,120,000            719
19       44,780,000            750
20       46,430,000            774
21       48,090,000            802
22       49,750,000            830
23       51,410,000            857
24       53,060,000            885
25       54,730,000            913

As there is no cap on experience gain anymore, there is no "minimum" amount of time that it takes to level a guild to level 25 as there was at the start of Cataclysm.
Source on WoWpedia

Guild experience math


Routing error in Ruby on Rails 3

Question: I am new to Ruby on Rails
I am getting this error

uninitialized constant WelcomeController

after creating the sample project. I enabled
root :to => 'welcome#index'

in routes.rb.
Comment: I also got this error when using the getting started guide: http://guides.rubyonrails.org/getting_started.html You have to actually change the line to home#index like Mohan Raj says in his comment below. You don't just un-comment the line.
Answer: When you say
root :to => 'welcome#index'

you're telling Rails to send all requests for / to the index method in WelcomeController. The error message is telling you that you didn't create your WelcomeController class. You should have something like this:
class WelcomeController < ApplicationController
  def index
    # whatever your controller needs to do...
  end
end

in app/controllers/welcome_controller.rb.
Comment: Hi i found the solution just i changed root :to => 'home#index'. I created the controller home. So set route to home.
Comment: @MohanRaj you should accept this answer as correct, as it is.
Answer: I'm very very new to Rails and also ran into this error while following along with Rails Tutorial by Michael Hartl. The problem I had was that in the config/routes.rb file, I just uncommented the root :to => "welcome#index":
# just remember to delete public/index.html.
root :to => "welcome#index"

but with the structure of the sample_app was that "welcome#index" should be 'pages#home' instead, since everything was originally set up through the "pages" controller.
root :to => 'pages#home'

It's even right there in the book, but I just overlooked it and spent quite a while afterwards trying to figure out where I went wrong.
Answer: Make sure WelcomeController is defined in a file called welcome_controller.rb
Answer: rails generate controller welcome index
Comment: The generator sets the route for you.
Rails.application.routes.draw do
  get 'welcome/index'
end
Answer: If you not generate the page with name welcome, then just generate the page like:  $ rails generate controller pagename index. So then into the: config->routes.rb you should edit root 'welcome#index' to root 'pagename#index'
Answer: Keep this if you want it to be your context root after you generate your welcome parts.
Rails.application.routes.draw do
  root 'welcome#index'
end

Comment: Years late and thousands short. :-)

Routing error in Ruby on Rails 3