Can I build a concrete block wall over floor tile?

Question: I am enclosing a tiled porch on concrete slab with a 3' short wall of concrete block, with windows above. Should concrete blocks be laid over a tile floor?
Answer: The tile floor shouldn't be a structural weakness, but if it's glazed you won't get a good mortar bond. I'd install anchor bolts every 32" or so, aligned with block cores, and fill those cores with mortar.
It might be easier to simply cut the tile inside the wall line and remove it, though.
Also be aware that your slab may not be designed to carry a heavy wall. If it doesn't have proper footings underneath it may crack and settle.
Answer: NO, NO, NO, never install concrete block on tile.  You don't say what kind of tile is installed on your concrete slab, but it doesn't matter if it's "ceramic tile" or "terra-cotta tile" or "porcelain tile" or "stone" or "slate". Regardless, you'll have future problems because: 1) differing strength in compression, 2) different expansion coefficients, 3) moisture absorption, and  4) mortar adhesion issues.
1) Concrete block is a structural material with high compressive strength compared to floor tiles. This will be a structural exterior wall and will move from Environmental events (wind, earthquake, settlement, etc.) which will cause pressure on the wall...causing the tile to crack. Cracks allow moisture into the wall and probably room.
2) Because the tile is made of a different material and thickness, it will expand and contract differently than concrete block depending on exterior temperature. When differential expansion occurs, it causes cracks.
3) Depending on where you live, moisture will adhere to the tile differently than the concrete block. If you cover the exterior edge of the tile with mortar, it will help reduce (but not eliminate ) the issue.
4) With a "finished" surface on a tile, it will not allow mortar to penetrate the surface and it will not adhere. Without adhesion, there will be a crack between the tile and mortar. This will allow moisture to penetrate the wall. Then, it could freeze, expand, and develop huge cracks.
Besides the "tile" issue, there are other issues too:
A) The concrete block wall must be tied into the roof structure or it's a retaining wall...and you'll need a ton of steel, depending on wind and earthquake conditions in your area.
B) This is en exterior wall and the footings must extend below the frost line. This could be anywhere from 12" in the south to 48" in the north. Otherwise the patio will "heave" and crack all those windows you are installing on top of that concrete block wall.
C) If the new room is considered a "habitable space" the Code says you need to have the wall and ceiling insulated. In addition, the perimeter of the slab will need insulation, there will be electrical issues, etc.
D) Structurally, you'll need #4 horizontal reinforcing steel at 32" on center plus #4 vertical reinforcing steel at 32" on center at a minimum...if it's not a retaining wall and if it's more than 12' long. If it gets to be 20' long or so, it'll need expansion control too. If you live in an extra cold climate, you may need to install more horizontal reinforcing steel.
E) Soil conditions: If you use 8" thick block it will weigh about 100 lbs. per square foot. So, with a 3' high wall plus's the windows, plus the roof...I'm guessing you're loading about 1,000 lbs. per square foot on the existing slab and soil. It's not a lot, if the existing slab is reinforced.
You asked about setting concrete block on an existing tiled concrete patio, so I won't get into setback requirements, lot coverage ratios, etc., but you'll need to verify that with your local Building Official.
You're getting a Building Permit, right.
Comment: @LyndonWhite The asker's unit of measure is in feet. (BTW, I like your tree top walk.)
Comment: You seem to be assuming something about the nation/location of asker. In that your example locations for the frostline doesn't hold the same for north/south of Britain as is does for north/south of Australia. And your statements about the "Code" certainly are not true of every Code.
Comment: A fair point, however in a lot of the world (or at least in my parts) feet are used as unit of convenience (as a short hand for about 30cms); so not conclusive. (Yeah, that  tree top walk is awesome)
Comment: Your confidence in the likelihood of failure is amusing, Lee. You raise some concerns, but most of them are edge cases and unlikely. Expansion rate variance probably isn't enough in the width of a block to be a problem. (The tile is bonded to concrete, after all, and can't really move.) Moisture would be handled as with any block wall--as needed. I mentioned sill bonding in my answer, and it isn't a terrible concern, either if handled well. If OP is in an earthquake zone (s)he probably wouldn't be using block to begin with, and there's no mention of it being a retaining wall.
Comment: @isherwood You say, "Moisture would be handled as with any block wall—as needed." The point is it will be a continuing problem due to lack of adhesion if mortar, differential thermal expansion of tile to block, movement causing cracks on tile, etc.  These items aren't "maybe issues" they will cause problems. Bad design is what we're trying to eliminate. No tile manufacturer will recommend their tile as a structural element.  Retaining walls aren't just from soil bearing on a wall. Any "lateral load" (like wind, earthquake) on a wall that is not restrained at the top and bottom is considered a
Comment: @isherwood is considered a retaining wall. Think of it as a cantilevered wall. Because this wall is built out of block, any deflection will be a major issue, unlike wood frame walls that have a zillion joints and can flex without causing a problem. The OP is building a wall with a hinge in it, unless they anchor the top of the wall or reinforce it so there is no deflection.


If else function not consistently working

Question: I cannot get this if/else to replace more than one row of of the column at a time. I have tried
spreadSheet.getRange(2, 38, 4000)

spreadSheet.getRange(2, 38, spreadSheet.getLastRow()-1)

and
spreadSheet.getRange(2, 38, sheet.getMaxRows())

