How to use the cancelEl in a Backbone Modal?

Question: I'm currently using this plugin for a modal: http://awkward.github.io/backbone.modal/
It comes with a cancelEl method to close the modal, and I am using it like so:
  var ActionModal = Backbone.Modal.extend({
    template: '#actionable-modal-template',
    cancelEl: '.bbm-btn-close'
  });

And here is what I am trying to do, written in pseudo code:
if (cancelEl.invoked) {
  // Do something
}

The psuedo code is based on the assumption that cancelEl causes clicking the backdrop of the modal, as well as the button, to close the modal.
How can I use the cancelEl method?
Thanks.
Answer: You can implement beforeCancel or cancel
  var ActionModal = Backbone.Modal.extend({
    template: '#actionable-modal-template',
    cancelEl: '.bbm-btn-close',
    beforeCancel: function() {
       // stuff
    }
  });

Looking at the source code, beforeCancel can be used to cancel the modal close:
if (this.beforeCancel) {
  if (this.beforeCancel() === false) {
    return;
  }
}

And cancel can be used to implement more functionality:
if (typeof this.cancel === "function") {
  this.cancel();
}


Multiple imports in python as the same keyword

Question: I am more or less a python noob and while getting my hands dirty, in one of the modules I am using, I encountered this statement:
from django.utils.translation import ugettext, ugettext_lazy as _
The statement is django and i18n related, but the question is of a more general nature... I think. So, if I use _("some string to be translated") in my code, which one is the function called, ugettext or ugettext_lazy?
Answer: The comma divides up clauses of the import statement.  That code is equivalent to:
from django.utils.translation import ugettext
from django.utils.translation import ugettext_lazy as _

Comment: Thanks for the short and clear answer to a newbie question, and finally... I can vote up too :P


How to put IntelliJ/Pycharm settings under version control?

