Ill formatted HTML from a PHP loop

Question: I am looping through an array and building tables. The HTML is then sent to DOMPDF. However, DOMPDF will not create the PDF if the HTML is ill formatted. I assume that is what is happening in my case. Here is my loop:
<?php foreach($credits as $credit) : ?>
        <?php if($credit['credit_type'] == "short") : ?>

                    <?php echo $credit['category_title']; ?>

                    <?php echo $credit['credit_heading']; ?>

        <?php endif; ?>

        <?php if($credit['credit_type'] == "long") : ?>
            <?php if($credit['category_title'] != $oldvalue) : ?>

            <?php endif; ?>

                    <?php if($credit['category_title'] != $oldvalue) : ?>
                          <?php echo trim($credit['category_title']); ?>
                          Title
                          Role
                          Director
                    <?php endif; ?>

                    <?php echo $credit['credit_heading'];?>
                    <?php echo $credit['credit_title']; ?>
                    <?php echo $credit['credit_role']; ?>
                    <?php echo $credit['credit_director']; ?>

                <?php if($credit['category_title'] != $oldvalue) : ?>

                <?php endif; ?>
                <?php $oldvalue = $credit['category_title']; ?>
        <?php endif; ?>
    <?php endforeach; ?>

I cannot for the life of me work out which tag I am not closing. If anyone could give some insight, that would be fab!
Specifically, the loop is creating rows that show some headings, and then spit out futher rows whenever the category title changes.
Comment: The easiest would be just to get the whole HTML with `ob_start()` and `ob_end()` but why doesn't your PDF lib work with "ill formatted HTML" ...?
Comment: what would that do? and how would I use it?
Comment: Which version of dompdf are you using? dompdf can work with ill formatted HTML, though there are some formatting problems that will kill a render. Plus, if the HTML isn't structurally correct the rendering may not be what you expect.
Comment: Also, starting with dompdf 0.6.0 (currently at beta 2) you can call $dompdf->output_html() to see what HTML dompdf is attempting to parse. But I agree with leo, if you need to check your HTML you should do it before passing it to dompdf.
Answer: This may be a simple solution but perhaps not the best:
I recommend you to use PHP's Tidy class (eventually you'll have to install it first...)
Here is the link for the Tidy class Manual.
At the first line:
ob_start();

This command buffers everything what is outputed by your follwing script.
The code below should be added at the end of your file, or there where you want to show the output.
It first gets the buffer with ob_get_contents() and than it cleans the code up.
Note that you'll eventually have to change the configuration parameters for your needs, there are really very much.
$raw_output = ob_get_clean();

$config = array('indent' => true, 'output-xhtml' => true, 'wrap' => 0);
$tidy = new Tidy;
$tidy->parseString($raw_output, $config, 'utf8');
$tidy->cleanRepair();

echo $tidy;

This Example Code was modified by the original version of the example on php.net.
Hope that helps you.
Answer: It's a bit difficult to parse without known more about your data. For example, why is a table for "short" credit open and closed with the record, but the table for "long" credit is conditional on the previous record? Is it because you have a flat data structure so related data shows up as a series of consecutive rows? If that's the case things would be easier if the data were a bit more normalized. I.e. you could iterate through each credit record then through the details separately. Any possibility of fixing your data structure?
Analyzing the code you have, your problem appears to be in the logic for the second section of the code. You are setting the value of the variable $oldvalue at the end of the loop. This is after the logic that closes the table. So if you parse two records that have the same category title the second record will output it's table rows completely outside a table (never mind that it will also have a completely empty row). Additionally, if you have a short credit type following a long the table will never be closed.
That being said, working with what you have I'm guessing you may need something like the following:
// build a dummy "previous" record for the first iteration so the conditionals don't break.
<?php $previous_credit = array('credit_type'=>null,'category'=>null); ?>
<?php foreach($credits as $credit) : ?>
    <?php if($credit['credit_type'] == "short" || ($previous_credit['credit_type'] == "long" && $previous_credit['category'] != $credit['category'])) : ?>

    <?php endif; ?>

    <?php if($credit['credit_type'] == "short") : ?>

                <?php echo $credit['category_title']; ?>

                <?php echo $credit['credit_heading']; ?>

    <?php endif; ?>

    <?php if($credit['credit_type'] == "long") : ?>
        <?php if($credit['category_title'] != $previous_credit['category_title']) : ?>

                <?php echo trim($credit['category_title']); ?>
                Title
                Role
                Director

        <?php endif; ?>

                <?php echo $credit['credit_heading'];?>
                <?php echo $credit['credit_title']; ?>
                <?php echo $credit['credit_role']; ?>
                <?php echo $credit['credit_director']; ?>

    <?php endif; ?>
    <?php $previous_credit = $credit; ?>
<?php endforeach; ?>

(That's some ugly code and I don't have time to keep revising it, so ... community wiki in case anyone else wants to clean it up.)

Ill formatted HTML from a PHP loop


In PlayN, how do you exclude a directory from being compiled by Maven?

Question: I want to build the html version of my game from the command line using maven. However, when I run the package command for the core folder:
mvn clean package -pl core,html

I get the following errors because of some unit tests in my source path:
[INFO] -------------------------------------------------------------
[ERROR] COMPILATION ERROR :
[INFO] -------------------------------------------------------------
[ERROR] /home/klenwell/projects/mygame/playn/mygame/core/src/main/java/mygame/playn/tests/unit/UserDataTest.java:[3,23] package org.junit does not exist

[ERROR] /home/klenwell/projects/mygame/playn/mygame/core/src/main/java/mygame/playn/tests/unit/UserDataTest.java:[7,16] package org.junit does not exist

...