It's not returning anything if it's not set up like below (and that only returns one cell.
function calculateHitPoints(){
    var spreadSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Form Responses 1");
    var setHP = spreadSheet.getRange(2, 38).getValues();

    if(setHP == "Fighter"){
        spreadSheet.getRange(2, 38).setValue("14");
    }
    else if(setHP == "Ranger"){
        spreadSheet.getRange(2, 38).setValue("13");
    }

}

Comment: Please consider explaining in more detail what you want to accomplish. It's not clear, based on the information you provided. It would probably be worth taking a look at the official docs for `getValue()`, `getValues()`, `setValue()`, `setValues()` and the different `getRange`.
Answer: It's because you're getting row 2 in column 38. That's why it's only getting that cell only.
getRange() has multiple implementations you can refer to this links here.
Sheet.getRange(row, column)
Sheet.getRange(row, column, numRows)
Sheet.getRange(row, column, numRows, numColumns)
Sheet.getRange(a1notation)
Comment: yes, but the numRows, etc aren't working.


Does the A.I cheat when performing charge attacks?

Question: Allegation:
When I was a kid, I swore that the Capcom artificial intelligence opponent cheated on the charge attacks, both vertical and horizontal.
Evidence:
My evidence for the horizontal charging was that the computer character would walk forward (or stand while not walking backward, while I was not attacking, and thus not be blocking, ergo not be charging back), then throw the charged attack in far less that the 2 seconds that would have required a human player to be holding back. The vertical charging discrepancy was not conclusively proven in my mind, but I think such cheating would be equally likely as the horizontal charging.
Possibilities:
I think the possibilities in terms of increasing complexity (and thus perhaps decreasing likelihood, based on Occam's Razor.)

The computer had a simple timer that prevented throwing the attack more than 2 seconds apart.
The computer has a directional key model, was carrying out the attacks with perfect charge timing, and I am simply wrong (but I doubt it!)
The computer had a disconnected directional key model allowing it to simultaneously press forward and back.
The computer would initially follow the rules (for easy difficulty levels) and begin to break them to increase the difficulty level.

Question:
Does the computer AI player cheat? What is the truth, and has this ever been proven?
Comment: Your possibilities list ignores the option that the computer would always follow the rules, and you only thought it was cheating because it would pull off the button combos with perfect timing.
Comment: @DavidM: You could have a video of an AI charging within two seconds of it walking away from you.
Comment: Also note that this exact example is listed as the AI cheating on two TV Tropes pages: [The Computer is a Cheating B______](http://tvtropes.org/pmwiki/pmwiki.php/Main/TheComputerIsACheatingBastard) and [Secret AI Moves](http://tvtropes.org/pmwiki/pmwiki.php/Main/SecretAIMoves)
Comment: @AshleyNunn: You could definitely test how long a human has to hold it and then test if the AI ever does it faster than that.
Comment: i'm pretty sure that what you are seeing is [charge partioning](http://forums.shoryuken.com/discussion/6578?threads/partitioning-versus-buffering.6578/)
Comment: @Ullallulloo That wouldn't really prove anything, as the idea that it takes two seconds for the human keypress is also rather unprovable definitively I would think.
Comment: There, I updated to include possibility. C'mon, you know this is a good question, please upvote! I upvoted these comments! :D
Comment: Its not cheating its the ai hitting the exact frames needed for charging
Comment: I can't find the video, but distinctly remember a human player being able to pull off a blanka roll while walking forward in sf2 by alternating charge and walk on the correct frames.
Comment: and I'm pretty sure they removed it in sf4, it was super big in sf3 but did exist in sf2
Comment: @z' The charge partitioning theory is a very interesting one, and should be straightforward to test with frame-by-frame TAS methods. I've watched a few TAS playthroughs of the SF2 games and haven't seen something quite like that, but it'd be pretty impressive if it works.
Answer: Here's an example video where the A.I. player doesn't appear to charge at all. I recorded it using ZSNES and the World Warrior version of Street Fighter II, on standard difficulty.
In the video I control Ken and repeatedly trigger the A.I. Guile's flash kick by performing dragon punches at medium/close range.
The best example of this "cheating" is at about 00:20 when Guile performs a flash kick apparently without ducking at all.
Another video (not by me) of the faithful-looking Sega Saturn port of SF2CE shows Guile performing a sonic boom apparently from a standstill.
My hypothesis as to why this is possible:
The joystick manoeuvres are required solely to communicate the player's intention to the computer so that it can execute the move intended by the player. Let us assume that there is a state machine of some kind which watches the joystick inputs and converts them to a "move number" - perhaps an integer in the range 0-255, where each number represents a different move that can be performed by your character.
When implementing the computer-controlled opponent then, the programmers have two basic options:

Have the opponent player routine (presumably, there would be one for
each possible opponent, so 12 in this case) generate the same button
presses and joystick movements used by the player, and have the
game engine interpret them in the same way. This is perhaps a more
modular way to go about writing the game, and would be more elegant
and simpler in some respects, but it may be complicated to generate
the fake joystick events as there is a temporal aspect to them.
Or one could simply avoid the joystick event part altogether. The
computer doesn't need to communicate its intended move by sending
fake joystick events to itself - instead, it can directly indicate
exactly what move it wants to perform, by setting the opponent's move number
to the number corresponding to the desired move.

Based on the video I've posted which can easily be verified in the SNES, PC Engine and arcade versions of Street Fighter II, I would suggest that the second option above was used by the game programmers, and therefore that yes - the computer can "cheat", in the sense that it can instantly execute a move that requires a "charging" action when a human player executes it with the joystick.
However, the computer does sometimes appear to exhibit charging behaviour - especially when playing E. Honda, Chun Li and Blanka. I'm not sure if it's just simulating this play mechanic out of some kind of programmed fairness, or if there is another explanation. A disassembly and analysis of the arcade game code in MAME is possible using the debugger or other tools and would give us definitive answers, but would take some time.
Comment: It's an interesting question, and an intriguing topic - thanks for posting it :)
Comment: I HAVE performed the disassembly.  My answer is below and matches yours.
Answer: There are a number of things at play here. I have done frame-by-frame analysis of the video, and have learned quite a bit about the mechanics of Street Fighter 2. But I also have some knowledge about the core mechanics of games like this as an active follower of the speedrunning and the Tool-assisted speedrun (TAS) communities. The timings for this type of thing are based on frames of input. Since I'm not a superhuman, I used an emulator and frame-advance to time exactly how many frames it takes for the player to make a charge attack work. A NTSC SNES runs at 60.0988 frames per second, which can cause some weird things to happen in recording. For the purposes of this, I will round that framerate to an even 60 frames.
Guile's Sonic Boom is performed by holding back for a specified number of frames, then pressing forward + punch. Using an emulator, I counted the number of frames of back input required, and came up with 60, exactly. This includes a down+back input. One real-time second. So where does the 2 second figure come from, you ask? Well, turns out the timer doesn't count in real-time; it's about twice as fast, ticking down every 31 frames (give or take).
The AI in this video, as you referenced, on the other hand, is able to pull off a Sonic Boom after approximately 45 frames.
So strictly speaking, can the AI perform charge attacks faster than the player (even the player with the fastest reflexes possible, the TASBot)? It appears so. But does that constitute "cheating"? Well, that's really a philosophical argument if you ask me, but, when one defines cheating as strictly "the ability to perform inputs faster than the player can even if the player gets it frame-perfect", it looks like it.
Comment: Playing perfectly is not cheating. Not having to obey the mechanics that humans have to obey **is** cheating. Humans cannot simultaneously press in opposing directions. Humans have to charge for 60 frames. Old TV's are at 30 frames per second, most SNES games are at 60, which explains the 2 seconds in the docs. You've documented that the AI cheats (where you reference the video I cited). Thanks!
Answer: Yes.  It does cheat.
No video analysis necessary.  I have reverse engineered the AI engine.  Any behavior that looks like charging or "button mashing" when the CPU executes a move is purely for show.
I can provide code snippets to back this up.
Here's exactly why charging isn't even possible:
The AI executes moves directly.  The CPU is not sending directional and button input into the game engine like some posters seem to think it is.
The reason you see the illusion of "charging" is because Capcom included this on purpose to telegraph the way moves are done.  For example, when performing E. Honda's hundred hand slap, the AI executes commands, in sequence, for two punches, then the call to execute the special move directly.   The same goes for all moves where you see the character moving backwards to "charge."   As another example, if you look at the code that performs Guile's flash kick in the middle of some of his rarer combos (yes, sequences have probabilities,) it is just called directly.  There isn't even the possibility of the AI "charging down" because the AI is not "pressing" any buttons at all.  It simply makes a call to execute the flash kick move.
Comment: James, it's a pity we haven't seen more from you on this... I imagine this would blow up on Hacker News if you made the analysis plain with examples of the reverse-engineered code.
Comment: A statement of reverse engineering is hard to believe without proof.
Comment: You're going to have to ask for the code you want to see.  The AI engine has a command to perform any move and that's how the specials are executed.  I would appreciate if you would undo the negative ranking based on the fact that you don't believe my answer versus that it is a bad answer.  I'll edit my answer to provide more detail.
Comment: I have withheld voting since you answered this question. Can you provide something that substantiates this? If persuasive enough, you could get an accept. Please consider how you might offer more proof! Thanks!
Comment: @AaronHall I'll see if I can come up with something that requires minimal assembly to explain.
Comment: You're still only stating that you've reverse engineered it.  You've provided nothing in the way of proof.  Until you do, this answer isn't very useful at all.  You've made a statement, it's up to you to back it up.
Comment: @Frank Do you understand Motorola 68000 assembly?
Comment: Irrelevant.  If you make a statement, it's up to you to back it up.  So far, I haven't seen anything that does so.
Comment: Great! I'm a bit rusty on 68k assembly but learned a little on my old Atari ST, and a couple of years ago also did a little disassembly and in-place patching of the SF2 ROM. Could you perhaps write up a blog post with some example annotated snippets to walk us through some of the stuff you found? That would be really interesting.
Comment: I could.  I've been meaning to do so.  It's actually pretty interesting and VERY hackable.  One could actually rearrange the entire repertoire of reactions and attack strategies without much fuss.  I also ended up with a thorough understanding of what the difficulty settings actually change and how it progresses from match to match.
Answer: Since I cannot comment (yet), it seems James answer is right, here you go
How the AI engine works
Here is the most relevant part of the article, in regards to this quesiton

A question addressed in an earlier post in this blog was whether the AI "cheats", and it certainly does. Charge moves such as blade kicks are simply executed as instructions, so they cannot fail. Guile can do a bladekick from a standing position simply because that's what's in the script. It's probably possible for the AI to command special moves in the air. One instruction is available to disable collisions against the computer player for a certain number of frames. Using it, you could write a script to simply walk through an approaching fireball.


Differential equation of $F(y,y',y'') = 0$ type

Question: I'm studying to solve the deferential equations of $F(y,y',y'') = 0$ type by using the example of the solution for the equation: $$(1 + yy')y'' = (1 + (y')^2)y'$$
In the example one uses the substitutions $ y'=p(y) $ and $ y'' = p \cdot p'$. The result of the substitutions is:
$$p' = \frac {1+p^2}{1+py} $$
Then one uses the substitutions $ p' = \frac {1}{y'} $  to rewrite the equation like this:
$$ y' = \frac {1 +py}{1 + p^2} $$
The solution's next steps are absolutely clear but I can't understand how the substitution $ p' = \frac {1}{y'} $ was worked out.
Answer: This is a standard trick, Instead of considering $p$ as a function of $y$, consider $y$ as a function of $p$. Then$$
p'=\frac{dp}{dy}=\frac{1}{dy/dp}=\frac{1}{y'}.
$$
Comment: $y(x)=C$ is one solution
Comment: @Julian Aguirre: So it is understood that the same primes employed denote no more differentiation  with respect to x , but with respect to p?
Comment: $p'$ means differentiation of $p$ with respect to $y$, and $y'$ differentiation of $y$ with respect to $p$. It may not be the best of notations, but it is useful.


Cannot run snap app

Question: I have successfully installed snapd on Ubuntu 16.04 but while running the app, say snap run hello I am getting the following error:
cannot create lock directory /run/snapd/lock: Permission denied
I have tried the following
sudo apparmor_parser --replace --write-cache /etc/apparmor.d/usr.lib.snapd.snap-confine.real --cache-loc /etc/apparmor.d/cache

but did not work even after restart. I am not able to run any snap app though able to install any apps.
The snapd service is also running. But still even after reboot, the problem remains the same.
Comment: Snapd is pre-installed on 16.04. The fact you installed it and it doesn't work suggests you are running a non standard build of Ubuntu with a non-ubuntu kernel. What's the output of 'snap version'
Answer: I suggest you to try reinstalling the package hello and then run:
sudo snap run hello

If this does not work, you should try reinstalling Snap and refreshing the snap core using:
sudo snap refresh core

Comment: `sudo snap run app_name` work for me
Comment: hi, I installed cmake using snap. So I can run 'snap run cmake' but not just 'cmake'. Many install scripts are provided to use command 'cmake'. So I made an alias (alias cmake='snap run cmake'). Is this the way people use applications installed by snap?

Cannot run snap app


How to consume the return value of a webservice in jquery ajax call?

Question: I have a simple webservice in asp.net which determine if the input parameter is valid or not :
[WebMethod]
public bool IsValidNationalCode(string input)
{
    return input.IsNationalCode();
}

I call it from an aspx page by jquery ajax function :
 $('#txtNationalCode').focusout(function () {
      var webMethod = "../PMWebService.asmx/IsValidNationalCode";
      var param = $('#txtNationalCode').val();
      var parameters = "{input:" + param + "}";

      $.ajax({
          type: "POST",
          url: webMethod,
          data: parameters,
          contentType: "application/json; charset=utf-8",
          dataType: "json",
          success: function (msg) {
              if(msg.responseText == true)
                  $('#status').html("Valid");
              else {
                  $('#status').html("Invalid");
              }
          },
          error: function () {
              $('#status').html("error occured");
          }
     });
 });

But I don't know how to get the return value of webservice in order to show appropriate message . Here if(msg.responseText == true) doesn't work
Answer: Make the IsValidNationalCode method static and use this in javascript:
success: function (msg) {
    if (msg.d == true)
        $('#status').html("Valid");
    else {
        $('#status').html("Invalid");
    }
}

For "d" explanation follow this link: Never worry about ASP.NET AJAX's .d again
Comment: Thanks , msg.d works if the return type would be html and not json . I turned returntype to 'html' and that worked by msg.d


How can a two-column Python list be shuffled?