Question: I'm a frequent user of PyCharm and a number of the other JetBrains IDEs. I try to keep my settings synchronized across the different IDEs, but I'm now considering moving to IntelliJ IDEA and am finding it extremely difficult to figure out what I've changed and what the differences are among my different settings files.
How can I put my PyCharm settings files under version control so that I can track my changes and also quickly revert back to old versions so I can try out new settings changes without fear?
(I don't mind exporting to a specific repo each time, but it seems that the settings always export as JAR files, which don't lend themselves to VCS.)
Comment: The global settings should be in a bunch of XML files under `$HOME/.IntellijIdea15/config` (this is platform dependend though, see [this](https://www.jetbrains.com/idea/help/directories-used-by-intellij-idea-to-store-settings-caches-plugins-and-logs.html) for more details). Project specific settings are in `.idea/` in the project directory. So I would personally try to put first mentioned directory under VC, change few settings and observe what happens (haven't tried it personally)
Answer: I am using the Settings Repository plugin to syncronize settings between PyCharm and PhpStorm and it is working very well. It is actually designed with version control and team sharing in mind, see project repo on github and have built in support for conflict resolution, merge and overwriting remote or local.
It does also support file system and, from what I can tell, what then is stored is the mirror version of the git repository.
Answer: PyCharm (at least the Linux 4.X and 5.0 Pro versions) places its config files in a .idea dir under the project dir:
$ find .idea/
.idea/
.idea/libraries
.idea/libraries/Google_App_Engine_SDK.xml
.idea/libraries/Generated_files.xml
.idea/apartsw.iml
.idea/misc.xml
.idea/modules.xml
.idea/runConfigurations
.idea/runConfigurations/apartsw.xml
.idea/encodings.xml
.idea/vcs.xml
.idea/inspectionProfiles
.idea/inspectionProfiles/MyProject.xml
.idea/inspectionProfiles/profiles_settings.xml
.idea/watcherTasks.xml
.idea/webResources.xml
.idea/workspace.xml
.idea/scopes
.idea/scopes/scope_settings.xml
.idea/dictionaries
.idea/dictionaries/username.xml

I added the entire dir with the exception of .idea/workspace.xml into the project's git repo, following JetBrains' PyCharm-specific and/or generic .idea-based Tools recommendations.


Anyone know how to solve the Missing Mesh signs when using Harvest Flora Mod?

Question: I've dug up Oblivion again and installed my favorite mods. Among other things "Harvest Flora". Unfortunately I get a lot of these ugly yellow exclamation marks ingame (they go away if I disable the mod) instead of some plants.
My google searches turned up the explanation that somehow the meshes to the mod aren't loaded. I have tried adding the bsa file to the ini file but I can't find it. I only have a Oblivion_default.ini and it is lacking the directive I was supposed to edit.
Anyone know how I can fix this? Because the Mod itself is great...
Comment: I've used Harvest Flora for several years now and never had a problem like this. Are you using proper archive invalidation and using version 3.0.1 from TESNexus? Also, converting the archive to an OMOD with Oblivion Mod Manager will simplify installation. OBMM can also enable BSA redirection which should help with modding.
Comment: In OBMM click the 'Utilities' button on the right-side of the window, then click 'Archive Invalidation'. Select 'BSA Redirection' mode then click 'Update now'. You shouldn't mess with Oblivion_default.ini, the only .ini's you should edit are the ones in your 'My Games' folder.
Comment: It is the latest version and I've converted it into an OMOD like all the others. However I don't know what you mean with archive invalidation...
Comment: Ok. I've tried that. I also uninstalled all other mods to be sure that it's really because of Harvest Flora. Didn't help the triangles are still there.
Answer: I solved the problem. And the culprit was * drumrolls * ...
corrupted mod files
I downloaded it again and now it works. Thanks anyway folks!
Comment: Yup. If all else fails, nuke it and do a fresh install!


How should I fit a new breaker for a subpanel in my main panel?

Question: I want to add a 100 amp subpanel in my basement with a 60 amp breaker next to my main panel which is 200 amp. I want to run my basement lights on their own breaker. Right now my garage and basement are on the same double 15 amp breaker.
What I need to know is what breaker I should remove to make my subpanel a 60. Here are pics of my box and what they feed.
Comment: Whichever you like. Decide what circuits you want to move to the new box (based on cable length, etc.) and there's your answer.
Comment: This seems like an opinion question.  Make sure to get a nice big subpanel so you never have to do this again! Remember large aluminum is proven safe, and #2 aluminum wire (90A) is quite a bit cheaper than #6 copper.  You can put it on a cheaper 60A breaker and upgrade to a 90A breaker if you need the extra capacity.
Answer: The 2 on the bottom right would be my choice, why they are small 15 amp and one looks open.
Use those 2 positions to feed the garage then remove the tandem and put the 20 amp in that location if there are 2 in use there another choice would be better but this would be my choice with what I can see.


Random numbers and sampling from uniform distrubution

Question: U1 ~ Uniform[0,1] and U2 ~ Uniform[2, 3]. In which region of the U1-U2 plane is the joint pdf of U1,U2 nonzero?
I have not understood the meaning of U1-U2 plane here.. Can anyone please explain how do I go about solving this question?
Comment: We actually cannot answer the question as written because you haven't specified the joint distribution of $U_1$ and $U_2.$ Are they independent?
Comment: Yes......they are independent
Comment: why all the dots? If they're independent, it's important to say so. In a lot of problems, it's more or less implicit that they're independent unless otherwise noted (though lots of people will police you on this regardless since it's a very strong assumption that is often forgotten). However this problem is about 'sketching supports' which is generally a class of problem where the dependence of the variables is a main feature, so it's somewhat strange to even see a problem where they're independent.
Comment: Actually, nothing is mentioned in the problem.... I am not able to understand this question. Especially the U1-U2 plane. I am sorry if I am lacking clarity. Il try to get more information on this if possible and will update it.
Comment: In my answer, your main question is answered in the first sentence and the rest is a sketch of how to do the problem. It's a plane of values for the two random variables. If you have further questions about that, let me know.
Answer: When you have two random variables, you can imagine each outcome as a point in the plane, since each outcome consists of a value for $U_1$ and a value for $U_2.$ For a continuous distribution, there will be a density $f_{U_1,U_2}(u_1,u_2)$ for the outcome occurring near every point $(u_1,u_2)$ in the plane, such that the probability of the outcome lying in a certain region is the integral of the density function over that region. This is what a joint PDF is.
The region of the plane where the PDF is nonzero is called the support, so this problem is asking you for the support of the PDF. Here, as you've indicated in the comments, the variables are independent, so the joint PDF is just the product of the marginal PDFs. Since they're uniform, we can write the marginal PDFs $$f_{U_1}(u_1) = 1_{[0,1]}(u_1) \\f_{U_2}(u_2) = \frac{1}{3-2}1_{[2,3]}(u_2)= 1_{[2,3]}(u_2),$$ where $1_A(u)$ is the indicator function that is $1$ when $u\in A$ and zero otherwise. By independence the joint is $$ f_{U_1,U_2}(u_1,u_2)=1_{[0,1]}(u_1)1_{[2,3]}(u_2)$$ so your task is to write down the region of the $u_1-u_2$ plane where this function is nonzero.

A couple of comments. First, I've used a lot of notation here, but really, at least in the independent case, this is pretty much common sense once you understand everything. It's basically equivalent to

$u_1$ can be any number between zero and one, and $u_2$ can be any
  number between $2$ and $3.$ What region of the plane can $(u_1,u_2)$
  lie in?

but I'll stress this is only in the case of independence.
Second, much less important comment for completeness's sake. This is not actually all that well-posed since you can always change the PDF on a set of measure zero (including setting the PDF to zero there) and still have the same distribution. So 'places where the PDF is zero' is not quite the same thing as 'support'. This is really a minor technical point you can probably ignore for now.
Comment: Ok... so co-ordinates of this region would be (0,2) (1,2) (1,3) (0,3) assuming U1 and U2 are independent. Actually, I got confused in U1-U2 notation.. I thought its an equation of plane of the form ax+by=d. Thanks a lot.
Comment: @Harshada Those are the corners of the region (which is a square), yes. We can write the region as either set notation $[0,1]\times [2,3]$ or as inequalities $0\le u_1 \le 1,$ $2\le u_2\le 3.$


Flex Menu Control - Click a button and a menu is displayed. How can I click that button a second time and hide that menu?

Question: Basically, I have a button and on click it displays a menu. I want to click that menu a second time and the menu closes. Currently, every time you click the button, the menu reopens. I pasted the Flex livedoc example below. If you click the button, the menu keeps reopening.
Now, I rigged it up by setting a var to open and closed, so when clicking the button it does a check. However, if you click away from the screen, the HIDE event gets dispatched, and the menu closes. This messed up the open close var being set.
How could I make this Flex example below show the menu on button click, and then on a second button click, it closes the menu? Take into affect that if you click away from the menu, it closes it.
Also, I played around with the MOUSE_DOWN_OUTSIDE event for the button and set the preventDefault, and the FlexMouseEvent event.cancelable is set to false.
Changing to a PopUpMenuButton is not an option. I have to much skinning involved.
Here is the Flex example:

<code><mx:Script>
    <![CDATA[
        // Import the Menu control.
        import mx.controls.Menu;

        // Create and display the Menu control.
        private function createAndShow():void {
            var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
            myMenu.labelField="@label";
            myMenu.show(10, 10);
        }
    ]]>
</mx:Script>

<!-- Define the menu data. -->
<mx:XML format="e4x" id="myMenuData">
    <root>
        <menuitem label="MenuItem A" >
            <menuitem label="SubMenuItem A-1" enabled="false"/>
            <menuitem label="SubMenuItem A-2"/>
        </menuitem>
        <menuitem label="MenuItem B" type="check" toggled="true"/>
        <menuitem label="MenuItem C" type="check" toggled="false"/>
        <menuitem type="separator"/>
        <menuitem label="MenuItem D" >
            <menuitem label="SubMenuItem D-1" type="radio"
                groupName="one"/>
            <menuitem label="SubMenuItem D-2" type="radio"
                groupName="one" toggled="true"/>
            <menuitem label="SubMenuItem D-3" type="radio"
                groupName="one"/>
        </menuitem>
    </root>
</mx:XML>

<mx:VBox>
    <!-- Define a Button control to open the menu -->
    <mx:Button id="myButton"
        label="Open Menu"
        click="createAndShow();"/>
</mx:VBox>
</code>
Answer: <code>//Declare menu as an instance variable instead of a local var
private var myMenu:Menu;

//var to store menu status
private var isMenuVisible:Boolean

//Create the Menu control. call this from the creationComplete of the
//application or the Component that it is part of.
private function createMenu():void
{
    var myMenu:Menu = Menu.createMenu(null, myMenuData, false);
    myMenu.labelField="@label";
    //menu fires an event when it is hidden; listen to it.
    myMenu.addEventListener(MenuEvent.MENU_HIDE, onMenuHidden);
}
private function onMenuHidden(e:MenuEvent):void
{
    /*
    menuHide event fired whenever the menu or one of its submenus
    are hidden - makes sure it was indeed the main menu that was hidden
    I don't have compiler handy to test this, so if for
    some reason comparing myMenu with e.menu doesn't work,
    try if(e.target == myMenu) instead;
    And please let me know which one works via comment :)
    */

    if(e.menu == myMenu)
       isMenuVisible = false;
}
//call this from button's click
private function toggleMenu():void
{
    if(isMenuVisible)
        myMenu.hide();
    else
        myMenu.show();
}
</code>
Comment: I just ran your code and it isn't quite what I am looking for.

When you click the button, the menu opens. If you click the button a second time, while the menu is still open, it closes the menu and reopens it. I want the menu to remain closed when you click the button while the menu is open. I am looking for a way to stop the menu from closing and reopening when clicking on the button while the menu is open.

We also need to take into account that when you click away from the menu, it also hides the menu by dispatching the HIDE_MENU event.

I need a way to do this. Any thoughts?
Comment: Here is why it doesn't work:

When you initially click the button the toggleMenu gets called and the myMenu.show(); is called. The Menu class, adds a MENU_HIDE listener on a show.

When the menu is open, and you click the button a second time, or click away from the menu, that MENU_HIDE gets dispatched. The Menu class listener happens before our onMenuHidden() gets called. So when our onMenuHidden() is called, the menu is already hidden, so it does myMenu.show().

Is there a way to call our onMenuHidden() before the Menu class listener? Or any other idea on how to get this to work?
Comment: @Dana Clicking on the button counts as clicking outside the menu. Try adding `toggleMenu` as click event listener using `addEventListener()` (through actionscript instead of mxml's click attribute) and set a higher priority (4th parameter) and call `event.stopPropagation()` and `event.stopImmediatePropagation()` from `toggleMenu` - this should prevent the button's click event from being handled as clicking outside.
Comment: Amarghosh, I really appreciate your help. Here is how I got it to work:

I call toggleMenu in the MXML on mouseDown (instead of on click):
mouseDown="toggleMenu(event)"

Instead of event.stopImmediatePropagation, I used callLater. I was afraid to use the stopImmediatePropagation because my application is fairly large, and I didn't want to cause any odd sideaffects. Here is what I did when mouseDown:

public function toggleMenu(e:Event):void
{
 if (myMenu.visible)
 {
  myMenu.hide();
 }
 else
 {
  this.callLater(function():void
   {
    myMenu.show();
   });
 }
}


Drupal 6 Layout issue

Question: i have recently started to learn drupal 6. I dont have any previous experience with drupal.
I was asked to implement a page on existing drupal site with the following structure.
a sopping page which will have an thumbail size image with lable and a quantity text box. This pattern will repeat for 10 products. At the end of the page i should have a submit button which results in sending an email with product and quantity to dedicated email address.
If its just a form then i can use webform but the requirement is having an image for every product.
I am  not sure how to implementn this...can someone guide me in the right direction please.
This is what i am trying to achieve(http://dontikurthi.com/sample.html)
thanks for the help in advance.
Cheers
R
Answer: For the image handling, I suggest ImageCache. If this is going to be a shop, use Ubercart. It's an extremely powerfull shop system with lots of functions and extensions.
It's hard to recommend a single way since Drupal offers many ways of doing it. I would go with CCK (let's you create your own content types with as many fields as you want) and/or Views (pulls data from many different areas of the database into viewable form, highly customizeable and on of the first modules to install together with CCK). Create a new content type with the help of CCK and create a view that displays this particular content type in a fashionable manner. That should get you pretty close to the image above.
Comment: thanks Dr, no, the site does not have shopping cart. Its just a product with quantity display for user to insert the quantity and send button will send an email. If i use Views, can it display forms?
Comment: No, it can't (without programming). When you want to use Drupal's forms, be sure to carefully read the docs http://api.drupal.org/api/group/form_api/6 and linked sites. What you want can't be done (at least not in my knowledge) with default settings/modules.
Comment: Using this solution you can only display form, but you can't process it easily without programing.
Answer: When creating a form with webform, you add form components, and you can add "markup" type component: it describes itself as "Markup allows you to enter custom HTML or PHP logic into your form."
So, to add a picture above or below a form item, just add a markup and put the appropriate HTML in it.
eg

Drupal 6 Layout issue


Sightseeing: Tollifer's Last Stand

Question: The Diablo 3: Reaper of Souls achievement Sightseeing says to "complete all of the following events in Westmarch." There are sixteen events to complete in Westmarch Commons and Westmarch Heights.
The final piece of the puzzle for me is Tollifer's Last Stand. According to this post on Blizzard's forums it is in Westmarch Commons. This video shows it being completed, but does not go into much detail.
I have performed a full clear of Westmarch Commons many times both in Adventure Mode and in Campaign Mode. I have seen every other event multiple times by now, but not this one. As the video advises I have been very diligent to keep my eyes peeled for doorways with the sparkly body and on the minimap for the dot. Nothing.
How do I complete this achievement? Do I need to be on a certain mode? Is it really super rare, or am I the victim of the RNG?
Answer: It has yet to be confirmed but the event does not seem to spawn in adventure mode (or at least not as often as it should). I've found it several time now in story mode so I advise you to try story mode. It's a rare spawn and there are no tricks to find this event, just luck.
Comment: There is a specific set piece that must appear in the map. The video linked in my question shows it at approximately 0:56. In addition, Tolifer's corpse must also spawn. The set piece is a rare tile to begin with, and the corpse also appears to be rare. This makes it double-rare. Almost a year after asking my question I was able to find a few videos and forum posts that corroborate your answer, although the rarity of Tolifer in adventure mode is still up for debate.

Sightseeing: Tollifer's Last Stand


Is there a way to stop Chrome/Firefox record history of a 'particular' website?

Question: I want Chrome/Firefox NOT to record history of a  'particular' website. Is it possible to do so? I searched in preferences, but couldn't find a solution.
Comment: Usually if you want no records of visiting a web page, you don't want anything to be recorded from this web page, so it would be strange to *store* a list of particular websites without history records. But yes, it might be usefull if you just want not to store sessions and so on.
Answer: This isn't the exact solution you want, but I couldn't find another way to do it more in line with the original question.
Chrome
The solution is to use incognito mode. To get to incognito mode, use the following keyboard shortcut:
Ctrl+Shift+N
Firefox
The solution is to use private browsing. To start private browsing, use the following keyboard shortcut:
Ctrl+Shift+P
Answer: In case of chrome there is an Extension called "Ghost Incognito",
Ghost incognito make sure that some domains always open in incognito mode. When navigating to a listed domain, the tab will open in a new incognito window.
Answer: You could also use these
history site blocker (for Chrome)

Note that while sites are prevented from being inserted into the history, autocomplete still works on URLs from those sites. I actually like the convenience of this, but it's definitely less secure than Incognito, which prevents those URLs from showing up in autocomplete.

History blocker (for Firefox)


How do I give other players money in GTA Online?

Question: Every time I go to Quick Menu > Inventory > Cash > Give Cash it says that I'm unable to give someone else cash.
I know you can only give $5000 each day, but I can't give anything.
Does anyone know why this is?
Comment: I have read on other forums that the option is currently disabled because of 'hackers' with a ton of money were handing out cash to people. I know before the last patch I was able to give cash using this method.
Comment: Last night when I was playing a friend of mine gave me 30% of the bounty when I helped him take someone down in via a helicopter I was flying.... So unless they JUST disabled this, it should still be an active feature - but I am unsure about the limit
Comment: @ZeroStack Sharing cash from the last job is not the feature in question, if that is what you are referring to
Comment: Oh, I dont have the ability to accept bounty missions on other players yet (I have yet to talk to Lester online)... My friends just handed it to me so I thought it would be in the same realm.  My apologies if I am referring to a different feature.
Comment: @Sharlike He was talking about killing someone with a bounty on them, not a job.  You can kill people with a bounty on them from day 1.  You just can't *put* a bounty on someone until you hear from Lester.
Comment: @Archer Well, holding up a store also isn't a 'job', but you can still select "Share cash from last job" after doing it. I assume it would apply to bounties. My point is just that OP is asking about the "Give Cash" option.
Comment: @Sharlike Yes, that's my point exactly.  He's not referring to jobs :)
Answer: From an answer by Rockstar Support in the Rockstar Support website post, "Why can't I give money on GTA online? says "unable to give money" yet I have so much":

It looks like this is a potential bug. Our dev team is now aware and looking into it; thank you for the report.
Comment: @fbueckert I think this was supposed to be a comment in reply to Robotnik from the other answer on this question.
Comment: @kazzamalla That's fine, but this answer doesn't stand by itself at all.  It's up to the original poster to edit the correct link into it.
Comment: @fbueckert Agreed, my point was that this user had no reputation to make a comment and likely having never used the SE network tried to leave the information in a helpful way.  Just pointing it out.
Comment: Yes it was. I was on my phone and didn't know how to add comments


Converting a specific Matlab Script to Python

Question: I need to make a 1-1 to conversion of the following Matlab script into Python using numpy and scipy.
This script computes a feature called LPQ (Local Phase Quantiser) which is oftenly used in face recognition.
The paper which documents the LPQ feature extraction can be found here:
http://www.ee.oulu.fi/mvg/files/pdf/ICISP08.pdf 2
The Matlab version of the script is the following:
function LPQdesc = lpq(img,winSize,mode)

%% Defaul parameters
% Local window size
if nargin<2 || isempty(winSize)
    winSize=3; % default window size 3
end

rho=0.90; % Use correlation coefficient rho=0.9 as default

% Local frequency estimation (Frequency points used [alpha,0], [0,alpha], [alpha,alpha], and [alpha,-alpha])
if nargin<4 || isempty(freqestim)
    freqestim=1; %use Short-Term Fourier Transform (STFT) with uniform window by default
end
STFTalpha=1/winSize;  % alpha in STFT approaches (for Gaussian derivative alpha=1)
sigmaS=(winSize-1)/4; % Sigma for STFT Gaussian window (applied if freqestim==2)
sigmaA=8/(winSize-1); % Sigma for Gaussian derivative quadrature filters (applied if freqestim==3)

% Output mode
if nargin<5 || isempty(mode)
    mode='nh'; % return normalized histogram as default
end

% Other
convmode='valid'; % Compute descriptor responses only on part that have full neigborhood. Use 'same' if all pixels are included (extrapolates image with zeros).

%% Check inputs
if size(img,3)~=1
    error('Only gray scale image can be used as input');
end
if winSize<3 || rem(winSize,2)~=1
   error('Window size winSize must be odd number and greater than equal to 3');
end
if sum(strcmp(mode,{'nh','h','im'}))==0
    error('mode must be nh, h, or im. See help for details.');
end

%% Initialize
img=double(img); % Convert image to double
r=(winSize-1)/2; % Get radius from window size
x=-r:r; % Form spatial coordinates in window
u=1:r; % Form coordinates of positive half of the Frequency domain (Needed for Gaussian derivative)

%% Form 1-D filters
 % STFT uniform window
    % Basic STFT filters
    w0=(x*0+1);
    w1=exp(complex(0,-2*pi*x*STFTalpha));
    w2=conj(w1);

%% Run filters to compute the frequency response in the four points. Store real and imaginary parts separately
% Run first filter
filterResp=conv2(conv2(img,w0.',convmode),w1,convmode);
% Initilize frequency domain matrix for four frequency coordinates (real and imaginary parts for each frequency).
freqResp=zeros(size(filterResp,1),size(filterResp,2),8);
% Store filter outputs
freqResp(:,:,1)=real(filterResp);
freqResp(:,:,2)=imag(filterResp);
% Repeat the procedure for other frequencies
filterResp=conv2(conv2(img,w1.',convmode),w0,convmode);
freqResp(:,:,3)=real(filterResp);
freqResp(:,:,4)=imag(filterResp);
filterResp=conv2(conv2(img,w1.',convmode),w1,convmode);
freqResp(:,:,5)=real(filterResp);
freqResp(:,:,6)=imag(filterResp);
filterResp=conv2(conv2(img,w1.',convmode),w2,convmode);
freqResp(:,:,7)=real(filterResp);
freqResp(:,:,8)=imag(filterResp);

% Read the size of frequency matrix
[freqRow,freqCol,freqNum]=size(freqResp);

%% Perform quantization and compute LPQ codewords
LPQdesc=zeros(freqRow,freqCol); % Initialize LPQ code word image (size depends whether valid or same area is used)
for i=1:freqNum
    LPQdesc=LPQdesc+(double(freqResp(:,:,i))>0)*(2^(i-1));
end

%% Switch format to uint8 if LPQ code image is required as output
if strcmp(mode,'im')
    LPQdesc=uint8(LPQdesc);
end

%% Histogram if needed
if strcmp(mode,'nh') || strcmp(mode,'h')
    LPQdesc=hist(LPQdesc(:),0:255);
end

%% Normalize histogram if needed
if strcmp(mode,'nh')
    LPQdesc=LPQdesc/sum(LPQdesc);
end

Trying to convert the Matlab LPQ function in python I produced the following code:
# -*- coding: cp1253 -*-
import numpy as np
from scipy.signal import convolve2d

def lpq(img,winSize=3,decorr=0,freqestim=1,mode='nh'):
    rho=0.90;

    STFTalpha=1/winSize;  # alpha in STFT approaches (for Gaussian derivative alpha=1)
    sigmaS=(winSize-1)/4; # Sigma for STFT Gaussian window (applied if freqestim==2)
    sigmaA=8/(winSize-1); # Sigma for Gaussian derivative quadrature filters (applied if freqestim==3)

    convmode='valid'; # Compute descriptor responses only on part that have full neigborhood. Use 'same' if all pixels are included (extrapolates np.image with zeros).

    img=np.float64(img); # Convert np.image to double
    r=(winSize-1)/2; # Get radius from window size
    x=np.arange(-r,r) # Form spatial coordinates in window
    u=np.arange(1,r) # Form coordinates of positive half of the Frequency domain (Needed for Gaussian derivative)

    if freqestim==1:  #  STFT uniform window
         #  Basic STFT filters
        w0=(x*0+1);
        w1=np.exp(-2*np.pi*x*STFTalpha)
        w2=np.conj(w1);

    ## Run filters to compute the frequency response in the four points. Store np.real and np.imaginary parts separately
    # Run first filter
    filterResp=convolve2d(convolve2d(img,w0,convmode),w1,convmode);
    # Initilize frequency domain matrix for four frequency coordinates (np.real and np.imaginary parts for each frequency).
    shape0, shape1 = filterResp.shape
    freqResp=np.zeros((shape0,shape1,8));
    # Store filter outputs
    freqResp[:,:,0]=np.real(filterResp);
    freqResp[:,:,1]=np.imag(filterResp);
    # Repeat the procedure for other frequencies
    filterResp=convolve2d(convolve2d(img,w1.transpose(),convmode),w0,convmode);
    freqResp[:,:,2]=np.real(filterResp);
    freqResp[:,:,3]=np.imag(filterResp);
    filterResp=convolve2d(convolve2d(img,w1.transpose(),convmode),w1,convmode);
    freqResp[:,:,4]=np.real(filterResp);
    freqResp[:,:,5]=np.imag(filterResp);
    filterResp=convolve2d(convolve2d(img,w1.transpose(),convmode),w2,convmode);
    freqResp[:,:,6]=np.real(filterResp);
    freqResp[:,:,7]=np.imag(filterResp);

    # Read the size of frequency matrix
    freqRow,freqCol,freqNum=freqResp.shape;

    ## Perform quantization and compute LPQ codewords
    LPQdesc=np.zeros((freqRow,freqCol)); # Initialize LPQ code word np.image (size depends whether valid or same area is used)
    for i in range(0, freqNum):
        LPQdesc=LPQdesc+((freqResp[:,:,i])>0)*(2^(i-1));

    ## Switch format to uint8 if LPQ code np.image is required as output
    if mode=='im':
        LPQdesc=uint8(LPQdesc);

    ## Histogram if needed
    if mode=='nh' or mode=='h':
        LPQdesc=np.histogram(LPQdesc[:],range(256));

    ## Normalize histogram if needed
    if mode=='nh':
        LPQdesc[0]=LPQdesc[0]/sum(LPQdesc[0]);

    print LPQdesc[0]
    return LPQdesc[0]

However after the execution of the python script for the same image I get the following error:
Traceback (most recent call last):
  File "C:\Users\user\Desktop\source\lpq_parametric.py", line 58, in lpq
    filterResp=convolve2d(convolve2d(img,w0,convmode),w1,convmode);
  File "C:\Python27\lib\site-packages\scipy\signal\signaltools.py", line 548, in convolve2d
    out = sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue)
ValueError: object of too small depth for desired array

Since I am a noob in python and scipy/numpy I need help bringing this python script in a functional state. Could you please help me fix the bug in the script?
Answer: The problem seems to be with w0, w1, and w2.  Matlab does not have 1D arrays, so if you create what should be a 1D array it is automatically converted to a 2D array.  numpy, however, does have 1D arrays, and arange produces 1D array.
In this case, x, and w0, w1, and w2 that are derived from x, are all 1D arrays.  convolve2d, as its name implies, requires 2D arrays.  img, on the other hand, is likely a 2D array.  That is why you are getting the error.
The solution is to convert your 1D x to a 2D value.  This will then be carried forward through the other operations involving x, making w0, w1, and w2 also 2D.
Either of these two approaches should work:
x=np.atleast_2d(np.arange(-r,r))

or
x=np.arange(-r,r)[np.newaxis]

The first case always make the array 2D or higher, while the second adds one new dimension no matter what the current dimension is.  Since you know the dimensionality already, that is not a problem.
Although you didn't reach it because of the error, your transpose operation also will not work as expected, since the transpose of a 1D array does nothing.  This will also fix that problem.
Also, three other things:
First, you don't need the semicolon (;) at the end of the lines.  It does nothing when placed at the end of a line in Python.
Second, you are doing transpose the hard way.  The easy way is this:
filterResp=convolve2d(convolve2d(img,w1.T,convmode),w0,convmode)

Third, it is probably easier to do something like:
filterResp1=convolve2d(convolve2d(img,w1.T,convmode),w0,convmode)
filterResp2=convolve2d(convolve2d(img,w1.T,convmode),w1,convmode)
filterResp3=convolve2d(convolve2d(img,w1.T,convmode),w2,convmode)
freqResp=np.dstack([np.real(filterResp1),
                    np.imag(filterResp1),
                    np.real(filterResp2),
                    np.imag(filterResp2),
                    np.real(filterResp3),
                    np.imag(filterResp3),
                    np.real(filterResp4),
                    np.imag(filterResp4)])

Update
There are a number of other problems that I noticed reading the code:
First, if you are using python 2.x, then by default division of integers returns an integer.  So, for example, 1/2==0.  To change this so 1/2==.5, then add this above your existing imports:
from __future__ import division

This is not an issue in python 3.x.
Next, in python np.arange does not include the upper end, so:
x=np.arange(-r,r)

Should be:
x=np.arange(-r,r+1)[np.newaxis]

Next, the Matlab version of this line uses complex numbers:
w1=exp(complex(0,-2*pi*x*STFTalpha));

The python version doesn't.  This means both w1 and w2 will be different between the python and Matlab versions.  So:
w1=np.exp(-2*np.pi*x*STFTalpha)

Should be:
w1=np.exp(-2*np.pi*x*STFTalpha*1j)

Next, in the matlab version you transpose the first w0:
filterResp=conv2(conv2(img,w0.',convmode),w1,convmode);

In the python version you don't, so:
filterResp=convolve2d(convolve2d(img,w0,convmode),w1,convmode);

Should be:
filterResp=convolve2d(convolve2d(img,w0.T,convmode),w1,convmode)

Next, in the python version, i already starts at 0, so subtracting 1 from it changes the values compared to the Matlab version.  Also, python uses ** for powers, not ^ (in python ^ is binary XOR).  So:
for i in range(0, freqNum):
    LPQdesc=LPQdesc+((freqResp[:,:,i])>0)*(2^(i-1))

Should be:
for i in range(0, freqNum):
    LPQdesc=LPQdesc+((freqResp[:,:,i])>0)*(2**i)

Next, in Matlab, as you know, arr(:) flattens an array.  This is not the case in python.  Python uses arr.flatten().  And the histogram returns the bin edges, which you don't want.  So you need to change:
LPQdesc=np.histogram(LPQdesc[:],range(256));

to:
LPQdesc=np.histogram(LPQdesc.flatten(),range(256))[0]

Once you do that, to keep things the same as the Matlab version, you would then need to change:
if mode=='nh':
    LPQdesc[0]=LPQdesc[0]/sum(LPQdesc[0]);

print LPQdesc[0]
return LPQdesc[0]

to:
if mode=='nh':
    LPQdesc=LPQdesc/sum(LPQdesc)

print LPQdesc
return LPQdesc

Next, while this is not an error, you can simplify:
w0=(x*0+1);

To:
w0=np.ones_like(x);

Finally, I don't see how this line could possibly work:
LPQdesc=uint8(LPQdesc);

You have probably not tried mode=='im'.  The line should be:
LPQdesc=np.uint8(LPQdesc)

Also not an error, but you can use arr.real and arr.imag to get the real and imaginary parts in python, and arr.sum() to get the sum.
Also not an error, but since taking a sub-array in python doesn't take any additional memory, this:
# Read the size of frequency matrix
freqRow,freqCol,freqNum=freqResp.shape

## Perform quantization and compute LPQ codewords
LPQdesc=np.zeros((freqRow,freqCol))

Can become:
LPQdesc=np.zeros_like(freqResp[:,:,0])

Next, you never use u, so you can get rid of this line entirely (if you had u you would need r+1 again):
u=np.arange(1,r)

And you never use decorr either.
Next, you never compute w0, w1, or w2 if freqestim is not 1, so your program will crash if you try to run for any freqstim value other than 1.  I can't fix this since I don't know what to do for other values of freqstim.
Finally, in both Matlab and Python, using the loop for the sums is slow.  Python lets you broadcast low-dimensional arrays to higher dimensions, so you can do something like:
    inds = np.arange(freqResp.shape[2])[np.newaxis,np.newaxis,:]
    LPQdesc=((freqResp>0)*(2**inds)).sum(2)

So your final python function should look something like this:
# -*- coding: cp1253 -*-

from __future__ import division

import numpy as np
from scipy.signal import convolve2d

def lpq(img,winSize=3,freqestim=1,mode='nh'):
    rho=0.90

    STFTalpha=1/winSize  # alpha in STFT approaches (for Gaussian derivative alpha=1)
    sigmaS=(winSize-1)/4 # Sigma for STFT Gaussian window (applied if freqestim==2)
    sigmaA=8/(winSize-1) # Sigma for Gaussian derivative quadrature filters (applied if freqestim==3)

    convmode='valid' # Compute descriptor responses only on part that have full neigborhood. Use 'same' if all pixels are included (extrapolates np.image with zeros).

    img=np.float64(img) # Convert np.image to double
    r=(winSize-1)/2 # Get radius from window size
    x=np.arange(-r,r+1)[np.newaxis] # Form spatial coordinates in window

    if freqestim==1:  #  STFT uniform window
        #  Basic STFT filters
        w0=np.ones_like(x)
        w1=np.exp(-2*np.pi*x*STFTalpha*1j)
        w2=np.conj(w1)

    ## Run filters to compute the frequency response in the four points. Store np.real and np.imaginary parts separately
    # Run first filter
    filterResp1=convolve2d(convolve2d(img,w0.T,convmode),w1,convmode)
    filterResp2=convolve2d(convolve2d(img,w1.T,convmode),w0,convmode)
    filterResp3=convolve2d(convolve2d(img,w1.T,convmode),w1,convmode)
    filterResp4=convolve2d(convolve2d(img,w1.T,convmode),w2,convmode)

    # Initilize frequency domain matrix for four frequency coordinates (np.real and np.imaginary parts for each frequency).
    freqResp=np.dstack([filterResp1.real, filterResp1.imag,
                        filterResp2.real, filterResp2.imag,
                        filterResp3.real, filterResp3.imag,
                        filterResp4.real, filterResp4.imag])

    ## Perform quantization and compute LPQ codewords
    inds = np.arange(freqResp.shape[2])[np.newaxis,np.newaxis,:]
    LPQdesc=((freqResp>0)*(2**inds)).sum(2)

    ## Switch format to uint8 if LPQ code np.image is required as output
    if mode=='im':
        LPQdesc=np.uint8(LPQdesc)

    ## Histogram if needed
    if mode=='nh' or mode=='h':
        LPQdesc=np.histogram(LPQdesc.flatten(),range(256))[0]

    ## Normalize histogram if needed
    if mode=='nh':
        LPQdesc=LPQdesc/LPQdesc.sum()

    print LPQdesc
    return LPQdesc

Comment: The error message i posted is from the latest version of the script


Text editor with syntax highlighting, theme support and code folding

Question: I like Notepad++ under Windows. I was wondering if there are some similar ones for Ubuntu? Or just the powerful and convenient one in your opinion.
Features that I like are:

syntax highlighting for language X
theme support
line numbering
code folding
regex style
Powerful, yet not resource-consuming
Comment: This sounds rather subjective. I recommend you add a few use-cases and requirements to your questions, so that it has [one correct answer](http://askubuntu.com/faq).
Comment: useful requirements could include things like syntax highlighting for lanugage X, theme support, line numbering, code folding, regex style.
Answer: I would think gedit would be perfect.   It is on Ubuntu by default, is easy to use, and can be extended with plugins.
That being said, since notepad++ is based on scintilla, scite  is probably worth checking out.   Scite is based on scintilla as well, though as fred.bear points out, it might be less feature-rich than you need.
Here are a couple more:
jEdit
jedit - A plugin-based editor for programmers

jEdit is a powerful open source editor
[...]  unlimited undos/redos,
syntax highlighting for more than 130
file formats, markers for fast and
easy navigation, online help, bracket
matching for programming languages as
well as auto-indent. Plugins can be downloaded and installed from within jEdit using the "plugin manager" feature.

vim / gvim / cream
gvim  or cream - VI IMproved, with optional VIM macros that make the VIM easier to use for beginners
Comment: I had forgotten about Cream... I had tried and it was very tempting.. but I decided to not use it.. basically because it kept me from learning vim's native keyboard style (which is where vim shines.. once you've re-trained your habits) .. but, yes it certainly has that stanard windows feel (which an Npp user is used to), and lots of power...  a good candidate..
Comment: Yeah, gedit is awesome.
Comment: Scite/Scintilla is basically a no-features editor... Massive work has been done by the Npp crew to supercharge it... (but it still only has a nominally useful single-line-only reg-ex) .. forget Scite/Scintilla ..
Comment: @fred I defer to you on scite versus Npp, but since I'm not clear on our OP's actual requirements, I'm leaving scite in my answer for now.  Having used strictly vi without extensions to do *important work*, I have a pretty expansive view of what can be useful. (*important work such as writing crappy perl code)
Comment: Also, I was going to link larger images from the thumbnail images, but I haven't found a way to do that.
Answer: Without GUI or with a simplified GUI (still needs to be run in terminal):

vi
vim
nano
ed
pico
emacs
xemacs

With GUI:

geany
mousepad (default under Xfce)
kate

Please note that some of these programs may not be available from Ubuntu's official repositories.
Comment: `ed`? Ha! Real programmers use `cat`.
Comment: @papukaija: how dare you say such heresy??? *Of course* `cat` is an editor. Actually, it's the *only* editor ***real men*** need:
`cat > myfile.c`. Type in your code, `CTRL+D` to save. Who needs more?
Comment: cat isn't really a text editor - it just reads a file and outputs its content.
Comment: Another example of a editor with GUI could be gVim, or vim-gnome, as I think the package is called
Comment: That's the  joke.. A **REAL** programmer is so good, he gets it right the first time ;)
Comment: On Xubuntu, mousepad has syntax highlighting and *a lot* of features for a light editor. It comes as the default editor for Xubuntu. On Raspbian, however (for Raspberry Pi), after I installed it (`sudo apt-get install mousepad`), mousepad has nothing. It's a bare-bones editor. How do I get syntax highlighting added for it in Raspbian?
Comment: @papukaija (or someone else), can you edit this post to put an asterisk or something by all of the text editors in the list with syntax highlighting?
Comment: REAL PROGRAMMERS USE > and >>.... and cat... ;-)
Answer: Try Bluefish, Geany, or even installing Notepad++ trough Wine if you want.
More on installing Wine on Ubuntu and one example of installing some application using Wine.
Answer: I'm an ex Notepad++ devotee!!!! It was hard making the shift to "nowhere land" after knowing exactly how to do things in Npp,  but I've gradually discovered that with the right plugins and a few personal scripts which you can easily add via the External Tools plugin, that gedit is the easiest and best transitional editor for hard-core ex- Npp users. I feel your pain ;)
After 4 months of Linux, I'm starting to get a good feel for things, and I'm branching out to GNU emacs because it leaves Npp standing still (really Npp's regex sucks!)  I've tried gvim and it seems very good too, but a few things about emacs gel better with me...
gedit with plugins is quite a good choice once you get to realize that this Ubuntu thing is a whole new world... so you need a matching editor... I've got Npp installed in wine for a sense of security, but I virtually never use it anymore, because gedit is basically just as good... and GNU emacs and Gvim are better (but they have a big learning curve) go for gedit.
You may be interested in running Notepad++ in wine (I was)... so here are some notes I've put together about the bugs I've found using Notepad++ in wine...

notepad++ - Wine-BUGS - Ubuntu.10.04
Answer: I love gEdit. Is not nearly as powerful as NotePad++, but its ultra-lightweight, and the default text editor in Ubuntu (or any other Gnome distro). It has a huge list of templates for syntax coloring. And be sure to download its gedit-plugins companion, it shines even more.
Also, you might consider geany. It's meant to be a more than just a text editor, it's actually a multi-language IDE. But since it's so simple, easy-to-use one, and lightweight, it could be considered a good editor alternative. And its in the official repos.
I would say that NotePad++ (I used it for years in my former job) would stand between geany and gedit, in terms of features. So I gave you a "little less than" and "a little more than". Pick any ;)
Answer: I love geany for its simplicity and plugins
sudo apt-get install geany geany-plugins

Answer: I've been using the Sublime Text 2 alpha on Ubuntu and enjoy it a lot. It's nice to have the same editor across multiple OS's
Answer: I prefer Komodo.
Answer: You can use KDE's Kate, it is very powerful (search for it in ubuntu software manager). Also if you want to pay for powerful text/html/programming editor, you can use UltraEdit LX. It has more features than Kate.
Answer: I didn't see gui or cli specified, so I'll throw out a few.
There is a rather steep learning curve, but learning the basics of emacs/vim is useful. Chances are you will have to use them at some point.
I like Netbeans for java, but it will do php/python/c/c++/etc. Eclipse will do as well.
Answer: Notepad++ is arguably the best editor for Windows. Now you can install it in Ubuntu via Wine:
Install Notepad++ in Ubuntu 12.04
Answer: No one mentioned the leafpad. The more I use it, The more I like it. Though, It has not that many features, but it is extremely resource-saver.
Installation from terminal: sudo apt-get install leafpad.
Installation from Ubuntu software center: Clicking this will do the job
Answer: I use Kate, because I like these features of it:

Very handy quick search (exactly like Firefox)
Code completion (using exciting code in current document)
Snippets
Integrate easily with terminal and file manager
Installable on Mac and Windows
Code highlighting
Answer: I'd like to add two less known but very powerful and feature-rich text editors to this list of recommendations:
KKEdit
http://www.webupd8.org/2014/03/kkedit-text-editor-inspired-by-bbedit.html
http://linux-apps.com/content/show.php/KKEdit?content=158161

The usual source view options, split-view, line wrap, line numbers etc.
Full source code highlighted printing.
Standard text search OR regex search in current or all open files.
Jump to function declaration, Find Function declaration.
Find API declarations in installed Gtk-Doc's.
Find and open include file.
Multiple bookmarks.
Run external tools.
Save/Restore session.
Run external tool synchronously or asynchronously.
Pass selected text to external tools.
Spell checking via ASpell, check selected word or check document via tab menu.

medit
Official site

Configurable syntax highlighting.

Configurable keyboard accelerators.

Multiplatform - works on unix and windows.

Plugins: can be written in C, Python, or Lua.

Configurable tools available from the main and context menus. They can be written in - Python or Lua, or it can be a shell script.

Regular expression search/replace, grep frontend, builtin file selector, etc.
Answer: gedit will be the best for you as it is lightweight yet powerful. If sometime in the near future you wish to upgrade to ide level capabilities, then consider emacs or vim.


What Miis can defeat the mummy ghost in Streetpass Quest/Find Mii 2?

Question: I am currently on Find Mii 2. There is a part where there are 2 enemies: an armored ghost and a mummy ghost. There is one problem: any person I streetpass gets caught off guard and flees!
Is there a specific type of Mii that I need to use to defeat this mummy ghost to get it out of the way?
Answer: There is no way to predict if they will scare your Street Pass Miis. Generally if the Mii is level 5 or higher they will not be as likely to be scared off by mummies (unless it is the Marauding Mummy, who tends to scare all Miis).
The best way to get past them is to make sure you have more than one person in your team - they will only scare the first person they encounter (one per mummy), so then you will have people to attack them still.


Can I use a Sharkbite on a running pressurized pipe?

Question: My main water shutoff valve no longer turns, and getting the city to come and shut water off at the curb is a bureaucratic hassle. I'd therefore like to install a valve without being able to shut off the water to the house. My thought is to cut the pipe downstream from the existing valve and install a new valve there, then use the new valve as the shutoff for the house.
Is it possible to install a Sharkbite (or other push-to-connect) valve on a pipe that is fully running? I assume I'd get pretty wet, but is there any reason why this wouldn't get the job done?
The water line into the house is 3/4-inch copper.
Comment: In Dallas Texas USA nearly everyone uses the city cutoff before the water meter at the street to shut off water. Our houses were built with water cutoffs (brass "gate" valves) in a box in the ground by the slab, but these valves all became frozen. I know of one person who has had this set of valves replaced with modern ball valves, but most people just leave them alone. Most of the new owners of these 1970 houses don't even know the valves are there.
Comment: If you try it, please post a video
Comment: Water pressure in my experience in the US has been 50 - 64 psi and generally on a .75 pipe. I wouldn't even consider it. Just go to the local hardware store and buy the water shut off tool, find the water box at the street and do it yourself. Perfectly within your right.
Comment: Many years ago I had a similar problem. I needed work done (water heater? can't remember). Shutoff inside house (old gate valve) worked ~ 90%. Plumber used utility (next to sidewalk) shutoff (also not perfect ~ 90%) and then worked as fast as he could to cut the pipe just past the house shutoff and install a new ball valve.
Comment: Using a slip valve could work but cutting out the 2 inch section while being blasted with city water  pressure  would be a challenge
Answer: Assuming this is inside your house, don't even think about it unless you are prepared to clean up the mess from water a couple of inches deep on the floor (and getting into the rest of the house under the doors, etc), and spray all over the walls.
If you have never tried this before, expect the jet of water to knock things out of your hands, so the job takes even longer while you are wading around in the flood trying to retrieve them!
You don't say what country you are in, but in the UK you should be able to find the shut-off valve on the curb and close it yourself. It's not clear why you need a contractor to do it for you.
Answer: If you have access to a length of pipe prior to where you want to fit that connector then there are systems available to freeze a section of pipe.
But you have to make sure no water is used downstream while you are trying to freeze that section (usually 6 or so inches) otherwise it keeps moving warmer water into the section you are trying to freeze...
Comment: I use dry ice and freeze pipes works great and stops the flow long enough to cut the pipe and install the new valve.+
Answer: I'd say no, not a chance in my opinion.   City water pressure will flood you and spray hard once you cut that pipe.
You need the water shut off.
From my experience with much lower pressure fitting failures and unsuccessfully trying to push a fitting back on to a running pipe.
Answer: If you can let the water run through the pipe while you press in the fitting. First install a valve on the fitting you want to install, leave the valve open so the water runs through. Push the fitting on then shut off the valve you had previously installed.
Answer: There are 3 possible solutions that you can choose from. You can opt for as @solar mike said and freeze the line. I have done this many times and it works as long as no water is being used in the house until the line freezes. I used shaved dry ice in a towel wrapped around the pipe. this method is great but you must use caution to protect your self from the extremely cold dry ice. It can give you frost bite almost instantly. If you know someone that has done this ask him for help. They also sell freeze kits that can be purchased. The 2nd way is to just cut the line and install a valve that you can shut off once you shove it onto the line. This will make a big mess and could flood your home if something goes wrong. I have also done this many times using compression ball valves or gate valves. I did this once at a college and me and the "head of maintenance" got very wet and it made quite a mess. #3 solution, go buy a curb box wrench and turn the water off yourself. However, if any thing breaks it will probably be at your expense.
Answer: I watched a water dept tech change the main ball valve at our meter. He had a special internal closure device (v.i.) that allowed doing this without a geyser.
He said the device will not always work and techs must be able to change the valve with the water on, but it is difficult.
He said whichever way it is done, if something goes wrong a heavy metal part can be propelled out with tremendous speed, and this has happened.
EDIT
IIRC the internal closure device worked like this: With the city valve in the closed position the device is fastened to the stub pipe on the valve and then the valve is opened. The device has a plunger that can be driven through the now open city ball valve into the pipe beyond and then expanded against the walls of the pipe. The city valve can then be replaced with a new one
and the process reversed.
I asked what would happen if the internal closure device suddenly gave way and he replied that it had happened and the part was later found in an alley 120 ft away.
Answer: You can buy a water main shut off key and turn it off yourself. You need to find the access port, it will be somewhere between the street and your house in the lawn or yard covering. It a usually about a 4inch round metal cover. It has and odd shape nut, ( 5 sided i believe ) so a normal wrench or socket will not work on it. Channel lock pliers or vise grips may work.
This guy made a key but i have seen them at home depot.
The possibility probability for not being able to get the sharkbite on while the water is running is a concern. If you can not get it on then you have full city water pressure pumping water into your house.
Answer: There are ways to interrupt a live water pipe, but they are complex. Essentially you have to construct a bypass with a shutoff, then pinch the main line. Trust me, you don't want to go there if you don't have to.
I would first just try to shut the city valve yourself. They are usually pretty simple to operate after you dig up the asphalt that some jerk has plastered over the valve plate.
Barring that, try using an anti seize agent on your house valve, and if that doesn't work, then try a propane torch. You ever seen the underside of a car? It's a rust palace. Guess how mechanics get bolts to function on those crap Japanese cars that have every single nut and bolt rusted tight? Propane torch.


Saving SAP R/3 Report Output in Local Folder

Question: We are accessing some data in a SAP R/3 System using SAP Dot Net Connector 3.0.
We are now asked to do the following, and would require some advise on how this can be achieved from our program (in VB.NET 2008) using SAP Dot Net Connector:
a) Accesss some standard and customized (I believe they are called Z-Reports written in ABAP) which are there in SAP R/3 System
b) Execute such reports with a given set of parameters
c) Save the output in a local folder
d) Email / Modify the output for further processing
We do not have any ABAP programmer and would like to do this with minimal efforts on SAP side. Any help or guidance would be highly appreciated.
Thanks
Rahul
Comment: I don't know _SAP Dot Net Connector_: Does it use RFC (remote function calls) or another technique? A 2nd question: You want a minimal effort on SAP side. But can you create at least one function module (SE37 and some developper rights). Which SAP version do you use?
Comment: here is the sample processing code https://stackoverflow.com/questions/22497235/how-to-fetch-data-from-sap-system-using-sap-net-connector
Answer: I did this many years ago using the DCOM Connector and before that Connection Server.. lots of dust on those. Basically you need to develop or utilize existing SAP functionality using the RFC Interface. We did this by extending the BOR using our own BAPI's that either wrapped our function modules or SAP function modules.
Your BAPI interfaces will be your API's you will write to in the .Net Connector. You should be getting the resulting output in an array or object that you can write to a file in VB. Anything you want your program to do that is outside SAP you will have to develop that on your own.
I am not sure you can call a zreport or program directly from the .Net connector without using a BAPI via the RFC interface.
There are better ways to do this in this day and age.


Can I run 6-3 Romex through 2ft. of 1" flexible non metalic conduit out of wall to EV charger?

Question: Can I run 6-3 Romex through 2ft. of  1" flexible non metalic conduit out of wall to EV charger in garage? Romex will run from end of flexible conduit to 50amp breaker. Is a GFCI needed if charger is wired directly to breaker? I plan to mount EV charger less than 3ft.from breaker.
Comment: So far a GFCI is not needed for hardwire connections, only plug in.  If the garage is attached to the house, romex should be okay since it is inside.
Comment: Garage is attached. Just wanted to make sure as the flexible conduit is less than 3 feet. How many support brackets will be needed to attach conduit to wall?
Answer: Depends on the shape of your 6/3 NM, from what I can see. The "more rounded" type appears to JUST squeak by for 1" LFNB only if it's 24" or less (nipple fill rule allows 60%, rather than 53% for one cable.)
Which likely means the oval/flat version is too wide. I am having a lousy time getting good dimensions for those, but for an oval cable you have to treat it as a round cable of the largest dimension of the oval.
EV charger has a GFCI built-in, so if there isn't a receptacle, you don't need one at the breaker.
THHN/XHHW wires would be a lot easier if you haven't already blown money on 6/3 cable. Or perhaps even if you have... Those would fit (without the 24" restriction)in 3/4" LFNB, FMC, LFMC, etc...
Or in 1/2" if under 24" long. I'd suggest 1/2" FMC (flexible metallic conduit) it's much nicer to pull in than liquid-tight. Or EMT of it's  a straight shot, assuming you don't have a bender nor want to buy one for a tiny project.
If your charger has "75°C connections" (and your breaker does, but that's pretty normal for breakers) 8 AWG copper (THHN in conduit, NOT cable, most types of which are 60°C limited) is enough for NEC (but if the manufacturer specifies larger you have to follow their directions. Not a big deal for 3 feet of wires.)
Answer: You could use Romex... but I would suggest THHN aluminum for this endeavor. 6 gauge should get the job done, and all 4 should fit in a 1" conduit.
NEC 2020 requires a GFCI breaker for receptacles in your garage. Hardwired chargers are not included.
Comment: And generally, the hardwired charger has a GFCI built into it.
Comment: Generally aluminum makes sense. Except that (a) some jurisdictions limit aluminum on branch circuits and more importantly, some chargers *require* copper.
Answer: Bear with me: I got good stuff for ya.
A lot of novice EVers get into a mindset that they need a 50A circuit to charge their EV at home.  That is gross overkill for most uses. What concerns me greatly is the new 50a circuit often overloads the panel!   Builders don't willingly leave you 50A of headroom on a panel.
Your starting point is a NEC Article 220 Load Calculation to be done on the house's service. Your municipality often has a worksheet they want you to use, but many such worksheets are on the web - take one from a city, don't read commercial web sites- there's a lot of lazily written disinformation out there.
Wire cost/size (for 3 feet) is not the issue, panel loading is.  Some people say "I pinky-promise to be prudent" - that doesn't really work.
Once you know the headroom you have on your panel, the next step is getting confidence that 50A is not necessary, and Technology Connections (an avid EVer) covers that well.  Now you can choose a size that is appropriate for you.  If you're V2G for 50A (or even more) that's fine IMO, the important thing is being sure.
I understand you already have a wall unit EVSE in mind, however the vast majority of those (well, not CrippleCreek) are configurable to any circuit ampacity, using DIP switches inside the EVSE, or a positively byzantine commissioning procedure using weird/special WiFi networks.  It's a UL requirement that this procedure be "hard" (DIP switch) or "hard" (difficult/byzantine).
Another option is that certain EVSEs place a "current transformer" on your service wires, reducing EV charge rate to prevent panel overload. These functionally disappear from your Load Calculation, and can be installed on a "maxed out" house.  Houses average only about 5 amps (1200W); panels are sized for peak loads and the rest of the time a house's draw is well under 5 amps. So that works very well.
An EVSE is not a charger; it is a smart GFCI.  As such, you don't need to feed it from a GFCI breaker (because you don't need to feed a GFCI receptacle from a GFCI breaker.)
If the entire run is in conduit, you have every right to use individual wires, and I would rather see you use two #8 black copper THHN wires for hot, and one bare or green #10 for safety ground.  EVSEs do not use neutral. Really.
Not least, stranded THHN is more flexible and easier to wrestle, and conduit size won't be a factor.  Two #8 and one #10 will easily fit in 1/2" conduit.
If you must use cable, minimum conduit internal diameter is 138% of the widest width of the cable.  Spin the cable in a caliper and measure its widest point, x 1.38 and that's your minimum conduit ID.

Can I run 6-3 Romex through 2ft. of 1” flexible non metalic conduit out of wall to EV charger?


HTML X JavaScript X Google Charts - Change chart according to radio button selection

Question: I'm trying to create an HTML page where a person can visualize a chart drawn with the Google Charts library according to the radio button selected out of 4. I have the radio buttons defined along with the chart calls. However, i'm having a couple of issues. When i first open the page, it doesn't show the chart for the radio option value which is selected by default ("global" in this case which then calls "drawGlobal()") like it's supposed to. And when i try to choose another option, it shows the same chart over and over (which is drawn with "drawBasic3()") instead of opening the corresponding one. If anyone could help me get around this, i would appreciate it!
Here is my code btw:
<!DOCTYPE html>

  <title>Global Sentiment Page V2</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

Charts

    <form name='test'>
    Choose type:
        <input type="radio" name="field" value="global" onChange="checkValue()" checked>Global
        <input type="radio" name="field" value="gender" onChange="checkValue()">Gender
        <input type="radio" name="field" value="location" onChange="checkValue()">Location
        <input type="radio" name="field" value="age" onChange="checkValue()">Age Range
    </form>

Answer: the switch statement needs a break after each case
without the break, all charts, beginning with the selected, were being drawn
resulting in the last chart in the sequence...
also, recommend calling setOnLoadCallback once per page load
in the following working example, it is set in the load statement...

  google.charts.load('current', {
    callback: checkValue,
    packages: ['corechart', 'bar']
  });

    function drawGlobal() {

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Date');
      data.addColumn('number', 'Sentiment');

      data.addRows([
        ['31/01/2016', 20],
        ['28/02/2016', 35],
        ['31/03/2016', 40],
        ['30/04/2016', 55],
        ['31/05/2016', 60],
        ['30/06/2016', 75],
        ['31/07/2016', 80],
        ['31/08/2016', 95],
        ['30/09/2016', 100]
      ]);

      var options = {
        title: 'Average Sentiment Over Time',
        colors : [ '#0000FF', '#00FFFF' ],
        hAxis: {
            title: 'Date'
        },
        vAxis: {
          title: 'Sentiment',
          viewWindow : {
                    max : 0,
                    min : 100
                }
        }
      };

      var chart = new google.visualization.LineChart(document.getElementById('chartdest'));

      chart.draw(data, options);
    }

    function drawBasic() {

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Date');
      data.addColumn('number', 'Male');
      data.addColumn('number', 'Female');

      data.addRows([
        ['31/01/2016', 10, 5],
        ['28/02/2016', 25, 15],
        ['31/03/2016', 30, 20],
        ['30/04/2016', 45, 35],
        ['31/05/2016', 50, 40],
        ['30/06/2016', 65, 55],
        ['31/07/2016', 70, 60],
        ['31/08/2016', 85, 75],
        ['30/09/2016', 100, 90]
      ]);

      var options = {
        title: 'Average Sentiment Over Time By Gender',
        hAxis: {
          title: 'Date'
        },
        vAxis: {
          title: 'Sentiment'
        },
        colors: ['#00008B', '#0000FF'],
        legend: 'bottom'
      };

      var chart = new google.visualization.LineChart(document.getElementById('chartdest'));
      chart.draw(data, options);
    }

    function drawBasic2() {

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Date');
      data.addColumn('number', 'East');
      data.addColumn('number', 'West');

      data.addRows([
        ['31/01/2016', 2, 8],
        ['28/02/2016', 10, 16],
        ['31/03/2016', 18, 24],
        ['30/04/2016', 26, 31],
        ['31/05/2016', 34, 39],
        ['30/06/2016', 42, 47],
        ['31/07/2016', 50, 55],
        ['31/08/2016', 58, 63],
        ['30/09/2016', 66, 71]
      ]);

      var options = {
        title: 'Average Sentiment Over Time By Location',
        hAxis: {
          title: 'Date'
        },
        vAxis: {
          title: 'Sentiment'
        },
        colors: ['#006400', '#008000'],
        legend: 'bottom'
      };

      var chart = new google.visualization.LineChart(document.getElementById('chartdest'));
      chart.draw(data, options);
    }

    function drawBasic3(){

      var data = new google.visualization.DataTable();
      data.addColumn('string', 'Date');
      data.addColumn('number', '0-30');
      data.addColumn('number', '31-60');
      data.addColumn('number', '61+');

      data.addRows([
        ['31/01/2016', 2, 8, 10],
        ['28/02/2016', 10, 16, 18],
        ['31/03/2016', 18, 24, 26],
        ['30/04/2016', 26, 31, 33],
        ['31/05/2016', 34, 39, 42],
        ['30/06/2016', 42, 47, 49],
        ['31/07/2016', 50, 55, 57],
        ['31/08/2016', 58, 63, 65],
        ['30/09/2016', 66, 71, 73]
      ]);

      var options = {
        title: 'Average Sentiment Over Time By Age Range',
        hAxis: {
          title: 'Date'
        },
        vAxis: {
          title: 'Sentiment'
        },
        colors: ['#FF7F50', '#FA8072', '#FFA500'],
        legend: 'bottom'
      };

      var chart = new google.visualization.LineChart(document.getElementById('chartdest'));
      chart.draw(data, options);
    }

    function checkValue()
    {
        switch(document.test.field.value)
        {

            case "global":
                drawGlobal();
                break;

            case "gender":
                drawBasic();
                break;

            case "location":
                drawBasic2();
                break;

            case "age":
                drawBasic3();
                break;

        }
    }
#global{
    width: 88.5%;
    max-width: 1232px;
    padding-left: 0.75%;
    padding-right: 0.75%;
    margin: auto;
    clear: none;
    float: none;
    margin-left: auto;
}

input[type=radio] {
    margin-left: 50px;
}

Charts

    <form name="test">
    Choose type:
        <input type="radio" name="field" value="global" onChange="checkValue()" checked>Global
        <input type="radio" name="field" value="gender" onChange="checkValue()">Gender
        <input type="radio" name="field" value="location" onChange="checkValue()">Location
        <input type="radio" name="field" value="age" onChange="checkValue()">Age Range
    </form>


Date output is different.So,can't compare correctly

Question: Here is my code.Please take a look first
import UIKit

var expireDate : Double = 1472647093

var date = NSDate(timeIntervalSince1970: expireDate)
print("Date : \(date)")

let current_date = NSDate()

if date.compare(current_date) == NSComparisonResult.OrderedDescending{
    print("is Greater than current date")
}else if date.compare(current_date) == NSComparisonResult.OrderedAscending{
    print("is Less than current date")
}else{
    print("Same")
}

Here is the output on playground :

I really don't know why "Date : " output is different than date variable.My server send me an expire date format in unix timestamp which is long format.And I really need to compare it with current date.Actually
Aug 31, 2016, 7:08 PM // It has correct day/month/year but incorrect time

2016-08-31 12:38:13 +0000\n // has all correct time and date that the server send which was 12:38PM

So,why I am having greater than current date?And why it was 7:08PM instead of 12:38PM
Any help?
UPDATE :
Comment: The "incorrect" output is missing the timezone. So, what timezone are you in?
Comment: The date is correct. `print` displays the time in UTC. Your time zone is most likely UTC+5
Comment: it's UTC+6:30,yeah...how do i solve it
Comment: There's nothing to solve. A `NSDate` does not have timezone information (it's not needed), only when you _print_ it you need to account for any timezones. The comparison is correct as well.
Comment: no actually the time (expire) that the server send to me was 12:38PM and my current time is 2:38PM.So,how that 12:38 should be greater than current time.It should be less than.I am feeling confuse.Please check my update photo.
Comment: The updated image still shows correct output. Look at the times more carefully. The "Expire time" and "Current time" outputs use 24h format, the lines above use AM/PM in local timezone. 7:08pm (local timezone) still is later than 2:38pm (local timezone).
Comment: Please call me dumb if u want.But,I am getting confuse. why 12:38 > 2:38(14:38).Actually,it 12:38 < 2:38.
Comment: Okay, please ignore the lines that contain AM/PM completely. It's a stupid system that seems to confuse you. Just look at the lines with "+0000" in them, they're in 24h format. 12:38 is greater than 08:08, isn't it?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/122262/discussion-between-6245htarwara-and-darkdust).
Answer: You don't have wrong dates since Aug 31, 2016, 7:08 PM is your current timestamp, whereas in the print you have with timezone UTC. When you compare the dates they are both in UTC so you don't have any problems.
Comment: Look at my output : its showing me "is Greater than current date".Actually it was less than.Any help?
Comment: @6245Htarwara: Both dates are on the same day. 7:08 pm _is_ greater (later) than 1:35 pm, isn't it? That's exactly what your playground output is showing.
Comment: @6245Htarwara write `print(current_date)` to check the date in `UTC`, you will see that `date` is greater than `your current_date`. (I can see with your timezone as well 7:08PM > 1:35PM)
Comment: no actually the time (expire) that the server send to me was 12:38PM and my current time is 2:38PM.So,how that 12:38 should be greater than current time.It should be less than.I am feeling confuse.
Comment: @6245Htarwara From your screenshot I see that the server is 12:38 and your `current_date` is 8:08 so the server is greatest. (2:38PM is in your timezone)
Comment: Please call me dumb if u want.But,I am getting confuse. why 12:38 > 2:38(14:38).Actually,it 12:38 < 2:38.
Comment: @6245Htarwara the compare uses the `UTC` version so: 12:38 and 8:08. The dates with your timezone are 7:08 and 2:38. You have to read just the date in the print which is in `UTC`
Comment: Thanks for your help.I figured it out now.Please check my answer.
Comment: No worries! If my answer helped you please flag as right, thanks
Answer: My above question has nothing wrong with it. I'm just misunderstood with the timezone or standard that I am dealing with. The server already send me expire date with my timezone locale in UTC standard format.
So,I don't need to change that expire date according to my current time zone.
All I have to do is get my current time,change it to UTC format using my current timezone. And compare server expire_date and current_date. Mission Accomplish.
// Using Expire Date
var expireDate : NSTimeInterval = 1472689452 // 00:24 AM UTC
var date = NSDate(timeIntervalSince1970: expireDate) // Since January 1 1970 Convert to NSDate

// Then I change this time format to UTC String without adding any timezone because its already included
var df_utc = NSDateFormatter()
df_utc.timeZone = NSTimeZone(name: "UTC")
df_utc.dateFormat = "yyyy.MM.dd G 'at' HH:mm:ss zzz"

// Get the expire date string by formatting it in UTC
var ts_utc_string : NSString = df_utc.stringFromDate(date)

// Getting current time of mine
var local_date = NSDate()
var df_local = NSDateFormatter()
df_local.timeZone = NSTimeZone(name: "MMT") // then use my locale to add that current time UTC [MMT +6:30]
df_local.dateFormat = "yyyy.MM.dd G 'at' HH:mm:ss zzz"
var ts_local_string : NSString = df_local.stringFromDate(local_date)

// Compare
if ts_local_string.compare(ts_utc_string as String) == NSComparisonResult.OrderedDescending{
    print("CurrentTime is Greater than Expire Time")
}else if ts_local_string.compare(ts_utc_string as String) == NSComparisonResult.OrderedAscending{
    print("CurrentTime is Less than Expire Time")
}else{
    print("Same")
}

Here is the output :

For those who are still seeking for such problem like me, UTC was just a standard for timezone. If you need to compare it with your timezone, you just need to change your current time according to your country timezone.


How do I collapse arrays in Mongo aggregation?

Question: I can get this result of nested arrays from a Mongo aggregation:
"vals": [
[ [ { "reference_date": "2013-09-01", "price": 79 },
    { "reference_date": "2013-09-02", "price": 69 },
    { "reference_date": "2013-09-03", "price": 101 }, ] ],
[ [ { "reference_date": "2013-08-01", "price": 101 },
    { "reference_date": "2013-08-02", "price": 106 },
    { "reference_date": "2013-08-03", "price": 101 }, ] ],
[ [ { "reference_date": "2013-07-01", "price": 129 },
    { "reference_date": "2013-07-02", "price": 163 },
    { "reference_date": "2013-07-03", "price": 192 }, ] ],

]
I am using this query:
coll.aggregate([
{ $match:   { 'account_id': '123', }, },
{ $group: {
        _id: { 'account': '$account_id' },
        vals: { $push: '$data.prices' } }, },
]);

My base documents look like this:
{'account_id': '123',
  . . .  other stuff . . .
  'data': [{
       'prices': [
          { "reference_date": "2013-08-01", "price": 101 },
          { "reference_date": "2013-08-02", "price": 106 },
          { "reference_date": "2013-08-03", "price": 101 },
        ],
        . . . other stuff under data key . . .
   }]

How can I modify the query so the nested arrays are combined into a single array, holding nothing but the object items?
UPDATED:
To provide a more complete view of the base documents.  Sorry that wasn't there before.
UPDATE 2
Meh, I'm a lousy question asker, my << data >> subdoc fails b/c the value under data isn't an object, it is an array holding only one object.  I'm futzing about about trying to figure out the extraction of that object, at which the answer will work.
Comment: to clarify: do your base documents actually have doubly-nested arrays? That is, your examples are all arrays of arrays with one entry which is an array of documents: `[[obj1,obj2,obj3]],[[obj4,obj5,obj6]],...` are you arrays actually double-wrapped like this or was that a typo?
Answer: UPDATED to reflect full doc details
You need to $unwind your data and data.prices arrays before your $group:
db.coll.aggregate([
  { $unwind: '$data' },
  { $unwind: '$data.prices' },
  { $match: { 'account_id': '123' } },
  { $group: {
    _id: { 'account': '$account_id' },
    vals: { $push: '$data.prices' } } }
]);

Comment: Thx for looking.  I've provided more of the document, please let me know if you need more information.
Comment: The only adjustment to the first update is to put '{ $unwind: '$data' },' before the data.prices unwind.  That compensates for the fact that the data key holds an array with one element, not an object -- I guess that first unwind lifts the object out of that array.  My apologies for the poor documentation of the base object, and thanks for all your help.
Comment: @chernevik Okay, I updated the answer for that.  Glad it worked in the end!


What's the difference between Interior and Exterior scaffolding?

Question: I've been looking into getting some scaffolding for some jobs around the house. Honestly, I may need it for both inside and outside.
I see various products where they specifically list scaffolding as being "interior" or "exterior". I cannot find an explanation anywhere.
Can I use exterior scaffolding indoors? Can I use interior scaffolding outside? Is there a difference? Do I need to get both?
FYI: Since I have no idea how to tag this (I used ladder because places like to group scaffolding and ladders), I fear it may be off topic. If so, please advise where I can ask this question.
Comment: You can never go wrong with exterior and put extra floor protection down when using it inside.
Comment: Guessing, but I would expect that exterior is stronger, has better feet, is better cross-braced, etc. since it may go up a much greater distance. Possibly better protection against rust.
Comment: Also guessing, but I'd think interior has softer feet (/wheels?) and possibly limited height, where outdoor would be seemingly infinitely stackable. Out of curiosity, what kind of interior heights are you facing?
Comment: @AloysiusDefenestrate I've got a vaulted ceiling < 12 feet. Most of the need would be for working on the 2nd story outside.
Comment: It could also do with anchoring methods.  The scaffolding my dad used when we resided our 2 story home when I was a kid was partially stabilized by brackets nailed to studs in the wall.  Not something you'd want to use inside.
Answer: You're really going to have to look at them up close & personal if a simple 2x12 across 2 or more supports isn't to your liking. Interiors are either a fancy version of the 2x12 on empty 5-gallon buckets or self-standing & rolling cages of quite short lengths.
Exterior usually is not self-standing & must be anchored to the building, negating its use inside altogether, but they are made to receive additional sections & levels.
If you haven't used ladders & ladder jacks for exterior scaffolding you may want to try that out first & they can be used indoors with the Werner type of adjustable ladders that can be used as step or straight ladders.


i have my eror in android studio (flutter)

Question: hi this is my eror and this is my code plzzz help me :)
RenderBox was not laid out: RenderRepaintBoundary#51d6d relayoutBoundary=up3 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1940 pos 12: 'hasSize'
my code:
Container(
          height: 80,
          child: ListView.builder(
            shrinkWrap: true,
            padding: EdgeInsets.symmetric(horizontal: 24),
            itemCount: categories.length,
              scrollDirection: Axis.horizontal,
              itemBuilder: (context,index){
              return categoriesTile(
                title: categories[index].CategorieName,
                imgUrl: categories[index].ImageUrl,
              );
              }),
        )

Answer: add width property
width: double.infinity
Container(
          height: 80,
          width: double.infinity
          child: ListView.builder(
            shrinkWrap: true,
            padding: EdgeInsets.symmetric(horizontal: 24),
            itemCount: categories.length,
              scrollDirection: Axis.horizontal,
              itemBuilder: (context,index){
              return categoriesTile(
                title: categories[index].CategorieName,
                imgUrl: categories[index].ImageUrl,
              );
              }),
        )

Answer: categoriesTile is causing an issue. I think it must be a Row. The solution is to provide a fixed width to it.
itemBuilder: (context, index) {
  return SizedBox(
    width: 100, // Give some width here.
    child: categoriesTile(...),
  );
}

If you want to give it full screen width, then replace above width with the following:
width: MediaQuery.of(context).size.width

Answer: Wrap Listview with Expanded widget. checkout the below code for help.
Container(
                height: 80,
                child: Expanded(
                  child: ListView.builder(
                      shrinkWrap: true,
                      padding: EdgeInsets.symmetric(horizontal: 24),
                      itemCount: categories.length,
                      scrollDirection: Axis.horizontal,
                      itemBuilder: (context,index){
                        return categoriesTile(
                          title: categories[index].CategorieName,
                          imgUrl: categories[index].ImageUrl,
                        );
                      }),
                ),
              )


Toggle player nametags on Ghost Recon

Question: Somehow the tags that appear above teammates heads have disappeared. I have tried clicking the '-' key but that toggles the entire HUD. how can I get them back?
Answer: The solution was going into hud settings, turning it off and turning it back on.

Toggle player nametags on Ghost Recon


OS X Quartz Events and the usage of some event flags

Question: I'm implementing virtual keyboard that is using modifier flags to enable input key events with this modification keys like: cmd, alt/opt, shift.
I would like to know two things:

what is the aim of kCGEventFlagMaskNonCoalesced and kCGEventFlagMaskNumericPad, can I map them to any key defined in kVK_* key codes?
What is the difference between kCGEventFlagMaskAlphaShift, kCGEventFlagMaskShift and how they corresponds to kVK_Shift, kVK_RightShift?
Is kCGEventFlagMaskSecondaryFn corresponding to kVK_Function?

I have done my modifier keys to modifier flags mapping function like this:
static uint64_t mod_key_code_to_mod_flag(uint16_t mod_key_code) {

    switch(mod_key_code) {
        case kVK_Shift:
            return kCGEventFlagMaskAlphaShift;
        case kVK_RightShift:
            return kCGEventFlagMaskShift;
        case kVK_Control:
            return kCGEventFlagMaskControl;
        case kVK_Option:
        case kVK_RightOption:
            return kCGEventFlagMaskAlternate;
        case kVK_Command:
            return kCGEventFlagMaskCommand;
        case kVK_Help:
            return kCGEventFlagMaskHelp;
        case kVK_Function:
            return kCGEventFlagMaskSecondaryFn;
        default:
            return 0;
    }
}

Is it complete?
Comment: Q2. A quick google of the keywords (top listing) answered the first part in just a few seconds. Try googling the others too.
Comment: @WeatherVane - may you share what you found please?
Comment: @Noitidart OK, with my browser you can select a word or phrase and then "search Google" with the context menu. This isn't a "let me google that for you" site. The OP is expected to have already done that, as you well know.
Answer: The purpose of kCGEventFlagMaskNonCoalesced isn't easily searchable at this point in time. Since one point of this site is to archive information necessary for answers, here is the definition of mouse coalescing in Cocoa (well, Carbon) from earlier documentation for IsMouseCoalescingEnabled:

If mouse coalescing is enabled, intemediate [sic] mouse movement events are merged into the most recent event, so that only one mouse moved or mouse dragged event is in the event queue at any time. For example, when the user moves the mouse across the screen, more mouse moved events are generated than most applications care about. Rather than place all these events in the queue (which would probably slow down the application), the Carbon Event Manager first checks to see if a mouse moved event already exists. If if does, that event is updated with the position and delta information from the more recently-generated event.

For some reason, current documentation leaves out this definition (the mouseCoalescingEnabled property might no longer be supported, even though it's in the documents). It's intended for consumers of mouse events. If your virtual keyboard isn't generating mouse events, this modifier can be largely ignored.


Reactjs mounting state before initial render or keep as is?

Question: State on the initial render here is the initial state.  Am using componentWillMount() however it won't work without first checking whether the component is mounted.  The result when using rawMarkup() is an empty initial state object.  Everything functions properly on the re-render but wondering why the post object within state is still empty on the initial render.  Is there a better way of accomplishing this?  Thank you.
var Post = React.createClass({
propTypes: {
    source: React.PropTypes.string.isRequired,
},

getInitialState: function() {
    return {
        post: {}
    };
},

getDefaultProps: function() {
    return {
        source: 'http://localhost:3000/api/posts/' + postSlug
    };
},

componentWillMount: function() {
    $.get(this.props.source, function(result) {
        if (this.isMounted()) {
            this.setState({post: result});
        }
    }.bind(this));
},

rawMarkup: function() {
    console.log(this.state.post);
    var rawMarkup = marked(this.state.post.body || '', {sanitize: true});
    return { __html: rawMarkup };
 },

render: function() {
    var post = this.state.post;
    var date = moment(post.date).format('MM[/]DD[/]YYYY');
    return (
        React.createElement('div', {style: {marginLeft: '115px'}},
            React.createElement('h1', {style: {marginTop: '50px'}}, post.title),
            React.createElement('h5', {style: {marginBottom: '25px'}}, date),
            React.createElement('span', {dangerouslySetInnerHTML: this.rawMarkup()})
        )
    );
}

});
Answer: By default, the jQuery get request is asynchronous, so the initial render happens before the request completes and this.setState({post: result}) is called.  You could make the get request synchronous (How can I get jQuery to perform a synchronous, rather than asynchronous, Ajax request?), or figure out a way to gracefully deal with no data on the initial render (recommended).
Comment: Yes this makes sense thank you.  Received further helpful input through another medium and set the initial post state to null with an if() statement in the render to check for state's preparedness.


Having Null Reference Exception in Vb.net Code

Question: I'm using vb.net and sql server 2000 for developing my application....The problem i'm having is the Null Reference Exception on the Following line of code:
<code>Dim cmd5 As New SqlCommand("select crtns_removed, pieces_removed, scheme from Outgoing_Invoice where invoice_no = '" & Me.ComboBox5.SelectedItem.ToString.Trim & "' And category = '" & Me.ComboBox1.SelectedItem.ToString.Trim & "' and item_name = '" & Me.ComboBox2.SelectedValue.ToString.Trim & "' and expiry_date = '" & Me.expiry_date.Text & "'", con)
</code>
I'm using this on the selectedindexchanged event of combobox1...The Code is on Return Stock form....But the exception is shown when I click the "Return Stock Button" on another form that will show the "Return Stock Form" but instead of showing the form it shows the exception on Combobox1 Selected Index changed event behind "Return Stock Form"
Can anyone help me out on this? Why is this issue arising and how can i get rid of it?
Comment: The following are all `Nothing` if nothing was selected (see http://msdn.microsoft.com/en-us/library/system.windows.forms.combobox.selecteditem.aspx): `Me.ComboBox5.SelectedItem` , `Me.ComboBox1.SelectedItem`, `Me.ComboBox2.SelectedValue`.
Comment: Have you figured out the meaning of a null reference exception?
Comment: Can't understand your point???? Null Reference Exception occurs when some object is not initialized....But don't understand why it's happening here
Comment: Have you stepped through the code in the debugger to see what's happening?   Something is not getting initialized like you expected it to.  Without seeing more of your code I'm not sure anyone can give you a more hepful answer.
Comment: Also, you should use parameterized queries - right now your code is a SQL Injection attack waiting to happen.
Answer: I would suggest validating each of the parameter values before defining the cmd5 command variable.
The problem is most likely that the index is not defined yet when the form is being openned for one or more of you comboboxes used for parameters in the SQL statement and thus they have do not have a value (NOTHING) and you and you are getting the exception.
Answer: Put a breakpoint on this line, and ensure that all the objects are not null. I suspect it's one of those selectedvalue or selecteditem, or possibly the con object.


CMake add_subdirectory with find_package?

Question: I have the following structure of projects/source:
MyProject
|-MyProject
| |-src
| | |-project.c
| |
| |-CMakeLists.txt
|
|-MyLibrary
  |-include
  | |-hello.h
  |
  |-src
  | |-hello.c
  |
  |-CMakeLists.txt

MyProject/src/project.c includes MyLibrary/include/hello.h, which in turn includes libusb.h from the system (found using CMake).
And I am adding the libusb dependency in MyLibrary/CMakeLists.txt using the following code:
# Find libusb
find_package(LibUsb REQUIRED)

# Include libusb
include_directories(${LIBUSB_INCLUDE_DIR})

# Add dependencies
target_link_libraries(owi535 ${LIBUSB_LIBRARY})

However when compiling MyProject (which includes MyLibrary using add_subdirectory and target_link_libraries), I get an error stating libusb.h cannot be found.
I can compile MyLibrary on it's own, however compiling MyProject requires libusb.h to be in it's include path, which it is not.
Is there a way to make it so that by adding MyLibrary as a dependency, MyProject pulls libusb.h through it? This would mean that I don't need to repeat the find_package code for every project that includes MyLibrary.

The other issue I am having is similar; I am getting an error stating that there are Undefined symbols when calling libusb functions in MyLibrary when I compile MyProject, however when compiling MyLibrary on it's own, there are no errors.
Undefined symbols for architecture x86_64:
  "_libusb_close", referenced from:
      _my_close_method in libMyLibrary.a(hello.c.o)
  "_libusb_exit", referenced from:
      _my_exit_method in libMyLibrary.a(hello.c.o)
  "_libusb_init", referenced from:
      _my_init_method in libMyLibrary.a(hello.c.o)
  "_libusb_open_device_with_vid_pid", referenced from:
      _my_open_method in libMyLibrary.a(hello.c.o)
ld: symbol(s) not found for architecture x86_64

Answer: From the cmake documentation:

PUBLIC and INTERFACE items will populate the INTERFACE_INCLUDE_DIRECTORIES property of <target>.
Targets may populate this property [INTERFACE_INCLUDE_DIRECTORIES] to publish the include directories required to compile against the headers for the target. Consuming targets can add entries to their own INCLUDE_DIRECTORIES property such as $<TARGET_PROPERTY:foo,INTERFACE_INCLUDE_DIRECTORIES> to use the include directories specified in the interface of foo.

So, you need to use this in MyLibrary/CMakeLists.txt:
target_include_directories(MyLibrary PUBLIC ${LIBUSB_INCLUDE_DIR})

Comment: I'm having the same issue with linking the actual library. Getting an `Undefined symbols` pertaining to libusb when compiling `MyProject` but `MyLibrary` compiles fine on it's own. Is there a similar fix to this?
Comment: This is a separate issue. You can reaccept this answer and open a new question with your new issue.
Comment: But to answer your question, it looks like you aren't actually linking the libusb library into MyLibrary correctly. It won't error out when compiling MyLibrary directly since it appears you are using static linking.
Comment: I think @jackwilsdon second problem looks like a typo. Could it be `LIBUSB_LIBRARIES` instead of `LIBUSB_LIBRARY`? E.g. if I look at [How to set LIBUSB_INCLUDE_DIR](http://stackoverflow.com/questions/21814266/how-to-set-libusb-include-dir)


Repair dual boot ubuntu 14.04 / Windows 10

Question: I have a dual boot system, entering in Grub, with i could choose between Windows 10 and Ubuntu in one ssd. All was fine since november update of W10. The boot is UEFI and when i power the laptop it cant enter in grub and goes to windows ahead.
Ive a /boot partition in Ubuntu. I have some important documents in ubuntu and i need a step by step guide.
If i enter in BIOS and change UEFI to Legacy mode, it gets stuck waiting for a bootable disk. If i change again to UEFI mode it starts Windows 10.
Any help would be apreciated.
Comment: Possible duplicate of [Windows 10 upgrade kills grub and boot-repair doesn't help](http://askubuntu.com/questions/655011/windows-10-upgrade-kills-grub-and-boot-repair-doesnt-help)
Answer: 1. Boot from a live disk/usb
2. Mount the ubuntu root partition to /mnt.
Find out ubuntu root partition by either
lsblk

or
sudo fdisk -l

(Assuming its sda5)
sudo mount /dev/sda5 /mnt

3. Bind mount other necessary partitions
for i in /sys /proc /run /dev; do sudo mount --bind "$i" "/mnt$i"; done

4. Chroot into /mnt
sudo chroot /mnt

5. Install grub
grub-install /dev/sda

6. Update Grub
sudo update-grub

7. Exit
ctrl + D

8. Reboot
Comment: Thanks but it doesnt work Ive created an usb live:.http://www.ubuntu.com/download/desktop/create-a-usb-stick-on-ubuntu. Every /dev/sda* appear mounted in /media/ubuntu/02bc.... large name. My boot partition is /dev/sda6, My / is /dev/sda8m swap is /dev/sda7....I can read all in gparted. It gives me error when i execute grub-install /dev/sda  as root: Permission denied error /usr/lib/grub/i386-pc/modinfo.sh doesnt exist. Pleease specify --target or --directory. I also tried to run grub-install --boot-directory=/media/ubuntu/02bcda.... /dev/sda . Any help would be apreciated
Comment: http://paste.ubuntu.com/13369587/ All my information of boot repair i could get from the live usb. Hope it helps.
Answer: After many tries i got a solution, hope it helps other people... Similar to duplicated post suggested but bit different as i have an partition for EFI:
What worked for me:
0) If not installed ( i have 64 bits system):
sudo apt-get install grub-efi-amd64
( this solves problems like Permission denied error /usr/lib/grub/i386-pc/modinfo.sh doesnt exist.Pleease specify --target or --directory).
1) Install gksudo:
sudo apt-get install gksu
2) It didnt work for me, but you dont loose anything to try it:
sudo add-apt-repository ppa:yannubuntu/boot-repair
sudo apt-get update
sudo apt-get install boot-repair
Execute boot-repair and use Recomended Repair.
If it doesnt work:
Observation: ( if live cd mounts any of this partitions, unmount them before mounting again in these folders):
4 ) As my / partition is /dev/sda8
sudo mount /dev/sda8 /mnt
5) This step Only if you have a separate boot partition ( my case /dev/sda6):
sudo mount /dev/sda6 /mnt/boot
Only if you have EFI in another partition also: mount the EFI partition . This solves errors like seems no efi partition
sudo mount /dev/sda2 /mnt/boot/EFI
6) Mount the critical virtual filesystems:
sudo mount --bind /dev  /mnt/dev
sudo mount --bind /dev/pts  /mnt/dev/pts
sudo mount --bind /proc /mnt/proc
sudo mount --bind /sys  /mnt/sys
7) Chroot into your normal system device:
sudo chroot /mnt
8) If there is no /boot/grub/grub.cfg or it's not correct, create one using
update-grub
9) Reinstall GRUB 2:
Substitute the correct device - sda, sdb, etc. Do not specify a partition number. In my case /dev/sda
grub-install /dev/sdX
10) Verify the install (use the correct device, for example sda. Do not specify a partition):In my case /dev/sda
grub-install --recheck /dev/sdX
11) Exit chroot: CTRL-D on keyboard exit
reboot
Optional: install grub-customizer in order to alter names and position of the entries