How can I exclude the directory with these test files from being included in the compilation?
Answer: It is not a good idea to mix source and test classes.  As per maven convention, you should move the tests from src/main/java to src/test/java.
You should add the dependency for junit so that the tests can be compiled.
You can choose to skip the tests (if they are broken) by using the -DskipTests or similar while running maven.
Comment: Thanks. Still getting acquainted with Maven and Java conventions.
Answer: Adding the following block to the plugins section of my core pom.xml file excluded tests from compilation and allowed the build to succeed:
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <configuration>
      <excludes>
        <exclude>**/*Test*.java</exclude>
      </excludes>
    </configuration>
  </plugin>


Can you display health values for monsters?

Question: Is it possible to display actual numerical values of the health of a mob in Diablo 3? I know I can turn on the bars and I found that I can turn on numbers for Players, but not for the mobs (mobiles, monsters, whatever).
I would swear I had this turned on in the open beta as I recall wondering how I could do 8 damage to something with 8 health and not kill it. It would leave it with a little bar.
Anywho, I am interested in this display as it just helps me compare the numbers and such better as I look to build an effective DPS character. Helps with estimating time/attacks till death of targets and the like.
(If this is just a check box I can not find I am going to be fairly annoyed)
Answer: Sure you can.

The problem is, it doesn't show the numbers if the enemy is at full health.
To enable this:
You can also press V to enable/disable this at any time.


When do users understand that a wizard navigation bar is clickable?

Question: In my web application, I use a wizard navigation bar like the one in the image:

While getting feedback from a fellow designer, he asked me if the progress bar is clickable. In my mind, most wizard navigation bars are clickable. Is there any good practice for making sure that users know that wizard navigation bars are clickable? Is there any research about it?
Do you have any suggestions on the current design to make it understandable to the user that they can click on the wizard navigation bar?
FYI, I am also using a button navigation on the bottom of the screen, as appears in the next picture:

I added some more ideas on the wizard navigation bar:
Comment: I didn't realise wizard navigation bars are supposed to be clickable. I've never clicked on one and the one we have on our website is not clickable.
Comment: One simple thing that helps making me understand if something is clickable: `cursor: pointer` inside your CSS...
Comment: @Mathlight `cursor: pointer` is not as useful as it used to be. Mobile users (phone, tablet) have a touch screen and no mouse. There is no cursor, and they don't scrub the page for information.
Comment: Buttons for navigation, bars to show current step.
Comment: Take a look at Dipaks answer. Simply underlining the label will make it immediately clear that it is clickable. Or at least underline it if you hover over it. Otherwise how about having a separate shevron to the left and right of the bar or elsewhere on the page? Also if i as a user want to go a step back, I usually use the back and forth buttons of my browser.
Comment: Most "where you are" bars (that I've attempted to click on) haven't been, and mostly I wouldn't expect them to be (forward and back buttons at the bottom, yes; clicking on the navigation at the top, no). Of your three examples, only the middle one would I even think might be clickable: the other two (particularly the top one) are like stops on a train-line: they show you where you are, but it's the driver (not you) that determines when to go forward or not.
Comment: A clickable navigation bar? Wow, that sounds interesting. So why do you have a step by step procedure if you are not enforcing the steps? Or are just all the previous and the "immediate next" step clickable?
Comment: Finally, someone is designing a clickable wizard bar. My prayers have been answered!
Comment: @Mathlight Also, if something doesn't appear clickable, the user might not even bother to hover it, assuming that it isn't clickable.
Comment: Do not click on the bars of wizards, for they are subtle and quick to anger.
Comment: @xxtesaxx: At least, this is valid on sites that _don't_ override the link styling to remove the underline, as seems to become ever more &%##%!! popular...
Answer: Note: when this answer was written, the question talked about a "progress bar". The question was later changed to mean "wizard". I am leaving this answer as is because it is still being voted up regularly; thus, it seems to kind of be a somewhat fitting answer for a "wizard"-style form as well.
Never
With all the examples in the question and the answers so far, I would never, as a user, get the idea to click on them. On the contrary; especially if it is a web application, I am usually paying a lot of attention on not clicking anything when an important page is still loading - for example on the final button of a payment operation.
So, I'd suggest putting the clickable parts well outside of the progress bar, and make them look like they always do (links, buttons, whatever you have in your application).
Outlook
If you want a somewhat nicer experience for long-running and important jobs, then you would probably avoid a "normal" progress bar completely. I.e., show the user the server-side progress, and make it 100% clear that the user is free to go away and come back later (maybe even in a new browser session). To do that, skip the progress bar metaphor, and just display something like "Progress: 77%; this has already taken 44 minutes and may take a long while, it is safe to close this window and come back later. Click here to abort the operation.". If the user does indeed close the window (i.e., the session) and comes later, your server should indeed have the results of the operation ready, of course.
Comment: @DimitraMiha Make the "back" button work like it's supposed to.
Comment: +1 for **not clicking anything when an important page is still loading** .If I have to show something important meanwhile I will probably show **progress** or **Show details** using ajax. Something like this http://www.sqlcoffee.com/images/SQLServer2008_0001_0026.PNG . But in any case, I would never want my user to click randomly when wizard or long running process is going on
Comment: @AnoE maybe the confusion is because I confused the term progress bar & wizard navigation bar. There is no operation running. The operation will only run when you click the last button of the task. Do I make more sense now?
Comment: @DimitraMiha, well, that's kind of pulling the rug, indeed!
Comment: what if you wanted to go back to a previous step of your shopping task? For example, if you wanted to review your shopping cart. Also, you are talking about buttons: Then, what do you think about the second example of the second image?
Comment: Think about it like this: the user sees a long-running operation. If he simply leaves the page, it is pretty unclear what should happen. Does the server abort the operation? Does it keep running? Does the server notice at all? An "abort" action would make this clear, so this is what you should have; and as said, it should be the usual (whatever is usual for your application), i.e., a nice, normal button. It is unusual (and probably confusing) to have this functionality on the bar itself. (And if you want to *support* the user going away and coming back, the same applies, with more UI elements)
Comment: +1. I actually always expect/hope these to be clickable. But in my experience they almost never are. :-( — So, yeah, people clearly can't be reasonably expected to think they are.
Comment: @AnoE I am sorry for the confusion. Your answer is correct in the case of progress bar, for sure :)
Comment: @DimitraMiha If there is a Previous/Next buttons, and i'm into a wizard, I don't expect to move freely thru the steps of the process. I just click Next until the process is done, and if I want to see the cart again, I just cancel the process or expect to have the chance to review it before I commit to anything
Answer: I believe you need to rely on icons in this case.

The pencil is associated with the edit action, which if I understood correctly is the reason why the step is clickable, while a check icon implies the step is completed and there is no possible edit:

The idea behind is that steps which have already been filled don't need a number anymore and they are either editable or non-editable (and completed). Steppers could either be linear or non-linear.

Source: Material design - Steppers
Comment: This does not look clickable to me. On the other hand I've never clicked on any step navigation in my life. I always use the next/back buttons at the bottom of the form
Comment: Look at the difference between editable and non-editable on the page. They are almost identical, and in each case, I for one, would not think to click on them.
Comment: Just saw that actually. Do you think that it appears clickable enough?
Comment: I think it looks editable and so clickable, you could also make use of some kind of pop-over that has to be dismissed ("You can edit the step, click this box to dismiss"), but this only adds extra elements that might or not be needed. I guess you would need to test to be sure.
Comment: pencil icon instead of check for completed steps would hint that you could click back to edit. That's hinted at in this answer.
Answer: A lot has been discussed here already, and I think we can take an advantage of user's Mental Model by using border-bottom which will indicate that the step in wizard is clickable.
I've never used this in my work, but it would be a great option for research.
Comment: This makes it really clear that there is a clickable link!
Comment: I read this as a strange choice to underline, not as clickable, sorry. Might work if the color matched links elsewhere on the page.

I think the the Check icon that does it. Change to pencil to hint "editability"
Comment: We have something like this where I work. The fist time you go through there is a requirement for all steps to be completed contiguously. Thereafter, you can skip between steps as you please, so we added an underline on the text. This makes it very clear that what you are looking at is a link.
Comment: @Dipak It's a new feature, so not in front of enough users to get real feedback yet, but small trials have come back positive. Our org is not too geared towards UX so examining the clarity of this feature is not a priority for them :(
Comment: @cheersphilip Great! Have you tested it with users? What's the feedback?
Answer: Real good discussion happening here. Some thoughts and ideas below.

Consider the design attached and multiple scenarios mentioned:
1) Introducing a status message that suggests that the data is saved and also that the section can be re-visited might help.
2) It could act as a confidence measure and an information item, that could help users understand more and feel in control.
3) Status messages can be carefully worded and additionally, a popup/tooltip could be put in place to supplement more information on hover of the bars/tabs.
4) Numbering of the steps can be ignored, as that gives a hint that you cannot go back. As in 1-2-3 is ok, but the mental model does not allow to think you can easily go 3-2-1.
Comment: Sometimes a word (or three) is worth a thousand pictures.
Comment: Oooh, I like. To me, the navigability of this UI feels comfortable. There's no guesswork, no wondering whether the developers *meant* for you to be able to click a back-link and re-edit, or whether the later tab states will be lost. The status is clear and explicit.
Comment: Would it be better to have an edit icon (like a pencil) instead of a text message?
Comment: @AlvaroMontoro The issue with having only a edit icon is that, many users might still not understand that as clickable/editable - since the elements in this case are not obviously 'clickable'. See above solution by '@Alvaro' which explores that and in my opinion, can be used if supplemented with some extra text aids. Confidence aspect, on if the data is saved or not should also be considered.
Answer: Going off Simon Richter's answer and O. R. Mapper's comment, what about something that looks sort of tab-like to help indicate it's clickable, but has an arrow shape communicating the flow of the wizard steps?
Rough ugly example:
Comment: I would definitely not even think about clicking on this. Would I be able to skip step 2 to go to step 3 immediately? Of course not!
Comment: @StephanBijzitter Good point, you'd probably want to gray out/disable or hide the tabs that depend on earlier steps.  As for clickability, the point is to make it look similar to any other tabs that might be in the app. Obviously this is a generic mockup - and I'm not a designer.
Comment: I am going to accept this answer because it resembles more my final solution! Thank @Josiah!
Comment: Maybe if the steps were underlined to resemble links. Or had rounded/3d borders and a gap between them to resemble buttons. I think the "I can click this" feeling starts to go away in general on elements that are visually touching and intertwined.
Comment: @StephanBijzitter This solution has to be tested and of course according to the design that it has to match with the current design of the app.
Answer: Deutsche Bahn are using a tabbed interface, adding tabs as the user progresses along the wizard, and with green lines indicating that the respective pages contain valid data. The user can go back by selecting an old tab.
(German) report with pictures.
Comment: Not about tabs, but as a foreigner I found Deutsche Bahn interface kinda confusing in general.
Comment: I think this suggestion is in direct conflict with a recommendation I encountered elsewhere (will add a link if I found it again), namely that if anyhow possible, no tab should influence the contents of another tab.
Comment: I think tabs are great IF the steps are all independent and can be completed  in any order.
Comment: Ah yes, use tabs. I just commented above that I've never clicked on wizard navigation bar before then when you mentioned tabs I realized that I do click on wizard navigation on AWS when creating a new virtual machine. It's because their wizard navigation is tab based instead of navigation-bar based.
Comment: For linear tab-progress, it's OK to disable (but not hide) tabs which have not yet been reached. This style of UI makes it really super clear that you can navigate between the enabled tabs, but is really only for use where frequently moving back-and-forth within the forms you've already completed is both *expected* and *desired*. Where your ideal is a linear flow, and back-nav is for error recovery only, it's best to avoid this.
Answer: If you want to make the user aware of the fact that the progress bar is clickable, show it to them by e.g. changing the mouse cursor while hovering over a certain area of the progress bar.
Also adding a balloon context message can help. Be sure not to put too much information in the balloon as it may get unreadable and cluttered.
Comment: Touch screen devices have no mouse cursor except in trackpad mode, which may activate when docked to an external display.
Comment: If something doesn't already stand out as clickable, a user won't hover over it to begin with.
Comment: I plan to have cursor events. I was looking for a more visual way to show. The balloon also sounds like a good idea, but I would like to keep it as simple as possible.


Did using the /give command to get items with attributes change in 1.17.1?

Question: I've already stumbled upon some similar threads, but none on version 1.17. So my issue is, I want to make custom items (sword, armors…) with custom attributes. I tried copy/pasting some commands, but none worked. It keeps telling me that the item name is unknown, here's an example of command :
/give @p diamond_sword{Unbreakable:1,AttributeModifiers:[{Slot:"mainhand", AttributeName:"generic.attack_damage", Amount:100000.0, UUID:[I; -1, -1, -1, -1]},{Slot:"mainhand", AttributeName:"generic.movement_speed", Amount:1, UUID:[I; -1, -1, -1, -1]}]} 1

It's from a tutorial for Minecraft 1.16.5, so I suppose that it does not work the same in 1.17.1.
Comment: Possible duplicate of [Can't Use /Summon Command](https://gaming.stackexchange.com/questions/285722/cant-use-summon-command)
Answer: Firstly, that's not /attribute, that's /give, you're using attribute modifiers. The command should work, or at the very least not say the item name is unknown - it sounds like you've got a plugin here that's using the old /give syntax. What happens if you use /minecraft:give @p ... instead?
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).
Comment: Yes it was because of a plugin using it's own /give, so the /minecraft:give work fine. Thanks for the answer.
Comment: @Althoris Please mark this as the answer using the check mark


Resizing UIView width while keeping subview anchored

Question: So I want to achieve something like this before-and-after thing:
http://demosthenes.info/blog/819/A-Before-And-After-Image-Comparison-Slide-Control-in-HTML5
I currently have this hierarchy (added in that order, I have marked them with an ID to make it easer to follow):
<code>UIView (1)
   UIImageView (2)
   UIView (3)
     UIImageView (4)
</code>
Now the top level UIView has a UIPanGestureRecognizer attached. My idea was to resize the second UIView (3) containing the UIImageView when a panning gesture is recognised. In other words I will move the x-position of the UIView (3) therefore hiding the containing UIImageView (4) to reveal the image behind it (2) thus achieving the desired effect. It works fairly well in that it does indeed resize but the containing UIImageView (4) is not resized, instead it either moves with the x-position of the resized UIView (3) (being anchored at (0,0)) or it just floats on top of everything. I have tried changing autoresizeSubviews of the UIView (3) and autoresizeMask/contentMode but nothing really works.
In other words, how can I resize the container without moving or resizing the subview?
What am I doing wrong? Not sure if this approach is the best. If you have any suggestions on a better way of doing the before-and-after thing please share!
Answer: I would change the structure you currently have to something like that:

UIView (1)

UIImageView (2)
UIImageView (3)

To achieve the effect you want put a layout constraint which is attached to the right of UIImageView (3). Modify the constraint using your UIPanGestureRecognizer.
Additionally set the UIImageView (2) AND UIImageView (3)'s View Modes in Interface builder to "Top Left". That should do the trick. That is you're modifying the size of UIImageView (3) to reveal the image.
Comment: But this would make the image stick to the "Top Left" side of the UIImageView and it would be moved along X when the view is resized?
Comment: Not if you add the constraint to the right side of the UIImageView and modify the constant of the Constraint (i.e. initially higher value = image view shrinked down)


How to apply Excel formula to a dataframe with first row blocked

Question: I would like to apply a formula to my dataframe columns B and C that would be equivalent of excel B2*100/$B$2 and C2 * 100/$C$2 and dragging down.
Input
Date    B      C
1/20   0.1    0.2
2/20   0.05    0.3
3/20  -0.1    -0.05

Desired Outcome
Date    B      C
1/20   100    100
2/20   50     150
3/20  -100    -25

Thank you
Comment: what have you tried and I think you mean `B3=B3*100/$B$2`?
Comment: I tried some for loops but didn't work. By B2 I meant  cell with 0.1 and by C2 I meant cell with 0.2
Comment: Excel equivalent formula would be: `df.B * 100 / df.B[0]`, same for `C`
Answer: df['B'] = df['B'].multiply(100).div(df['B'].iloc[0])
df['C'] = df['C'].multiply(100).div(df['C'].iloc[0])

Note that dataframe indexes start at 0, not 1, and headers do not count, so the second row of you spreadsheet has the index of 0 in the dataframe.
Comment: that is incorrect. You need `.iloc[0]` not `.iloc[1]`
Comment: I realized that after the comment was posted by the author. Now fixed after edit.


How to safely get full URL of parent directory of current PHP page

Question: I'm using:
$domain = $_SERVER['HTTP_HOST'];
$path = $_SERVER['SCRIPT_NAME'];
$themeurl = $domain . $path;

But this of course gives the full URL.
Instead I need the full URL minus the current file and up one directory and minus the trailing slash.
so no matter what the browser URL domain is eg localhost, https://, http://, etc that the full real (bypassing any mod rewrites) URL path of the parent directory is given without a trailing slash.
How is this done?
Safely so no XSS as I guess (from reading) using anything but 'SCRIPT_NAME' has such risk.. not sure though ofc.. just been reading a ton trying to figure this out.
examples:
if given:
https://stackoverflow.com/questions/somequestions/index.php

need:
https://stackoverflow.com/questions

without the trailing slash.
and should also work for say:
http://localhost/GetSimple/admin/load.php

to get
http://localhost/GetSimple

which is what I'm trying to do.
Thank you.

Edit:
Here's the working solution I used:
$url  = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'];
$url .= htmlspecialchars($_SERVER['REQUEST_URI']);
$themeurl = dirname(dirname($url)) . "/theme";

it works perfectly.
Comment: realpath($_SERVER["DOCUMENT_ROOT"] . "/../");

define('SITE_PATH', realpath(dirname(__FILE__)));
define('UPPER_PATH', dirname(SITE_PATH));

realpath(dirname(__FILE__) . "/../");

$url_folder = substr(substr($_SERVER["REQUEST_URI"],1), 0,
      strpos(substr($_SERVER["REQUEST_URI"],1), "/"));

$_SERVER['REQUEST_URL']

$_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URL"] . "/../" a ton of different stuff.. I'm new to PHP and doing the best with what I've got so far.
Comment: As hek2mgl mentioned, it's correct, and a more dynamic approach would be dirname(dirname($_SERVER['REQUEST_URI']));
Comment: dirname x2 doesn't work... I've tried it Sid and pasted the results given... it outputs the directory tree twice in the URL string.
Comment: Why that htmlspecialchars() @RocketSpaceman ?
Answer: Thats easy - using the function dirname twice :)
echo dirname(dirname('https://stackoverflow.com/questions/somequestions/index.php'));

Also note @Sid's comment. When you you need the full uri to the current script, with protocol and server the use something like this:
$url  = isset($_SERVER['HTTPS']) ? 'https://' : 'http://';
$url .= $_SERVER['SERVER_NAME'];
$url .= $_SERVER['REQUEST_URI'];

echo dirname(dirname($url));

Comment: Try using dirname(dirname($_SERVER['REQUEST_URI'])); I've posted it as an answer. It's working for me, should work for you too.
Comment: Edited hek2mgl's post. This is without the port no. Hope this works out for you.
Comment: @hek2mgl that does not work... that outputed: http://localhost/GetSimple/theme/FoundationNation/localhost/GetSimple/FoundationNation/images/foundation/plus-toggle-2.png... so no there's a problem with your solution.
Comment: @YogeshSuthar his solution doesn't work Yogesh... see my question and try it... $domain = $_SERVER['HTTP_HOST'];
   $path = $_SERVER['SCRIPT_NAME'];
   $themeurl = dirname(dirname($domain . $path)); doesn't work
Comment: Yea... this doesn't work guys.. I'm localhost trying every option given so far. Again I need to work with the SCRIPT_NAME, remove the page and queries, move up one directory (not down from root) and then remove the trailing slash....
Comment: I have `http://localhost/a/b/c/test.php` for testing .. It outputs : `http://localhost:80/a/b`. This should be what you requested. Isn't it?
Comment: @hek2mgl Not exactly no.. if you have http : / / localhost/a/b/c/test.php I'd need http : / / localhost/a/b
Comment: without the port? without the protocol? without both? Please read your question, there you say you need the 'http://' in front of. Just give me a schema and I can finally answer the question
Comment: protocol (+plus) domain (+plus) entire directory tree (-minus) one directory (-minus) ending slash
Comment: the port number... eg need `http://localhost/a/b` or `http://example.com/a/b` or `https://example.org/a/b` etc
Comment: Then please think **5 seconds** which of the 5 line example you'll have to remove. (although I would not remove the port) .. SO is not to prevent you from thinking at least a little bit for yourself. This site is just to *help* you
Comment: Thanks, no need to be nasty.. I explained earlier that I'm new to PHP and when trying your example I wasn't sure if SERVER_NAME was only the name and not the suffix (which I would need) since I am on localhost testing this.
Comment: Thats not about nasty.. I like helping. But sometimes its better to think, try, think, try before post.. and its better to learn the basics of programming, like variables, functions, classes, *manuals* before thinking about XSS attack prevention ;) believe me, I just want to help. the dirname() tip is good! prevents you from getting *nasty* code... good luck! ;)
Comment: "Then please think 5 seconds which of the 5 line example you'll have to remove. (although I would not remove the port) .. SO is not to prevent you from thinking at least a little bit for yourself. This site is just to help you" I'm not disagreeing about thinking.. but obviously if I was sure of something I'd try it. Thank for help but it'd be nice if you helped without making assumptions on what I have done or haven't done. And alluding to me not "thinking" is rude.. no way to justify that type of comment. But thanks for a working solution anyway.
Comment: Note that using the `HTTP_X_FORWARDED_HOST` header is a security hole. It can be easily spoofed.
Comment: @hek2mgl please explain what kind of security hole it is
Comment: Better to use SCRIPT_NAME instead of REQUEST_URI since dirname() will fail with the latter if you have query strings with paths.
Answer: I have more simple syntax to get parent addres with port and url
lets try my code
dirname($_SERVER['PHP_SELF'])

with this code you can got a direct parent of adres
if you want to 2x roll back directory you can looping
dirname(dirname($_SERVER['PHP_SELF']))

dirname is fungtion to get parent addrest web and $_SERVER['PHP_SELF'] can showing current addres web.
thakyou Sir https://stackoverflow.com/users/171318/hek2mgl
Answer: I do not suggest using dirname()as it is for directories and not for URIs. Examples:

dirname("http://example.com/foo/index.php") returns http://example.com/foo
dirname("http://example.com/foo/") returns http://example.com
dirname("http://example.com/") returns http:
dirname("http://example.com") returns http:

So you have to be very carful which $_SERVER var you use and of course it works only for this specific problem. A much better general solution would be to use currentdir() on which basis you could use this to get the parent directory:
function parentdir($url) {
    // note: parent of "/" is "/" and parent of "http://example.com" is "http://example.com/"
    // remove filename and query
    $url = currentdir($url);
    // get parent
    $len = strlen($url);
    return currentdir(substr($url, 0, $len && $url[ $len - 1 ] == '/' ? -1 : $len));
}

Examples:

parentdir("http://example.com/foo/bar/index.php") returns
http://example.com/foo/
parentdir("http://example.com/foo/index.php") returns http://example.com/
parentdir("http://example.com/foo/") returns http://example.com/
parentdir("http://example.com/") returns http://example.com/
parentdir("http://example.com") returns http://example.com/

So you would have much more stable results. Maybe you could explain why you wanted to remove the trailing slash. My experience is that it produces more problems as you are not able to differentiate between a file named "/foo" and a folder with the same name without using is_dir(). But if this is important for you, you could remove the last char.
Answer: This example works with ports
function full_url($s)
{
    $ssl = (!empty($s['HTTPS']) && $s['HTTPS'] == 'on') ? true:false;
    $sp = strtolower($s['SERVER_PROTOCOL']);
    $protocol = substr($sp, 0, strpos($sp, '/')) . (($ssl) ? 's' : '');
    $port = $s['SERVER_PORT'];
    $port = ((!$ssl && $port=='80') || ($ssl && $port=='443')) ? '' : ':'.$port;
    $host = isset($s['HTTP_HOST']) ? $s['HTTP_HOST'] : $s['SERVER_NAME'];
    return $protocol . '://' . $host . $port . $s['REQUEST_URI'];
}
$themeurl = dirname(dirname(full_url($_SERVER))).'/theme';
echo 'Theme URL';

Source: https://stackoverflow.com/a/8891890/175071
Answer: I'm with hek2mgl. However, just in case the script isn't always specifically 2 directories below your target, you could use explode:
$parts = explode("/",ltrim($_SERVER['SCRIPT_NAME'],"/"));
echo $_SERVER['HTTP_HOST'] . "/" . $parts[0];

Comment: question... why would this $path = explode("/",$_SERVER['SCRIPT_NAME']);
   $themeurl = $_SERVER['HTTP_HOST'] . "/" . $path[0]; give me a result of this:      http://localhost/GetSimple/theme/FoundationNation/localhost//FoundationNation/images/foundation/plus-toggle-2.png there's a double slash and it's repeating the root twice... :(
Comment: I've updated it my friend, please make changes. I have added an `ltrim()` into the mix
Comment: Thank you, but that wont work either: localhost//FoundationNation/images/prettyPhoto/default/sprite.png. See one problem is the amount of total directories can change and using explode limits me from going UP one directory and instead starts me at the root of the path, now if I don't know how many directories total their are I'm screwed... so need to work with the original full length URL.. then remove the page, any queries, one directory, and a trailing slash... that's what I've been trying so hard to do.. 3 options give so far and none of them do the trick needed yet.
Answer: As hek2mgl mentioned, it's correct, and a more dynamic approach would be dirname(dirname(htmlspecialchars($_SERVER['REQUEST_URI'])));.
EDIT:
$_SERVER['REQUEST_URI'] will omit the domain name. Referring @hek2mgl's post, you can echo dirname(dirname(htmlspecialchars($url)));
Comment: Doesn't REQUEST_URI have XSS security risk?
Comment: XSS, yes. You can clean it up with htmlspecialchars(). I've edited the post plz check it.
Comment: this just outputs the parent directory... eg /GetSimple instead of http : / / localhost/GetSimple (I don't know how to format code in replies) but it's a start... will it work if the directory tree is much larger?
Comment: $_SERVER['REQUEST_URI'] will omit the domain name. You can refer @hek2mgl's edited post and add htmlspecialchars to it. I'll edit my post.
Comment: this kinda works but is missing the protocol: echo $_SERVER['HTTP_HOST'] . dirname(dirname(htmlspecialchars($_SERVER['SCRIPT_NAME'])));
Answer: Here are useful commands to get the desired path:
( For example, you are executing in http:// yoursite.com/folder1/folder2/file.php)
__FILE__   (on L.Hosting)   === /home/xfiddlec/http_docs/folder1/folder2/yourfile.php
__FILE__   (on Localhost) === C:\wamp\www\folder1\folder2\yourfile.php
$_SERVER['HTTP_HOST']     === www.yoursite.com (or without WWW)
$_SERVER["PHP_SELF"]      === /folder1/folder2/yourfile.php
$_SERVER["REQUEST_URI"]   === /folder1/folder2/yourfile.php?var=blabla
$_SERVER["DOCUMENT_ROOT"] === /home/xfiddlec/http_docs

// BASENAME and DIRNAME (lets say,when __file__ is '/folder1/folder2/yourfile.php'
basename(__FILE__)  ==== yourfile.php
dirname(__FILE__)   ==== /folder1/folder2

Examples:
*HOME url             (   yoursite.com   )
<?php echo $_SERVER['HTTP_HOST'];?>

*file's BASE url     (   yoursite.com/anyfolder/myfile.php   )
<?php echo $_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF']; ?>

*COMPLETE current url (   yoursite.com/anyfolder/myfile.php?action=blabla   )
<?php echo $_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];?>

*CURRENT FOLDER's  URL (   yoursite.com/anyfolder/   )
<?php echo $_SERVER['HTTP_HOST'] . dirname($_SERVER['REQUEST_URI']);  ?>

*To get RealPath to the file (even if it is included) (change /var/public_html to your desired root)
<?php
$cur_file=str_replace('\\','/',__FILE__); //Then Remove the root path::
$cur_file=preg_replace('/(.*?)\/var\/public_html/','',$cur_file);
?>

p.s.for wordpress, there exist already pre-defined functions to get plugins or themes url.
i.e. get plugin folder ( http://yoursite.com/wp-content/plugins/pluginName/ )
<?php echo plugin_dir_url( __FILE__ );?>


Stop scheduled timer when shutdown tomcat

Question: I have a WAR file deployed to Tomcat server, one of the class will get called at start up time, then the init() method will schedule a timer to fire every 5 hours to perform some tasks.
My init() code looks like this:
public void init()
{
    TimerTask parserTimerTask = new TimerTask() {

        @Override
        public void run() {
            XmlParser.parsePage();
        }
    };

    Timer parserTimer = new Timer();
    parserTimer.scheduleAtFixedRate(parserTimerTask, 0, PERIOD);
}

My application runs without problem, but when I shutdown the Tomcat using /etc/init.d/tomcat7 stop,  then I check the log (catalina.out) it has a entry like this:
SEVERE: The web application [/MyApplication] appears to have started a thread named [Timer-0] but has failed to stop it. This is very likely to create a memory leak.
I understand this is caused by me schedule the timer, but my question is:

I didn't set setDeamon to true, so shouldn't the timer prevent Tomcat from shutting down, rather than left running?
Can I, in my application, detect Tomcat is going to be shutdown and cancel my timer?
What are the other solutions I can use to take care of this issue?

Thanks!
UPDATE
I changed my code to the following based on some search and DaveHowes's answer.
Timer parserTimer;
TimerTask parserTimerTask;

public void init()
{
    parserTimerTask = new TimerTask() {

        @Override
        public void run() {
            XmlParser.parsePage();
        }
    };

    parserTimer = new Timer();
    parserTimer.scheduleAtFixedRate(parserTimerTask, 0, PERIOD);
}

@Override
public void contextDestroyed(ServletContextEvent arg0) {
    Logger logger = Logger.getRootLogger();
    logger.info("DETECT TOMCAT SERVER IS GOING TO SHUT DOWN");
    logger.info("CANCEL TIMER TASK AND TIMER");

    otsParserTimerTask.cancel();

    otsParserTimer.cancel();

    logger.info("CANCELING COMPLETE");
}

@Override
public void contextInitialized(ServletContextEvent arg0) {

}

Now my new question:

I cancel TimerTask first then Timer, is this correct?
Are there other thing I should do?

Thanks!
UPDATE
It doesn't work. I put some logging statement in the contextDestroyed() method, after I shutdown Tomcat, the log file only has the following:
PowderGodAppWebService -> [07 Feb 2012 04:09:46 PM]  INFO (PowderGodAppWebService.java:45):: DETECT TOMCAT SERVER IS GOING TO SHUT DOWN
PowderGodAppWebService -> [07 Feb 2012 04:09:46 PM]  INFO (PowderGodAppWebService.java:46):: CANCEL TIMER TASK AND TIMER
CANCELING COMPLETE is not there.
I also checked processes that are running (I'm not a Linux expert so I just use Mac's Activity Monitor.

Make sure no java process is running
Start Tomcat, note the PID of that java process
Stop Tomcat
Found the Tomcat process is gone
Start Tomcat, note the PID of that java process
Deploy my war file
Sample the process, see [Timer-0] thread is there
Shutdown Tomcat
Found that the process is still there
Sample the process
See [Timer-0] is still there

FIXED
I changed my code to parserTimer = new Timer(true); so that my timer runs as a daemon thread because the contextDestroyed() gets called after Tomcat actually shuts down.
"All servlets and filters will have been destroyed before any ServletContextListeners are notified of context destruction."
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContextListener.html
Comment: TimerTask#cancel won't interrupt the task if it is currently running - it'll just make sure that it'll never run again - but apart from that, I'd say that you'd be fine with that
Comment: Shouldn't those cancels be in contextDestroyed() ?
Comment: Yes... I guess it's time for bed, thanks for pointing out!
Comment: since you used `parserTimer = new Timer(true);` does that mean the parser will continue running as a background process even after Tomcat stops? Or does it mean that it blocks Tomcat from stopping until it is finished? I'm in a very similar situation - hoping to reliably shutdown a thread when Tomcat is being stopped, and I'm not sure what works.
Answer: Do not use Timer in an Java EE environment! If the task throws a runtime exception, then the whole Timer is killed and won't run anymore. You basically needs to restart the whole server to get it to run again. Also, it is sensitive to changes in the system clock.
Use ScheduledExecutorService instead. It's not sensitive to exceptions thrown in tasks nor to changes in system clock. You can shutdown it by its shutdownNow() method.
Here's an example of how the entire ServletContextListener implementation can look like (note: no registration in web.xml required thanks to the new @WebListener annotation):
@WebListener
public class BackgroundJobManager implements ServletContextListener {

    private ScheduledExecutorService scheduler;

    @Override
    public void contextInitialized(ServletContextEvent event) {
        scheduler = Executors.newSingleThreadScheduledExecutor();
        scheduler.scheduleAtFixedRate(new YourParsingJob(), 0, 5, TimeUnit.HOUR);
    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        scheduler.shutdownNow();
    }

}

Comment: Wow! This answer was *amazingly* helpful. Thank you very much. For other readers, one point of clarification… The `new YourParsingJob()` should be an instance of the interface [Runnable](http://docs.oracle.com/javase/7/docs/api/java/lang/Runnable.html) as the JavaDoc explains.
Comment: @rekiem87: if you have EJB at hands, use `@Schedule` instead. Examples: http://stackoverflow.com/a/8482933 and http://stackoverflow.com/q/7499769 (bottom part). Current question is about Tomcat which doesn't have JPA and EJB. Be careful in finding answers ...
Comment: Small correction, Tomcat project comes with TomEE for enterprise. It has prepackaged CDI, EJB and JPA. (see http://openejb.apache.org/apache-tomee.html)
Comment: @user1697575: TomEE !== Tomcat.
Comment: And what happend if i need access to some resource like an `EntityManager`, can you have acces to this or you have to use `@Singleton` with `@Startup` anntotation?
Comment: To clarify, [Apache TomEE](https://en.wikipedia.org/wiki/Apache_TomEE) is a *superset* of [Apache Tomcat](https://en.wikipedia.org/wiki/Apache_Tomcat), thus the cute choice of name. The idea was to start with Tomcat (for Servlets & JSP, and web server), then add the necessary Java EE related libraries to meet the requirements of the spec for [Java EE Web Profile](https://en.wikipedia.org/wiki/Java_Platform,_Enterprise_Edition#Web_profile) (a subset of full Java EE). As of 2017-05, TomEE 7.0.3 is based on Tomcat 8.5.11. In other words: `( Tomcat + some Java EE components ) = TomEE`
Answer: The servlets destroy method is called as the servlet is about to be unloaded. You could cancel the timer from within there, providing that you altered the scope of the parserTimer itself to make it an instance variable. I don't see a problem with that provided that you access it only from within init and destroy.
The servlet engine is free to unload the servlet whenever it sees fit, but in pratice I'm only ever seen it called as the servlet engine is stopped - other people may have other experiences of this though that might prove me wrong.
Answer: Try to use framework for scheduling.
If you adapt Spring Framework you could use the build in scheduling capabilities.
When scheduling with Spring I had never any problem stopping application server.
Answer: Put parseTimer.purge() in your onContetexyDestroyed.It will remove all the timers in the queue if they exist.


Variably modified type in C language

Question: Can anyone explain what a variably modified type is?

If we have an array a[n] and n is not known at compile time then a is a VLA.  Given an array b[c][d] where c and d are not known until runtime implies b is a VLA, right?

In my book they have said that a variably modified type contains a VLA.
That's it; nothing more.
How do I create a pointer to a variably modified type?
Answer: A variably-modified type is the type of a VLA (variable length array). There's a similar type in a structure with a flexible array member, but I don't plan to discuss flexible array members further.
The key point about a VLA is that the dimension of an array is not known until run-time.  Classically, in C89 and before the standard, all dimensions of an array except the first had to be a known constant value at compile time (and the first dimension could be specified as int a[] or int b[][SIZE] or int c[][SIZE1][SIZE2] where the sizes are constants).
void some_function(int n)
{
    int a[n];
    int c = n+1;
    int d = n+2;
    int b[c][d];
    another_function(n, a, c, d, b);
    ...
}

void another_function(int n, int a[n], int c, int d, int b[c][d])
{
    ...
}

Both a and b are variable length arrays.  Prior to C99, you could not have written some_function() like that; the size of the arrays would have to be known at compile time as compile-time constants.  Similarly, the notation for another_function() would not have been legal before C99.
You could, and still can (for reasons of backwards compatibility, if nothing else) write a moderate simulation of another_function():
enum { FIXED_SIZE = 32 };

void yet_another_function(int a[], int n, int b[][FIXED_SIZE], int c)
{
    ...
}

This isn't a perfect simulation because the FIXED_SIZE is a fixed size, but the pure C99 VLA code has a variable dimension there.  Old code would often, therefore, use a FIXED_SIZE that was large enough for the worst case.
Inside another_function(), the names a and b are basically pointers to variably modified types.
Otherwise, you do it the same as for a fixed size array:
int z[FIXED_SIZE];
int (*z_pointer)[FIXED_SIZE] = &z;

int v[n];
int (*v_pointer)[n] = &v;

Comment: A structure with a flexible array member is not a variably modified type. See N1570 6.7.6p3 for the definition.
Comment: OK; I'd not checked -- modified to match your comment.  Thanks!
Comment: @KeithThompson Does it mean that a variably modified type is a VLA _only_?
Comment: Consider: `sizeof( int[R][C])` . Do you see any array in there? I don't. That is VMT. Variably Modified Type.
Comment: @ChefGladiator— I wasn't writing the C standard; such precision was not required.  Yes, in `sizeof(int[R][C])` you have a VMT, but its size is the size that an object of the VMT would have, and the object would be a VLA, so colloquially it is an array (type).
Comment: Then please change your first sentence. Kind regards.
Answer: VLA == Variable Length Array
Variable Length Arrays were introduced in the C99 spec to allow for things like this:
int someArraySize;
int myArray[someArraySize];

Variably Modified type is the type of a Variable Length Array. Thus, a Variably Modified type CONTAINS a VLA. In the case of your example of b[c][d] where c and d are not known until run time, b is a Variably Modified type that happens to be a Variable Length multi-dimensional array. b[c][d] is a variable length array of variable length arrays-- phew, what a mouthful.
Here is a great source I found that describes these VLAs and the Variably Modified type with examples:
http://gustedt.wordpress.com/2011/01/09/dont-be-afraid-of-variably-modified-types/
Comment: Almost right.  VMT can not "contain" an array. VMT != VLA. Yes that Gustedt text explains VMTs and VLAs rather well.
Answer: VMT is a type usually used to allocate heap blocks of VMT size. The pointer to VMT is not VLA.
#include <stdlib.h>

int main( const int argc, char * const argv[argc])
{
    typedef char * VMT [argc] ;

    VMT * vmt_ptr = malloc(sizeof(VMT));

    * vmt_ptr[0] = argv[0] ;

    free(vmt_ptr);

   return 42;
}

Some people prefer to call them "VLA on the heap". For some people that defeats the purpose of VLAs.  For them, VLA is a small(er) array on the stack.
 { // VMT is a type of VLA
   VMT VLA  ;
       VLA[0] = argv[0] ;
 }

No mem leak here. But then some people are wondering what the fuss is all about.
{
    typedef char * VMT [argc] ;

    VMT * vmt_ptr = alloca(sizeof(VMT));

    * vmt_ptr[0] = argv[0] ;
}

They are using alloca, using the VMTs in the process. Effectively creating VMT pointers to blocks allocated on stack space.
There are valid use cases for all three snippets. I hope also showing what are the VMT's.
Mandatory Godbolt: https://godbolt.org/z/zGe4K5hez
Comment: (1) `alloca` is mostly obsolete, you should simply use VLAs instead. Using `alloca` as you show is completely useless. (2) Your `vmt_ptr` variable is a pointer to an array (yes, this is possible, and it can be very very useful actually), so you should write `(*vmt_ptr)[0]` to access the first element. Here, this is the same just because you ask for index 0.

Variably modified type in C language


How do I move files whose name changes daily to AWS S3 bucket using AWS CLI?

Question: I have script that runs daily and saves a CSV file with daily time stamp below is the AWS CLI command for moving a file to S3 bucket and then delete it from source I am using.
aws s3 mv /path/NW_test_Export_03_05_2020_14_37_24.csv s3://bucekt-name/folder/ --acl public-read-write

I want to automate this daily moving of file to S3 bucket using a Cron job. How do I make the file name variable in the AWS CLI command?
Answer: Ok by trial and error the below command is working perfectly for me.
aws s3 mv /path-to-file/ s3://bucekt-name/folder/ --exclude "*" --include "*.csv" --recursive


How do the 3-day Guest Passes work?

Question: I want to give a guest pass to my friend so he can roll some Nuclear Dawn with me this weekend, but when should I send it?  If I give it to him now (Wednesday), will the 3-day clock start ticking immediately (if done direct to a Steam account), or does he need to do some activation?  Can he "pre-load" it before the timer starts?
Comment: [Related question](http://gaming.stackexchange.com/questions/22821/do-guest-passes-have-an-expiration-date), but doesn't address how the actual "license timer" works.
Answer: The person is unable to download the game until after they receive the 3 day pass. By receiving the pass, they can download the game and can play the game after the download (and any subsequent patching) is done. The timer starts the moment they choose to activate the pass, so it would be best to let the game download overnight if they have a slow computer and plan to play all day the following day.
Comment: Oh my you're right, I totally jumped the gun there. :3 But I remade my post so I hope this clears things up. XD
Comment: That doesn't answer the question at all.
Comment: Looking good, does activation happen before download can begin?
Comment: @Kote The download is the activation; by starting the download you activate the game and the pass.
Answer: I took a look at forums that ask your question and it looks like it starts when they download the game from the guest pass. Hope you enjoy playing!
http://muslimgamer.com/forums/viewtopic.php?f=24&t=1241&start=30

How do the 3-day Guest Passes work?


How do I turn the heat down in my house?

Question: I just moved into this house. It still has the radiator unit but it's too hot. How do I turn the heat down? I turned the thermostat off, but it's still hot: does that mean I need a new thermostat?
Answer: With a hot water system you can have more than one zone. Check if you have other thermostats in the house.
Comment: If that is the correct thermostat, I think a stuck control valve is more likely than a bad thermostat. Could be either, or broken wiring, or something else depending on the specifics of your system.


Sims 3 DLC, do I have to use the expansion packs in the bundle?

Question: If I purchase The Sims 3 bundle from Steam, and, say, I don't want to use the Pets EP, can I turn that expansion pack off?
Also: can I use the same cheat codes I would use if I had installed The Sims 3 with the disc?
This is my first time using Steam, and the only reason I'm interested in it is because of the great deal they have for The Sims.
Answer: There is a way to disable The Sims 3 Expansion Packs, but it's weirdly and unnecessarily complicated. Moreover, in all probability your saved games will not work afterwards.
This was originally written for Windows 7, but the same steps more or less apply in 8 and 10.

Shut down The Sims 3 completely.
In your Steam Library, right-click The Sims 3 and choose Properties.
In the ['DLC' tab], untick the EP you don't want to use any more then close the Properties window.
Create a System Restore Point (in Windows, right-click My Computer or your version thereof; select Properties; select System Protection;
  click "Create").

[As extra precaution, backup your registry and The Sims 3 saved games here! Disabling EP's is essentially the same as disabling mods (in other games), and your saved games could become useless.]

In Windows, use your "Find" charm or "Run" box to run the program regedit.exe.
In Registry Editor, go to File > Export and save the file to somewhere you can find it easily. This is in case something goes
  wrong.
In Registry Editor, navigate to your Sims 3 registry keys. This is normally found under: HKEY_LOCAL_MACHINE > SOFTWARE > Wow6432Node > Sims(Steam)

There you will see a list of all [Expansion Packs] and [Stuff Packs] that you have installed. Right-click the EP you want to uninstall, and choose
  "Delete".
After this, your game should start normally.

For details on restoring your registry, if it got messed up, see this page.

Alternatively - and this is pure guesswork - if you don't want to edit your Windows registry, and bandwidth and data limits are not keeping you back, you can uninstall the game after step 3, and Steam should redownload only the files of the EP's you have selected.
I guess you can even make a backup of the game folder, uninstall the game through Steam, move the backup to its original position, and let Steam reinstall. I don't think it will even be necessary to remove the folder of the EP you don't want, since it's not selected and should not load (but you can to save space, of course).
(NB I'm not sure these non-registry-altering solutions will work, and I can't test it. If they do, please leave a comment with your experience. It seems to have been done successfully here, however)

As for the cheats, they still work.
Open the console by clicking Control+Shift+C
And type in any of the cheats. Like these:

kaching = Adds 1,000 simoleons
motherlode = Adds 50,000 simoleons
familyfunds x = familyfunds
  only goes up to 99,999,999.

For some you'll have to enter testingcheatsenabled true for them to work:

moveobjects on / off = Allows you to move or delete any object.
freerealestate = When building a house in World Edit , this cheats
  ignores the the price of the lot. Making the lot free.

More can be found on the linked page.


All files under Home folder are write protected by unknown username

Question: Using Ubuntu 16.04, I gave all the permission of my home folder to an unknown username and now I am unable to write to the files under my home folder including Documents, Downloads etc...
How do I give back permission to the current user account?
Comment: What *exactly* did you do to change the ownership of the home directory? What does `/var/www/html` (mind the slash direction!) have to do with your user account's home directory. Please [edit] your post when you want to clarify something or add information. It's best to have everything relevant in one place. Additionally, comments may be deleted for various reasons. Thanks.
Comment: what exactly did you do to cause the problem?
Comment: When i tried to give permission of Apache server to Wordpress to create directory in \var\www\html  .
Comment: @devius: No. This question is about **ownership** while your linked question is about **access control flags**.
Answer: To change the ownership of a directory recursively run
sudo chown -R USER: PATH

and replace USER with the user name and PATH with the path of the directory tree in question (here: the home directory).


How do I initially load an observable array asynchronously

Question: This is my viewmodel:
function PitchViewModel() {
var self = this;
self.selectedPitch = ko.observable();
self.pitches = ko.computed(function () {
    return $.getJSON("/api/Pitch", function (data) {
        var obs = ko.mapping.fromJS([])
        ko.mapping.fromJS(data, {}, obs) ;
       // seems to work, but somehow observables are changed back into objects after binding
        return obs();
    })}, this).extend({ asyncArray: [{ Id: 1, PitchNumber: 1, Length: 0, Width: 0, HasElectricity: false, Name: "Test" }] });

// behaviours
self.selectPitch = function () {
    console.log("inside selectPitch");
    self.selectedPitch(this);
}

}
I'm using an async extender as shown here: asynchronous computed observables
adapted a little bit for observablearrays like so (in line 3):
var plainObservable = ko.observableArray(initialValue), currentDeferred;

In my view i do this:
 var domNode = $('#content')[0];
 var pitchViewModel = new PitchViewModel();
 ko.applyBindings(pitchViewModel, domNode);

It seems to work fine. The binding happens asynchronously. Pretty cool so far.

However!

When (in Chrome) I put a breakpoint on
return obs();

the obs()  function is an observableArray and has objects with observable properties.
But when I break on
console.log("inside selectPitch");

and inspect self.pitches() it has become a 'normal' array with objects the have 'normal' (not observable) properties.
What am I missing here?

BTW: I have tried using a an observableArray for self.pitches instead of the computable. But then the ko.applybindings happens before the initialization of the observable array, leading to binding errors.
Thanks for your help.
Frans
Answer: I have not tried to run your code but what I SUSPECT happens is that the extender uses the result of the ajax call returned as a Deferred/Promise. Your processing of the results happens in the callback function and is not used for anything afterwards.
You should not mix Deferreds and callbacks like this. Try the following instead:
self.pitches = ko.computed(function () {
    return $.getJSON("/api/Pitch")
        .then(function(data) {
            return ko.mapping.fromJS(data);
        });
}).extend({ asyncArray: [...] });


Leavebuster while playing with bots only

Question: If you play a custom league of legends game (hosted by you and passwords and such), but you are only playing with bots, will you get leavebusted if you leave that game? Sometimes I just want to have a 20 minute game for practice, but I would not like to get banned.
Answer: If you go to the support FAQ for leavebuster you can read:

I left a custom/tutorial game and I got a warning that my account may be temporarily suspended? I thought custom games didn't count?
They don't. This message will appear every time you leave a game, but custom and tutorial games will not earn you a Leaver Level. Leaverbuster only applies to games you have to queue up for = Normal, Ranked, Co-Op Vs AI, Dominion, etc.

So custom game does not count.
Comment: Oh crap I didn't see that, that answered my question. Thanks :)
Comment: Is that why people leave ARAM and dont even care? Does reports in customs game even count ?


Secure boot ON/OFF while installing ubuntu 16.04 alongside windows 10

Question: I wanna dual boot ubuntu 16 alongside windows 10. As a part of installation process its asking a checkbox to Turn Off Secure boot.
Should I click it or not. Please help.
Which is safe? I want to run both OS'es in my laptop.
Answer: you should check it. it let the kernel modules to load. ubuntu 16.04 come with the secure boot enabled because of EFI_SECURE_BOOT_SIG_ENFORCE in linux kernel 4.4.0-20 and later. you can later disable the secure boot when ever you want. Don't worry disabling the secure boot will not harm your windows. i have dual booted my system giving the key.
you may later face some problems after installing the ubuntu 16.04. you may refer nvidi-361 login loop ubuntu 16.04 lts
Comment: Now I want to load windows automatically after startup. Do i need to enable TURN OFF SECURE BOOT NOW?
Comment: You said it won't harm Windows. What I want to know is if disabling Secure Boot along the lines of this tutorial for Ubuntu will render the existing Ubuntu install unbootable: https://wiki.ubuntu.com/UEFI/SecureBoot/DKMS. This would be an after the fact change where the user has data they want to preserve on the Ubuntu OS but disable Secure Boot which was left enabled by default at install time.


how to add browser-sync in gulp-4

Question: //Importing gulp files to variables
    const { src , dest , watch , series , parallel } = require('gulp');
    const autoprefixer = require('autoprefixer');
    const cssnano = require('cssnano');
    const concat = require('gulp-concat');
    const postcss = require('gulp-postcss');
    const replace = require('gulp-replace');
    const sass = require('gulp-sass');
    const sourcemaps = require('gulp-sourcemaps');
    const uglify = require('gulp-uglify');
    const browserSync = require ('browser-sync').create();

// File path variables in my projects folder
    const files = {
    scsspath:'assets/scss/**/*.scss' ,
    jspath:'assets/js/**/*.js'}