Question: It is straightforward to shuffle a Python list:
<code>>>> import random
>>> random.seed(100)
>>> a = [1, 2, 3, 4, 5, 6, 7]
>>> random.shuffle(a)
>>> a
[7, 1, 5, 6, 4, 3, 2]
</code>
How can two-column Python list be shuffled?
So, to be specific, I have a list of the following representative form:
<code>[
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        1
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        2
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        3
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        4
    ],
    # ... etc.
]
</code>
You could imagine this as being a form of data that captures three characteristics of an event (the three high-precision numbers) in one column and has the event numbers in the second column.
I want to shuffle this two-column list such that the events with their corresponding event numbers are shuffled. Note that I do not want to shuffle the list of event characteristics. So, in this example, the result of a shuffle could be the following:
<code>[
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        3
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        4
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        1
    ],
    [
        0.121282446303956,
        2.1595318494748978,
        0.43386778589085612
    ],
    [
        2
    ],
    # ... etc.
]
</code>
You can see that the order of the events has been changed from 1, 2, 3, 4 to 3, 4, 1, 2.
What would be a good way to do this type of shuffle?
Comment: Convert the list of lists with different semantics to a list of tuples (http://stackoverflow.com/questions/5389507/iterating-over-every-two-elements-in-a-list) and shuffle the tuples.
Comment: Probably not a good idea to use a list with repeated elements as an example for shuffling. If you use different "event" numbers, the example will be much clearer
Answer: Numpy allows inplace shuffling of array slices.
<code>import numpy as np
a  = np.array(a)
np.random.shuffle(a[1::2])
</code>


Should I replace existing 4x4 posts?

Question: I currently have a high 20x14 deck attached to the back of my house on a very sloped yard. It is 13 ft off the ground and in great shape. However, It is currently supported by 4x4 posts that are in the ground(don't know if they are attached to concrete footings or not) and notched at the top where it is attached to a 2x8 and 2x10 ledger support.
We want to eventually close in half of the deck and make it a 3-seasons room. Should I replace these 4x4 posts with 6x6 posts(due to added weight of 3 seasons room)? Or could I just add the 6x6 posts directly right next to the existing 4x4 posts, so I don't have to jack up deck/remove 4x4s? I would dig new holes for the 6x6 posts, with poured concrete and use post base to attach them above ground and use post caps to attach to the existing support ledgers.
I am looking for the safest, most efficient way a DIYer can achieve this herself. We are located in Georgia, so we really don't get snow, but we do get a little ice here and there.
BTW One of the posts is shredding at the ground level and the corner posts looks like it is cracking.
Comment: I'm having a hard time knowing what I'm seeing in that extreme closeup. Maybe back out a bit and show a couple angles.
Comment: I'm sure you'll have this conversation with the building inspection/permits people, but I'd be concerned about how appropriate the floor structure is for your 3 season room plan.
Answer: Deck
If the 4x4 posts were up to code for when the deck was built then your proposal would be considered a repair and repairs usually have looser guidelines.
Yes, adding 6x6 posts next to the 4x4 posts would be a huge safety improvement and likely exceeds current code so that's super!
Your main consideration is whether you are okay with the look of doubled up posts. If not then jack up the deck and do a replacement. If you're okay with the look then follow through with your plan since it sounds like a huge improvement.
Sunroom
I do not know if deck conversion into sunroom has additional code implications that your current deck does not meet.
I would check the code requirements for a sunroom before proceeding with your 6x6 idea because it would be a shame to do the 6x6 posts and later find out that the sunroom must be built from scratch due to deficiencies with the deck.
Comment: @ChrisCudmore Yes, I addressed that in my answer. I bolded a few things to make the distinction more prominent. It sounds like OP is working with the town to legally build this sunroom.
Comment: @FreeMan OP commented on the double-post look. It's a free country! =)
Comment: And yes, I am working with the city and inspectors to do everything correctly. Hopefully, I won't have to tear down the existing deck and could just do some minor renovations to bring it up to code.
Comment: The only caveat is the OP's point that the 4x4s are starting to fail. Yes, new 6x6 sistered up to them will take the load should one fail (and will probably prevent the failure of the cracked one, while the rotting one will continue to rot). In that case, replacement seems to make more sense and avoids the (potentially ugly) double-post look.
Comment: I honestly don't mind the look of the double posts, because I know how to strategically place plants, decor to make it look great...lol. I am waiting on the senior inspector to contact me back with his recommendations. thanks for your answers.
Comment: The legal question is whether adding a 3-season room is a simple modification or major renovation.  Only the building department can answer this.
Comment: @TerriLScott if you're happy with the double-post look, then by all means go with it. Do be aware, though, that since you mentioned that one of the 4x4s was "shredding" (I presume that's your term for what you see as it rots), it will continue to rot, even with a 6x6 next to it. If that 4x4 is wicking water up from the ground, the parts that remain in contact with the ground and the 6x6 _could_ transfer water to the new post and cause premature damage to it. Something to consider.
Comment: @FreeMan OP did mention new holes and concrete for the 6x6 posts so presumably this means they'll be far enough away from the old ones.
Comment: Yes, the 6x6s will be next to the 4x4 post on both sides, but not attached to it. I honestly don't care if I have a WALL of 6x6s...as long as it is safe and up to code and sufficient for a 3 seasons room.
Answer: YES YES YES!
You should do this even if you are not going to enclose the area. This deck is not to current code.  I suggest you consult a professional, as you have no idea what other deficiencies there are.
See Page 7 of  Georgia Deck Code Amendments

Deck posts shall be 6x6 with a maximum height of 14'-0" measured from
the top of the footing to the underside of the beam.

EDIT: Comments say that original deck was built under permit and was constructed to code at the time, and is grandfathered in.  However, the building department may require it to be brought up to code as part of a major renovation.  I suggest consulting an engineer on this build - it's money well spent.  13 feet is a long way to fall and could be potentially fatal.
Comment: Thank you so much for your answer. For clarification, take them down and replace them or just add the 6x6s next to them? The inspector was out and said it was up to code for when it was built.
Comment: Well, the inspector knows best.  Did you pull a permit for the 3-season room?   They may consider it a major renovation and require you to bring it up to code.  Also, do you know if the original deck was built under permit?  If it was, you can usually for a reasonable fee,  have the inspectors office pull the file containing the original application and plans - It might help you answer a few questions about the current construction.
Comment: No, we haven't pulled the permit for the 3 seasons room yet. We are just trying to make sure everything is up to code 1st, before moving forward. The existing deck was built under permit. I will contact the permits office to get the plans. Thanks again!
Comment: My son's former house had a sun room (heated & air conditioned, so 4 seasons) built over an existing deck.  The deck was supported away from the house with 4x4 posts (3 or 4) on which the beam rested.  This was permitted and inspected in anal retentive Howard County, MD.  One difference from your situation is that his maximum post height was 8', and some of the posts were only 4" tall (built over a hill).
Comment: I'm finding max height for a 4x4 tops out at 10 feet according to current codes.  The issue is not strength in vertical compression, but buckling. That is, bowing out in the middle like )

Should I replace existing 4x4 posts?


Do you need Xbox Live to get the special list of cars?

Question: Do you have to have Xbox Live to have a special list of cars on GTA V?
I have signed up for the social club but don't know how to get the special list of cars.
Comment: @PeterFinney - You should post that as an answer
Comment: Which special cars? :0
Comment: In the big garages there is a prompt to press right on the d-pad to access special cars. Currently this only includes the Eleghy RH8 and I believe this is tied to the Social Club so yes, you most likely need Xbox Live Gold. It seems all of the Social Club features (leaderboards, friend stats, photos) require Gold.
Comment: @Robotnik Have done now. Wanted to double check this was the case before posting it properly.
Comment: Closely related: http://gaming.stackexchange.com/questions/131605/do-you-need-xbox-live-gold-to-play-gta-v-with-rockstar-social-club/131717#131717
Answer: Each character has their own special garage (purchasable, not the one at their houses) when you are in one there should be a prompt to press right on the d-pad to access special cars.
On my normal Xbox Gold account this works fine but on a secondary Xbox Silver account this prompt does not appear at all.
Currently the special car list only includes the Eleghy RH8 which is a Rockstar Social Club bonus car.
On the Xbox 360 version most of the Social Club content (including leaderboards, friend stats and photos) requires Xbox Live Gold so it looks like yes, you will currently require an Xbox Live Gold account to access the Special Cars list.
Comment: But they still can train chop too.
Comment: @ColeBusby Good point, there have been reports of that. Tweaked it to say "most of the Social Club content". Thanks
Answer: I FOUND THE PROBLEM!!!!
YOU JUST HAVE TO GO ONLINE MODE AND DO ALL UPDATES AND PATCH YOU CAN DO TO PLAY ONLINE!!!!
Then just go back single mode and return to your garage. (You'll have messages from Social club again to say new contains in garage, dock, airport etc...) TADAM Car list as T20, Turismo, Zentorro, etc is back.
I play Xbox360.
Thanks.
NsE420


AngularJS NgResource API call

Question: So I'm currently working with $ngResouce. My api: api/Content/resource/user.post.failed returns the following:
{
  "user.post.failed": "Thing.."
}

app.factory('testResource', function ($resource) {
return $resource(apiurl + '/Content/resource/:resourcename', {}, {
    show: { method: 'GET', isArray: false, params: {resourcename: '@resourcename'} },
    update: { method: 'PUT', params: {id: '@id'} },
    delete: { method: 'DELETE', params: {id: '@id'} }
})

});
This is what I call in my controller
$scope.test = testResource.get({resourcename: 'test'});

The question is actually really simple; how do I get just the 'content part' so test. I'm now getting the whole JSON part back.
So the scope test is now: {"user.post.failed":"Thing.."}
And I want the scope to be just Thing.
Probably really simple, but I couldn't find the answer.
Answer: Use the $promise property of the object to see errors:
$scope.test = testResource.get({resourcename: 'test'});

$scope.test.$promise.catch(function onReject(response) {
    console.log('ERROR: ',response.status);
    console.log(response);
});

So the scope test is now: {"user.post.failed":"Thing.."} And I want the scope to be just Thing.

 console.log($scope.test["use.post.failed"]);

Use the property accessor syntax.
For more info see MDN JavaScript Reference -- Property Accessors
HTML
{{ test["use.post.failed"] }}

Comment: Marked this one as the answer. Since this answer gives some more info ;) Thanks both of you for answering.
Answer: testResource.get({resourcename: 'test'}, function(data) {
    $scope.test = data['user.post.failed'];
})

AngularJS NgResource API call


Is it useful to paint outdoor conduit white to reduce the temperature?

Question: The typical color of most types of electrical conduit is dark gray.
I plan to run some kind of conduit along the edge of a flat roof to install security cameras, and I'm already worried about the heat radiating from the black roof not being good for the cables.
Will painting the conduit white help it absorb less heat from the sunlight directly in the conduit itself? Even if it is less heat, will it be enough to make a difference? Or am I worrying about nothing and it will be fine?
Comment: Ideally you'd route the conduit so its out of the sun and out of the rain as much as possible.
Comment: What is it in contact with? Or is it supported on posts acrosd the middle of the roof? Ie shortest run?
Comment: @SolarMike. Sorry I didn't elaborate. I had just written the linked question so I didn't think to put more info here. It would be resting on the surface of the roof as close to the edge as possible or (where possible) screwed to the wall of the taller party of the building about an inch or two above the roof surface. There is a picture at the other question in the link above.
Comment: While the original question for the following answer was for plumbing PVC and UV light, the answer still applies to electrical PVC and may be helpful in your decision of whether or not to paint it: https://diy.stackexchange.com/a/18349
Answer: Elevating the conduit 7/8" or more off the roof surface will be more effective than painting but yes white is the least heat absorbing color.  Why 7/8" elevation? That is what code requires or a temperature adder is used when derating the wire; with 7/8" elevation, the adder is not required. This is located in section 310.15(A)(3)(c), "Raceways and Cables Exposed to Sunlight on Rooftops".
Answer: The heat radiated from a black roof will be less than radiated from any other colour of roof (because other colours reflect more light).
You haven't said what type of cable you plan to use, but it will probably be fine.
Conduit may be is hard to water-proof. use damp resistant cable.
Comment: We did an experiment once about plate colors and insulation in the sun to explain how solar thermal panels worked. Panels of white metal, red, blue and black, then no insulation behind, with insulation and no glass cover and with glass cover. All could be touched and all had a temperature display. Black, insulated & covered got the hottest by some 18 degrees - white remained the coolest.
Comment: Jasen,  black roofs are the hottest surface they don't reflect heat like white but absorb the heat and the roof temp can be much hotter than the ambient temperature this is why code requires a 7/8" elevation or a temp adder to de rate the wire.
Comment: How is that experiment in any way relevant to heat radiated from the roof?
Comment: Because the OP makes it clear that the conduit will be in contact with the roof...
Comment: **Radiate** and **reflect** are not the same thing at all. Black absorbs and radiates very effectively.
Comment: Refelected radiation is still radiation.... he said radiated from, not radiated by.  black gets hotter, and thus loses more heat to convection than lighter colours, so energy radiatted from a black roof during the day is less than for a lighter colour.


might and magic from g2a

Question: If I'll buy the game from G2A, I think I'll only get the serial number, and not the actual game.
So, where can I download the game after that?
G2A seams a lot cheaper than Steam.
Answer: Open your steam client, and go to the library tab. At the bottom left corner of the client there should be an "Add Games" link. Clicking that opens up a prompt that walks you through adding the game.
Comment: If the game is Might and Magic X (I can't find any other M&M games (other than Heroes spin-offs) on steam), then it is very likely that they are selling a uplay key, rather than steam key.
Comment: I'm just making an assumption that he's talking about a steam-based game because he explicitly mentioned that g2a was cheaper than steam. Either way, I'd never recommend someone actually buy from them, they're a terribly shady, underhanded company. Unfortunately that's an opinion thing and not welcome as part of an answer.

might and magic from g2a


How to enable ufw firewall to allow icmp response?

Question: I have a series of Ubuntu 10.04 servers and each one has ufw firewall enabled.  I have allowed port 22 (for SSH) and 80 (if it's a webserver).  My question is that I am trying to enable icmp echo response (ping reply).
ICMP functions differently than other protocols--I know it is below the IP level in a technical sense.  You can just type sudo ufw allow 22, but you cannot type sudo ufw allow icmp
Answer: ufw does not allow specifying icmp rules via the command line interface command. It does allow you to adjust your ruleset via its rules files, which are iptables-restore style files.
ufw does allow certain icmp traffic by default including icmp echo reply, and this is already configured by default in /etc/ufw/before.rules:
-A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT

If your host is not responding to ping, look in this file to make sure the above line is present and if that doesn't work, look at the pinging host and any firewalls between them.
Comment: not works for me: 11.04 server.how can i troubleshoot this issue?
Comment: @AmirKarimi `sudo ufw reload` (and to allow ping requests I had to add `-A ufw-before-output -p icmp --icmp-type echo-request -j ACCEPT` in `/etc/ufw/before.rules`)
Comment: Does it need any reset or something like that?
Answer: For Ubuntu 18.04, you should have the following rules in your /etc/ufw/before.rules file:
# ok icmp codes for INPUT
-A ufw-before-input -p icmp --icmp-type destination-unreachable -j ACCEPT
-A ufw-before-input -p icmp --icmp-type source-quench           -j ACCEPT
-A ufw-before-input -p icmp --icmp-type time-exceeded           -j ACCEPT
-A ufw-before-input -p icmp --icmp-type parameter-problem       -j ACCEPT
-A ufw-before-input -p icmp --icmp-type echo-request            -j ACCEPT

# ok icmp code for FORWARD
-A ufw-before-forward -p icmp --icmp-type destination-unreachable -j ACCEPT
-A ufw-before-forward -p icmp --icmp-type source-quench           -j ACCEPT
-A ufw-before-forward -p icmp --icmp-type time-exceeded           -j ACCEPT
-A ufw-before-forward -p icmp --icmp-type parameter-problem       -j ACCEPT
-A ufw-before-forward -p icmp --icmp-type echo-request            -j ACCEPT

These were in my default file.
Of course, be sure that this is really the problem. My issue was that my computer was blocking pings from getting out to the network where the server I was trying to ping existed.  I ended up using a web site that was already out on the internet to do the ping for me (e.g. https://ping.eu/ping/).
Answer: Add the following to the /etc/ufw/before.rules file:
# allow outbound icmp
-A ufw-before-output -p icmp -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT
-A ufw-before-output -p icmp -m state --state ESTABLISHED,RELATED -j ACCEPT

After editing the file, run the command:
sudo ufw reload

Answer: It should be noted that, at least in Windows, ping (by default) attempts to communicate via IPv6 and that UFW (by default) blocks that.
In order to ping the IPv4 address, use ping -4 <ip.add.re.ss>
Answer: Here is a help document that discuesses how to enable/disable ping et al responses.
UFW help
Answer: If you are still having problems, maybe it is your VirtualBox or VMWare network settings. I often use NAT addressing and so I need to go to Devices/Network/Network Settings... -> Advanced -> Port Forwarding and add a rule to map host to guest ports for port 22.


Android Speech Recognition NullPointer Exception

Question: I have made an android app which uses speech recognition. The problem is that it shows nullpointerexception.
The code which shows the error is :
public void startVoiceRecognitionActivity()
{
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Give Me An Order!");
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
            RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 1);
    startActivityForResult(intent, VOICE_RECOGNITION_REQUEST_CODE);
}
/**
 * Handle the results from the recognition activity.
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == VOICE_RECOGNITION_REQUEST_CODE && resultCode == RESULT_OK) {
        //store the result that the user might have said but google thinks he has said that only
        ArrayList<String> r=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        String[] result = new String[r.size()];
        result = r.toArray(result);
        Intent i=new Intent(getApplicationContext(),search.class);
        if(result[0].length()<=0)
        {
            showToast("Could not fetch command properly try again");
        }
        else
        {
            i.putExtra("q", result[0]);
            startActivity(i);
        }
    }

    super.onActivityResult(requestCode, resultCode, data);
}

the error is occurring on the line    if(result[0].length()<=0)
Answer: Taken from the documentation of <T> T[] toArray(T[] a):

If the list fits in the specified array with room to spare (i.e., the
  array has more elements than the list), the element in the array
  immediately following the end of the list is set to null.

Thus if your r variable points to empty list the first element of your array will be null. This is causing your NPE. You can try verifying the size of the list, but it is most certainly the case.
Comment: thanks for the reply. see i published the app to android market and i saw this error. i tried two bugfixes but it failed. the main problem is that r is being returned null from the voice recognition engine. can you help me out a bit..?
Comment: @HimanshuJaju regretfully I have not worked with the voice recognition API, I can just point you to the cause of the current error you get.
Comment: btw if i have 10 things in the list and 11 can be stored in my array, then which one will be null..?


What do I do with these extra multiway wires in my light fixture?

Question: I have been modifying some fluorescent light fixtures for led lamps. Ballast bypass lamps. Have done several so far and all good so far.
I have a fixture that is a 4 lamp, 2 ballast. It is on a 3-way circuit with multiple light fixtures. There is a single 3-wire cable coming into fixture. Red wire and black are alternately hot when switch is switched. My question is how do I wire this up correctly. This scenario is kinda throwing me off. Probably making it more difficult than it is.
Comment: In the age of selfies, you'd thing more people would start out by taking pictures...
Comment: Are you sure that's the only cable coming into the fixture?  Can you post a photo of the existing wiring?
Comment: There should not be any "alternating" hot leads connecting to any of the fixtures.  Please provide pictures and identify which wires connect to the fixtures.
Answer: TLDR: Find the ballast.  Cut its #18 white and black power lead halfway down its length, and fit a ballast disconnect there. (don't bother connecting the ballast side). Connect your LEDs on the ballast side of that.

Since the fixure did not tap into those wires before, you leave them the heck alone.
The irrational need to play with wire groups that are not involved, is the undoing of many lamp projects.  We had one case in an old apartment building where instead of the two wires needed, the asker had dug out a full ten wires from the ceiling, unhooked them all (knocking out the neighbor's power), shot a photo, and asked "how do I hook these back up?"  You don't.  That information was stored in "how they were hooked up before", which the person destroyed.  Now, an electrician has to tone out all those wires and try to figure out what was originally intended. Cost the asker over $300.
The old ballast has a white and black wire.  The ballast black goes to certain wire(s) in the ceiling. That is where your supply black (hot) goes to.  It doesn't matter what colors they are.  If the wire(s) are white, they must be re-marked with black tape as they are actually hot.
The ballast white goes to certain other wires in the ceiling, probably white.  That is where your supply white goes to.   You must keep them all together. They're not spares, they're working for a living!
Really, you should be installing Wago style or Ideal ballast disconnect plugs to the aforementioned wires.  (Not least, it allows you to turn the power back on the moment the disconnect is installed, instead of having to do the whole job in the dark.) However, installing the ballast disconnects will also help you keep the wires straight.


Error - Unhandled Exception: This widget has been unmounted, so the State no longer has a context

Question: i call the data i get from the service in didChangeDependencies to reflect it on the page. Because when i call this in initState, i'm facing an error. Anyway, this is not my main problem. My main problem is when page loaded, i got datas but when i want to go previous page, im facing a problem :
"Unhandled Exception: This widget has been unmounted, so the State no longer has a context (and should be considered defunct)."
"Consider canceling any active work during "dispose" or using the "mounted" getter to determine if the State is still active."
According to my research, i should use "mounted" in if state. But it didn't work.
Also i tried if statement like this:
<code>@override
  void setState(VoidCallback fn) {
    if (mounted) {
      super.setState(fn);
    }
  }
</code>
These are errors i got
My code:
<code>List<DetailObjects?> onOdemeDetay = [];

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    OnOdemeListeClass().fetchList(context).then((value) {
      final checkData = Provider.of<LoginInfo>(context, listen: false);
      if (mounted) {
        setState(() {
          if (value != null && value.detailObjects != null) {
            onOdemeDetay = value.detailObjects!;
            checkData.updateLabel(onOdemeDetay[0]?.label);
            checkData.updateValue(onOdemeDetay[0]?.value);
          }
        });
      }
    });
  }
</code>
Answer: If you want to update the state before going to previous page, you have to add delay of 2 seconds, which means when user press back button, firstly state will be update and then user will navigate to previous page.
<code> onPressed: () {

  //First Update your state here

  Future.delayed(Duration(seconds: 2)).then((value) {
     //Code to navigate previous page
  });
},
</code>
Comment: I dont know how to reach navigator.push's backbutton code thats why i removed it and added iconbutton. So my problem is solved, thank you so much!


Building 2 levels navigation from database using While()

Question: I'm trying to build a navigation bar using pages stocked in a database. Nothing difficult for the first level but it gets trickier when pages have to be listed as children of a same parent. here's my code :
$dropdown = array();
while ($pages = mysqli_fetch_assoc($rq_page)) {
  $url_pg = url_rewrite('page-' . $pages["id"] . '-' . $pages["intitule"] . '');

  // Creating a dropdown button
  if($pages["dropdown"] == "oui" && $pages["parent"] == 0) {
    echo '
';
        echo '';
        echo $pages["intitule"];
        echo '';
        echo '
';
        foreach($dropdown as $variable) {
          echo '' . $variable . '';
          }
        echo '
';
    echo '
';
  }
  // If single page = no dropdown
  else if($pages["dropdown"] == "non" && $pages["parent"] == 0) {
    echo '
';
      echo '' . $pages["intitule"] . '';
    echo '
';
  }
  // If content is a dropdown item
  else {
    $dropdown[] = '"' . $pages["parent"] . '" => "' . $pages["intitule"] . '"';
  }
}

So. First I get the databse content. Then I create an array() to list every content that has a $pages["parent"] equals the mother's ID. The while() deals with the 3 types of content : single page, dropdown page and items of the dropdown button.
i tried many PHP methods. The first level appears properly but the $dropdown array remains empty when used into the while() loop. When printed outside of the while(), it show the content I passed through the else { }
Can you see something wrong in this code and what would be the best way to create the navigation ? Let me know if I can provide more information.
Thanks for your help.
Comment: How is the data organized? It looks like your approach should work as long as the "dropdown button" comes *after* the dropdown items.
Comment: Here's the request :
"SELECT id, intitule, parent, dropdown FROM db_page ORDER BY parent"

id = INT, intitule = VARCHAR, parent = INT, dropdown = VARCHAR
What do you mean a bout placing the button after the item , I used the Bootstrap 4 structure.
Answer: Your code doesn't work because when it finds a page that has $pages["dropdown"] == "oui", the $dropdown array is always empty.
The reason why it's always empty is because your query returns dropdown "item" pages last, after all of the dropdown "button" pages. If you add var_dump($dropdown) into a few strategic places in the loop you'll see it for yourself.
A quick hacky fix is changing the ordering of your query, so that the dropdown "items" (with parent>0) are returned first:
SELECT id, intitule, parent, dropdown FROM db_page ORDER BY parent DESC

This will make every dropdown "button" include every dropdown "item," including the ones that are not related. The sort order will need further modifications to make your current approach work the way you expect.
Comment: I figured it could be a problem of request order but no matter how I turn it upside down, the result is the same : $dropdown is empty everytime is in the loop. Unfortunately I need its result in the loop.
Comment: It seems to be working now. It wasn't just a matter of order, I also made a mistake when using the array(). It needed the keys to be declared $var[3]


Does my refrigerator benefit from a water filter if the water is already filtered by reverse osmosis?

Question: The water going into my GE refrigerator, Model #:PYE22KYNFS, is already filtered by a reverse osmosis system. Do I gain anything by having a water filter on my refrigerator?
Also, if I don't need it, after it expires do I need to remove it or can I leave it in?
Thank you
Comment: Water filter *on the fridge* is probably to keep particulate crud out of the delicate ice maker and valves, where it could land on a valve face and stick the valve open.
Answer: The fridge filter is a simple one compared to the RO system.
Remember the instructions to flush the fridge filter with like 2 gallons when installed. That is to remove most of the particle.
It will certainly not improve the RO water quality, but it might reduce it.
Since it is actually not filtering anything after RO, just leave it in, it is not contaminated, or find and insert a blank.
Answer: If your RO system does the job for you, you don't need the filter in the fridge. However, do not leave the old filter in for an extended period of time! Filter makers warn that as they age they are subject to rupture - and they will. I had it happen to me on a filter I left in for a year.
Depending on the make and model, if you leave the filter off, you may have to replace it with a cap supplied by the manufacturer.
Comment: I forgot to change mine for 5 years, it is still in there
Comment: @Ruskes - You're lucky - don't count on it!
Comment: Do you have a reference for your claim, since the filters can be stored for 10 years
Comment: @Ruskes - Yes, they can be stored unused for years. The problem is that under pressure over time they can give out. Although it is especially true of offbrand filters it also happens with OEM filters. Mine happened to be a generic filter which did have a caution on it in the fine print. I would not trust any filter to hold up long term.
Answer: Having a water filter can't hurt...unless you leave it in for too long and it restricts or even blocks the water flow.
If you prefer not to have to deal with it, the manufacturer should have supplied a cap to be installed to use without a filter.
Comment: I would expect that feeding the built-in filter with RO filtered water should result in the built-in filter effectively lasting for ever. There shouldn't be anything in the water to cause it to ever clog up. Even if the manufacturer does supply a dummy cap for the filter you'll probably still have to reset the "replace filter" message if the fridge has one programmed to appear periodically.
Answer: Most RO systems have filters already built into them and if they are good systems, automatically flush out debris.  Regular maintenance (about yearly) is needed to keep them in top operating condition to be sure if it does have a filter, that it's cleaned.


Determining slopes of lines in perspective projection

Question: Suppose I have parallel lines running along the ground (into the horizon). If I have a camera and I know its tilt angle, is there a way to calculate the slopes of the lines as projected to the 2D image plane? That is, the green angles:

However, the distance from the lines are not known. What parameters of the camera are used in the calculation?
Answer: You definitely need to know distances and angle of view of the camera.  For example, if you add lines that are slightly further apart, they will be at different angles.  Like a multi-lane highway.


excel to word using VBA

Question: Sub TextFile_Example2()

    Dim Path As String
    Dim FileNumber As Integer
    Dim LR As Integer
    Dim LC As Integer

    Dim k As Integer
    Dim i As Integer

   LR = Worksheets("Sheet1").Cells(Rows.Count, 1).End(xlUp).Row
   LC = Worksheets("Sheet1").Cells(1, Columns.Count).End(xlToLeft).Column

   Path = "C:\New folder\textfiles\Hello.txt"
   FileNumber = FreeFile

   Open Path For Output As FileNumber

   For k = 1 To LR

       For i = 1 To LC
           If i <> LC Then
               Print #FileNumber, Cells(i, k),
           Else
              Print #FileNumber, Cells(i, k)
           End If
      Next i

   Next k

   Close FileNumber

   Shell "notepad.exe " & Path, vbNormalFocus

End Sub

This is the code that convert excel sheet to text file  But, the problem is that want to print data in desired format.
Excel sheet : View excel sheet
and should print the data in text file in desired format
text file :  [View text file][2]
But not able to achieve that any help would be appreciated
Dependent Dropdown :
click to view screenshot
Comment: why do you have that `If i <> LC` in your inner loop?
Answer: Sub TextFile_Example7()
Dim sPath As String
Dim FileNumber As Integer
Dim aData As Variant
Dim i As Long, k As Long
    aData = Worksheets("Sheet1").Cells(1).CurrentRegion.Value

    sPath = ActiveWorkbook.Path & "\textfiles\"
    On Error Resume Next
    MkDir sPath
    On Error GoTo 0
    sPath = sPath & "Hello_" & Format(Now, "YYYYMMDD_HHmmSS") & ".txt"

    FileNumber = FreeFile

    Open sPath For Output As FileNumber

    For i = LBound(aData) + 1 To UBound(aData)
       For k = LBound(aData, 2) To UBound(aData, 2)
            Select Case LCase(aData(1, k))
                Case "first_name"
                    Print #FileNumber, "First Name=" & aData(i, k)
                Case "last_name"
                    Print #FileNumber, "Last Name=" & aData(i, k)
                Case "email_address"
                    Print #FileNumber, "E_mail Address=" & aData(i, k)
                Case "password"
Rem Skip column, nothing to output
                Case Else
                    Print #FileNumber, aData(1, k) & "=" & aData(i, k)
            End Select
        Next k
    Next i

   Close FileNumber
   Shell "notepad.exe " & sPath, vbNormalFocus
End Sub

Comment: suppose, if I want to only read  the password column.  but,  should not write to text file
how would this can be achieve
Comment: i want to only read the column lets say last_name column. but should not write, is this possibe ?
Comment: @BhushanAgrawalJSR Of course it is possible! You can program anything you want. Just add `If aData(1, k) <> "password" Then `  before `Print #FileNumber,...`
Comment: Last but not least. This code saves the .txt file once . Is it possible to save with new file always when the code runs.
Comment: @BhushanAgrawalJSR One of the many ways to do this is to include the current date and time in the name of the generated file: `sPath = "C:\New folder\textfiles\Hello_" & Format(Now, "YYYYMMDD_HHmmSS") & ".txt"`
Comment: when I run the above code it should create the folder lets say "Textfile",  up or below the Excel file ("Excel1.xlsm") and should save the .txt file into that folder
Comment: Is this Possible ?
Comment: Thanks Sir ! I tested the code and working perfect as per my requests.
Comment: I need One help Sir, I want to read the column heading **first_name**,**last_name**,**email_address**  like wise want to only read and write in the format as **First name**,**Last name** , **E_mail address** I tried If-else, switch case but didn't get the solution.
Comment: How do i replace this strings ? Any suggestion
Comment: Hello sir I have data up to column "J" and skipping the column I have data in column "Z" so how write the Z column data in .txt file. You have used here `For i = LBound(aData) + 1 To UBound(aData)
       For k = LBound(aData, 2) To UBound(aData, 2)` so it does not read and write the data in column Z. Any suggestion Plz !
Comment: Just copy column Z to J before run macro
Comment: I want to read and write data from A to J column and Z column I want not loose the data from column J . I want to read Upto column J and column Z

excel to word using VBA


Jquery basic file upload

Question: I been working on a screencast pro proposed by Ryan called the Jquery file uploads. However every time i input images it doesn't get uploaded. I am not sure what i am doing wrong here my code. I am using google and did try to upload it but it doesn't seem to be doing anything
Javascript
application.js
//= require jquery
//= require jquery_ujs
//= require jquery-fileupload/basic
//= require jquery-fileupload/vendor/tmpl
//= require_tree .

painting.js.coffee
jQuery ->
  $('#new_painting').fileupload

Views
_form.html.erb
<%= form_for @painting, :html => {:multipart => true} do |f| %>

    <%= f.hidden_field :galley_id %>

    <%= f.label :image %>

    <%= f.file_field :image %>

    <%= f.submit %>

<% end %>

index.html.erb
Painting Gallery
<%= form_for Painting.new do |f| %>
  <%= f.label :image, "Upload paintings:" %>
  <%= f.file_field :image, multiple: true, name: "painting[image]" %>
<% end %>

show.html.erb

<%= image_tag @painting.image_url %>

  <%= link_to "Edit", edit_painting_path(@painting) %> |
  <%= link_to "Destroy", @painting, :confirm => 'Are you sure?', :method => :delete %> |
  <%= link_to "Back to Paintings", paintings_path %>

Controller
def index
    @paintings = Painting.all
  end

  def show
    @painting = Painting.find(params[:id])
  end

  def new
    @painting = Painting.new
  end

  def create
    @painting = Painting.create(params[:painting])
  end

  def edit
    @painting = Painting.find(params[:id])
  end

  def update
    @painting = Painting.find(params[:id])
    if @painting.update_attributes(params[:painting])
      redirect_to paintings_url, notice: "Painting was successfully updated."
    else
      render :edit
    end
  end

  def destroy
    @painting = Painting.find(params[:id])
    @painting.destroy
    redirect_to paintings_url, notice: "Painting was successfully destroyed."
  end

Model
  attr_accessible :image
  mount_uploader :image, ImageUploader

My main issues is when it comes to upload any picture it just doesn't have a submit button and not sure how to make it work, did i miss something??
Answer: So just got this fixed by adding timezone (i.e utc) to the expiration in S3Uploader > initialize method
for more info see:
upload to amazon S3
Answer: You are likely successfully uploading the file to your controller action,  but you're not doing anythin with it other than
@painting = Painting.create(params[:painting])

You need to do more,  like maybe saving the uploaded file somewhere on the server?
def  create
  filename = params[:painting][:image].original_filename
  filetype = params[:painting][:image].content_type
  filedata = params[:painting][:image].read
  File.open("#{Rails.root.to_s}/images/#{filename}","wb") { |f| f.write(filedata) }
  @painting = Painting.create(params[:painting])
end

This will extract the uploaded image and write it to the server.  Content_type is handy if you want to record the MIME type in the database as well.

Jquery basic file upload


How can I schedule a one-off background task in Firebase?

Question: I'm working on improving code in an application that uses Firestore. I would like to ensure that Firestore will cleanup some bits of a transaction after the transaction is completed. Instead of doing this, I may opt to run the transaction and cleanup in one transaction. However, I believe this may also introduce a race condition if other architectural changes are not made.
Anyways, in working on this problem, I realized I don't know of a way (besides making a task queue) to dispatch a one-off task in Firestore.
I think the toy example below will help explain what I want to do.
// push cleanup task to Firestore to execute in 3000ms
await dispatchTransactionCleanup({id : "xxx", inMs : 3000}); // !important

// run the actual transaction, which should not take more than 1000 ms
await runMyTransaction({id : "xxx"});

// also dispatch a cleanup here, to reduce latency over the other cleanup.
// but, importantly this cleanup isn't guaranteed to run, e.g.,
// the server crashes between request to run transaction
// and this part of the program.
await runManualCleanup({id : "xxx"});

So, how would I dispatchTransactionCleanup to run a one-off task at some point in the future? Is this possible without my own task queue? Or, do I need to introduce additional structure?
Answer: Firestore doesn't have any sense of "task" or "queue".  It just responds to the API calls you make, at the time you make them.
If you want a queuing mechanism, you'll have to build that, perhaps with some other software products.  You already linked to one solution that uses Cloud Functions on the backend.
You might want to reconsider simply doing all the work in a single transaction.  It's not clear why you think that this would be problematic.  Maybe you could post a second question to explain in more detail what you tried that wouldn't work the way you expect.
Comment: Roughly speaking it's because we use multiple (not all Firestore) stores. We have to be able to check for an available identifier, lock up transactions against that identifier, run the update, and unlock the identifiers. Not all these transactions are in Firestore. I do believe the freeing can be combined with the `runTransaction`. However...
Comment: I was more curious about a general way to do this that doesn't involve adding queue-like structure. Not solving this particular problem.
Comment: So, it sounds like if I wanted some kind of delayed operation, I'm left with (a) build the task queue like above
or (b) create a function that will await a specified delay. Is that, right?
Comment: You're definitely going need a product or some code that will schedule the work in the way you need.


Alternatives to running a single Neutral wire?

Question: I have a switch box with two switches.  I'd like to replace one of them - a single-way switch controlling a light in the hallway (which is controlled by no other switches) - with a smart switch.  The smart switch requires a neutral wire, and there is not one present in the box.  The box has cables for the other switch (the secondary end of a 3-way with switched hot and 2 travelers), and the cables for the switch I want to replace (an always-hot and a switched-hot).
It's not very far to the light: my plan was to get the ~10 feet of insulated wire that would be required, and run a single wire up through the box into the attic (following the wires that are already there), then to the light fixture where I could tap neutral.
Reading about it, it seems like single-wire runs in free air are prohibited (I'm in the US, the construction is early 2000s).  I've come up with this plan instead, and I wanted to know: (1) Is this an acceptable alternative?  (2) Is this necessary or have I misread, and I could just run a single neutral?
My plan: I can get 10' of 14/3 (it's the cheapest thing by the foot that I can find available at my hardware store... I could get 12/3 for a little more, but there's not 14/2 or 12/2), and that'll be enough for the run.  Patch white into light fixture's neutral, unplug the fixture's switched hot and instead connect the red conductor in the 14/3.  Wire the bare copper to ground, obviously.  Take the old switched-hot line and cap it.  On the switch end: run the new cable into the box, tie bare copper to the GND there, tie the switched-hot (red) to the output of the smart switch, and then I'll have my neutral.  Take the extra conductor (black) on the 14/3 and cap it on both ends.
I'm worried that this isn't quite right, either, since apparently the current in a cable needs to be net 0: does that mean I need to find where the always-hot is coming from into my switch, and wire that to the black cable in the 14/3?  If I did so I would expect I should cap the old always-hot on both ends, but I don't know if it goes and connects anywhere else.
I appreciate your help!
Side note: the GND in the switch box gets pulled in and just kinda... seems to sit there, maybe touch the wall of the box - but doesn't seem to be directly connected to the 2 switches chassis/ground: is that kosher?
Comment: if "_the construction is early 2000s_", you should have neutrals in there somewhere, maybe just behind the box.
Comment: @dandavis If it's behind the box, is there any way to get at it (shy of pulling out drywall)?
Comment: sometimes you can fish them out or through a knock-out. sometimes you can replace the box with an old work without messing up the drywall too bad.
Answer:
My plan: I can get 10' of 14/3 (it's the cheapest thing by the foot that I can find available at my hardware store... I could get 12/3 for a little more

Hold on there, you need to go find your circuit breaker first. The breaker could be 15A or 20A (rarely: 30A) but #14 can only be used on 15A breaker. Breakers protect wires.
"but my lamp only draws 12 watts" We don't design electrical for normal conditions, if we did, we wouldn't need grounds or breakers at all!

Patch white into light fixture's neutral, unplug the fixture's switched hot and instead connect the red conductor in the 14/3. Wire the bare copper to ground, obviously. Take the old switched-hot line and cap it. On the switch end: run the new cable into the box, tie bare copper to the GND there, tie the switched-hot (red) to the output of the smart switch, and then I'll have my neutral. Take the extra conductor (black) on the 14/3 and cap it on both ends.

In other words, presently you have what's called a "switch loop" with a single cable from lamp to box, using /2 cable (always-hot and switched-hot).  You are proposing adding a 14/3 cable (because it's cheaper) and using 2 wires out of it.
In 2011 Code changed to ban the old 2-conductor "switch loop".  They can still be done, but must use 3-conductor cable, with white as Real Neutral (unused and capped off) plus the usual always-hot and switched-hot.  I'll give you one guess why that code requirement was added.
So - completely unbeknownst to you - your plan is exactly what you're required to do post-2011.  Use /3 cable for switch loops.

I'm worried that this isn't quite right, either, since apparently the current in a cable needs to be net 0: does that mean I need to find where the always-hot is coming from into my switch, and wire that to the black cable in the 14/3?

Obviously you have some experience with low voltage DC from vehicles or electronics (e.g. "GND" for safety ground).  In DC you can run random individual wires wherever you need, you don't need to twist pair or otherwise couple wires unless there's a signal on them.  However, a DC magnetic field is like a refrigerator magnet.  An AC magnetic field is like a refrigerator magnet that is spinning at 3600 RPM.  Not good!
So NEC 300.3 requires current to be balanced (or equal/opposite) in each cable.  (a cable is several wires in a sheath). In practice that means your wiring diagram can be a tree topology but it can never be a loop.  Just like on a real tree where branches never merge into each other, neither can cables.
From that there's a simple rule: A device can only take neutral from a cable that it's already taking a hot wire from.
So you must use the /3 cable as the one and only cable, and remove or destroy the /2 cable.  That way, you have all 3 conductors in the same cable.
The /2 cable is unlikely to ever be useful. To destroy a cable, cut it off at the edge of the box to where it cannot be used, and push it out of the box.
Comment: Thank you for the clear explanations: I can go with the 12/3, that's not a big deal - and (if I understood correctly) my initial initial plan, to just run the neutral, is no-go.  My second plan (to just use neutral/switched hot from the new cable I'd run) is also a no-go, because the net cable power should be 0.  My final plan is OK - I'll just need to be sure that the hot I'm removing from the switch doesn't go anywhere else (or I'll need to wire that in to the new cable).  As far as "destroying" a cable: I'll agree it's "unlikely to ever be useful," but is it kosher to just cap it instead?
Comment: Update: I did it.  Running a new cable through the fiberglass in the attic was miserable, but it's all working now.  Thank you for the help!
Comment: It is kosher to just cap instead. *Except* that often switch boxes are just barely big enough, and if the wires are left capped inside the box then they count (both code-wise and physically) towards box fill.
Comment: @manassehkatz-Moving2Codidact Where can I learn/read about box fill limits?  Obviously I understand the physical implications, but I'm concerned about the legal ones.
Comment: Look around this site - there have been a lot of questions where box fill comes up (which is how I learned about it). Or try a box fill calculator like: https://www.constructionmonkey.com/calculations/misc/boxfill Sometimes the hardest part is figuring out the box size on an old box because it is marked *somewhere*...
Comment: @user112697 All the wires in the cable would need to be capped, except the ground. But yes, box fill is an issue.
Answer: To use the 14/3 the circuit must be on a 15 amp breaker, for a light circuit it is possible, most circuits with outlets are usually on 20 amp breakers now and require 12/2 or 12/3 cables.
14 gauge wire cannot be on 20 amp breakers, but 12 gauge can be on 15 amp breakers.
It sounds like you have a switch loop and to use /3 cable, one hot of /3 is connected to the hot in the ceiling to the switch.
The second hot is connected to switch and to the hot of the light.
The neutral from the ceiling is pigtail to the light neutral and the neutral of the /3 cable.  the /3 neutral is capped off at the switch, till needed for the smart switch change over.
Ground should not be "hanging" in the box, but must be screwed to the box(if metal box), if plastic box must be screwed to the switch.
If a metal box usually an option to run a ground wire from box to switch, but not usually needed since the metal of the switch, grounds to the metal of the box.


Linking a select form with a switch case PHP

Question: I am trying to link a select form with a switch case statement.
booking.php
<?php
session_start();
echo $_SESSION['$usernamepassword'];
?>
<!DOCTYPE html>

Book day!

<form method ="post" action='booking2.php'>
<select>
  <option value="friday">Friday</option>
  <option value="saturday">Saturday</option>
  <option value="sunday">Sunday</option>
 </select>
    <input type="Submit" name="submit">

</form>

pbooking.php
<?php
session_start();
echo $_SESSION['$usernamepassword'];
?>
<!DOCTYPE html>

<?php
    switch ($_POST["value"]) {
        case "friday":
            header('Location: friday.php');
            break;
        case "saturday":
            header('Location: saturday.php');
            break;
        case "sunday":
            header('Location: sunday.php');
            break;
    }
?>

I have created two documents.
The first document, booking.php contains the form.
In the form there is the dropdown.
On the second document, pbooking.php contains the switch case.
I am trying to link the switch off the value.
As the value changes the case changes, friday - saturday - sunday.
It doesn't work... returning undefined index line 7 ('value')
This would suggest to me that it needs to be linked off something else?
Any suggestions? Thanks.
Answer: Please use name attributes in <select> tag
like this:
<select name="value">

Answer: Try this :
<form method ="post" action='booking2.php'>
<select name="value">
  <option value="friday">Friday</option>
  <option value="saturday">Saturday</option>
  <option value="sunday">Sunday</option>
 </select>

Your $_POST['value'] is not linked with any input
Answer: You need to give name attribute to your select type. Also change your action to pbooking.php
<form method ="post" action='pbooking.php'>
    <select name="value">
      <option value="friday">Friday</option>
      <option value="saturday">Saturday</option>
      <option value="sunday">Sunday</option>
     </select>
 <input type="Submit" name="submit">

</form>

Answer: Put name="value"
<select name="value">

Comment: This answer has been flagged as low quality. I will not recommend deletion but I will request you to kindly explain why adding that code will solve OP's question. That should improve the quality of your answer.


time() to DateTime

Question: I have an application that uses time() to record the time a topic was posted. I have done this for a long time and the only glitch i ever had with the method was that the time was always off by an hour (mainly a DST issue i never looked into).
I'm want to switch to the DateTime method, since I'm also switching to Twig, which uses that date format when setting a timezone.
But from what I can see, you can't use timestamps to parse the date. my question is, how do you input a date and parse it and what format are they looking for if it isn't time()?
Comment: it followed until half of the second paragraph.. then it is not very clear..
Comment: I'm assuming this is database driven (given your mention of saving topic creation time) so my biggest question is--why aren't you using the DB's integrated time? (Let the database handle the time, PHP should only convert it to a local time for the user).
Answer: By the sounds of it your server's default timezone is UTC. I suggest you try changing the default_timezone setting in php.ini to something that applies DST. This will mean that when you use date(), the resulting output will be correctly adjusted for DST.
Comment: the thing is, this application is used on different systems, so i sorta need to do something that the typical user can do on a shared hosting account. I wouldn't mind to UTC if i knew what i had to do to make the switch.
Comment: example of what I'm talking about: http://twig.sensiolabs.org/doc/filters/date.html
Comment: `date_default_timezone_set("Europe/London")` would help you. Or whatever timezone you need. Just put that at the start of your PHP scripts and you don't have to worry.
Comment: the issue is, each user could be at a different timezone. also all my time values are in time, datetime doesnt accept it.
Answer:
you can't use timestamps to parse the date

There is a way, if your php version is >=5.3 :
$time = time();//or other time
$date = DateTime::createFromFormat('U',$time);

but as a matter of fact it is somewhat weird to use timestamp as DateTime does not rely on it. You can parse a date string directly with the datetime constructor if your date is english or "french" (i.e d/m/y). You can also create your custom format.

how do you input a date and parse it and what format are they looking for if it isn't time()

if it is a a standard format date :
$date = new DateTime($yourString);//would throw an exception if the format is wrong

if it is a custom format, like DD/MM/YYYY 14h32mins
$date = DateTime::createFromFormat('d/m/Y h\hi\m\i\n\s',$yourString);
if($date === false){//if format does not fit
   exit('Your wrong !');
}

I have an application that uses time() to record the time a topic was posted.

Very bad practice. In MySQL you have DateTime format (and each relational data base system has his own equivalent) to store date times and there are fully compatible with the DateTime constructor in PHP so migrate to it (use FROM_TIMESTAMP to change into DateTime).

time() to DateTime


Windows Batch File for loop on user dir

Question: I need to create a batchfile to delete a specific file in the users appdata dir. The batchfile is executed as localsystem.
I did test the following senarios:
Command Prompt as localsystem - this works
Command Prompt as admin - this works
Command Prompt as user - this works for all folders where the user has permissions
As soon as i put the for loop in a batch file, it dosent work anymore.
It also dosent matter in which context (User,admin,localsystem) i start it.
for /D %i in ("C:\Users\*") do del /Q /F "%i\AppData\LocalLow\Sun\Java\Deployment\deployment.properties"

The exit code shows 255, which means to long error.
The error i get is the following:
C:\Windows\Scripts>sync_exeptionsiteslistandconfig_java.bat > output.txt
\Users\*") do del "i\AppData\LocalLow\Sun\Java\Deployment\deployment.properties"  /Q /F was unexpected at this time.

Any help why the single line is working and a batchfile with this single line is not working is welcome.
Please also explain why it is not working. (I always run tasks as localsystem)
Answer: This may do what you want, but it only processes normal folders, not hidden etc.
Your problem may have been using %i within a batch script.
@echo off
for /D %%i in ("C:\Users\*") do del /Q /F "%%i\AppData\LocalLow\Sun\Java\Deployment\deployment.properties" 2>nul

Comment: Hi,Thank you very much, it works. But do you know why using %%i instead of %i? I could still not understand why it is working directly in a command prompt.
Comment: It's required in a batch file for loop to double the `%` signs.  At the cmd prompt only one `%` is used.

Windows Batch File for loop on user dir


How should I terminate a looped sub-thread in Java?

Question: I need to do some clean up work when I am going to terminate a looped thread. Such as saving a buffer so I can continue later.
PseudoCode:
private class CalculatePI(Byte[] resume) implements Runnable{
    public void Run(){
       while(true){
          resume=resumeCalculating(resume);
       }
    }
}
Thread calculator= new Thread(new CalculatePI(Byte[] resume));
Thread.sleep(200);
//And now I want to kill calculator

So what's the best way implement this?

Use a flag: But the problem is what if resumeCalculating() takes (EDIT: a long time) forever to end?
Put an exception into calculator, how?
Can I use event listeners or something? I thought they were used for GUIs
Just stop it? And Class Thread includes some kind of deconstructor that will be called when the thread is terminated and I could do the processing there?

EDIT by Owner:
I know I can use a flag. But consider this:
    public void Run(){
       while(true){
          resume=calculate_stepone(resume); //takes one minute
          resume=calculate_steptwo(resume); //takes two minutes
          resume=calculate_stepthree(resume); //takes three minutes
          resume=calculate_steplast(resume); //takes four minutes
       }
    }

Is putting a if(flag) saveResultsAndExit(); between every line practical or pretty?
I just want to throw away the half-processed results, and save the previous results.
Answer: The proper way to stop a thread is to interrupt it.
If the task running in the thread is performing IO or is using sleep then it will receive the signal (InterruptedException at that point); else the task should regularly poll to see if its interrupted.
Lets adapt the original poster's psuedocode:
private class CalculatePI(Byte[] resume) implements Runnable{
    public void Run(){
       while(!Thread.interrupted()) { //###
          resume=resumeCalculating(resume);
       }
    }
}
Thread calculator= new Thread(new CalculatePI(Byte[] resume));
calculator.run(); //###
//...
//And now I want to kill calculator
calculator.interrupt(); //### sends the signal
//...
calculator.join(); //### actually waits for it to finish

Comment: just don't forget that `interrupted()` also clears the *interrupted status* so subsequent calls will return `false`.
Answer: Answer to 1.: You can process the abort flag in resumeCalculating() too.
Comment: Yes I can process the abort flag in resumeCalculating(), but that isn't as pretty I would like it to be. resumeCalculating should care only about calculating PI, not handling how it should die. That code would be best in the calculator thread. And what if I had many steps?
Answer: It is probably best to use a flag, wait for a while for the thread to end, and if it hasn't (resumeCalculating hasn't returned) kill the thread manually. It is probably best not to involve too much thread based logic in resumeCalculating, it really depends on how it is implemented as to how easy it is to abort halfway through an operation.
Answer: Design your program so that resumeCalculating does NOT take forever to continue. Also, synchronize access to your flag.


Flexbox CSS Overflow Div Content is Expanding Div

Question: I am working on styling an app. I have made a mock layout here: https://codepen.io/Sean713/pen/VwdgMEx?editors=1100
My code will also be pasted at the bottom.
Everything works the way I want it to, except for the fact that when the green div has too much content (you can uncomment the p tags), it increases the size of all the divs. I don't want those divs to change in size, rather I just want the content in the green div to compress to a scrollable section, how can I fix this?

Solve

About

Other

      This is the top left half

      This is the top right half

I can scroll

I can scroll

I can scroll

body {
  margin: 0;
  padding: 10px;
  background-color: white;

  display: flex;
  flex-direction: column;
  height: 100vh;
}

.yellow {
  background-color: yellow;
  padding: 10px;

  flex: 1; /* should occupy the entire screen except the navbar */
  display: flex; /* should create flex for blue and red */
  flex-direction: column;
}

.blue {
  background-color: blue;
  flex: 2; /* should take up 2/3rds of yellow */
  display: flex; /* should create flex for the top left and top right halves */
  min-height: 240px;
  padding: 10px;
}

.red {
  background-color: red;
  padding: 15px;

  flex: 1; /* should take up 1/3rd of yellow */
  display: flex; /* should create flex for green, so that green can expand to fill it */
  flex-direction: column;
  min-height: 120px;

}

.green {
  background-color: green;
  overflow: scroll;

  flex: 1; /* should fill the entire red */
}

.darkgrey {
  background-color: darkgrey;
  flex: 1; /* will fill half the width of blue */
}

.lightgrey {
  background-color: lightgrey;
  flex: 1; /* will fill half the width of blue */
}

/*  navbar stuff */
ul {
  list-style-type: none;
  display: flex;
  align-items: center;
  margin: 0;
  box-sizing: border-box;
}

/*  navbar stuff */
li a {
  display: block;
  text-align: center;
  padding: 15px 15px;
  text-decoration: none;
}

Answer: Display: flex;

  1
  2
  3`enter code here`
Comment: Hi Deeptimaan, thank you very much for your answer. Could you explain this further? I do not really understand. What is this code doing, and where do I put it?
Answer: .green{
overflow:auto
}

if you specify sizes, it'll show scrolls
Comment: When I enable `overflow:auto` and uncomment the additional p tags, the green div expands which I do not want. Does specifying sizes fix this? How can I do that?
Comment: As a mentioned, add min-max height
Comment: Thanks, but I think this doesn't really work. If I add `overflow: auto;` and `max-height: 80%;` to the green div, my blue div will still expand to be huge if I populate the green div with a lot of content.


Open CL clEnqueueReadBuffer execute time

Question: im writing open cl flocking and i have strange issue. Before Kernel Execute, clEnqueueReadBuffer read from gpu mem to program mem 20000 array float with no problem, very fast, but after kernel execute which did some operation on that passed array, readbuffer last too long (~150 ms). Why? In both case array was filled with data. What possibly wrong my kernel doing? (that passed array is __global).
Comment: how was the gpu memory filled with data before a kernel is executed?
Answer: clEnqueueNDRangeKernel doesn't actually launch the kernels, it "enqueues" them. The OpenCL implementation is free to start kernels whenever it sees fit (in this case, when you ask to read the results, since it needs to run the kernel to know the results).
You can, however, force the implementation to start the kernels via clFinish.
In your case, the 150ms delay is, in fact, the time taken for the kernel to run.
If you call clFinish between execute and second read, it will work.


Vert.x ReadStream to InputStream

Question: I am trying to set up Vert.X with Jersey to handle POST data (not necessarily form data).
The Jersey ContainerRequest.setEntityStream takes in an InputStream which is what I am trying to build.  However, I can't seem to get around passing that data without reading the whole thing into memory using bodyHandler or my own custom method that does something similar but limits the input
    final Buffer body = Buffer.buffer();
    event
        .handler(buffer -> {
            if (!event.response().headWritten()) {
                body.appendBuffer(buffer);
                if (body.length() > 10 * 1024 * 1024) {
                    event.response()
                        .setStatusCode(REQUEST_ENTITY_TOO_LARGE.getStatusCode())
                        .setStatusMessage(REQUEST_ENTITY_TOO_LARGE.getReasonPhrase())
                        .end();
                }
            }
        })
        .endHandler(aVoid -> {
            request.setEntityStream(new VertxBufferInputStream(body));
            appHandler.handle(request);
        });

VertxBufferInputStream is a simple wrapper to the VertXbuffer.  Just to save some memory by avoiding converting to a ByteArrayInputStream().  But it has the whole body.
I want to avoid having the whole body and have it streamed.  I've tried a few things all pretty hacky and bad code that eventually does not work because it blocks the event loop because the handler is not called and is waiting for it.
Answer: There are two components that are needed.

you need to make sure you separate the processing for anything that may block using vertx.executeBlocking see https://github.com/trajano/app-ms/blob/7f1de326683473839ffe85fe711cbe719f7a0a74/ms-engine/src/main/java/net/trajano/ms/engine/JaxRsRoute.java#L128

you need to handle two events: when new buffer of data comes in and when it ends.  https://github.com/trajano/app-ms/blob/7f1de326683473839ffe85fe711cbe719f7a0a74/ms-engine/src/main/java/net/trajano/ms/engine/JaxRsRoute.java#L123

you need to implement an InputStream that would be able to accept data from another thread and block when there is no data along with the capability of receiving a message that there is no more input.
https://github.com/trajano/app-ms/blob/master/ms-engine/src/main/java/net/trajano/ms/engine/internal/VertxBlockingInputStream.java
Answer: Such a beautiful problem to solve :)
You can get an inspiration at https://github.com/jersey/jersey/blob/12e5d8bdf22bcd2676a1032ed69473cf2bbc48c7/containers/netty-http/src/main/java/org/glassfish/jersey/netty/httpserver/JerseyHttp2ServerHandler.java#L124
where Jersey integration with Netty is implemented.
I believe there are exactly the same problems solved (although for a different webserver, Netty in this case), that is:

The http request is handled on an event loop (by Netty), as such the ApplicationHandler.handle() method has to be called on a different thread (non event loop)
Non blocking API has to be converted to blocking InputStream. That is implemented at NettyInputStream. It takes advantage of the fact that Netty's ByteBuf can be easily converted to an InputStream and as a result by using LinkedBlockingDeque these InputStreams are converted to a single one. (Just fyi, I'm not 100% sure if the provider, the event loop thread, is guarantied to never block which would be a bug.)

