Count-up Timer required

Question: I've been wanting to create a timer for my website that countsup, and displays alerts at certain intervals. So like, it starts from 0 and counts upwards when the user pushes a button. From there, it will display a a custom alert at certain intervals... (4 minutes for example)... 45 seconds before that interval,  I need the number to change to yellow and 10 seconds before that interval, I need it to change to red... then back to the normal color when it passes that interval.
I've got a basic timer code but I am not sure how to do the rest. I am quite new to this. Any help? Thanks so much in advance.

var pad = function(n) { return (''+n).length<4?pad('0'+n):n; };

jQuery.fn.timer = function() {
    var t = this, i = 0;
    setInterval(function() {
        t.text(pad(i++));
    }, 1000);
};

$('#timer').timer();

Answer: You can try something like this:

JSFiddle

This is a pure JS timer code. Also for popup you can use something like Bootbox.js.
Code

function timer() {
  var time = {
    sec: 00,
    min: 00,
    hr: 00
  };
  var finalLimit = null,
    warnLimit = null,
    errorLimit = null;
  var max = 59;
  var interval = null;

  function init(_hr, _min, _sec) {
    time["hr"] = _hr ? _hr : 0;
    time["min"] = _min ? _min : 0;
    time["sec"] = _sec ? _sec : 0;
    printAll();
  }

  function setLimit(fLimit, wLimit, eLimit) {
    finalLimit = fLimit;
    warnLimit = wLimit;
    errorLimit = eLimit;
  }

  function printAll() {
    print("sec");
    print("min");
    print("hr");
  }

  function update(str) {
    time[str] ++;
    time[str] = time[str] % 60;
    if (time[str] == 0) {
      str == "sec" ? update("min") : update("hr");
    }
    print(str);
  }

  function print(str) {
    var _time = time[str].toString().length == 1 ? "0" + time[str] : time[str];
    document.getElementById("lbl" + str).innerHTML = _time;
  }

  function validateTimer() {
    var c = "";
    var secs = time.sec + (time.min * 60) + (time.hr * 60 * 60);
    console.log(secs, finalLimit)
    if (secs >= finalLimit) {
      stopTimer();
    } else if (secs >= errorLimit) {
      c = "error";
    } else if (secs >= warnLimit) {
      c = "warn";
    } else {
      c = "";
    }
    var element = document.getElementsByTagName("span");
    console.log(element, c)
    document.getElementById("lblsec").className = c;
  }

  function startTimer() {
    init();
    if (interval) stopTimer();
    interval = setInterval(function() {
      update("sec");
      validateTimer();
    }, 1000);
  }

  function stopTimer() {
    window.clearInterval(interval);
  }

  function resetInterval() {
    stopTimer();
    time["sec"] = time["min"] = time["hr"] = 0;
    printAll();
    startTimer();
  }

  return {
    'start': startTimer,
    'stop': stopTimer,
    'reset': resetInterval,
    'init': init,
    'setLimit': setLimit
  }
};

var time = new timer();

function initTimer() {
  time.init(0, 0, 0);
}

function startTimer() {
  time.start();
  time.setLimit(10, 5, 8);
}

function endTimer() {
  time.stop();
}

function resetTimer() {
  time.reset();
}
span {
  border: 1px solid gray;
  padding: 5px;
  border-radius: 4px;
  background: #fff;
}
.timer {
  padding: 2px;
  margin: 10px;
}
.main {
  background: #eee;
  padding: 5px;
  width: 200px;
  text-align: center;
}
.btn {
  -webkit-border-radius: 6;
  -moz-border-radius: 6;
  border-radius: 6px;
  color: #ffffff;
  font-size: 14px;
  background: #2980b9;
  text-decoration: none;
  transition: 0.4s;
}
.btn:hover {
  background: #3cb0fd;
  text-decoration: none;
  transition: 0.4s;
}
.warn {
  background: yellow;
}
.error {
  background: red;
}

 00
    : 00
    : 00

  <button class="btn" onclick="startTimer()">Start</button>
  <button class="btn" onclick="endTimer()">Stop</button>
  <button class="btn" onclick="resetTimer()">Reset</button>

Hope it helps!
Answer: Something like this should work:
Here is a jsFiddle DEMO
jQuery
$.fn.timer = function (complete, warning, danger) {

var $this = $(this);
var total = 0;

$this.text(total);

var intervalComplete = parseInt(complete, 10);
var intervalWarning = parseInt(intervalComplete - warning, 10);
var intervalDanger = parseInt(intervalComplete - danger, 10);

var clock = setInterval(function () {

    total += 1;

    $this.text(total);

    if (intervalWarning === total) {
        // set to YELLOW:
        $this.addClass('yellow');
    }

    if (intervalDanger === total) {
        // set to RED:
        $this.removeClass('yellow').addClass('red');
    }

    if (intervalComplete === total) {
        // reset:
        clearInterval(clock);
        $this.removeClass();
        alert('COMPLETE!');
    }

}, 1000);

};

$(function () {
   $('#timer').timer(240, 45, 10);
 });

CSS
.red {
background-color: red;
}

.yellow {
    background-color: yellow;
}

An additional point:

You should place some error validation within the function to ensure your counter completion time is greater than both the warning and danger time intervals.
Answer: You could do something like this

var pad = function (n) {
    return ('' + n).length < 4 ? pad('0' + n) : n;
};

jQuery.fn.timer = function () {
    var t = this,
        i = 0;
    setInterval(function () {
        t.text(pad(i++));
        checkTime(i, t);
    }, 1000);
};

$('#timer').timer();

checkTime = function (time, t) {
    switch (time -1) {
        case 10:
            t.css('color','red');
            break;
        case 20:
            t.css('color','yellow');
            break;
        case 30:
            t.css('color','green');
            break;
        case 40:
            t.css('color','black');
            break;
        default:
    }
};

Comment: This is good. However, at the intervals I need a popup that won't affect the timer counting up and also buttons to Start, Stop and Reset.
Comment: Use jquery dialog instead of alert, it will look nicer and will not stop the count.
Comment: Can I msg you about this on G+?

Count-up Timer required


Find no of discontinuity of the function $f(x)=\max\{[x^2];x \in[0,2]\}$

Question: Here $[y]$ denotes greatest integer less than or equal to y.
My effort: $f(x)=0$ when $0\le x<1$
<code>            =1 when x=1 ; so x is a point of discontinuity

            =2 when $x^2>2; so x is a point of discontinuity

            =3 when $x^2>3; so x is a point of discontinuity

            =4 when x=2 ;so x is a point of discontinuity
</code>
Hence no of discontinuity is 4. Am I right?
Answer: Note that $$\lfloor x^2 \rfloor = \begin{cases} 0, &x\in [0,1) \\ 1, & x\in [1,\sqrt 2) \\ 2,& x\in [\sqrt 2,\sqrt 3) \\ 3, & x\in [\sqrt 3, 2) \\ 4, & x=2 \end{cases} $$ From here it is easy to deduce that in $[0,\sqrt 2)$, $x$ will be greater than $\lfloor x^2 \rfloor$, and in $[\sqrt 2, 2]$, $\lfloor x^2 \rfloor $ is greater. Hence, $$f(x) =\begin {cases} x, & x\in [0,\sqrt 2) \\ \lfloor x^2 \rfloor, & x\in [\sqrt 2,2] \end{cases} $$ Before, $\sqrt 2$, we have no discontinuities, but there are discontinuities at $x=\sqrt 2, \sqrt 3, 2$ arising from the floor function, giving a total of $\mathbf 3$ discontinuities.


Rewiring house and replacing breaker panel. Wiring layout and breaker selections

Question: I'm doing a major kitchen and bathroom remodel project and decided the old federal pacific breaker box needs to be replaced. Since I'll be rewiring the bath and kitchen, I figured it makes sense to plan to eventually rewire the entire house.
I made a spreadsheet with all of the current and future loads I may add to the house then sectioned them off into different branch circuits with the type of breaker that will protect them. Would someone mind taking a look at my planned-out wiring and let me know if it looks correct or if I'm missing something obvious? I hope to get some feedback about best practices for planning house circuits and what methods are needed to protect them, using NEC 2014 for reference (I live in Portland, OR).
Some additional information relating specifically to my project:

My house was built in 1956
Most of the wiring is NC fabric-coated wire. Some of it is romex
The old house panel is a 100A sub panel, fed by a 200A main panel in the detached garage
I plan to replace the house panel with a 16 or 20 slot 100A panel (is one or the other better?)
If there are any AFCI and GFCI combination requirements, the main breaker will be AFCI and any outlets on that branch will be GFCI outlets
I plan on driving in two new grounding rods at the sub panel and bond them to the water main (house is getting re plumbed with pex) and gas pipes
Does this sub panel need a grounding wire connected to the main panel in the garage?