//Sass Task
    function scssTask(){
    return src(files.scsspath)
    .pipe(sourcemaps.init())
    .pipe(sass())
    .pipe(postcss([autoprefixer(), cssnano()]))
    .pipe(sourcemaps.write('.'))
    .pipe(dest('assets/css'))
    .pipe(browsersync.stream());}

//JsTask
    function jsTask(){
    return src(files.jspath)
   .pipe(concat('all.js'))
   .pipe(uglify())
   .pipe(dest('assets/js')).pipe(browsersync.stream());}

//WatchTask
   function watchTask(){
   watch([files.scsspath , files.jspath], parallel(scssTask,jsTask));}

//DefaultTask
  //I don't know how to use browser-sync in gulp-4
   exports.default = series(parallel(scssTask,jsTask) , cashBustTask ,
   watchTask,browsersync);

Comment: Please clarify your question, so that people who see this have a chance of understanding where you need help.
Comment: You need a browser-sync task too.  And you used `const browserSync...` so change your references to `browserSync` from `browsersync`.
Answer: Create a separate task for browser-sync. Here's an example of how I've set this up:
const bs = require('browser-sync').create();
// Other inputs used with browser-sync
const { src, dest, watch } = require('gulp');
const sass = require('gulp-sass');

function browserSync() {
  // Run serveSass function when starting the dev server to make sure the SCSS & dev CSS are the same
  serveSass();

  bs.init({
    // Dev server will run at localhost:8080
    port: 8080,
    server: {
      // I'm using 'src' as my base directory
      baseDir: 'src',
    },
  });

  // These watch for changes to files and reload in the browser
  watch('src/*.html').on('change', bs.reload);
  watch('src/scss/*.scss', serveSass);
  watch('src/js/*.js').on('change', bs.reload);
}