By the way, this is just a processing of the incoming data. For the response, you'll have to implement a conversion of OutputStream (used by Jersey) to Vert.X non-blocking API.
Comment: Thanks I also looked into it.  One of my attempts was similar to that but it still blocks because "take()" will block.
Comment: I don't understand. That's perfectly ok; `take()` is blocking (that's the contract of `InputStream.read()`). The important part is what I described at [1], the `ApplicationHandler.handle()` has to be delegated to a different thread. As a consequence, the `take()` method is called by this other thread and everything works perfectly. There's no other way than this unless Jersey came with non-blocking API which didin't happen (unfortunately; but it was close).
Comment: Correct it is the closest one.  (I just got it working right now)

Vert.x ReadStream to InputStream


Menu Change sprite and color on click

Question: I am trying to change my menu icons and color of text on click.
in my menu Each

 element has a hyperlink tag there are 2 child below it  and
 what i am trying to achieve is on click the class has to be changed to

 and when the next menu item is clicked this active class has to be removed
JS Fiddel
HTML CODE

Menu1

Menu2

Menu 3

Menu4

Menu5

Menu6

CSS CODE
#grid{
    width: 750px;
    margin:0 auto;
}
#menuBase{
    background: #fff;
    width:100%;
    height:44px;
    -webkit-border-radius: 90px 90px 0 0;
    -moz-border-radius: 90px 90px 0 0;
    border-radius: 90px 90px 0 0;
    border-right:2px solid #fff;

}