Here is my spreadsheet:
based on feedback, here's an updated plan:
Updated!! v2
Comment: @Sparky256, this is not at all true in most areas. And the part about the fire marshal is an old school fire and brimstone wives tale. ......+1 for balance.
Comment: Depending on jurisdiction, he doesn't neccessarily require an electrician to sign off on the work, but he likely requires at least a permit. Professional advice, for a project of this complexity (and potential hazard) is a good idea, but it may not be required.
Comment: You have all 20amp breakers listed on your spreadsheet. Are all of these branch circuits wired with 12 gauge wire?  Also your knowledge of grounding where more is better is wrong. There are specific codes that address this. You must feed the sub-panel with 4 conductors, you should not bond additional grounding at that point. Watch out for ground loops.
Comment: @Tyson, ground loops are not really an issue with residential dwelling wiring. It's not like he's wiring a sound studio.
Comment: Thanks all. @Tester101 -Ed, below, mentioned the same. I will make sure to have two dedicated outlet branches for the kitchen. Exactly the kind of feedback I was looking for.
Comment: Just to add to this, I'm _definitely_ having the whole thing inspected and permitted... and if anyone reading this wants to do a similar project, don't skip this step! I want to make sure I have a well thought out circuit before wiring everything up, then come to find out I did it wrong when the inspector comes.
Comment: @Sparky256, generally an inspectors does the inspections. But that wasn't my point.
Comment: 1 additional comment about your bathroom circuit. I am guessing you only have 1. You can feed the lights fan and outlets on 1 circuit if there is only 1 bathroom and this circuit is dedicated to the bathroom. If there are 2 bathrooms the bathrooms the outlet circuit can have no other loads.
Comment: @EdBeal yep, I've got them all on one circuit. The house is a 3/1 so yeah, no other bathroom.
Answer: That Federal Pacific panel has to go as they are dangerous.  As far as concerns about your skill, you sound like that particular kind of newbie who is well capable of learning to do it all safely and well; however my hunch is you are still thinking too much, and need to read a little more.  It's OK, we all start there.
Normally, just replacing a sub panel is a straightforward thing.  Change panel, reattach wires, done.  However, this is only part of a project with a much larger scope.  You must contemplate (i.e. ask your permitting authority) whether you have crossed the legal threshold of a remodel.  If you have, everything in-scope must be done to all current codes.  Even ADA!
The 2-circuit requirement for kitchen outlets is not intended to mean "1 circuit for this wall, 1 circuit for the other wall".  I'd encourage some more research but if it was me, I'd interleave the outlets, every other outlet on a different circuit.  Also there's nothing wrong with more than 2 outlet circuits in a kitchen, the whole point is to prevent trips when the chef is madly at work, so the chef isn't hobbled with limitations like having to put the toaster here and the George Foreman over there, and avert ugly workarounds like extension cords draped across sinks or stoves, etc.
I see you plan to go 12 AWG wire for almost everything (that's what 20A breakers mean) - that's awesome.  Feel free to kick the refrigerator and smoke detector up to 12AWG also - that way you don't have to buy any 14AWG wire.  I don't own any!  If you have some other reason to use a 15A breaker you are welcome to use that on a circuit wired in 12AWG.
You may want to run the water heater circuit in 10/2 or even 8/2.  That will allow you to easily upgrade to an electric water heater in the future.  Still use a 15A or 20A breaker because the outlet is still only good for 20A.   There is a trick to fitting 8+ AWG wire on a 15-20A outlet, just ask.
I would go with a much larger panel. You have either -1 or 3 circuits left, and that's too little headroom for my comfort.  Getting a larger panel is dirt cheap compared to the cost of replacing perfectly good breakers with duplex breakers (I call them double-stuff) merely to shoehorn everything in.   Also, larger panels in combo-packs come with more breakers and that is far-and-away the cheapest way to buy breakers.  Another reason to avoid duplex breakers is if you ever need AFCI, GFCI or whatever future thing comes out - those are much more expensive in duplex breakers because of the miniaturization required.  Don't think you must use a 100A panel - you can use a larger panel (200A), you just can't use a smaller one (70A).
Remember each sub-panel must have its neutral bus bar separate and isolated from its ground bar.  That means removing bond straps, magic green screws, neutral bar kits, whatever the panel requires to do that.  You might consider a panel with a neutral and ground bar on each side of the panel.  That's a convenient feature so wires don't have to cross over the panel.
Keep in mind how your house got a dangerous Federal Pacific panel.  The last guy bought cheap.  Feel free to research the good-better-best that each manufacturer offers, the price differential for "best" is quite small compared to the overall cost of a remodel.  You may find better selection and better prices at a real electrical supply house.
There is nothing wrong with more ground rods.  Go nuts.  The key is that all the grounds are connected to each other by wire - and they are not connected to neutral anywhere except one place - the main service panel.
Comment: I have not seen duplex/quadruplex GFCI/AFCI breakers yet -- and when I asked Eaton about 'em, they weren't in the cards from what I was told.  Also, re: ADA -- "universal access benefits everyone".  (As a simple example from the commercial space -- being able to use a barrier-free water fountain while your hands are full *chuckles*.)
Comment: Thank you for the great insight. You're right, I'm a total noob at this and if it were my choice, I'd leave the electrical to a pro. Unfortunately I can't afford it. Not only that, I love to learn and have always wanted to know more about electrical work so this seemed like a good opportunity. Saying I up to a 150A sub panel, can I keep the existing conductor from the main panel? The sub panel is fed by a 100A breaker in the main panel. Thanks for the water heater recommendation... That should be an easy upgrade. I'll also just run full 12AWG (had this originally in the plans)
Comment: Also! Good info on the kitchen circuit. That makes sense. I was mainly planning it based upon ease of install. My kitchen is quite small which is why I have just the 2 circuits for the outlets. Can I get your opinion on the number of outlets I have listed for each of those and if you think it's enough (circuits 14 and 16)? I suppose if I'm going to go with a 150 or 175A panel, adding another branch would be pretty trivial. I just feel like I'd kinda be wasting wire/breakers if I don't really need to.
Comment: Yeah, you can use any size panel you like, as long it is 100A or more, and you can use the old wire run.  The breaker in the main panel must be the lesser of what the sub-panel allows and what the wire from main to sub-panel allows.  I'd hit up a bookstore or HD/Lowes, check out their books and find one that speaks to you and devour it.  Beware library books as they tend to be old, and there have been big code changes recently.  You really want to take note of the code stuff e.g. around kitchens.
Comment: Kitchen outlets totally depend on the peculiar geometry of the kitchen.  Those rules are fairly picayune and I can't guess without seeing a layout.  But the books will tell you. The rules seem arbitrary but do eventually make sense if you work with them enough.
Comment: It's my understanding, that the folks in the frozen north like to split countertop duplex receptacles between separate circuits. So the top of each receptacle is one 20 ampere circuit, and the bottom is another. Just thought I'd throw that out there.
Comment: @tester101 I came across that yesterday. I might actually just do that since all I need is a 12/3 run to each outlet. That'd save quite a bit of cable in the long run
Comment: @tbox not so fast. If the receptacles are GFCI protected, you'll have to keep the load side neutrals separate.  So you'll need 12/3 to the first GFCI, then 12/2/2 after that. If you use GFCI breakers, you'll need two separate 12/2 cables or a 12/2/2 for the whole run.
Comment: @Tester101 ah yes, the neutrals need to be isolated. Thanks for the reminder. 12/2/2 seems to be my best bet.
Comment: Today, Code prohibits everything that made that "frozen north" shortcut make sense.  Terrible idea now.  #1 Code now requires GFCI, so either expensive 2-pole GFCI or very tedious separation of neutrals.  #2 you'd need to pigtail all 4 wires, box fill is an issue.  #3 consumers don't expect it and it's hard to explain: they trip breaker, ok move the George Foreman to the next receptacle down, still trips breaker, what?  #4 it can leave you too little ground wire capacity.  #5 even if it wasn't GFCI you need to pigtail neutrals because MWBC. I would just use dual 12/2 and leapfrog receptacles.
Answer: I am a licensed Oregon electrician and it IS 100% legal to do your own wiring including planning. It needs to meet code or it will not pass inspection.
First I would never update to a new panel for a home with a 100A even as a sub.
I would put in at least a 150A panel with more breakers, the cost difference is not that big. 100A is the minimum size allowed by code so it is legal.
After a quick look, you need 2 20A circuits for counter top appliances in the kitchen these can have no other loads  (with the exception of a clock outlet & an A gas range igniter outlet). You will need tamper resistant outlets in all areas below 5-1/2'. I am not aware of a 240V AFCI and you have one listed for the dryer. To my knowledge only 120v AFCI protection is required. You should install a outlet close to the water heater because in the future it looks like we wont have pilot lite water heaters available. The garbage disposal dishwasher  afci/gfci not a good idea ORS918 table 1E gfci not required for dishwasher , also GFCI AFCI not required on equipment known to have problems with these. Garbage disposals wipe them out regularly. Maybe I missed it but I don't see a refrigerator, freezer outlets. The Oregon exception for GFCI on these is behind equipment not easily moved. Stoves, refrigerator, freezer, built in microwave, dishwasher are all examples where they are not required in Oregon. You listed porch lights there will need to be a GFCI outlet at each porch (outside). That's a quick first Pass it always is a good idea to get a review. I will look it over again later just in case I spot something I missed. Good luck and be safe.
Comment: Thank you @Ed Beal. I was wondering about the GFCI requirements. Good to know I don't need them behind "not easily movable" appliances. I thought since they weren't hardwired they were required.

The water heater is a tankless gas heater so I can easily change that to a single outlet instead of hard wire.
Comment: My mistake on the 240V AFCI--that will just be a regular 30A breaker. I will also leave out AFCI/GFCI for the dishwasher/disposal. And yes, I totally forgot the refrigerator... that doesn't need a dedicated circuit does it? I also forgot to add in a circuit for hardwired fire/co2 alarms. So you would recommend going to a 150A panel instead? Does that mean I'd have to run new conductor from the main 200A panel to the house? I don't know if that would be worth it for me. It's a small house and what I have listed is probably the max I could ever add to the house.
Comment: There are two-pole AFCIs out there but they only go to 20A.
Comment: Since this is a sub you could put in a larger panel with the feeder wiring sized to the breaker in most areas I have worked in Oregon. With the AFCI the breakers cost $ and I am sure 1/2 are way expensive if they exist I have not looked or purchased a 1/2" AFCI but the few 1/2" GFCI's that I did buy almost caused my brother heart failure!
Comment: I did just update my spreadsheet image with revised circuits. I added the second circuit to the kitchen and, after looking through the code, found I could actually add my gas range to one of the circuits. I also noticed the dining room and pantry must belong to these two separate circuits so I made sure that abides to code as well.
Comment: @Ed Beal So, Oregon has an exception for the 2014 NEC requirement to put the dishwasher on GFCI?
Comment: yes 210.8.D requires them but ORS 918 table 1.E exempts them for Oregon. I have had inspectors try to make me put them until I showed him the Oregon code. In Oregon they have to cite the code reference to call for a change. Every code cycle I pull the exemptions and make notes in my code book so I can find them quickly. There are ~80 changes to code in Oregon most reducing the requirements but a few are tougher than NEC requirements.
Comment: I usually put the refrigerator on a circuit that feeds the dining room. not many folks use high amperage outlets in the dining area now. A toaster, waffle iron and the fridge on the same circuit will usually trip the breaker. since there is a 100A breaker in the main you can use a bigger Sub without up sizing the wiring. The ground rods need to be 6' apart or more and 8' long, Galvanized pipe is allowed for ground rods but many inspectors frown on it because it could have been a shorter length.
Answer:
Does this sub panel need a grounding wire connected to the main panel in the garage?

Yes, you need a 4 wire connection (2 legs hot, neutral, and ground) from the main to the sub panel. Also the sub needs to be grounded, as you have planned two ground rods you are all set there.
I agree with Ed Beal that in the case of electrical panels, bigger is better. At least more circuits is better. You asked if the wire feeding the house would need to be upsized if you went with a bigger panel at the house. The answer is, no. If you have a 100 amp breaker feeding the house now with wire rated for 100 amps then that can all stay the same, if you wish. You can then buy your choice of >=100 amp panels to use in the house. For instance another 200 amp 40 circuit panel could be used. The rating of the sub-panel can be higher than what it is fed with. It just can't be lower. You also don't need a main breaker at the house unless you want one, or you locality requires it. So, you can install a main-lug-only panel if you wish.
So, that being said, if you want to plan for future expansion install a 24 circuit or greater panel. Such as this one.
Otherwise, you have a very well thought out methodical approach here that should lead to a superior installation. Not bad for a DIYer.
Good luck!
Comment: Thanks, I will go the bigger panel route. Seems to be the consensus. I have to double check, but one of the electrical bids I got, the electrician thought they hadn't run a ground from the main panel to the sub. He wasn't 100% sure because he didn't thoroughly check it--I hope he's wrong! Replacing that wire would be a big pain in the butt. At least if that's the case, I can run a thicker gauge to the sub in case things change in the future.
Comment: Oh, one more thing on panels.  Many are labeled as (for instance) 32 circuit 16 space.  That means it takes 16 normal breakers and 32 duplex "double stuff" breakers.  Those are more expensive and often not available in GFCI or AFCI.  Don't be fooled.  Until recently, the legal limit was 42 space.
Comment: In existing installations there is an exception to continue to have a 3 wire connection from the main to the sub. It is contained in 250.32(B). There are three requirements but it is too wordy to quote here. But paraphrased, you don't have a ground wire, you don't have any metallic pathways between the buildings (things like gas lines or metal water lines), and you don't have GFPE upstream (this is for commercial/industrial).
Comment: @ArchonOSX looking at the main panel yesterday, I noticed there's a bare ground that's bundled with the load conductors heading to the house and sub panel, but at the house there is no ground entering the panel. There is another 60A sub panel for a hot tub (which is being removed) that also has a ground wire running to it. This sub panel _does_ have the grounding wire all the way to the sub panel and is connected to ground and the neutrals and ground busses are separate from one another. Any clue why there would be a bare ground running with the 3 loads to the house but no connection there?
Comment: Sounds like someone either bonded it to the panel with a bond bushing or just cut it off. That would be a mistake. Connect the neutral bar to the panel at the house with a small wire. Then disconnect the ground and neutral at the garage and test for continuity between the neutral and ground that go to the house. If they just cut it off you won't get continuity.


What options are available for insulating interior walls myself with minimal damage to the wall?

Question: United State | California
I'd like to insulate the interior walls in my house using a minimally invasive method.
My understanding that is that "blown-in insulation" requires specialized equipment and  licensed professionals to do it.  Are there alternative insulation solutions I can install myself that are cost-effective and won't require me to tear down the wall?
Comment: Why do you need to insulate your interior walls (if not for sound/fire protection)?
Comment: Are the walls insulated now, and with what? Without understanding your reasons, it's very hard to make recommendations, not to mention that this may not even be the solution to your problem. For example - if it feels cold due to drafts, that can better be solved by finding and stopping the drafts (a big draft can completely undermine any insulation -- even if you put in new insulation). Maybe the ceiling or floor is not insulated. Give us some background information at least..
Comment: I removed the `united-states` tag. See http://meta.diy.stackexchange.com/q/649/22.  A description of how the wall is constructed would be more useful than knowing where it is.
Answer: Retrofitting walls with insulation as a DIY project isn't really viable if you don't want to tear open the walls.
The options that I am aware of:

blown in cellulose (they come in, drill 1 small hole in each stud bay, and then fill the bays with insulation)
spray in foam (same general technique as the one above)
exterior foam boards (they remove the siding, insulate with foam panels, add new siding)

Alas, none of them are really DIY.
The only DIY method I can think of would be to take down the sheetrock and insulate yourself, but that would be a huge amount of work and likely not save you much much money in the long run.
Answer: Keep in mind that heat always moves to cold.
You want to keep your expensive heat inside your home.
Therefore you should remove your drywall and replace it with sheets of polystyrene or similar closed cell insulation carefully fitted, this closes all the gaps and cracks in a wall
Then fit new drywall over - job done.
The joy of this process is, you can strip off just as much drywall as you can replace over a typical weekend, you don't have to worry about rain or snow or it getting dark, you merely continue at your own pace, insulating the inside of each outside wall at your own speed.
Fitting the insulation on the inside, means you don't have the cost of heating your frame, nor do you waste energy heating the spaces between the sticks.
When you add up the amount of wood in a typical wall and look at it as a proportion of that wall you can appreciate just how much heat the wall is conducting to the cold outside air.
Answer: Try using teflon lamination wall paints. This will provide insulation. They are a bit expensive than the normal paints but is definitely worth the money.
Comment: May I mention that all effective insulations are based on trapped air bubbles.
From the most expensive "Aerogel" with millions of tiny sealed air bubbles, to the likes of fibreglass and old newspaper products that are full of large open holes that let your heat race through to the cold outside.
There is no way that a solid coat of paint a few thousandths of an inch thick can provide any form of insulation. It may bridge a number of small cracks and stop a tiny draft - but, it does not insulate. Sorry!
Comment: Can you please provide a link to an example of one of these paints?


After getting socket data call separate thread for further processing?

Question: Currently I have this socket programme which will recieve data from the devices and then do a lengthy process like checking for geo fence and other relevant logic and finally saves data into the db. Below is how my codes looks
This the code to start the socket
    public static void main(String[] args) {
      new commS();
   }
   commS() {

   try {
      // setup the connection pool
            HikariConfig  config = new HikariConfig ();
            config.setJdbcUrl("jdbc:mysql://localhost:3306/****");
            config.setUsername("*****");
            config.setPassword("*****");
            config.setMaximumPoolSize(20);
            //config.setPartitionCount(1);
            connectionPool = new HikariDataSource(config); // setup the connection pool
      }
      catch (Exception e) {
            e.printStackTrace(System.out);
      }
      try
      {
               final ServerSocket serverSocketConn = new ServerSocket(8000);
               while (true)
                    {
                        try
                        {
                                Socket socketConn1 = serverSocketConn.accept();
                                new Thread(new ConnectionHandler(socketConn1)).start();
                        }
                        catch(Exception e)
                        {
                            System.out.println("MyError:Socket Accepting has been caught in main loop."+e.toString());
                            e.printStackTrace(System.out);
                        }
                    }
      }
      catch (Exception e)
      {
         System.out.println("MyError:Socket Conn has been caught in main loop."+e.toString());
         e.printStackTrace(System.out);
         //System.exit(0);
      }

Here is the rest of the socket connection codes which does the connection handler.
class ConnectionHandler implements Runnable {
      private Socket receivedSocketConn1;
    ConnectionHandler(Socket receivedSocketConn1) {
      this.receivedSocketConn1=receivedSocketConn1;
    }

public void run() { // etc
     w = null;
     BufferedReader r = null;
     String message="";
     try {
          /// here I read for the data and call the rest of the function etc.
          I would like to split into separate thread?
     }
     catch (SocketTimeoutException ex)
          {
               System.out.println("MyError:SocketTimeoutException has been caught in in the main first try");
               ex.printStackTrace();
          }
          catch (IOException ex)
          {
               System.out.println("MyError:IOException has been caught in in the main first try");
               ex.printStackTrace();
          }

}

I have marked /// here I read for the data and call the rest of the function etc. In that run function I receive data, verify and call all various other function etc and finally save the data into the db. I feel this is a lengthy process. I want to  break  it two section one just to read the data and then pass this string of data to separate thread so  is below what I am trying to achieve is correct.
So in the run function I plan to do this Thread t = new Thread(new MyRProcessing (parameter));
   t.start(); I am not too sure is this correct? Should I write the MyRProcessing as separate .java or put all into one java?
public class MyRProcessing implements Runnable {
      private X parameter;
      public MyRProcessing (X parameter) {
         this.parameter = parameter;
      }

      public void run() {
      }
   }

Comment: You might want to read a few multithreading tutorials before getting into it. It's a complex subject and since you're asking so many questions, you'll probably be in over your head if you try to "wing it". Otherwise this seems like it could benefit at least a little from a producer-consumer pattern, if you have a long running process.
Comment: You need to read more.
Comment: Look into producer-consumer pattern. I can guarantee you'll run into plenty of problems if you just google for snippets and try to insert them into your code.
Comment: Yes I have read some and google and this where I found about calling this Thread t = new Thread(new MyRProcessing (parameter));
Comment: I need some kind of confirmation whether what I am trying to do is correct or not? Actually my problem is simple I want to break into two separate thread reading as one and the rest of the processing I want to pass to separate thread so that the main thread is not overloaded with all the other processing?
Comment: Is there any good link you will suggest? I have been googling on this maybe on a wrong direction?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/126659/discussion-between-user5313398-and-kayaman).
Answer: You can find an example for producer-consumer here
This deals with the general question of multithreading and synchronization, I highly recommend reading up on those before proceeding.
The simplest way to do what you are proposing is to simply extend the Thread class and pass your data in via the constructor, then processing it in the run() method. This isn't the best way to go about doing it in most cases, but it is simple.
Ex.
public class MyThread extends Thread {
    private String data;
    public MyThread(String data) {
        this.data = data;
    }

    public void run() { /* process data */ }
}

and then just start up the thread, once it's done, it'll return and the thread will terminate.
Comment: thank you for the link yes I was trying to achieve the simplest and fastest way to convert my codes cause there quite lengthy?
Comment: in your opinion should I leave my current codes or change to this producer-consumer codes?  Will there be heavy impact with my current codes in terms of memory usage and scalability its working fine so far just worried about future?
Comment: producer-consumer is probably better in the long run. You probably won't notice any performance issues either way. If you are only expecting a few threads to be running at once, doing it the simple way is probably just fine. One problem is that this can choke your computer if you get too many running at once. It all depends on what you are doing
Comment: @so far running on this single run function and then calling multiple functions in it is functioning well I dont really see a big problem only that the I dont know whether it impact on the device by me holding and doing a length process?
Comment: Depends on how many simultaneous connections you are expecting and how intensive the operations you want to do are. If you are only expecting a few connections, you likely won't notice any issues at all, it'll just take up a little more memory. Modern hardware has been very well optimized to handle a great many simultaneous threads so it only really becomes an issue in large applications
Comment: @let say I am going to have at maximum say 2000 simultaneous connection if even it happens so which way to go with my current to way to split?  My worry is that by split infact its going to take up more memory cause I need to create extra threads right?
Comment: If you have 2000 simultaneous connections, it means you'll have around 4000 threads running (2000 for reading the data, 2000 for processing). With this method, that would likely cripple your CPU and consume a huge amount of memory (on the order of several GB). In that case you absolutely would want to use a producer-consumer system, probably with a Thread Pool
Comment: @I have been reading about producer and consumer is like put thing into queue I am worried about sequence of data coming and being processed and also the time taken to process will there be any impact on this later if I use producer and consumer?
Comment: Having it in a queue simply means it'll be processed in a first come first serve basis. As for performance, if you want it to be very high performance, look into [thread pools](https://docs.oracle.com/javase/tutorial/essential/concurrency/pools.html)
Comment: just to clarify now is that in my case the reading thread is considered the producer right? Then the consumer thread will the processing thread right?
Comment: that is correct. If it helps, think of it like a restaurant, it produces the food, the customers (threads) consume the food. But the restaurant has only so much space for customers so you can't have too many of them.
Comment: so how to set in the consumer to have the database pooling? So are you suggesting from the multiple producer it will go into a single consumer or multiple consumer?
Comment: You'll have multiple producers (the reading threads) but a shared consumer (whether that's 1 or more than 1 depends on how much work you want to do). For the database, you'll have to research whatever database you are using how it handles concurrency.
Comment: I am clear now so its multiple producer and either single or more? So in my scenario say its going to be 2000 producer what do you suggest surely not single consumer right? Currently I am using hikari connection pooling for my single method? How to cater that for my consumer ?
Comment: This is getting a little off topic, I recommend creating another question specifically about producer-consumer, connection and thread pooling
Comment: Sure I will do that later thank you for your guidance.


How to change permissions (chmod)?

Question: I have created a folder not in /home but on other volume which is free (eventually I'd like to share the folder via Samba).
I have found the path:
/media/xduser/kingstone

I did:
cd /media/xduser/kingstone
sudo mkdir share23
sudo chmod 777 -R share23
sudo chown -R xduser:xduser  /media/xduser/kingstone/share23

But when I ls, I see:
$ ls -li /media/xduser/kingstone
total 32
4 drwxr-xr-x 2 xduser xduser 32768 Dec  7 09:48 share23

Also, I cannot change permissions in the GUI. So, I see the share23 on another machine but cannot open it because of permissions.
This is the output of findmt:
$ sudo findmnt -T /media/xduser/kingstone/
TARGET                 SOURCE    FSTYPE OPTIONS
/media/xduser/kingstone /dev/sdc1 vfat  rw,nosuid,nodev,relatime,uid=1001,gid=1001,fmask=0022,dmask=0022,codepage=437,iocharset=

How can I change the permissions?
Comment: That filesystem doesn't support Linux permissions ... But, you can change `fmask`, `dmask` to `0000` or probably remove them from your mount options and use `umask=0000` instead.
Comment: Please [edit] your question to include the output of `findmnt -T /media/xduser/kingstone`
Comment: Also note that the permissions on the local machine are unlikely to be the problem on the remote machine. Those will depend on how the remote machine mounts the directory.
Comment: @Raffa thank you. I see, it is FAT. I can  format disk. What file system to use?
Comment: Any *nix filesystem should support Linux type permissions ... EXT4 is the default on Ubuntu ... However, Windows will not be able to read it directly, so you can't mount it on Windows ... You'll need to mount it on a Linux machine and then, Windows can read it as a Samba share for example
Comment: If you decide to use EXT4 for example, then you might want to modify ACLs instead. See for example https://askubuntu.com/a/1494895/968501 ... You might as well (with SAMBA) consider editing `smb.conf`. See for example https://unix.stackexchange.com/q/206309
Comment: SSHFS is another option to be able to mount linux file systems in windows.
Comment: I have unmount, formatted (ext4) , mount the disk. Now It is visible in Disks, in FIles. But I cannot create a folder via GUI (greayed). I have created sudo mkdir shared17. But cannot chown: sudo chown -R xoleg:xoleg /media/xduser/112e86d7-fc5d-4d63-b04a-9f32e7160eb/media17
----chown: cannot access '/media/xduser/112e86d7-fc5d-4d63-b04a-9f32e7160eb/media17': No such file or directory
Comment: Did you mean to run `sudo chown -R xoleg:xoleg /media/xduser/112e86d7-fc5d-4d63-b04a-9f32e7160eb/shared17` instead of `sudo chown -R xoleg:xoleg /media/xduser/112e86d7-fc5d-4d63-b04a-9f32e7160eb/media17`  … Check the last directory name :)
Comment: Yes, thanx, I try to solve it using one, another user etc. But anyway:  I have created inside the media17 folder yet another folder media171, then I go to the directory and performed 2 commands sudo chown -R xoleg:xoleg media171
sudo chmod 777 -R media171 They completed without errors.
Comment: I have added a section to smb.config and now the folder is visible in remote machine but  I cannot open it because of permissions....
Comment: That folder might be affected by the permissions of its parent folders i.e. `media17` and up to the mount point itself i.e. `112e86d7-fc5d-4d63-b04a-9f32e7160eb` ... So, look into those as well.
Comment: Oh, yes, may be , the owner of media17 is root and permissions restricted. Why I cannot create a Folder in the /media/xoleg/112e86d7-fc5d-4d63-b04a-9f32e7160eb
Comment: The mount point `112e86d7-fc5d-4d63-b04a-9f32e7160eb` is also a folder so check its permissions and ownership … depending on how you mounted your drive, it could also be owned by `root` and with restricted permissions
Answer: It's a free world, but ...
Assuming you understand that granting full permissions of read, write, and execute and especially for the other group is going to compromise the security and probably integrity/existence (given the sticky bit isn't set as well) of all files under that directory allowing anyone to view, modify and delete them beyond any possible recovery or even functional traceability ... So, not discussing that ... And skipping, as well, the fact that in most use cases not all those permissions need to be granted and some of them will suffice ... That's for you to decide anyway as you will be the the only one who will suffer if your creation happens to be wanting to bite its creator back ... But, let's hope this won't happen as I have nothing that I can offer you in that situation except hope and backups if they existed.
Why are permissions not set?
Because your filesystem on that drive is of the FAT family and those folks don't understand or accept Linux type permissions.
Why is that filesystem mounted with such limited permissions anyway?
Because, it's mounted with the fmask=0022 and the dmask=0022 mount options and those masks translate to 0755 or rwxr-xr-x permissions for directories and "actually" 0644 or rw-r--r-- for regular files.
What are the options?

Change the mount options of dmask and fmask to the value of 0000 which will translate to the permissions of 0777 and 0666 for directories and files respectively ... Or, probably, alternatively remove those and use umask=0000 instead which should comparatively affect both directories and files.

Format that media ( !!! will erase it !!! ) to a filesystem of the *nix family e.g. EXT4 as those will allow setting Linux type permissions and even ACLs, see for example How to grant full access to any new folders/files/subfolders created in a specific folder?.

If using SAMBA for your shares, look into setting specific USERSHARES options, see for example How to create a Samba share that is writable from Windows without 777 permissions?.
Comment: Thank you for the detailed answer. But I did not find yet a few things: I have re-formatted the HDD as ext4 volume, created  a folder in terminal but not in GUI. What should I do next?

How to change permissions (chmod)?


Could not get dependencies for project reference when mixing .NET Core and .NET Framework projects

Question: I recently pulled down a project that had upgraded to .NET Core 3.1.  The rest of my projects are running .NET Framework 4.5.1, and use references from that .NET Core project.  When I try to add these references, I get the error "Could not get dependencies for project reference".  In Visual Studio, IntelliSense still completes code in the .NET Framework for the .NET Core code, but I still get the error.
Is there any way to import and reference this package?
Comment: https://blog.lextudio.com/which-class-library-project-to-go-in-visual-studio-2015-2017-a48710cf3dff Rule of thumb is that .NET Framework projects cannot consume .NET Core libraries.
Comment: Thanks @LexLi. That was the answer I both suspected, and didn't want.
Answer: See Lex Li's answer from above.  They did turn out to be incompatible, prompting me to replace the old projects with .NET core projects.  It was a hassle but worth it by far.  Using entity framework make life much easier, too.


Garmin USB insufficient permissions

Question: Attempting to download GPX files from Garmin to QGIS. Error message states insufficient permission or gpsbabel is missing.
GPSbabel is part of the QGIS software, so I assume I need to change permissions.
sheep@pen:~$ ls -l /dev/ttyUSB0
crw-rw-rw- 1 root dialout 188, 0 May 16 12:25 /dev/ttyUSB0
sheep@pen:~$ lsmod | grep garmin_gps
garmin_gps             32768  0
usbserial              57344  1 garmin_gps

sheep@pen:~$ groups
sheep adm lp dialout cdrom sudo dip plugdev lpadmin lxd sambashare

sudo journalctl --follow as far as I can see doesn't give device name.

May 24 16:39:42 pen kernel: usb 1-4: New USB device found, idVendor=091e, idProduct=0003, bcdDevice= 0.01
May 24 16:39:42 pen kernel: usb 1-4: New USB device strings: Mfr=0, Product=0, SerialNumber=0
May 24 16:39:42 pen mtp-probe[76479]: checking bus 1, device 7: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-4"
May 24 16:39:43 pen mtp-probe[76479]: bus: 1, device: 7 was not an MTP device
May 24 16:39:43 pen mtp-probe[76482]: checking bus 1, device 7: "/sys/devices/pci0000:00/0000:00:14.0/usb1/1-4"
May 24 16:39:44 pen mtp-probe[76482]: bus: 1, device: 7 was not an MTP device

The alternative commands, ls -1 /dev >dev.before and ls -1 /dev >dev.after;diff dev.{before,after}
output identical files of 240 lines, no name there either
Thanks for your suggestions Waltinator
Comment: Comments are designed for US to ask YOU questions about your Question. You should [Edit] your question to add information. By updating your Question, and using the formatting buttons, you make all the information available to new readers. People shouldn't have to read a long series of comments to get the whole story. AskUbuntu is a Question and Answer site, not a conversation site. If you have an update, [edit] your Question.  If you have a new question, see  [Ask].
Comment: Is `gpsbabel` in your `PATH`? Do: `type --p gpsbabel`. Also try `gpsbabel -h`.
Comment: gpsbabel is in the PATH , but these suggestions haven't helped cheers
Comment: Thanks for your suggestions, but I feel Linux no longer has any love from Garmin. I've opted for a gps with bluetooth, fingers crossed I have a work around.
Comment: Waltinator thanks for your suggestions. So far this issue isn't resolved
Answer: This is an answer I've used before. I hope it helps.
Many device access problems can be resolved through group membership changes.
You can find the device name by watching sudo journalctl --follow as you connect your device. OR ls -1 /dev >dev.before, connect the device, wait 10 seconds, ls -1 /dev >dev.after;diff dev.{before,after}.
Specifically, if ls -l  shows that the group permissions (the second "rwx" triplet) is "rw" (e.g."-rw-rw----"), then, adding oneself to the group that owns the device will grant rw access.
Here's how:
# change to your device name
device="/dev/dvdrw"
sudo adduser $USER $(stat -c "%G" $device)

This allows you membership in the group that can rw the device, but there is one more step.
To make all your processes members of the new group, logout and login. Group memberships are set up at login time.
To create a single process in the new group (for testing, prior to logout/login):
newgrp $(stat -c "%G" $device)

or, just type the group name. See man newgrp.

Garmin USB insufficient permissions


Placement of a Change language button

Question: Where would you place a Change language button/Country selector (or dropdown) on a web page? In a footer menu or in a utility menu in the top right corner of a web page or somewhere else on the page? What are your findings? Where does it feel most natural?
Comment: Be aware that country and language selectors are not the same thing at all.
Comment: Thx. I'm aware...
Comment: possible duplicate of [Choose Your Country: Best Usability approach](http://ux.stackexchange.com/questions/5161/choose-your-country-best-usability-approach)
Comment: No, this is not a duplicate. This question is only about the best placement of a Change language button. Not how it should behave.
Comment: IMHO, neither this question nor the other has particularly good answers. There may be some good information in one of the links on the other question that could be surfaced in a good answer.
Answer: I won't go for the note in the footer since the primary use of such a selector is when landing the very first time on the website, as soon as the user sees that he does not understand the site language, he must not have to scroll to the footer to switch language.
But this should be a secondary action. So given the cultural context, I'll put it on the top right corner for left-to-right layout.
Comment: I'd agree with this. If research has shown you need a selector and you cannot automatically identify language/country, top right would be the place to put it.
Comment: Automatic language detection should never rule out the possibility of a user wanting to view a page in a language that is different from the one set by their OS. I live in Switzerland where there are 4 official languages. How would identifying that I'm visiting your website from Switzerland help you make a decision on which language I understand? What's more, none of those languages are my preferred language, which is English. Personally, I find being being served a language based on my geographical location very frustrating. I'm looking at you, Google.
Answer: This case study shows that users mostly expect that the language button is in the top right:
http://flagsarenotlanguages.com/blog/2013/10/case-study-onefinestay-com-and-dropdown-language-selection/
Answer: I think it is good standard to have language selector at top right corner which allows the user to quickly change the selection besides having at the bottom. Refer the McAfee home.mcafee.com website, like how they have combined the actual language name/characters with country.

Also, Refer this thread which has detailed study on the placement of country selector. I think this thread will answer what you are after...
Choose Your Country: Best Usability approach
Comment: I've read it and I cant' see that the dicussion is about where to position it but how.
Comment: Eventhough it doesn't say where exactly you should place the selector but it gives you lot of insights on how we should go about in placing it. I think it all depends what kind of website or ecom website or company website you are designing for.
Comment: Wow, that's a really bad example. Note how _Hrvatska_ 'Croatia', _Suomi_ 'Finland', _Deutschland_ 'Germany', _Magyarország_ 'Hungary' and _España_ 'Spain' are placed in a seemingly alphabetically sorted list. (It's not as bad for non-roman entries, but why are Greece, Israel and the Arabic one not transcribed?) Also, I'm pretty sure they do business in Belgium if Luxembourg and the Netherlands are in the list, but they speak Dutch (Flemish), French and German there which all have major country entries. Same goes for German-speaking Austria, although polyglot Switzerland has a German entry.

Placement of a Change language button


Cannot set focus on input field in infoWindow

Question: Why is focus not set to noteTitle?
I am using google maps API V3.
The getNoteForm() returns a input field "noteTitle".
The $("#noteTitle").focus() works fine when executed in firebug.
I call this function when clicking on the map:
<code>function setNewNoteInfowindow(latlng) {
 if (geocoder) {
       geocoder.geocode({'latLng': latlng}, function(results, status) {
   var address = "";

     if (status == google.maps.GeocoderStatus.OK) {
    if (results[1]) {
     address =  results[1].formatted_address;
            }
         }

   newNoteInfowindow = new google.maps.InfoWindow({
    content: getNoteForm(latlng, address),
       size: new google.maps.Size(40,50)
   });

   newNoteInfowindow.open(map, newNoteMarker);

   google.maps.event.addListener(newNoteInfowindow, 'domready', function() {
          $("#noteTitle").focus();
      });

   google.maps.event.addListener(newNoteInfowindow, 'closeclick', function() {
          newNoteMarker.setVisible(false);
      });
  });
 }
}
</code>
Comment: Have you tried moving the `$("#noteTitle").focus();` statement elsewhere? Start with it in $(document).ready perhaps?
Comment: have you verified that the event is fired correctly ? add an `alert('something');` to see if it executes..
Answer: It looks like you are opening your infowindow before adding the event listener. So the event has already been fired by the time you add the listener.  Try reversing the order of open() and addListener()
<code>   google.maps.event.addListener(newNoteInfowindow, 'domready', function() {
          $("#noteTitle").focus();
      });

   newNoteInfowindow.open(map, newNoteMarker);
</code>
Comment: Solved it like this. Not pretty, but it works.
google.maps.event.addListener(map, 'click', function(event) {
 placeNewNote(event.latLng);
 setTimeout(function(){$("#noteTitle").focus()}, 500);
});


I'm connected to Wi-Fi network but my internet keeps dropping randomly

Question: I am running Ubuntu 16.04 LTS and I have problem with wireless. It says it's connected all the time but randomly, every few minutes, internet is gone and after minute or two it comes back again. All other devices in my home (other computers, phones etc.) have internet all the time.
I ran the script I found on this forum and put it into this Ubuntu Paste bin: http://paste.ubuntu.com/25660911/
Can anyone offer me a solution? Many thanks in advance!
Comment: Does it do that with all wireless networks? Do you have other Linux machines connected?
Comment: Yes, with all wireless networks and no, this is the only one.
Comment: See this for tips and hacks: https://askubuntu.com/q/529347/ and this [article](https://itsfoss.com/speed-up-slow-wifi-connection-ubuntu/).
Answer: We notice this in your paste:
Address: <MAC 'RJNSL' [AC1]>
                    Channel:6
                    Frequency:2.437 GHz (Channel 6)
                    Quality=60/70  Signal level=-50 dBm
                    Encryption key:on
                    ESSID:"RJNSL"
                    Bit Rates:1 Mb/s; 2 Mb/s; 5.5 Mb/s; 11 Mb/s; 6 Mb/s
                              9 Mb/s; 12 Mb/s; 18 Mb/s
                    Bit Rates:24 Mb/s; 36 Mb/s; 48 Mb/s; 54 Mb/s
                    Mode:Master
                    Extra:tsf=0000000531e3c64c
                    Extra: Last beacon: 160ms ago
                    IE: IEEE 802.11i/WPA2 Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : CCMP TKIP
                        Authentication Suites (1) : PSK
                    IE: WPA Version 1
                        Group Cipher : TKIP
                        Pairwise Ciphers (2) : CCMP TKIP
                        Authentication Suites (1) : PSK

First, check the settings in the router. WPA2-AES is preferred; not any WPA and WPA2 mixed mode and certainly not TKIP. Second, if your router is capable of N speeds, you may have better connectivity with a channel width of 20 MHz in the 2.4 GHz band instead of automatic 20/40 MHz, although it is likely to affect N speeds. I also have better luck with a fixed channel, either 1, 6 or 11, rather than automatic channel selection. Also, be certain the router is not set to use N speeds only; auto B, G and N is preferred. After making these changes, reboot the router.
Next, I recommend that your regulatory domain be set explicitly. Check yours:
sudo iw reg get

If you get 00, that is a one-size-maybe-fits-all setting. Find yours here: http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2 Then set it temporarily:
sudo iw reg set IS

Of course, substitute your country code if not Iceland. Set it permanently:
sudo nano /etc/default/crda

Change the last line to read:
REGDOMAIN=IS

Proofread carefully, save and close the text editor.
Next, I'd set IPv6 to Ignore in Network Manager: http://docs.fedoraproject.org/en-US/Fedora/18/html/Installation_Guide/images/netconfig/network-connections-ipv6-ignore.png  This example is for ethernet, but you want wireless.


LocalStorage Reliability with Phonegap

Question: I'm making a PhoneGap app that needs to store some user data. On the initial app startup, the user will be asked to type in a URL. Because the URL may potentially be long, I wish to save it on the user's device so the he doesn't need to re-enter the entire string every time he starts up the app.
Initially, I was planning on using LocalStorage for this. However, I've heard that LocalStorage doesn't save data very permanently. It would greatly hurt my app's usability if the user had to type in the URL more than once every month or so.
Should I use SQLite instead of LocalStorage for this purpose, or is LocalStorage reliable enough on most mobile devices for this kind of usage?
Answer: You should'nt use LocalStorage because it's no longer a persistant storage on IOS since 5.1 and also because Apple can reject your application.
You have several choices :

Using the File API
Using WebSQL (5 Mo max i think)
Installing the SQLite Plugin

For the last choice, you can also install Lawnchair (included) which provides an easy to use key value system on top of SQLite. You won't need to write any line of SQL to use SQLite.
Comment: Actually, webkit-sqlite.js is the adapter used by the SQLite Plugin, and it requires it. Installing and using the SQLite plugin + Lawnchair is a breeze don't worry. it just makes the development longer because you need to use the ios/android simulator to make it work and not just Rippler or AppGyver. If you don't like this solution, you can still use the File API btw
Comment: Is the LocalStorage a problem on Phonegap 3.0 as well?
Comment: It is not a Phonegap problem but a Apple one. http://techblog.troyweb.com/index.php/2012/05/relocating-localstorage-in-ios-5-1-for-phonegap-applications/
Comment: If I don't want to install the SQLite plugin, can I just use Lawnchair with webkit-sqlite.js as the adapter?
Comment: My bad! You can use Lawnchair + webkit-sqlite.js without the SQLite Plugin. Sorry for the mistake
Comment: OK, thank you! Right now, I'm using PhoneGap Build for compiling my app, so I'd prefer not to install any plugins.
Comment: You can still use plugins with PG Build, there is a list of supported plugins here https://build.phonegap.com/plugins. You just need to activate the ones you want in your config.xml :)

LocalStorage Reliability with Phonegap


How to select the string names which has a more than 5 character

Question: I am trying to get the names (first) which has a longer than 5 letter but I could not make it
const fullNames = [
  { first: "Albus", last: "Dumbledore" },
  { first: "Harry", last: "Potter" },
  { first: "Hermione", last: "Granger" },
  { first: "Ron", last: "Weasley" },
  { first: "Rubeus", last: "Hagrid" },
  { first: "Minerva", last: "McGonagall" },
  { first: "Severus", last: "Snape" },];

const firstNames = fullNames.map(function (arg) {
  return arg.first.lenght >4;
});

Comment: Javascript.......
Comment: You spelled length incorrectly as "lenght".
Comment: Omg since this morning, I have been looking this :) Thank you so much
Comment: Just takes a second set of eyes sometimes.
Comment: What does the OP [`map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map) expect to do? Going through an array and e.g. _"... trying to get the names (first) which has a longer than 5 letter ..."_ sounds more like a [`filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) task.
Answer: You can simply achieve this requirement with the help of Array.filter() method as Array.map() will return the same number of elements you passed as a input.
Live Demo :

const fullNames = [
  { first: "Albus", last: "Dumbledore" },
  { first: "Harry", last: "Potter" },
  { first: "Hermione", last: "Granger" },
  { first: "Ron", last: "Weasley" },
  { first: "Rubeus", last: "Hagrid" },
  { first: "Minerva", last: "McGonagall" },
  { first: "Severus", last: "Snape" }
];

const res = fullNames.filter(({ first }) => first.length > 5).map(({ first}) => first);

console.log(res);
Comment: @TahaYasin Can you please accept this answer if it helps so that it will be helpful for other fellow developers as well.


How to remove duplicates in an array in python

Question: I'm trying to implement a difference function, which subtracts one list from another and returns the result. Here is what i have so far:
def array_diff(a, b):
    for e in b[:]:
        for i in a:
            a.remove(i)
    return a

in1 = [1, 2, 2]
in2 = [1]
print(array_diff(in1, in2))

I have two sample tests that i'd like to run.
Test.assert_equals(array_diff([1,2,2], [1]), [2,2], "a was [1,2,2], b was [1], expected [2,2]")
Test.assert_equals(array_diff([1,2,2], [2]), [1], "a was [1,2,2], b was [2], expected [1]")

How would i be able to remove the same value more than once?
Comment: Does this answer your question? [Delete intersection between two lists](https://stackoverflow.com/questions/9331627/delete-intersection-between-two-lists)
Answer: array_diff = lambda a, b: [ i for i in a if i not in b]

array_diff(in1,[1])
 [2, 2]

array_diff(in1,[2])
 [1]


How to printk() a s32 kernel data type

Question: When working with a wireless driver module, noise in the wireless medium is reported to the module as a s32 data type, which is defined in linux/types.h.
I would like to use printk() to print out this value to the syslog, however when I do I get unintelligible results. Current attempts have been:
printk("%d", val);
printk("%d", (int) val);
printk("%3i", (int)val);
printk("%3i", val);
printk("%lx", val);
printk("%lx", long val);

I don't understand is how to format this for printing. I have also not been able to find any information thus far on how to do so.
Since it deals with kernel data types, I thought it might be appropriate to post in askubuntu.
Comment: You can always edit your question to improve/correct it :-)
Comment: My talk of sign of extenion was misleading and have removed it, the s32 type is an explicitly sized data type, used in the case where certain hardware registers require 32 bits.
Comment: Btw can you add name of function returning that __s32?
Answer: Because you know it is a 32-bit int, try casting it before passing it to printk:
printk("%d", (int32_t) val);

Answer: typedef         __s32           int32_t;

So you should treat it like simple integer value.
Comment: It seems the OP tried that in line 1 of the original code examples; something is missing
Answer: It turns out that the sign extension was important:
sign_extend32(AR5K_REG_MS(value, AR5K_PHY_NF_MINCCA_PWR), 8)
where:
AR5K_PHY_NF_MINCCA_PWR      0x0ff80000  /* Minimum measured noise level, read from hardware in 1 dBm units */
The AR5K_REG_MS functions masks and shifts that value read from the hardware register with respect to the minimum measured noise level .
sign_extend32 /* sign extend a 32-bit value using specified bit as sign-bit */
After these are completed, the number can be written to syslog using '%d' for formatting.

How to printk() a s32 kernel data type


How to install PgAdmin3 version 1.20.0 in Ubuntu 14.04

Question: I try to install using PPA
First, I add a link to a file repository source.list directory the /etc/apt/sources.list
$ Sudo nano /etc/apt/sources.list

 deb http://ppa.launchpad.net/pitti/postgresql/ubuntu precise play

 deb-src http://ppa.launchpad.net/pitti/postgresql/ubuntu precise play

Secondly I did update the repository with the command
$ Sudo apt-get update

although there is an error
: W: GPG error: precise http://ppa.launchpad.net Release: The following signatures could not be verified Because The public key is not available: NO_PUBKEY 99B656EA8683D8A2

I added a way to overcome the apt-key, create a folder Key1 contains the code on the link below
code key1
then I run the command
$ Sudo apt-key add / directory / key1

succeed
I tried to update the back third repository
$ Sudo apt-get update

succeed
four I try to run the following command to install pgadmin3 vs. 1.20.0
$ Sudo apt-get install pgadmin3

yet installed fixed vs. 1.18.0
how do I fix it?
Comment: About "broken packages" or "stable solution", see  **[this similar question](http://askubuntu.com/q/715048/439867)**
Answer: That is because, as mentioned in the PPA page, the PPA is deprecated and will NOT receive ANY UPDATES any more. The 'latest' version available in that PPA is 1.18.1-1.
If you want the latest version, checkout the repository maintained by The PostgreSQL Global Development Group (PGDG). In short,
Create /etc/apt/sources.list.d/pgdg.list and put the following contents:
deb http://apt.postgresql.org/pub/repos/apt/ precise-pgdg main

Import repository key, update and install the packages:
sudo apt-get install wget ca-certificates
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install postgresql-9.4 pgadmin3

There is also a shell script that will automate repository setup.
Refer documentation for more information.
Comment: Thank for your tutorial, but why when I repeat the simulation OS Ubuntu in VirtualBox fails? All no errors such as tutorial you give
Answer: Why do you use Precise repositories in Trusty? pgadmin3 is in the Ubuntu repositories for Trusty and so on.
Therefore remove the lines
deb http://ppa.launchpad.net/pitti/postgresql/ubuntu precise play
deb-src http://ppa.launchpad.net/pitti/postgresql/ubuntu precise play

from your sources.list and install with
sudo apt-get update
sudo apt-get install pgadmin3

To install version 1.20.0~beta2-1 you need at least Vivid or another PPA:
wget --quiet -O - https://www.postgresql.org/media/keys/ACCC4CF8.asc | sudo apt-key add -
sudo sh -c 'echo "deb http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg main" >> /etc/apt/sources.list.d/postgresql.list'

Check with
% apt-cache policy pgadmin3
pgadmin3:
  Installed: (none)
  Candidate: 1.20.0-1.pgdg14.04+1
  Version table:
     1.20.0-1.pgdg14.04+1 0
        500 http://apt.postgresql.org/pub/repos/apt/ trusty-pgdg/main i386 Packages

And install
sudo apt-get update
sudo apt-get install --reinstall pgadmin3

Comment: because I followed the tutorial on the following link [PostgreSQL backports for stable Ubuntu releases](https://launchpad.net/~pitti/+archive/ubuntu/postgresql) ,
it is already outdated link
Comment: I want to install that version 1.20.0 pgadmin for support on postgresql-9.4, can't directly use

$ sudo apt-get install pgadmin3


Automatically assign a customer to a specific customer group on sign-up - Bigcommerce

Question: I've been told by BC support that this isn't possible, but I would be surprised if there really wasn't a way.
I need to be able to automatically assign a customer to a specific customer group when they create an account. My thought:

I would add an extra field to the sign-up form
Provide a user with a code (a string or number)
User enters code when creating new account
User hits submit
On form submit I would grab the value of the extra field:

var codeInput = document.getElementById('code-input').value;

I would then compare that value to a pre-defined string, and if there is a  match, I would assign that customer to groupX (with a group id of 8):
 if ( codeInput === "codeIGaveToTheUser" ) {
    currentUserGroupID = 8;
 }

Is it possible to assign a customer to a specific group on sign-up like this (or any other way)?
Any help is much appreciated.
Comment: To be clear, when support tells you something can't be done, it means there isn't a setting. This can be accomplished through customization. It requires your own web server that is configured to listen for webhooks and assign the created customer based on your own business/code logic.
Comment: Thanks Alyssa, can you give me an idea of how complicated that is, or maybe explain it in slightly simpler terms?  I'm not a complete noob, but this type of project is a bit foreign to me.  Note - Are BCs Server Settings of any use?
Comment: There's a typo. My name is Alyss, not Alyssa :) . BC server settings are not of use. You'd need to have an external server or something like heroku that could. Javascript would likely be insufficient.
Answer: Although using BigCommerce webhooks would ensure the highest success rate of executing your customer group assignment app, it requires quite a bit of setup on BigCommerce (creating a draft app, getting an oAuth key, jumping jacks, etc), and may be a bit of overkill for your requirements.
Here's an easier way, in my {mostly} humble opinion, that takes advantage of much of what you included in your original question. Any solution though will nonetheless require an external server to handle the customer group assignment through the BigCommerce API.

Within the BigCommerce control panel, add in the extra field to the user sign up form like you mentioned.

So as you can see, this new input field has been added natively to the default registration page:

So now, when a user creates an account on your site, the value for the Signup Code (the custom field created) will be directly accessible through the API for that customer's account. Take a look at what that JSON data looks like:

Okay, so this is nice and all, but how do we automate it?
To do so, we will have to let our external application know that a customer just registered. Furthermore, our external application will need some sort of reference to this newly created customer, so that it knows which customer to update the customer group for. Normally a BigCommerce webhook would notify us of all this, but since we aren't using a BigCommerce webhook, here's the alternative method to triggering the external script.

We will trigger our external application via the BigCommerce Registration Confirmation page - createaccount_thanks.html. This page is loaded immediately after a customer creates an account, so it is the perfect place to insert our trigger script.
Additionally, now that the customer is logged in, we can access the customer's email address via a BigCommerce Global system variable -%%GLOBAL_CurrentCustomerEmail%%.
We should make an HTTP request from this page to our external application along with the customer's email address. Specifically, we can make an XMLHttpRequest via JavaScript, or to be modern, we'll use Ajax via jQuery. This script should be inserted before the closing  tag on createaccount_thanks.html.

Example of POST request (although a GET would suffice as well):

Now finally, you just need to create your serverside application responsible for handling the request above, and updating the customer's customer group. You can use any language that you desire, and BigCommerce even offers several SDK's you can use to save mega development time. Just remember that you need to host it somewhere online, and then insert its URL to the JS script above.
PHP Example (quick & dirty):
git clone https://github.com/bigcommerce/bigcommerce-api-php.git
curl -sS https://getcomposer.org/installer | php && php composer.phar install
<?php
/**
 * StackOverflow/BigCommerce :: Set Customer Group Example
 * http://stackoverflow.com/questions/37201106/
 *
 * Automatically assigning a customer group.
 */

//--------------MAIN------------------------//

// Load Dependencies:
require ('bigcommerce-api-php/vendor/autoload.php');
use Bigcommerce\Api\Client as bc;

// Define BigCommerce API Credentials:
define('BC_PATH', 'https://store-abc123.mybigcommerce.com');
define('BC_USER', 'user');
define('BC_PASS', 'token');

// Load & Parse the Email From the Request Body;
$email = json_decode(file_get_contents('php://input'))->email;

// Execute Script if API Connection Good & Email Set:
if ($email && setConnection()) {
    $customer = bc::getCollection('/customers?email=' .$email)[0];        //Load customer by email
    $cgid     = determineCustomerGroup($customer->form_fields[0]->value); //Determine the relevant customer group ID, via your own set string comparisons.
    bc::updateCustomer($customer->id, array('customer_group_id' => $cgid)) ? http_send_status(200) : http_send_status(500); //Update the customer group.
} else {
    http_send_status(500);
    exit;
}

//-------------------------------------------------//

/**
 * Sets & tests the API connection.
 * @return bool true if the connection successful.
 */
function setConnection() {
    try {
        bc::configure(array(
        'store_url' => BC_PATH,
        'username'  => BC_USER,
        'api_key'   => BC_PASS
        ));
    } catch (Exception $e) {
        return false;
    }
    return bc::getResource('/time') ? true : false; //Test Connection
}

/**
 * Hard define the customer group & signup code associations here.
 * @param string The code user used at signup.
 * @return int   The associated customergroup ID.
 */
function determineCustomerGroup($signupCode) {
    switch ($signupCode) {
        case 'test123':
            return 1;
        case 'codeIGaveToTheUser':
            return 8;
        default:
            return 0;
    }
}

So then you would do your customer group string comparisons directly in the serverside program. I'd recommend you rewrite your own BC API script as the one above in quality is really something along the lines of functional pseudo-code,  but more so present to show the general idea. HTH
Answer: You would need to set up a server to listen for webhooks unless you wanted to do a cron job. We have some basic information on the developer portal, but I included more resources below. From there, you'd need to choose your server language of choice to listen for the webhooks once they been created, respond correctly (200 response if received), execute code based on this information, and then take action against the BC API.
So if you were looking for a code, you'd need to listen for the store/customer/created webhook, and have your code look for a custom field that contained the code. If it was present, then take action. Else, do nothing.
https://developer.github.com/webhooks/configuring/
http://coconut.co/how-to-create-webhooks
How do I receive Github Webhooks in Python
Comment: Sorry Alyss!  And thanks so much for this.  I'm having a pretty hard time understanding, and I am trying to figure out what listening for a webhook means exactly, but I will look at and read these links, and see if I can't learn a few things.  I appreciate the time


How to display image on html from SQLAlchemy LargBinary column

Question: I'm writing a gallery web app that saves photos and display them.
I'm using SQLAlchemy for the database and store the image in a LargeBinary column.
When I try to display every image I run into the problme that for displaying html image you need the url for the <img src= and I dont know how to reach the url of the BinaryData column in the
database, is there a different way? (I dont want to save all images in a folder because i already have then stored in the database)
from flask import Flask, render_template, url_for, request, redirect, send_file
from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from io import BytesIO

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db'
db = SQLAlchemy(app)

class GalleryImage(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    pic = db.Column(db.LargeBinary, nullable=False)
    content = db.Column(db.String(200), nullable=False)
    name = db.Column(db.String(200), nullable=False)
    date_time = db.Column(db.DateTime, default=datetime.utcnow)

    def __repr__(self):
        return '<Gl %r>' % self.id

I transfred the elements to html script, I did not save the images in a folder because they are saved in the database
{% for pic in gallery %}

{{pic.name}},
 {{pic.content}}

{% endfor %}

Comment: see this https://stackoverflow.com/questions/31849494/serve-image-stored-in-sqlalchemy-largebinary-column
Answer: In .py
def get_images():
images = db.session.query(GalleryImage).all()
image_list = []
# read image data from db back to form a rendable in html
for img in images:
    image = base64.b64encode(img.pic).decode('ascii')
    image_list.append(image)
return render_template('gallery.html', image_list=image_list)

In .html

{% if image_list|length == 0 %}

Add some Images to the Gallery

{% else %}
{% for image in image_list %}

Worked for me


Electrical Ceiling Lights: Torsion vs Friction Clips Installation Differences

Question: Is there any difference between Using Torsion springs vs Friction clips in installing ceiling lights? I am trying to understand the advantages/differences between the two methods.
https://www.youtube.com/watch?v=QdJlo5RVZCw

Halo Eaton Lights
Answer: Whether you use the torsion springs or friction clips depends entirely on the type of housing you're mounting the trim plate on. If the housing has a spring bracket in it like the picture below, you would use the torsion springs. If there is no spring bracket, only a few holes or slots for a straight spring, then you'd use the friction clips to secure the trim plate to the housing.
I like the torsion springs. they do a better job of hugging the ceiling. If there's a little play in the mounting of the housing, the friction clips are harder to push up for a tight fit. Plus they are easier to pull down and adjust if necessary
(Note: picture from utube)
Comment: I like the torsion springs. they do a better job of hugging the ceiling.  If there's a little play in the mounting of the housing, the friction clips are harder to push up for a tight fit.  Plus they are easier to pull down and adjust if necessary.
Comment: Given the opportunity to choose, torsion springs for sure (though these days there are also "junction box mount" LED lights that save the cost of a housing at all, if you are still in the "shopping" phase.)
Comment: so its depends on the housing, whats better durability, or general advantage wise? I can choose my housing depending on the answer


scope of eval function in python

Question: Consider the following example:
i=7
j=8
k=10
def test():
    i=1
    j=2
    k=3
    return dict((name,eval(name)) for name in ['i','j','k'])

It returns:
>>> test()
{'i': 7, 'k': 10, 'j': 8}

Why eval does not take into consideration the variables defined inside the function? From the documentation, optionally you can pass a globals and a locals dictionary. What does it means?Finally, how can I modify this small case to make it work?
Comment: you could modify it to work by adding `global` before variable declaration inside a function but that's a bad idea, on the other hand, using `eval` is usually a bad idea as well.
Comment: What rusty said - unless you're sure you _have_ to use eval, stay far away from it.
Comment: @l4mpi I knew that eval is a bad idea, but i was just playing around with scopes, and i just didn't understand this behaviour
Answer: Generators are implemented as function scopes:

The scope of names defined in a class block is limited to the class
  block; it does not extend to the code blocks of methods – this
  includes generator expressions since they are implemented using a
  function scope.

So, the generator inside the dict() constructor has its own locals() dictionary. Now let's take a look at Py_eval's source code, specially when both globals() and locals() are None:
if (globals == Py_None) {
        globals = PyEval_GetGlobals();
        if (locals == Py_None)
            locals = PyEval_GetLocals();
    }

So, for your example PyEval_GetLocals() will be empty at the moment the loop is executing and globals() will be the global dictionary. Note that i, j and k defined inside the function are not in local scope of generator, rather they are in its enclosing scope:
>>> dict((name,eval(name, globals(), {})) for name in ['i', 'j', 'k'])
{'i': 7, 'k': 10, 'j': 8}

Answer: This occurs because the generator expression has a different scope to the function:
>>> def test():
    i, j, k = range(1, 4)
    return dict((j, locals()) for _ in range(i))

>>> test()
{2: {'.0': <listiterator object at 0x02F50A10>, 'j': 2, '_': 0}}

Using j inside the scope binds it from the function, as that's the nearest enclosing scope, but i and k are not locally bound (as k isn't referenced and i is only used to create the range).

Note that you can avoid this issue with:
return dict(i=i, j=j, k=k)

or a dictionary literal:
return {'i': i, 'j': j, 'k': k}

scope of eval function in python


SQL equivalent of COUNTIFs Excel formula?

Question: I am trying to recreate some excel formula in Netezza Aginity SQL so the processing can be done at the database level, but struggling with countifs.
The formula is roughly:
If( Countifs( policycolumn, policy, matchcolumn, "Match", codecolumn, code) >0, "true", "false")

So if there are any rows that match policy and "match" and code, itll be greater than 0 and be true. I am just struggling with the policy colimn part as the policy to count is the policy from that row.
Is there any way that people have used something to mimic countifs in sql?
Edit: To give some examples, my dataset looks like: (sorry i am bad with formatting):
policycolumn  |  matchcolumn  |  codecolumn

12345         | match         | c

12345         | no match      | d

9876          | match         | c

9876          | no match      | c

I would like to have an additional column that would show
policycolumn  |  matchcolumn  |  codecolumn | yesno

12345         | match         | c           | yes

12345         | no match      | d           | no

9876          | match         | c           | yes

9876          | match         | d           | no

Row 1 would be a yes because its counting the number of times 12345 appears, with a "match" and a "c". This row matches that so would be >0 and trigger the IF rule to be "yes"
ROw 2 wouldnt be a yes because its although its policy number 12345, its a "no match" and a "d".
Row 3 would be a yes because that row policy number 9876 is a "match" and a "c".
Row 4 isnt a yes because that row policy number 9876 is a "no match".
All criteria (Match Column = match and Codecolumn = c) have to be met for that row to be true, and the new column to set to "yes".
Comment: Can you explain what you're trying to do (sample input data, sample output) in a way that doesn't involve Excel?
Comment: Not sure if I'm understanding the whole issue, but it sound like you just want to use `SUM` with a few conditions `SELECT SUM(CASE WHEN a=b AND c=d AND e=f THEN 1 ELSE 0 END) FROM mytable`
Comment: The above answer is probably as close as we will get unless you provide a full SET of input rows and desired output rows...
Comment: Thank you sorry I added in some additional information and an example of what I have put in and what I hope to get out, hope it helps. I am trying to match the logic that countif performs in Excel, by all conditions needing to be true for something to be counted once. Once all conditions are met and its counted once, the IF that wraps the COUNTIF is easy to replicate.
Comment: In standard SQL you can use  `count(*) filter (where ...)` - but I don't know if Netezza supports that
Answer: This SQL should do what you are asking.
select policycolumn, matchcolumn, codecolumn,
case when matchcolumn = 'match' and codecolumn = 'c' then 'yes' else 'no' end yesno
from <your table>

test result
with test_data_set as(
  select 12345 policycolumn, 'match' matchcolumn, 'c' codecolumn union all
  select 12345, 'no match', 'd' union all
  select 9876, 'match', 'c' union all
  select 9876, 'match', 'd')
select policycolumn, matchcolumn, codecolumn,
case when matchcolumn = 'match' and codecolumn = 'c' then 'yes' else 'no' end yesno
from test_data_set;

*returns*
policycolumn matchcolumn codecolumn yesno
12345   match   c   yes
12345   no match    d   no
9876    match   c   yes
9876    match   d   no

Please let me know if it helped


Disable Windows 8 CharmsBar in WPF-Fullscreen App

Question: I want to create a new fullscreen "kiosk" WPF Application for Windows 8.
It's not a modern UI app.
The app should be start automatically and must be unclosable.
A few things are already implemented.
The app disables the hardware windows key with a registry value and
starts with Windows.
The only thing that doesn't work is the disabling of the Charms-Bar.
I've tested a lot of things, like a DisableCharmsHint-Registry Value.
But it doesn't work. And than I searched on the web and I've seen a API-Call, that should disable the CharmsBar - But it doesn't work.
I hope anybody could help.
Here is my helper-class. I call the EnableEdgeGestures - Method with the MainWindow-Handle and false - disable.
The result of the API-Call SHGetPropertyStoreForWindow is always 0.
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;

namespace Helpers {
    public class EdgeGestureUtil {
        #region Strukturen

        [StructLayout ( LayoutKind.Sequential, Pack = 4 )]
        public struct PropertyKey {
            public PropertyKey ( Guid guid, UInt32 pid ) {
                fmtid = guid;
                this.pid = pid;
            }

            [MarshalAs ( UnmanagedType.Struct )]
            public Guid fmtid;
            public uint pid;
        }

        [StructLayout ( LayoutKind.Explicit )]
        public struct PropVariant {
            [FieldOffset ( 0 )]
            public short vt;
            [FieldOffset ( 2 )]
            private short wReserved1;
            [FieldOffset ( 4 )]
            private short wReserved2;
            [FieldOffset ( 6 )]
            private short wReserved3;
            [FieldOffset ( 8 )]
            private sbyte cVal;
            [FieldOffset ( 8 )]
            private byte bVal;
            [FieldOffset ( 8 )]
            private short iVal;
            [FieldOffset ( 8 )]
            public ushort uiVal;
            [FieldOffset ( 8 )]
            private int lVal;
            [FieldOffset ( 8 )]
            private uint ulVal;
            [FieldOffset ( 8 )]
            private int intVal;
            [FieldOffset ( 8 )]
            private uint uintVal;
            [FieldOffset ( 8 )]
            private long hVal;
            [FieldOffset ( 8 )]
            private long uhVal;
            [FieldOffset ( 8 )]
            private float fltVal;
            [FieldOffset ( 8 )]
            private double dblVal;
            [FieldOffset ( 8 )]
            public bool boolVal;
            [FieldOffset ( 8 )]
            private int scode;
            //CY cyVal;
            [FieldOffset ( 8 )]
            private DateTime date;
            [FieldOffset ( 8 )]
            private System.Runtime.InteropServices.ComTypes.FILETIME filetime;
            //CLSID* puuid;
            //CLIPDATA* pclipdata;
            //BSTR bstrVal;
            //BSTRBLOB bstrblobVal;
            [FieldOffset ( 8 )]
            private Blob blobVal;
            //LPSTR pszVal;
            [FieldOffset ( 8 )]
            private IntPtr pwszVal;
            //LPWSTR
            //IUnknown* punkVal;
            //IDispatch* pdispVal;
            //        IStream* pStream;
            //        IStorage* pStorage;
            //        LPVERSIONEDSTREAM pVersionedStream;
            //        LPSAFEARRAY parray;
            //        CAC cac;
            //        CAUB caub;
            //        CAI cai;
            //        CAUI caui;
            //        CAL cal;
            //        CAUL caul;
            //        CAH cah;
            //        CAUH cauh;
            //        CAFLT caflt;
            //        CADBL cadbl;
            //        CABOOL cabool;
            //        CASCODE cascode;
            //        CACY cacy;
            //        CADATE cadate;
            //        CAFILETIME cafiletime;
            //        CACLSID cauuid;
            //        CACLIPDATA caclipdata;
            //        CABSTR cabstr;
            //        CABSTRBLOB cabstrblob;
            //        CALPSTR calpstr;
            //        CALPWSTR calpwstr;
            //        CAPROPVARIANT capropvar;
            //        CHAR* pcVal;
            //        UCHAR* pbVal;
            //        SHORT* piVal;
            //        USHORT* puiVal;
            //        LONG* plVal;
            //        ULONG* pulVal;
            //        INT* pintVal;
            //        UINT* puintVal;
            //        FLOAT* pfltVal;
            //        DOUBLE* pdblVal;
            //        VARIANT_BOOL* pboolVal;
            //        DECIMAL* pdecVal;
            //        SCODE* pscode;
            //        CY* pcyVal;
            //        DATE* pdate;
            //        BSTR* pbstrVal;
            //        IUnknown** ppunkVal;
            //        IDispatch** ppdispVal;
            //        LPSAFEARRAY* pparray;
            //        PROPVARIANT* pvarVal;
            //

            ///
            /// Helper method to gets blob data
            ///
            private byte[] GetBlob ( ) {
                byte[] Result = new byte[ blobVal.Length ];
                Marshal.Copy ( blobVal.Data, Result, 0, Result.Length );
                return Result;
            }

            ///
            /// Property value
            ///
            public object Value {
                get {
                    VarEnum ve = ( VarEnum ) vt;
                    switch ( ve ) {
                        case VarEnum.VT_I1:
                            return bVal;
                        case VarEnum.VT_I2:
                            return iVal;
                        case VarEnum.VT_I4:
                            return lVal;
                        case VarEnum.VT_I8:
                            return hVal;
                        case VarEnum.VT_INT:
                            return iVal;
                        case VarEnum.VT_UI4:
                            return ulVal;
                        case VarEnum.VT_LPWSTR:
                            return Marshal.PtrToStringUni ( pwszVal );
                        case VarEnum.VT_BLOB:
                            return GetBlob ( );
                    }
                    throw new NotImplementedException ( "PropVariant " + ve.ToString ( ) );
                }
            }
        }

        internal struct Blob {
            public int Length;

            public IntPtr Data;
            //Code Should Compile at warning level4 without any warnings,
            //However this struct will give us Warning CS0649: Field [Fieldname]
            //is never assigned to, and will always have its default value
            //You can disable CS0649 in the project options but that will disable
            //the warning for the whole project, it's a nice warning and we do want
            //it in other places so we make a nice dummy function to keep the compiler
            //happy.
            private void FixCS0649 ( ) {
                Length = 0;
                Data = IntPtr.Zero;
            }
        }

        #endregion

        #region PropertyStore

        [ComImport, Guid ( "886D8EEB-8CF2-4446-8D02-CDBA1DBDCF99" ), InterfaceType ( ComInterfaceType.InterfaceIsIUnknown )]
        interface IPropertyStore {
            [MethodImpl ( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime )]
            void GetCount ( [Out] out uint cProps );

            [MethodImpl ( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime )]
            void GetAt ( [In] uint iProp, out PropertyKey pkey );

            [MethodImpl ( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime )]
            void GetValue ( [In] ref PropertyKey key, out PropVariant pv );

            [MethodImpl ( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime )]
            void SetValue ( [In] ref PropertyKey key, [In] ref PropVariant pv );

            [MethodImpl ( MethodImplOptions.InternalCall, MethodCodeType = MethodCodeType.Runtime )]
            void Commit ( );
        }

        #endregion

        #region Methoden

        [DllImport ( "shell32.dll", SetLastError = true )]
        static extern int SHGetPropertyStoreForWindow (
            IntPtr handle, ref Guid riid, [Out, MarshalAs ( UnmanagedType.Interface )] out IPropertyStore propertyStore );

        public static void EnableEdgeGestures ( IntPtr hwnd, bool enable ) {

            IPropertyStore pPropStore = null;
            int hr = 0;
            hr = SHGetPropertyStoreForWindow (
                hwnd, ref IID_PROPERTY_STORE, out pPropStore );

            if ( hr == 0 ) {
                PropertyKey propKey = new PropertyKey ( );
                propKey.fmtid = DISABLE_TOUCH_SCREEN;
                propKey.pid = 2;
                PropVariant var = new PropVariant ( );
                var.vt = VT_BOOL;
                var.boolVal = enable;
                pPropStore.SetValue ( ref propKey, ref var );
                Marshal.FinalReleaseComObject ( pPropStore );
            }
        }

        #endregion

        static Guid DISABLE_TOUCH_SCREEN    = new Guid ( "32CE38B2-2C9A-41B1-9BC5-B3784394AA44" );
        static Guid IID_PROPERTY_STORE      = new Guid ( "886d8eeb-8cf2-4446-8d02-cdba1dbdcf99" );
        static short VT_BOOL                = 11;
    }
}

Regards
Ronny
Answer: Just kill explorer.exe when your application launches.


What could cause the garage door overhead light to not stay on while the door is opening?

Question: We replaced one wall switch with a door bell button and now the overhead light flashes on when I hit the button, goes off and then the light comes back on when the door is fully open.  Before replacing the button, the light would come on and stay on during the door opening operation.  When the door is opened with a different second wall switch or with the remote door opener in the car, the light will come on and stay on.
Comment: Did you have a question?
Comment: That's easy, gremlins. I have them in my house, too.
Answer: The doorbell switch is not equivalent to the garage door switch it replaced, in some manner that upsets the opener.
If your unasked question is "how to make the light stay on when the door is opening" you need to remove the doorbell switch and replace it with a garage door switch compatible with your opener.


Twilio Ruby Gem calls.create param - adding r.Say message

Question: I'm trying to add the option of adding a spoken message before a prerecorded message plays in my outbound calls. The closest question of this this type I could find was this Does Twilio Ruby Gem Take Other Params
I currently have a form where you enter the number you want to call and field for the message you'd like to
<form action="calls" method="post">
    <input type="text" name="number" placeholder="number e.g. 2124095555" />
    <input type="text" name="message" placeholder="add a message" />
    <input type="submit" value="Roll em!">
</form>

In my call's controller I have:
 def create

    data = {
      :from => CALLER_ID,
      :to => params['number'],
      :say => params['message'],
      :url => 'http://howenstine.co/rick_roll.mp3',
      :if_machine => 'Continue'
    }

    begin
      client = Twilio::REST::Client.new(ACCOUNT_SID, ACCOUNT_TOKEN)
      client.account.calls.create(data)
    rescue StandardError => bang
      redirect_to :action => '.', 'msg' => "Error #{bang}"
      return
    end
    redirect_to root_path
  end

Obviously the :say param is not working. I've something like this for inbound calls, but I don't believe that will work for an outbound call
 def voice
    response = Twilio::TwiML::Response.new do |r|
      r.Say 'fooo bar', :voice => 'alice'
         r.Play 'http://linode.rabasa.com/cantina.mp3'
    end

    render_twiml response
  end

Any help or guidance would be greatly appreciated.
Answer: Twilio developer evangelist here.
When creating calls via the REST API, you need to send the from, to and either url or applications_sid parameters and there are a bunch of optional parameters, like if_machine, that you can send too. The full list is available in the REST API documentation.
However, as you have discovered, you can't send a say parameter. In order to get the result you're looking for, you'll need use your voice endpoint url to read the message, then play the file.
Since you already have a voice endpoint, you will also need to decide at the time of the call what to do.
So, if you modify your create action to something like the following, which passes the message along to your voice url:
def create
  data = {
    :from => CALLER_ID,
    :to => params['number'],
    :url => voice_url(:message => params['message']),
    :if_machine => 'Continue'
  }

  begin
    client = Twilio::REST::Client.new(ACCOUNT_SID, ACCOUNT_TOKEN)
    client.account.calls.create(data)
  rescue StandardError => bang
    redirect_to :action => '.', 'msg' => "Error #{bang}"
    return
  end
  redirect_to root_path
end

Then in your voice endpoint, check for the message and return it, followed by the file you wanted to play, otherwise return what you had already.
def voice
  if params['message'].present?
    # if we have a message, say it followed by the rick roll
    response = Twilio::TwiML::Response.new do |r|
      r.Say params['message'], :voice => 'alice'
      r.Play 'http://howenstine.co/rick_roll.mp3'
    end
  else
    # otherwise return the original response
    response = Twilio::TwiML::Response.new do |r|
      r.Say 'fooo bar', :voice => 'alice'
      r.Play 'http://linode.rabasa.com/cantina.mp3'
    end
  end

  render_twiml response
end

Let me know if that helps at all.