// This compiles Sass when running browser-sync and reloads the CSS
function serveSass() {
  // My dev Sass files are found in 'src/scss/'
  return src('src/scss/*.scss')
    .pipe(sass())
    // My dev CSS files are found in 'src/css/'
    .pipe(dest('src/css))
    .pipe(bs.stream());
}

// Then I run 'gulp serve' in the terminal to start browser-sync and my dev server
exports.serve = browserSync;

My full Gulp setup is here if you want more context.
Answer: Quick solution:
Add a function to trigger BrowserSync:
function reload(){
    browserSync.reload();
}

Modify your watchTask() function to:
function watchTask(){
    browserSync.init({
        server: { baseDir: "./dist" }
    });
    gulp.watch([files.scsspath , files.jspath], parallel(scssTask,jsTask,reload));
}

Modify your exports to:
exports.default = watchTask;

Answer: I found this guide to upgrade gulp 4, that explains that gulp.series or gulp.parallel needs to be used. Example:
var gulp        = require('gulp');
var browserSync = require('browser-sync').create();

gulp.task('browserSyncReload', gulp.series( function(done) {
  browserSync.reload();
  done();
}));

gulp.task('default', gulp.series( function(done) {
  browserSync.init({
      notify: false,
      proxy: "127.0.0.1:5003/nl"
  });
  gulp.watch("app/templates/**/*.", gulp.series('browserSyncReload'));
  gulp.watch("app/static/**/*.*", gulp.series('browserSyncReload'));
  done();
}));

how to add browser-sync in gulp-4


Save the input of loop without creating 3 different variables

Question: for (var i = 0; i < 3; i++) {
            var rgb = Math.floor(Math.random() * 255 + 1);
            var randomRGB = ("rgb"+"("+rgb+","+rgb+","+rgb+")");
            console.log (randomRGB);
        }

I am getting this as input :
rgb(165,165,165)
rgb(195,195,195)
rgb(231,231,231)

what i would like to get is this instead :
rgb(165, 195, 231)

What am i doing wrong?
Answer: var color = [];
for (var i = 0; i < 3; i++) {
    var rand = Math.floor(Math.random() * 255 + 1);
    color.push(rand);
}
var randomRGB = ("rgb"+"("+ color.join(",") +")");
console.log (randomRGB);

Comment: `var randomRGB = ("rgb"+"("+ color +")");` This is enough. When converting an array to primitive, the `toString()` of array's prototype would use join for you..
Comment: @RajaprabhuAravindasamy Wow, all this time I really didn't know array's prototype was using join. That could have saved a lot of code for me. Thank you for the info.
Answer:   var r = Math.floor(Math.random() * 255 + 1);
  var g = Math.floor(Math.random() * 255 + 1);
  var b = Math.floor(Math.random() * 255 + 1);
  var randomRGB = "rgb(" + r + "," + g + "," + b + ")";
  console.log (randomRGB);

You need three variables if you want to store three values.
Answer: Try this:
var r = Math.floor(Math.random() * 255 + 1);
var g = Math.floor(Math.random() * 255 + 1);
var b = Math.floor(Math.random() * 255 + 1);
var randomRGB = "rgb(" + r + "," + g + "," + b + ")";
console.log (randomRGB);

Or if you do want to avoid creating variable:
var randomRGB = "rgb(" + Math.floor(Math.random() * 255 + 1) + "," + Math.floor(Math.random() * 255 + 1) + "," + Math.floor(Math.random() * 255 + 1) + ")";

Answer: You can do this using an array:
for (var i = 0; i < 3; i++) {
    var rgb = [];
    for (var i = 0; i < 3; i++){
        rgb.push(Math.floor(Math.random() * 255 + 1));
    }
    var randomRGB = ("rgb"+"("+ rgb.join(",") +")");
    console.log (randomRGB);
}

This way you're technically using one variable (an array of integer values) to set the RGB values, it's running a for loop to create the rgb array (or this can be done on initialization without using a for loop, but I feel this looks neater). This also means the variable is being re-initialized each time it runs the outer loop so you'll end up with different RGB's for the 3 times the outer loop is run.
Answer: You can do it without a looping statement,
var getRgb = () => Math.floor(Math.random() * 255 + 1);
var randomRGB = ("rgb"+"("+ getRgb() +","+ getRgb() + ","+ getRgb() +")");
console.log (randomRGB);

If you want to do it by iteration then do like,
var getRgb = () => Math.floor(Math.random() * 255 + 1);
var randomRGB = "rgb(" + (["","",""].map(getRgb) + ")"
console.log (randomRGB);

Comment: But if i wanted to do it via a loop statement how do i go about it?
Comment: @Yunislav `map` uses looping statement inside of its implementation. If you want to use a for loop for sure then please prefer answers below.


Git commits linked to wrong user on Github, correct in git log output

Question: I have been using git for some months now. I am working primarily on my own, working on a repository primarily of .html and .txt files with a little (terrible) python. My coding skills are average at best, and I have been using linux & the unix command line for 2 years at a fairly basic level.
While I was visiting my parents in the UK, I installed git on their Mac Mini to continue working on my repository. I then set up a second repo for a different purpose and used git config in that repo to set up local values for user.email user.name etc. I set up a second github account using a different email address and pushed to it once.
Since then, every time I push from my 1st git repository on my own computer, the commits are listed as being by the second user set up on the mac, though I never pushed there from my own computers. The output of git log on my local repo has the author as what it ought to be "Author: pocketapocketa ", but github has it as "Christopher-Rozruch". (In fact, looking over the commit history, the "Christopher-Rozruch" commits pre-date my use of the Mac Mini and the setting up of the Christopher-Rozruch identity in any form by a week or so.)
I have searched for this problem but only found issues involving changed config files, multiple accounts on the same computer etc. Github's own help on the topic discusses conflicts involving the same e-mail address associated with different accounts, which is not the case here.
I have found a script to retrospectively change the git history if I decide to do this (nobody else is working on the project), but I would like to understand why this has happened.
I have pushed to the primary repo in question from 2 computers in this time: one running on a MacBook, and one on Debian 8. The git version on Debian from which I have most recently pushed is 2.1.4. The others should be similar. The problem has been the same on each.
Can anyone help?
Answer: GitHub associates commits to GitHub users by the email used in the commit, see here.
Looking at your repository's history, we see that you have two different commit emails being used:
Author: pocketapocketa <email@example.com>

This one seems to be associated with the Christopher-Rozruch user.
Author: pocketapocketa <firstname.lastname@example.com>

This one seems to be associated with the pocketapocketa user.
Check your local settings, and be sure you have the appropriate email set. Additionally, if you own both of these accounts, you can unlink the email from one and assign it to the other if you want (this will clear up the GitHub history as well).
Comment: Thank you. I had glanced over the Christopher-Rozruch user and seen that I had indeed set the **primary** e-mail to a not-yet-used email address. I had thought I had avoided using the e-mail linked to my other account but I had used it as a backup until I was confident with the passphrase of the new e-mail etc. My bad. Changing the local e-mail changed the latest commit to the correct user. Deleting the common e-mail from the Christopher-Rozruch account retrospectively changed the commit history.


Titanium remote imageView doesn't update

Question: I am making sort of a news app for a company, and i need my app to load an image, but the image in the url changes if you update the news, but if I update it, and I load the app again, the image still shows the previous image.
This is my code;
<code>    imageremote = Ti.UI.createImageView({
         image: "http://www.mydomain.com/"+company+"/image0001.png"
    });

    win.add(imageremote);
    win.open();
</code>
Answer: try adding a unique param on the url so the url is not cached
<code>imageremote = Ti.UI.createImageView({
     image: "http://www.mydomain.com/"+company+"/image0001.png" + "?t=" + new Date()
});

win.add(imageremote);
win.open();
</code>
Comment: After 2 days of searching on google, I came across this answer. Thanks @Aaron. Your answer saved my day. This needs +1.


Lazy loading images works only sometimes, sometimes it doesn't

Question: I'm using lazy loading images based on this question. I'm implementing a search function that, when the user enters a keyword, the application will do a request and parse the result using SAX and then place the data into a ListView. Sometimes the images can be loaded into ImageViews of the ListView rows but sometimes it will load only one or two images and the application crashes.
Below is my LogCat output:
05-16 16:37:37.414: ERROR/AndroidRuntime(620): FATAL EXCEPTION: Thread-11
05-16 16:37:37.414: ERROR/AndroidRuntime(620): java.lang.NullPointerException
05-16 16:37:37.414: ERROR/AndroidRuntime(620):     at com.TPLibrary.Search.ImageLoader.getBitmap(ImageLoader.java:71)
05-16 16:37:37.414: ERROR/AndroidRuntime(620):     at com.TPLibrary.Search.ImageLoader.access$0(ImageLoader.java:68)
05-16 16:37:37.414: ERROR/AndroidRuntime(620):     at com.TPLibrary.Search.ImageLoader$PhotosLoader.run(ImageLoader.java:173)

Below is where the errors are occuring at:
private Bitmap getBitmap(String url) { // line 68
    //I identify images by hashcode. Not a perfect solution, but ok for the demo
    String filename = String.valueOf(url.hashCode()); // line 71
    File f = new File(cacheDir, filename);

    //from SD cache
    Bitmap b = decodeFile(f);
    if (b != null)
        return b;

    //from web
    try {
        Bitmap bitmap = null;
        InputStream is = new URL(url).openStream();
        OutputStream os = new FileOutputStream(f);
        Utils.CopyStream(is, os);
        os.close();
        bitmap = decodeFile(f);
        return bitmap;
    } catch (Exception ex){
        ex.printStackTrace();
        return null;
    }
}

class PhotosLoader extends Thread {
    public void run() {
        try {
            while(true)
            {
                //thread waits until there are any images to load in the queue
                if (photosQueue.photosToLoad.size() == 0)
                    synchronized(photosQueue.photosToLoad) {
                        photosQueue.photosToLoad.wait();
                    }
                if (photosQueue.photosToLoad.size() != 0) {
                    PhotoToLoad photoToLoad;
                    synchronized(photosQueue.photosToLoad) {
                        photoToLoad=photosQueue.photosToLoad.pop();
                    }
                    Bitmap bmp = getBitmap(photoToLoad.url); // line 173
                    cache.put(photoToLoad.url, bmp);
                    Object tag = photoToLoad.imageView.getTag();
                    if (tag != null && ((String)tag).equals(photoToLoad.url)){
                        BitmapDisplayer bd =
                            new BitmapDisplayer(bmp, photoToLoad.imageView);
                        Activity a = (Activity)photoToLoad.imageView.getContext();
                        a.runOnUiThread(bd);
                    }
                }
                if (Thread.interrupted())
                    break;
            }
        } catch (InterruptedException e) {
            //allow thread to exit
        }
    }
}

EDIT
I have tracked down the NullPointerException that comes from the PhotoToLoad class below:
private class PhotoToLoad {
    public String url;
    public ImageView imageView;
    public PhotoToLoad(String u, ImageView i) {
        url = u;
        imageView = i;
    }
}

How can I solve the problem?
Answer: It seems that you pass null to this method. Make sure that you handle null appropriately, or make sure you don't pass null there (first is better ;)).

Your error log indicates, the NPE occurs in
String filename=String.valueOf(url.hashCode());

So, url is null at this point. So Either you integrate a check like
if (url == null) {
    Log.w("null has been passed to getBitmap()");
    return null;
}

or you have a look on every call where you pass null to this method making it crash.
Comment: I added some more explanations to my post. I hope it is clearer now.
Comment: Thanks. I solved the issue. I just replace the null image with a drawable item and it wont crash anymore. Thanks to you and Octcavion!
Answer: Remove return null from your catch() block because this might be throwing an Exception and the Bitmap is getting NULL object.
Comment: Depends on what you what to happen.
If it's relly critical, let the program crash with a message to tell to the dev. Or you handle it and give the user maybe some feedback what he or she did wrong. There are lots of different possibilities...
Comment: What I want is that the application will download the images and place them into the ImageViews. Instead of crashing.


e.preventDefault() is not working in IE8

Question: I'm working on a piece of code to prevent a Telerik Grid from contacting the server to save a duplicate piece of data.  Here is what I have thus far.
View
@(Html.Telerik().Grid<CategoryModel.CategoryUnitsModel>()
                    .Name("categoryunits-grid")
                    .DataKeys(keys =>
                    {
                        keys.Add(x => x.Id);
                        keys.Add(x => x.CategoryId);
                        keys.Add(x => x.UnitId);
                    })
                    .DataBinding(dataBinding =>
                    {
                        dataBinding.Ajax()
                            .Select("CategoryUnitsList", "Category", new { categoryId = Model.Id })
                            .Insert("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
                            .Update("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
                            .Delete("CategoryUnitsDelete", "Category", new { categoryId = Model.Id });
                    })
                    .Columns(columns =>
                    {
                        columns.Bound(x => x.UnitId)
                            .Visible(false);
                        columns.Bound(x => x.UnitText);
                        columns.Command(commands =>
                        {
                            commands.Edit();
                            commands.Delete();
                        })
                       .Width(100);
                    })
                    .ToolBar(commands => commands.Insert())
                    .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                    .ClientEvents(events => events.OnRowDataBound("onRowDataBound"))
                    .ClientEvents(events => events.OnSave("onSave"))
                    .EnableCustomBinding(true))

Controller
[HttpPost, GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsList(GridCommand command, int categoryId)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var categoryUnits = _categoryService.GetCategoryUnits(categoryId, command.Page - 1 , command.PageSize);
        var categoryUnitsModel = PrepareCategoryUnitsModel(categoryUnits);

        var model = new GridModel<CategoryModel.CategoryUnitsModel>
        {
            Data = categoryUnitsModel,
            Total = categoryUnitsModel.Count
        };

        return new JsonResult
        {
            Data = model
        };
    }

    public ActionResult CheckForCategoryUnit(int categoryId, int unitId)
    {
        var categoryUnit = _categoryService.GetCategoryUnitByCategoryIdAndUnitId(categoryId, unitId);
        return Json(categoryUnit != null, JsonRequestBehavior.AllowGet);
    }

    [GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsInsert(GridCommand command, CategoryModel.CategoryUnitsModel model)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var categoryUnit = new CategoryUnits
        {
            UnitId = Int32.Parse(model.UnitText),
            CategoryId = model.CategoryId
        };

        _categoryService.InsertCategoryUnit(categoryUnit);

        return CategoryUnitsList(command, model.CategoryId);
    }

At this point and time, I get an alert that I am hitting within my ajax.  However, the e.preventDefault() is not stopping the server from going on ahead and saving my data.  I've tried several different things concerning this issue, including:
return false, e.stop(), e.returnValue = false, e.stopPropagation().
None have worked thus far.  If anyone has any ideas, I'm open to them.  The combination of OS and browser I have are Windows XP and IE8.  Just adding in case that would help.  Thanks.
Kindest Regards,
Chad Johnson
Answer: Thanks for the responses so far.  I did try e.returnValue also but it failed like the others unfortuantely, Nathalie.
I've actually come up with a solution similar to what IronMan84 had.
Instead of using OnSave, I waited till during the Insert on my Controller to do the check for duplicate data.  Here is what I came up with:
Controller:
[GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsInsert(GridCommand command, CategoryModel.CategoryUnitsModel model)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var searchForEntry = _categoryService.GetCategoryUnitByCategoryIdAndUnitId(model.CategoryId, Int32.Parse(model.UnitText));
        if (searchForEntry != null)
        {
            var scriptText = "alert('Units may not be added twice for a category');";
            return JavaScript(scriptText);
        }

        var categoryUnit = new CategoryUnits
        {
            UnitId = Int32.Parse(model.UnitText),
            CategoryId = model.CategoryId
        };

        _categoryService.InsertCategoryUnit(categoryUnit);

        return CategoryUnitsList(command, model.CategoryId);
    }

I just returned a JavaScript action in the case of duplicate data.  Thanks all for the help.
Answer: I'm doing a similar check in my application as well, but I handled it in a different way. Instead of trying to do that alert on saving in AJAX I ended up doing it in my controller. If it found any duplicates it would set a value in the ViewData dictionary. Then, on my main page, I have an alert box that will show up with that value.
if(ViewData.ContainsKey("PopupMessage"))
    {
        var message = ViewData["PopupMessage"].ToString();

    }

Comment: I see what you mean.  The only issue I have with your solution is I don't want to refresh the page and show the popup immediately while keeping the grid's insert open.
Answer: There is no preventDefault on events in IE.
Look at this thread: preventdefault alternative for ie8
for IE you have to use: e.returnValue
(e.preventDefault) ? e.preventDefault() : e.returnValue = false;

Comment: I tried e.returnValue and am now receiving the following error:  Error: Array or arguments object expected
Answer: Okay guys, I came up with a completely different solution.  However, I do have one other issue that I want to ask about.
First off, here is what I did.  Instead of catching when I would repeat data, I instead removed that data from the dropdownlist so that the option never happens.  Aside from that, I dynamically load the dropdownlist now, thus keeping the data fresh and allowing me to keep from having duplicates.
View
var gridPageSize = EngineContext.Current.Resolve<Nop.Core.Domain.Common.AdminAreaSettings>().GridPageSize;

                @(Html.Telerik().Grid<CategoryModel.CategoryUnitsModel>()
                    .Name("categoryunits-grid")
                    .DataKeys(keys =>
                    {
                        keys.Add(x => x.Id);
                        keys.Add(x => x.CategoryId);
                        keys.Add(x => x.UnitId);
                    })
                    .DataBinding(dataBinding =>
                    {
                        dataBinding.Ajax()
                            .Select("CategoryUnitsList", "Category", new { categoryId = Model.Id })
                            .Insert("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
                            .Update("CategoryUnitsInsert", "Category", new { categoryId = Model.Id })
                            .Delete("CategoryUnitsDelete", "Category", new { categoryId = Model.Id });
                    })
                    .Columns(columns =>
                    {
                        columns.Bound(x => x.UnitId)
                            .Visible(false);
                        columns.Bound(x => x.UnitText);
                        columns.Command(commands =>
                        {
                            commands.Edit();
                            commands.Delete();
                        })
                        .Width(100);
                    })
                    .ToolBar(commands => commands.Insert())
                    .Pageable(settings => settings.PageSize(gridPageSize).Position(GridPagerPosition.Both))
                    .ClientEvents(events => events.OnRowDataBound("onRowDataBound"))
                    .ClientEvents(events => events.OnEdit("onEdit"))
                    .EnableCustomBinding(true))

EditorTemplates/CategoryUnit.cshtml
@using Telerik.Web.Mvc.UI;
@Html.Telerik().DropDownList().Name("UnitText")

My Model is the same.
Controller
[HttpPost, GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsList(GridCommand command, int categoryId)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var categoryUnits = _unitsService.GetCategoryUnits(categoryId, command.Page - 1, command.PageSize);
        var categoryUnitsModel = PrepareCategoryUnitsModel(categoryUnits);

        var model = new GridModel<CategoryModel.CategoryUnitsModel>
        {
            Data = categoryUnitsModel,
            Total = categoryUnitsModel.Count
        };

        return new JsonResult
        {
            Data = model
        };
    }

    public JsonResult LoadAvailableUnits(int categoryId)
    {
        var categoryUnits = _unitsService.GetAvailableUnits(categoryId);
        var categoryUnitsModel = PrepareAvailableUnitsInModel(categoryUnits);
        var returnData = new SelectList(categoryUnitsModel, "UnitId", "UnitText");
        return Json(returnData, JsonRequestBehavior.AllowGet);
    }

    [GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsInsert(GridCommand command, CategoryModel.CategoryUnitsModel model)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var searchForEntry = _unitsService.GetCategoryUnitByCategoryIdAndUnitId(model.CategoryId, Int32.Parse(model.UnitText));
        if (searchForEntry != null)
        {
            return CategoryUnitsList(command, model.CategoryId);
        }

        var categoryUnit = new CategoryUnits
        {
            UnitId = Int32.Parse(model.UnitText),
            CategoryId = model.CategoryId
        };

        _unitsService.InsertCategoryUnit(categoryUnit);

        return CategoryUnitsList(command, model.CategoryId);
    }

    [GridAction(EnableCustomBinding = true)]
    public ActionResult CategoryUnitsDelete(GridCommand command, CategoryModel.CategoryUnitsModel model, int id)
    {
        if (!_permissionService.Authorize(StandardPermissionProvider.ManageCatalog))
            return AccessDeniedView();

        var categoryId = model.CategoryId;
        _unitsService.DeleteCategoryUnit(model.CategoryId, id);

        return CategoryUnitsList(command, categoryId);
    }

My new issue is the paging does not work.  I'm unsure why it doesn't since I haven't really messed with it.  I suspect it's something to do with the way I'm loading the grid.  Any help would be appreciated.
Comment: Just a heads up: StackOverflow is not really a "forum", but rather a place for questions and answers. What you've done here is answered your own question with another question. If an answer has helped, but not completely, upvote, then add a comment (like this one) and ask for more information. Also update your original question (the one at the top of the page) with more details on the solution as it progresses. Thanks.
Comment: My apologies.  I'll mark this one as done and post another question.


jQuery Easing and Animation with CSS3 Styles

Question: I have a loop rotation animation going from '-1deg' to '1deg' and its a very choppy as im just changing the css, not animating.. Because if im correct you currently cannot animate rotation?
Is there any way I can use easing or am I wrong about animating css rotations?
jQuery('.foo').css('transform','rotate(-1deg)');
jQuery('.foo').css('transform','rotate(1deg)');

Thanks
Comment: You can animate rotation in CSS
Answer: Use two classes. Before and after. Add the after to the before and then use a transition e.g.
.before{
color: blue;
}

.after{
color: red;
-moz-transition:all 0.3s ease-out;
-webkit-transition:all 0.3s ease-out;
-o-transition:all 0.3s ease-out;
transition:all 0.3s ease-out;
}

Then on the element before:
<element class="before"></element>

The element after:
<element class="before after"></element>

Or something like that.
Answer: I hate to offer a plugin solution, but this one is very neat: http://ricostacruz.com/jquery.transit/
The syntax is identical to animate, eg:
$('.box').transition({ rotate: '45deg' }, 1000, 'ease-in');

Answer: If you can use @keyframes animation With css:
@-webkit-keyframes rotate {
  from {
    -webkit-transform: rotate(0deg);
  }
  to {
    -webkit-transform: rotate(360deg);
  }
}

You can see an example here http://jsfiddle.net/NBS7p/6/.
The compatibility http://caniuse.com/css-animation
And more tips about @keyframes http://css-tricks.com/snippets/css/keyframe-animation-syntax/
Answer: Try with CSS animation:
@-webkit-keyframes sway {
    0% {
        -webkit-transform: rotate(-1deg);
    }
    100% {
        -webkit-transform: rotate(1deg);
    }
}

.foo {
    -webkit-animation: sway 500ms ease-in-out infinite alternate;
}

Here's a working example: http://jsfiddle.net/SMPKd/1/


SQL Update statement with a column that has a space

Question: I have come across a situation where a column name in the SQL database is [column name] and I am trying to update it by that column.
Selecting is easy:  Select [column name] from MyDatabase.
I am trying to do this (parameterized):  UPDATE MyDatabase WHERE [column name] = @[column name]
the errors say:  column name does not exist:  @column
I cant just change the name in the database because it has been around for a while and it will most likely break a bunch of stuff.
Thank you all for your help!
Dave
Comment: UPDATE MyTable,not mYDb
Comment: in sqlserver I think is @variables,parameters cannot have spaces
Comment: If this is SQL-Server specific, please remove the MySQL tag.
Answer: The parametername does not have to match the column name.   (In fact, it cannot have spaces)
Just change your parameter name to not include a space.
 UPDATE MyDatabase WHERE [column name] = @columnname

Answer: Parameter/variables cannot have spaces in them. But then again they do not have to match column names.
You can have something like
UPDATE MyDatabase WHERE [column name] = @column_name

Answer: According to http://technet.microsoft.com/en-us/library/ms176027(v=sql.105).aspx :

Microsoft SQL Server does not recognize variable names and stored procedure parameters that are delimited. These types of identifiers must comply with the rules for regular identifiers.

This means you can't use @[variable name] in your code. You have to make do with @variable_name or similar.
Answer: UPDATE MyTable WHERE [column name] = @this_is_parameter_name


Re-use of deleted MySql keys

Question: Everyone says don't re-use deleted MySql keys. eg. Stack Overflow question: I want to reuse the gaps of the deleted rows
I have read all of the "expert" opinions but have not found a single answer that gives a valid reason why not. Everyone simply asks "why do you want to"?
Well here is a very good reason. If my users have a choice of entering URL mysite.com/person.php?id=123 or a URL mysite.com/person.php?id=123456789123, which one would they most likely prefer?
So can anyone give me a reason why re-using 123 would be a bad idea? I am actually not talking about one record. My records get added and deleted in blocks of several thousand. Updates are very rare and I am the only person who does updates.
There are also no dependencies. Nothing points to those records so there are no integrity issues with other tables.
When I want to add another block of records I will have a simple search routine that searches for the first block of unused record keys large enough to accommodate all of the records being added. Much the same way that hard disk space usage works.
Answer: Keys are usually used as unique identifiers, if they are used again, they stop being unique, and become shared. This is the logic behind the idea of not to reuse keys.
So I would suggest, split the key and the id of the user, to two fields, key the key as unique, and the id make it "choose-able" via a gap-finding function.
Before you split, create this new column called user-id, and copy to it the id (which is currently your key) of the users.
Then make this column unique, so that you prevent accidental cases of id reuse.
And you are "home" free.
Comment: My keys are totally unique. When I delete key 27 it is totally gone. No dependencies. The only possible dependency is people who bookmark that link. But they have never been able to do that because we regularly delete and reassign blocks of records so the numbers regularly change anyway.
Comment: So if you have good `constraints` on your tables, and you prevent accidental reuse of keys without them being purged before. There is no reason to reuse. However as I said, if you want to give your users a nice `id` don't use the `id` you use as a key, call it `user-id`
Comment: We will have 1.5M userids just as we currently have 1.5M "main keys". They will both just be random numbers so we are back where we started from.
Comment: But over time, those 1.5M userid will diverge from the id, and it will also allow you to grant access to cool user ids, such as 1111 which previously was allocated to some lost-soul

Re-use of deleted MySql keys


Type error in javascript

Question: I am using select2.js for highlighting a particular li which is being received as a response.
var cityCounter = -1;
var sul = $('.select2-search-choice');
$(".select2-input").keyup(function (e) {
    // TODO CODE
    // console.log($(this).val());
    var kKey = e.which;
    if (kKey === 40) {
        var sli = sul.$('li');
        var slen = sli.length;
        ++cityCounter;
        if (cityCounter > slen - 1) cityCounter = 0
        //sli[suggDateCounter].getElementsByTagName('a')[0].focus();
        for (k = 0; k < slen; k++) {
            sli[k].getElementsByTagName('a')[0].style.background = '#F9F9F9';
        }
        sli[cityCounter].getElementsByTagName('a')[0].style.background = '#CCCCCC';
        //alert(suggcounter);
        //console.log("suggDateCounter: "+suggDateCounter);
        if (cityCounter != (slen - 1)) // Current isn't last
        sli[slen - 1].getElementsByTagName('a')[0].style.background = '#000000';

    }
    if (ajaxInProgress == false) {
        if ($(this).val().trim().length >= 3) {
            ajaxInProgress = true;
            $(".select2-results").html("");
            $.ajax({
                url: '<?php echo $this->registry->siteurl; ?>/index.php',
                data: 'route=index/get_home_cities/' + $(this).val(),
                type: 'GET',
                success: function (response) {
                    $(".select2-results").append(response);
                    //$(".select2-results").append("
UAE
");
                    ajaxInProgress = false;
                }
            });
        }
    }
});

The problem is that I am getting a Type error  and I can't figure out why I am getting this.
         TypeError: sul.$ is not a function

Comment: I think it should be `sul.find('li')` instead of `sul.$('li')`
Answer: I think you meant
 var sli = sul.find('li');

Comment: Thanks, it did the job for me though my question was a little vague.

Type error in javascript