#menu{
    background: #E1E1E3;
    width:100%;
    height:100%;
    -webkit-border-radius: 99px 99px 0 0;
    -moz-border-radius: 99px 99px 0 0;
    border-radius: 99px 99px 0 0;
    border-right: 1px #fff solid;
    border: 2px    #ccc solid;
    border-right: none;
    border-bottom: none;
}

#hrhead{
    background: #cccccc;
    height: 3px;
    -webkit-margin-before:0;
    -webkit-margin-after:0;
    border-bottom: 1px #ffffff solid;
}

#hrfoot{
    background: #cccccc;
    height: 3px;
    -webkit-margin-before:0;
    -webkit-margin-after:0;
    border-top: 1px #ffffff solid;
}

#menu ul{
    float:left;
    width:100%;
    padding-left:43px;
    margin:0;
    list-style-type:none;
}

#menu li{
    display: block;
    float: left;
    width:40px;
    height: 25px;
    margin-right: 68px;
    margin-top: 11px;
}

#menu li:last-child{
    margin-right: 0px;
}

.icon{
    height:25px;
    width: 40px;
    display: block;
    color:#777777;
}

#mtext{
    height:27px;
    width: 80px;
    display: block;
    margin: 11px 0 0 -20px;
    text-align: center;

}
#menu li a{
    text-decoration:none;
}
#menu li a:hover #mtext{
    color:#DC0000;
}
#menu li a:hover .icon{
    background-position-y:24px;
}

#home{
    background: url(http://i47.tinypic.com/2nroe9k.png)0 0;
}

#about{
    background: url(http://i47.tinypic.com/2nroe9k.png)0 0;
}

#soln{
    background: url(http://i47.tinypic.com/2nroe9k.png)0 0;
}

#lab{
    background: url(http://i47.tinypic.com/2nroe9k.png)0 0;
}

#port{
    background: url(http://i47.tinypic.com/2nroe9k.png)0 0;
}

#contact{
    background: url(http://i47.tinypic.com/2nroe9k.png)0 0;
}

.active{
    background-position-y:24px !important;
    color:#DC0000 !important;
}

Jquery [Damm i am lost]:
$("#menu > ul > li > a").click(function(e){
    e.preventDefault();

});

Comment: check this fiddle out http://jsfiddle.net/uWEwJ/
Answer: DEMO : http://jsfiddle.net/VLXxR/8/
$("#menu > ul > li > a").click(function(e){
     e.preventDefault();
     $("#menu .icon").removeClass("active");
     $(this).children(".icon").addClass("active")

  });

Answer: DEMO : http://jsfiddle.net/VLXxR/7/
 $("#menu > ul > li > a").click(function(e){
     e.preventDefault();
     $("#menu .icon").removeClass("active");
     $(this).find(".icon").addClass("active")

  });

Check out the documentation for removeClass - http://api.jquery.com/removeClass/
Answer: Your js should be like this ,FIDDLE
 $("#menu > ul > li > a").click(function(e){
     e.preventDefault();
     $("#menu > ul > li > a > div,#menu > ul > li > a > span").removeClass('active');

     $('div',this).addClass('active');
     $('span',this).addClass('active');
 });

Menu Change sprite and color on click