Q:

Getting a root of a continuously differentiable function by Banach's Fixed Point Theorem.

Banach Fixed Point Theorem: Consider a metric space $X = (X, d)$, where $X\neq \varnothing$. Suppose that $X$ is complete and let $T: X \to X$ be a contraction on $X$. Then $T$ has precisely one fixed point $\tilde{x}$.  Furthermore, for any $x_0\in X$ we have $\tilde{x}=\lim\,x_n$ where $(x_n)$ is given by $x_1=x_0$ and $x_{n+1}=T(x_n)$.

Problem: Using Banach's theorem, set up an iteration process for solving $f(x) = 0$ if $f$ is continuously differentiable on an interval $J = [a,b]$, $f(a)<0<f(b)$ and $0<k_1\leq f'(x)\leq k_2$ ($x\in J$); use $g(x) = x-\lambda f(x)$ with a suitable $\lambda$. (This exercise was taken of Kreyszig's Functional Analysis book).
What I have tried: if we take $$\lambda=\left\{\frac{1}{2k_1},\frac{1}{2k_2}\right\}>0$$ and $\alpha=1-\lambda k_1\in(0,1)$ then (by Mean Value Theorem in $g$) we get $$|g(x)-g(y)|\leq\alpha|x-y|$$ for all $x,y\in[a,b]$. Hence, with this choose for $\lambda$ the function $g:[a,b]\to\mathbb{R}$ becomes a contraction on the metric space $[a,b]$. However, to use Banach's Theorem it's necessary to get $g([a,b])\subset[a,b]$. It seems my choice for $\lambda$ doesn't implies it. So, I need help.
Thanks.

A:

You want to have $ x-\lambda f(x)\ge a$ for all $x\in [a,b]$. This is equivalent to
$$
f(x) \le \lambda^{-1} (x-a), \quad x\in [a,b]  \tag{1}
$$
By assumption, $f<0$ in  some neighborhood $[a,a+\epsilon)$; in particular, (1) holds there no matter what (positive) $\lambda$ you take. Outside of this neighborhood, the right hand side of (1) is at least $\lambda^{-1}\epsilon$. Choose $\lambda$ so that $$\lambda^{-1}\epsilon>\max_{[a,b]} f$$
and you are done.
The other inequality,  $ x-\lambda f(x)\le b$, is similar.


Q:

How view the navigation path in the master page?

I have a splitapp application with two cols.
On the left I have a tree that i can navigate level by level.
I want indicate to user the current position in the menu tree by a path.. now I use this trick: insert a button to show the current path

but i don't like this solution. Any suggestions?
P.S. The path could also be very long and I can't see it in the detail page because the content of the detail page could not always sync with the master page.

A:

This really sounds like a breadcrumb. If the path becomes too long you could limit it to show the two latest dives within the object hierachy which would be like ... > Product A > Info D. The individual links can be used for back navigation. From technical perspective the path can be obtained from the binding context.
And this is how it could look like as shown in the SAPUI5 Explored:


Q:

Showing $\prod_{n < \omega} n = 2^{\aleph_0}$

I have to show that $\prod_{n < \omega} n = 2^{\aleph_0}$. I'm having trouble getting started. I know that $2^{\aleph_0}$ is the set of binary sequences, or the space of functions from $\mathbb{N}$ to $\{0, 1\}$, but I'm having trouble parsing $\prod_{n < \omega} n$. My best guess is that it's the infinite Cartesian product $$0 \times 1 \times 2 \times 3 \times \dots$$ but because $0$ is $\emptyset$, then so is this product. Alternatively, $$\prod_{n < \omega} n = \{f : \omega \rightarrow \bigcup n | (\forall n) f(n) \in n\}$$ Thus has the same problem, though, that this would be an empty space of functions because none of them can map $0$ anywhere.

A:

Hint. The product is bounded below by $\prod 2$ and above by $\prod \aleph_0$.


Q:

form_remote_tag to upload a Paperclip file attachment

I am having a rails form which has one field of image upload, like:
<% form_for @c, :html => { :multipart => true } do |f| %>
   <%= f.file_field(:b, :size=>63, :class=>"fontsize13") %>
   <%= image_tag @c.b.url(:thumb) %>
<% end %>

On saving this form, the action is
def update
  @c = C.find(params[:id])
  if params[:c]
    @c.update_attributes(params[:c])
    if @c.save
               redirect_to :action => "index"
    else
      flash[:error] = @c.errors.full_messages.join('<br />')
    end
  end
end

This will upload the image and loads the same page again to show the image uploaded in the preview and in the layout logo too.
I am trying to show the image on save by ajax instead of page refreshing again.
I have tried with form_remote_tag by
<% form_remote_tag :url => {:controller => "c",:action => "update"}, :html => {:multipart => true } do |f| -%>
  <%= f.file_field :b%>
<% end %>

But this shows me error as Undefined method file_field for nil
Please give suggestions

A:

check this blog post http://railsblaster.wordpress.com/2007/09/20/ajax-forms-and-file-uploading-in-rails/
form_remote_tag and file_field doesn't marry each other for some security reasons. The blog post will give you some alternate options instead.


Q:

Conditional insert in SqlServer Compact Edition

Is there a way to do a conditional insert in the compact edition?
I've tried two ways that I think would work on SqlServer:
INSERT INTO CUSTQUOTE (QTE_ID) VALUES (1)
WHERE EXISTS(SELECT * FROM JOB WHERE JOB_NUMBER = 'EW090800345')
There was an error parsing the query. [ Token line number = 2,Token line offset = 1,Token in error = WHERE ]

IF EXISTS(SELECT * FROM JOB WHERE JOB_NUMBER = 'EW090800345')
BEGIN
    INSERT INTO CUSTQUOTE (QTE_ID) VALUES (1)
END
There was an error parsing the query. [ Token line number = 1,Token line offset = 1,Token in error = IF ]

A:

Why not :
INSERT INTO CUSTQUOTE (QTE_ID)
SELECT 1
FROM JOB WHERE JOB_NUMBER = 'EW090800345'

or TOP 1 if JOB_NUMBER is not unique


Q:

Wrapping C library

I have a private.h, public.h and the file.c, and I need to wrap it into Cython.
How do I wrap the function Person_ptr Person_create(const char* name);?
private.h:
#ifndef __PERSON_PRIVATE_H__
#define __PERSON_PRIVATE_H__

#include "Person.h"

typedef struct Person_TAG {
    char* name;
    int age;
} Person;

void person_init(Person_ptr self, const char* name);

# endif /* __PERSON_PRIVATE_H__ */

public.h
#ifndef __PERSON_H__
#define __PERSON_H__

#include <assert.h>

typedef struct Person_TAG* Person_ptr;

#define PERSON(x) \
    ((Person_ptr) (x))

#define PERSON_CHECK_INSTANCE(x) \
    assert(PERSON(x) != PERSON(NULL))

/* public interface */
Person_ptr Person_create(const char* name);
void Person_destroy(Person_ptr self);

const char* Person_get_name(const Person_ptr self);
int Person_get_age(const Person_ptr self);
void Person_birthday(Person_ptr self);

# endif /* __PERSON_H__ */

And this is file.c:
#include "Person.h"
#include "Person_private.h"

#include <stdlib.h>
#include <string.h>
#include <assert.h>

Person_ptr Person_create(const char* name)
{
    Person_ptr self = PERSON(malloc(sizeof(Person)));
    PERSON_CHECK_INSTANCE(self);
    person_init(self, name);
    return self;
}

void Person_destroy(Person_ptr self)
{
    PERSON_CHECK_INSTANCE(self);
    if (NULL != self->name) free(self->name);
}

 /* Do not free not change the returned string! */
const char* Person_get_name(const Person_ptr self)
{
    PERSON_CHECK_INSTANCE(self);
    return self->name;
}

int Person_get_age(const Person_ptr self)
{
    PERSON_CHECK_INSTANCE(self);
    return self->age;
}

void Person_birthday(Person_ptr self)
{
    PERSON_CHECK_INSTANCE(self);
    ++self->age;
}

/* private/protected methods */
void person_init(Person_ptr self, const char* name)
{
    self->name = malloc(sizeof(char) * (strlen(name) + 1));
    assert(NULL != self->name);
    strcpy(self->name, name);
    self->age = 0;
}

What I have tried to do is file.pyx:
from ctypes import *

cdef extern from "Person.h":
ctypedef struct Person_ptr:
        pass
Person_ptr Person_create "P_create" (char *name)

cdef class Person:
    cdef Person P_create(p_name):
    return Person_create(p_name)

It's not right - it compiles in Cython but then it gives me a lot of errors in GCC.
How can I fix this problem?

A:

cperson.pxd:
cdef extern from "Person.h":
    cdef struct Person_TAG:
        pass
    ctypedef Person_TAG* Person_ptr

    Person_ptr Person_create(char* name)
    void Person_destroy(Person_ptr self)

    char* Person_get_name(Person_ptr self)

person.pyx:
from cperson cimport Person_ptr, Person_create, Person_destroy, Person_get_name

cdef class Person:
    cdef Person_ptr thisptr

    def __cinit__(self, char* name):
        self.thisptr = Person_create(name)
        if self.thisptr is NULL:
            raise MemoryError

    def __dealloc__(self):
        if self.thisptr is not NULL:
            Person_destroy(self.thisptr)

    property name:
        def __get__(self):
            return Person_get_name(self.thisptr)

person.pyxbld:
import os
from distutils.extension import Extension

dirname = os.path.dirname(__file__)

def make_ext(modname, pyxfilename):
    return Extension(name=modname,
        sources=[pyxfilename, "Person.c"],
        include_dirs=[dirname],
        # or libraries=["person"], if you compile Person.c separately
        )

test_person.py:
import pyximport; pyximport.install()

from person import Person

p = Person('Garry')
print p.name

Example
$ python test_person.py
Garry


Q:

Android TabLayout does not display contents anymore as soon as fragment is switched

I am using a navigation drawer in my project, with 5 fragments in it. In one fragment I have the in the design support library introduced TabLayout, which includes 2 Fragments. All works fine, except when I leave the fragment which has the TabLayout and switch back to it, all the content is gone.
In each fragment in the TabLayout I have a SwipeRefreshLayout with a ListView in it, they both don't display anything upon switch.
I also noticed the TabLayout starts acting strange. by strange I mean the white indicator starts jumping, you are able to hold it still in the middle of the two tab...
So am I missing something that the TabLayout acts so strange?
The code here:
Fragment which contains the TabLayout:
public class MainFragment extends Fragment {
    private static String locale;
    private static ViewPager viewPager;
    private static TabLayout tabLayout;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        Utils.changeLanguage(getActivity());

        final Context contextThemeWrapper = new ContextThemeWrapper(getActivity(), R.style.MyStyle);

        LayoutInflater localInflater = inflater.cloneInContext(contextThemeWrapper);

        View view = localInflater.inflate(R.layout.fragment1, container, false);

        viewPager = (ViewPager) view.findViewById(R.id.viewpager);
        tabLayout = (TabLayout) view.findViewById(R.id.tabs);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        setupViewPager(viewPager);
        tabLayout.setupWithViewPager(viewPager);
    }

    private void setupViewPager(ViewPager viewPager) {
        LinesTabsAdapter adapter = new LinesTabsAdapter(getActivity().getSupportFragmentManager());
        adapter.addFragment(new Fragment1(), "Fragment 1");
        adapter.addFragment(new Fragment2(), "Fragment2");
        viewPager.setAdapter(adapter);
    }

    public static class Fragment extends Fragment {
        private static List<RowItems1> rowItems;
        private static ListView listview;
        private static Adapter1 adapter;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

            View view = inflater.inflate(R.layout.activity1, container, false);

            listview = (ListView) view.findViewById(R.id.listview1);

            return view;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            updateInfo(true);
        }

        public static void updateInfo() {
            rowItems = new ArrayList<>();
            adapter = new Adapter1(context, rowItems);
           listview.setAdapter(adapter);
        }
    }

    public static class Fragment2 extends Fragment {
        private static List<RowItems2> rowItems;
        private static ListView listview;
        private static Adapter1 adapter;

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

            View view = inflater.inflate(R.layout.activity_lines_all, container, false);

            listview = (ListView) view.findViewById(R.id.activity2);

            return view;
        }

        @Override
        public void onActivityCreated(Bundle savedInstanceState) {
            super.onActivityCreated(savedInstanceState);

            updateInfo(true);
        }

        public static void updateInfo() {
            rowItems = new ArrayList<>();
            adapter = new Adapter2(context, rowItems);
            listview.setAdapter(adapter);
        }
    }
}

I am using the MainFragment as a singleton and replacing the content with it as soon as the user selects it in the navigation drawer. When I switch to it, everything works fine, the ListView contains its data, the SwipeRefreshLayout works fine. When I switch to another fragment using the navigation drawer and switch back to this fragment, it displays nothing, as described above.
EDIT: Am I the only one having trouble with this? If anyone had problems, how did they fix it?

A:

When I used viewPager and back on it, I had empty fragments until switch when I used getSupportFragmentManager.
Try to use: getChildFragmentManager.


Q:

Concurrent web requests with Ruby (Sinatra?)?

I have a Sinatra app that basically takes some input values and then finds data matching those values from external services like Flickr, Twitter, etc.
For example:
input:"Chattanooga Choo Choo"
Would go out and find images at Flickr on the Chattanooga Choo Choo and tweets from Twitter, etc.
Right now I have something like:
@images = Flickr::...find...images..

@tweets = Twitter::...find...tweets...

@results << @images

@results << @tweets

So my question is, is there an efficient way in Ruby to run those requests concurrently?  Instead of waiting for the images to finish before the tweets finish.

A:

Threads would work, but it's a crude tool. You could try something like this:
flickr_thread = Thread.start do
  @flickr_result = ... # make the Flickr request
end

twitter_thread = Thread.start do
  @twitter_result = ... # make the Twitter request
end

# this makes the main thread wait for the other two threads
# before continuing with its execution
flickr_thread.join
twitter_thread.join

# now both @flickr_result and @twitter_result have
# their values (unless an error occurred)

You'd have to tinker a bit with the code though, and add proper error detection. I can't remember right now if instance variables work when declared inside the thread block, local variables wouldn't unless they were explicitly declared outside.
I wouldn't call this an elegant solution, but I think it works, and it's not too complex. In this case there is luckily no need for locking or synchronizations apart from the joins, so the code reads quite well.
Perhaps a tool like EventMachine (in particular the em-http-request subproject) might help you, if you do a lot of things like this. It could probably make it easier to code at a higher level. Threads are hard to get right.


Q:

Extract everything within brackets

I have a string of HTML with tags inside saved in the database e.g:

Hello {$name}, welcome to {$shop_name}....

I want to replace all of the tags with real data, now at the moment I loop through all available data and replace if it exists.
foreach($data as $key => $data){
    $content = str_replace('{$'.$key.'}', $data, $content);
}

Is there a better way of doing this without looping through all of the $data? This is now growing to over 5000 rows.
I mean is it possible to extract all variables {$name}/{$shop_name} then do a replace on only the found?

A:

You can do it with a single str_replace call.
$find = array();
$replace = array();
foreach($data as $key => $data) {
    $find[] = "\{$" . $key . "}";
    $replace[] = $data;
}
$content = str_replace($find, $replace, $content);

Unless there is a real performance issue, I wouldn't worry about it too much.


Q:

I can't understand a weird behavior, subclassing tablet widget

Using qooxdoo 5.0.2 (or previous version) I subclass a tablet widget and override _onKeyPress method.
Then, generating source I get a correct behavior, but with generate build the behavior is different.
I simplified my question, with this example below.
I subclass table widget and override _onKeyPress method WITH THE SAME CODE from qooxdoo 5.0.2 table widget source.
Run the example, edit a cell, and press enter.
Using
var tbl = new qx.ui.table.TableModified(tableModel)

the behavior is bad.
Using
var tbl = new qx.ui.table.Table(tableModel)

the behavior is correct.
If you put the example in a blank 5.0.2 project, using qx.ui.table.TableModified, you get a behavior if compile source, and another with compile build.
What is wrong with this? Where is my error?
Playground example

A:

In qooxdoo there are, per convention, protected and private class members like methods or instance variables. Protected members start with an underscore like _myProtectedMethod, private members start with two underscores like __myPrivateMethod. The protected members are not affected by the build process and left as they are. This way they are override-able by derived classes.
Private members are obfuscated by the compiler to a random name, so that trying to access the private method or variable outside the class where they are defined leads to an exception.
In your playground example you've overridden the method _onKeyPress which per se is OK to be overridden as it is a protected member.
But within the overridden code you're using private members like this.__focusedRow which fails, because in the build version there is no more __focusedRow member as it got obfuscated. There are more private members in the code like __focusedCol, __selectionManager etc.
To successfully override the method, you have to replace those private members  by their accessors, like this.getFocusedRow() instead of this.__focusedRow, this.getFocusedColum() instead of this._focusedCol etc.


Q:

How to add NUKE API to Visual Studio code?

I'm new to Python scripting in NUKE. I'm using VS code for learning Python and Python for NUKE.
Is there any way to add a NUKE API to VS code?

A:

The foundry offer support on using Nuke as a Python module here : https://learn.foundry.com/nuke/content/comp_environment/script_editor/nuke_python_module.html
Though personally, I would recommend installing a better Python Script Editor into the Nuke UI and working inside of Nuke with that - lots of what you do with Nuke's API is dependent on selecting Nodes or visually confirming your code is working as intended. I feel this is an important aspect of learning Nuke's python API.
I use this : https://github.com/plasmax/PythonEditor
Since it gives you tabs and is generally much nicer to use than Nuke's vanilla script editor. Later on once you've got a handle on this and want to start running Nuke batch scripts via the terminal is more the time when using an external IDE makes more sense. Good luck!


Q:

PowerShell - Get Password Expiration for all non Disabled Users in AD

My goal is to create a single object in powershell that shows the AD display name and password expiration date for all non-disabled users.
This is relatively easy. However, the date is retrieved in an unreadable format so I convert the date.
Creating the two variables that contain the data I want is working.
The problem is when I try to combine those two variables I get a single object with two headers as expected but the two columns below are empty.
I'm using PowerShell V2 on Win 7 Pro SP1
Any ideas what the issue could be?
# Get users DisplayName and password expiration time from AD
$msdsComputed = Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq  $False} -Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |
        Where-Object {$_.DisplayName -ne $null}

# Convert date to human readable format
$ExpiryDate = $msdsComputed | Foreach-Object {
             ([datetime]::FromFileTime(($_)."msDS-UserPasswordExpiryTimeComputed"))
                          } | Select-Object "DateTime"

$combined = @{
              DisplayName   = $msdsComputed.DisplayName
              ExpiryDate    = $ExpiryDate.DateTime
             }
New-Object PSObject -Property $combined | ConvertTo-Csv -NoTypeInformation

A:

Here's a revised version of your script without looping issues:
$reportObject = @()
$userList = Get-ADUser -filter {Enabled -eq $True -and PasswordNeverExpires -eq  $False} -Properties "DisplayName", "msDS-UserPasswordExpiryTimeComputed" |  Where-Object {$_.DisplayName -ne $null}
$userList | %{

    $output = "" | Select DisplayName, ExpiryDate
    $output.DisplayName = $_.DisplayName
    $output.ExpiryDate = ([datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")).DateTime
    $reportObject += $output
    #Next 2 Lines provide debugging... I'm not sure the date time portion will work without having AD to play with
    $output | fl *
    ([datetime]::FromFileTime($_."msDS-UserPasswordExpiryTimeComputed")).DateTime
}

$reportObject | Convertto-CSV -NoTypeInformation


Q:

Is there a cheaper way to do load testing than upgrading to Visual Studio 2010 Ultimate

I have a Visual Studio 2010 Professional license so Ultimate is a long way off and all I want it for is load testing for a few weeks or so.
Is there a cheaper way of getting just the load testing part of VS2010 ultimate or an alternate load testing tool with decent metrics of how the load testing is doing? I'd like to know pages/sec, page speed, database connections and less important: CPU, memory, errors.

A:

I have always found that the Radview Webload tool gives a good alternative but you will probably need to set up performance counters for CPU etc... and tie the data together yourself.  Have you considered using an evaluation version of Ultimate to check if that would meet you needs? ;)

A:

We developed a free Fiddler extension for load testing called StresStimulus. It replays sessions recorded in Fiddler under varied load levels and measures performance metrics. It is not nearly as complete as testing tools in Visual Studio 2010 Ultimate, but satisfies some of your requirements. You can get requests per/s and response times. The interface with PerfMon is not ready yet, so Windows performance counters should be tied manually.


Q:

Assigning numbers manually in ArcGIS field calculator?

I want to assign 3 numbers manually in a field

at the field of Ddensity i want to assign 10,40,85 ... how can i do that?

A:

Right click on the Feature Class "bound" in the table of contents and select edit.
Then you should be able to enter the numbers into each box.


Q:

how can i delete an acl rule from a registry key using the command line

I would like to know how to delete a "Deny rule" that makes imposible to modify a register key, using the command line.
Context:
In windows every file extension association resides in:
HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\

For instance the default app for .mp4 files is managed in:
HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.mp4\UserChoice

The Userchoice key has a deny permission above all other permisions. The following picture shows what I mean:

I have tried with Powershell using set-acl but due the same deny Deny rule I can't modify anything of that key.
Why all this? I was creating a script to define easily through command line the default app for an specific extension. The change in the registry is a must to make this works.

A:

Have you tried non-Microsoft solutions? Give http://helgeklein.com/setacl/documentation/command-line-version-setacl-exe/ a go.


Q:

Magento : Gender Select box empty

In the create account form the Gender Select box options are empty

A:

resolved
First you need to identify the gender attribute from Database with running the following queries:
SELECT * FROM eav_attribute where attribute_code = 'gender'

take the id of the resulted row. For me it's 18.
INSERT INTO `eav_attribute_option` SET `attribute_id` = 18, `sort_order` = 0;
INSERT INTO `eav_attribute_option` SET `attribute_id` = 18, `sort_order` = 1;

This will insert 2 options. for the attribute (replace 18 with the id you get from the first select).
Now these 2 inserted rows should have an autoincrement value for option_id.

Take these 2 values and run the following queries. Let's say the value are 9 and 10.
INSERT INTO `eav_attribute_option_value` set `option_id` = 9, `store_id` = 0, `value` = 'Male';
INSERT INTO `eav_attribute_option_value` set `option_id` = 10, `store_id` = 0, `value` = 'Female';

This will insert the option labels. Replace 9 and 10 with the values you get after the first set of inserts.
Clear the cache should be set.


Q:

Determining if shapefile has elevation or z coordinate values stored using ArcGIS Desktop?

I have a water main (line feature) that I wanted to get the elevation. As this is a subsurface feature I can't use any surface file to find these calculations. I wanted to use the calculate geometry tool to find the Z coordinate but that is not available.
It will allow me to calculate X & Y for start, mid pt, and end pt, so I'm assuming that this shapefile does not have elevation information stored in it?
How can I confirm that this shapefile only has X-Y information stored?

A:

Your question title and content are a little ambiguous as to what you are asking.  As for checking to see if a shapefile has z information, which seems to be your ultimate question, is as follows:
Open the shapefile in ArcMap, go to the layer properties (right-click -> properties, or simply double-click) and go to the source tab.  Look under Data Source, and see if 'Coordinates have Z values'


Q:

How to know radius while drawing a circle on Google Maps

What I have :
As per Google suggestion we have used MVC object and the events DistanceWidget & RadiusWidget to display the radius while re-sizing the circle which is working fine for existing circle (circle drawn by DistanceWidget).
Fiddle Demo
What I need :
I need to show the radius of the circle while drawing a new circle. The event DistanceWidget & RadiusWidget are used only for existing circle (circle drawn by DistanceWidget) not for new circle (user drawn circle by using DrawingManager tool).
Is it possible to show DistanceWidget for creating new circle?
Fiddle

A:

a nice challenge indeed. As @DaveAlperovich has commented, you can't use the DrawingManager to retrieve this piece of information; While drawing, you don't have any access to the circle; You have to wait for the DrawingManager to trigger the circlecomplete event to get a reference to this circle.
Nevertheless, if you can't have a real manager, just fake it.
See the snippet and the description right below.

var FakeDrawer = function(controlDiv, map) {
  var self = this;

  /* Initialization, some styling ... */
  self._map = map;
  self.initControls(controlDiv);

  /* Setup the click event listener: drawingmode for the circle control */
  google.maps.event.addDomListener(self._controls.circle, 'click', function() {
    /* Ensure consistency */
    self.reset();

    /* Bind the drawing mode */
    self._map.setOptions({
      draggableCursor: "crosshair"
    });
    self._drawListener = self._map.addListener('mousedown', self.drawingMode(self));
  });

  /* Just reset things for the stop controls */
  google.maps.event.addDomListener(self._controls.stop, 'click', function() {
    self.reset();
  });
};

FakeDrawer.prototype.drawingMode = function(self) {
  return function(center) {
    /* Let's freeze the map during drawing */
    self._map.setOptions({
      draggable: false
    });

    /* Create a new circle which will be manually scaled */
    var circle = new google.maps.Circle({
      fillColor: '#000',
      fillOpacity: 0.3,
      strokeWeight: 2,
      clickable: false,
      editable: false,
      map: self._map,
      radius: 1,
      center: center.latLng,
      zIndex: 1
    });

    /* Update the radius on each mouse move */
    var onMouseMove = self._map.addListener('mousemove', function(border) {
      var radius = 1000 * self.distanceBetweenPoints(center.latLng, border.latLng);
      circle.setRadius(radius);

      /* Here is the feature, know the radius while drawing */
      google.maps.event.trigger(self, 'drawing_radius_changed', circle);
    });

    /* The user has finished its drawing */
    google.maps.event.addListenerOnce(self._map, 'mouseup', function() {
      /* Remove all listeners as they are no more required */
      google.maps.event.removeListener(onMouseMove);

      circle.setEditable(true);

      /* Restore some options to keep a consistent behavior */
      self.reset();

      /* Notify listener with the final circle */
      google.maps.event.trigger(self, 'circlecomplete', circle);
    });
  };
};

FakeDrawer.prototype.reset = function() {
  var self = this;

  self._map.setOptions({
    draggableCursor: "",
    draggable: "true"
  });

  /* Remove any applied listener */
  if (self._drawListener) {
    google.maps.event.removeListener(self._drawListener);
  }
};

/* Create views and associated css */
FakeDrawer.prototype.initControls = function(controlDiv) {
  var self = this;

  function createControlUI(title, image) {
    var controlUI = document.createElement('div');
    controlUI.style.backgroundColor = '#fff';
    controlUI.style.border = '1px solid rgba(0, 0, 0, .15)';
    controlUI.style.boxShadow = '1 4px -1px rgba(0, 0, 0, .3)';
    controlUI.style.marginTop = '10px';
    controlUI.style.textAlign = 'center';
    controlUI.style.width = '25px';
    controlUI.style.height = '25px';
    controlUI.style.display = 'inline-block';
    controlUI.title = title;
    if (image == "circle") {
      controlUI.style.borderLeft = "none";
    }

    var controlImgWrapper = document.createElement('div');
    controlImgWrapper.style.width = '16px';
    controlImgWrapper.style.height = '16px';
    controlImgWrapper.style.overflow = 'hidden';
    controlImgWrapper.style.display = 'inline-block';
    controlImgWrapper.style.marginTop = '4px';
    controlUI.appendChild(controlImgWrapper);

    var imageOffset = {
      "circle": 0,
      "openhand": -9 * 16
    }[image];

    var controlImg = document.createElement('img');
    controlImg.src = 'https://maps.gstatic.com/mapfiles/drawing.png';
    controlImg.style.marginTop = imageOffset + "px";
    controlImgWrapper.appendChild(controlImg);

    var focusBackground = function() {
      controlUI.style.backgroundColor = '#eee';
    };

    var unfocusBackground = function() {
      controlUI.style.backgroundColor = "#fff";
    };

    controlImg.addEventListener('mouseenter', focusBackground);
    controlImg.addEventListener('mouseout', unfocusBackground);
    controlUI.addEventListener('mouseenter', focusBackground);
    controlUI.addEventListener('mouseout', unfocusBackground);

    return controlUI;
  }

  self._controls = {
    circle: createControlUI("Draw a circle", "circle"),
    stop: createControlUI("Stop drawing", "openhand"),
  };

  controlDiv.appendChild(self._controls.stop);
  controlDiv.appendChild(self._controls.circle);
};

FakeDrawer.prototype.distanceBetweenPoints = function(p1, p2) {
  if (!p1 || !p2) {
    return 0;
  }
  var R = 6371;
  var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
  var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
  var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c;
  return d;
};

function InitializeMap() {
  var latlng = new google.maps.LatLng(29.760193, -95.36939);
  var myOptions = {
    zoom: 12,
    center: latlng,
    zoomControl: true,
    mapTypeId: google.maps.MapTypeId.ROADMAP,
    disableDefaultUI: true
  };
  var map = new google.maps.Map(document.getElementById("map"), myOptions);

  /* Add a custom control */
  var fakeDrawerDiv = document.createElement('div');
  var fakeDrawer = new FakeDrawer(fakeDrawerDiv, map);

  fakeDrawerDiv.index = 1;
  map.controls[google.maps.ControlPosition.TOP_CENTER].push(fakeDrawerDiv);

  var updateInfo = function(circle) {
    document.getElementById("info").innerHTML = "Radius: " + circle.getRadius();
  };

  google.maps.event.addListener(fakeDrawer, 'drawing_radius_changed', updateInfo);
  google.maps.event.addListener(fakeDrawer, 'circlecomplete', function(circle) {
    google.maps.event.addListener(circle, 'radius_changed', function() {
      updateInfo(circle);
    });
  });
}

google.maps.event.addDomListener(window, 'load', InitializeMap);
html,
body {
  height: 100%;
  margin: 0px;
  padding: 0px
}
#map {
  height: 80%;
  width: 100%;
}

Step 1: Create a custom control
Somewhere in the file or as an external library:
var FakeDrawer = function (controlDiv, map) {
    var self = this;

    /* Initialization, some styling ... */
    self._map = map;
    self.initControls(controlDiv);
};

FakeDrawer.prototype.initControls(controlDiv) {
    var self = this;

    function createControlUI (title, image) {
        var controlUI = document.createElement('div');
        /* ... See the snippet for details .. just some styling */
        return controlUI;
    }

    self._controls = {
        circle: createControlUI("Draw a circle", "circle"),
        stop: createControlUI("Stop drawing", "openhand"),
     };

     controlDiv.appendChild(self._controls.stop);
     controlDiv.appendChild(self._controls.circle);
};

Step 2: Add some sugars
This are functions that we may use; Highly inspired from your JsFiddle :)
A reset method to recover a consistent state when needed:
FakeDrawer.prototype.reset = function () {
    var self = this;
    self._map.setOptions({
        draggableCursor: "",
        draggable: "true"
    });

    /* Remove any applied listener */
    if (self._drawListener) { google.maps.event.removeListener(self._drawListener) ; }
};

And, a distance computer:
FakeDrawer.prototype.distanceBetweenPoints = function (p1, p2) {
    if (!p1 || !p2) {
        return 0;
    }
    var R = 6371;
    var dLat = (p2.lat() - p1.lat()) * Math.PI / 180;
    var dLon = (p2.lng() - p1.lng()) * Math.PI / 180;
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(p1.lat() * Math.PI / 180) * Math.cos(p2.lat() * Math.PI / 180) * Math.sin(dLon / 2) * Math.sin(dLon / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;
    return d;
};

Step 3: Create your own drawing mode
Now that we have some controls, we have to define their behavior. The stop control is straightforward; Let's have a look to the circle control.
FakeDrawer.prototype.drawingMode = function (self) {
    return function (center) {
        /* Let's freeze the map during drawing */
        self._map.setOptions({draggable: false});

        /* Create a new circle which will be manually scaled */
        var circle = new google.maps.Circle({
            fillColor: '#000',
            fillOpacity: 0.3,
            strokeWeight: 2,
            clickable: false,
            editable: false,
            map: self._map,
            radius: 1,
            center: center.latLng,
            zIndex: 1
        });

        /* Update the radius on each mouse move */
        var onMouseMove = self._map.addListener('mousemove', function (border) {
            var radius = 1000 * self.distanceBetweenPoints(center.latLng, border.latLng);
            circle.setRadius(radius);

            /* Here is the feature, know the radius while drawing */
            google.maps.event.trigger(self, 'drawing_radius_changed', circle);
        });

        /* The user has finished its drawing */
        google.maps.event.addListenerOnce(self._map, 'mouseup', function () {
            /* Remove all listeners as they are no more required */
            google.maps.event.removeListener(onMouseMove);

            circle.setEditable(true);

            /* Restore some options to keep a consistent behavior */
            self.reset();

            /* Notify listener with the final circle */
            google.maps.event.trigger(self, 'circlecomplete', circle);
        });
    };
};

Step 4: Bind controls
Now that everything is okay, let's add some listeners to the initial version of the constructor so that each control has a corresponding action when clicked.
var FakeDrawer = function (controlDiv, map) {
    var self = this;

    /* Initialization, some styling ... */
    self._map = map;
    self.initControls(controlDiv);

    /* Setup the click event listeners: drawingmode */
    google.maps.event.addDomListener(self._controls.circle, 'click', function() {
        /* Ensure consistency */
        self.reset();

        /* Only drawingmode */
        self._map.setOptions({draggableCursor: "crosshair"});
        self._drawListener = self._map.addListener('mousedown', self.drawingMode(self));
    });

    google.maps.event.addDomListener(self._controls.stop, 'click', function () {
        self.reset();
    });
};

Step 5: Use it!
Assuming that your map has been initialized correctly.
Inside your map init function:
var fakeDrawerDiv = document.createElement('div');
var fakeDrawer = new FakeDrawer(fakeDrawerDiv, map);

fakeDrawerDiv.index = 1;
map.controls[google.maps.ControlPosition.TOP_CENTER].push(fakeDrawerDiv);

var updateInfo = function (circle) {
    document.getElementById("info").innerHTML = "Radius: " + circle.getRadius();
};

google.maps.event.addListener(fakeDrawer, 'drawing_radius_changed', updateInfo);
google.maps.event.addListener(fakeDrawer, 'circlecomplete', function (circle) {
    google.maps.event.addListener(circle, 'radius_changed', function () {
        updateInfo(circle);
    });
});

Enjoy, hope it will help.


Q:

Understanding the implementation of Euclid's Algorithm for GCF in Python

Euclid's Algorithm for GCF of two numbers is: GCF(a, b)=GCF(b, a mod b). I have seen this implemented in Python as follows:
def gcf(a, b):
    return b and gcf(b, a%b) or a

I don't understand how to parse this function or specifically how boolean logic is applied to integers. For example, gcf(42, 56) = 14. When I walk through it, I see that eventually the recursive part returns zero. I follow that 0 or n == n and 0 and n == 0. However, once I have a pair of non-zero integers being compared with and/or logic, I don't understand what happens and why.
Can someone walk me through this function?

A:

Python boolean operators 'or' and 'and' don't return boolean values. They return one of the values they are comparing.
0 or n - returns n
0 and n - returns 0
a and b or c is just a trick to implement the (a ? b : c) syntax in C.
Read section 4.6 of Dive into Python for a great description of python's boolean operations and this trick.


Q:

NHibernate - mapping classes that implement multiple interfaces

I am using the Table Per Subclass strategy to persist an inheritance hierarchy:
alt text http://dl.dropbox.com/u/1563210/budget%20obj%20graph.jpg
I am running into some confusion as to how to map the Debit class, which implements 2 interfaces. I may be overthinking it; I'm still learning NH.
Thanks for any input.
EDIT
What's confusing me is that the only properties that my concrete classes have, they are getting from those interfaces. This is why I think I will have to map the Interfaces along with the concrete classes.

A:

NHibernate doesn't know or care about the interfaces. You can't, for example, use NHibernate to query for objects that implement a specific interface. You have a table-per-class mapping so you should map it with subclass declarations as described in the documentation.


Q:

can't get result from total footerData in jqgrid

I'm creating jqgrid dynamically, but have a problem. By creating footer jqgrid, I want total column 'get' ; but it doesn't  show any results.

How can I solve this problem?
this my code
  loadComplete: function () {

                var $self = $(this),
                       sum = $self.jqGrid("getCol", "get", false, "sum");

                $self.jqGrid("footerData", "set", { get: sum });

            },

this json data
     data:
          [
            {ID:'1', get: 15 },
            { ID: '2', get: 585 },
           { ID: '3', get: 585 }
      ]

 colModel:
     [
     { ID: 'ID' IsForce: 'False', FieldType: Integer'},
      { ID: 'get'  FieldType: 'Integer'  }
  ]

A:

I created the demo, to reproduce your problem and found the bug in footerData, which exists only in RTL languages. I posted the corresponding fix to GitHub. The demo https://jsfiddle.net/OlegKi/dnfk8hmr/144/ loads the latest version of free jqGrid from GitHub (the fixed version) and you can verify that the problem is fixed.
I plan to publish version 4.15.3 recently (probably during the next weekend). After that it will be available on CDN. Till the time you will have to download the free jqGrid from GitHub.


Q:

Alternate play / pause button for WordPress wpaudio soundmanager plugin

I am using the wpaudio plugin to convert mp3 links into a javascript/flash audio player. My problem is that I use this plugin in two areas on my site: one on a black background, and one on a white background. I need to use an alternate set of play/pause buttons for each page (white buttons for the black background and vice versa). I am at a total loss on how to do this.
I need to some how incorporate a "if page is..." statement into the wpaudio.js but I don't know how to do this with jQuery.
Here is the code in the plugin i think i need to alter:
jQuery(this).prepend('');

and:
function wpaButtonCheck() {
    if (!this.playState || this.paused)
        jQuery('#' + this.sID + '_play').attr('src', wpa_url + '/wpa_play.gif');
    else
        jQuery('#' + this.sID + '_play').attr('src', wpa_url + '/wpa_pause.gif');
}

the plugin adds the  element to the DOM in the following format:

A:

Ok i get it now.
What you need to do is instead of setting the src attribute for showing the correct image. Have both type of images in the same image.
for example instead of wpa_play.gif you will have a bigger one which contains wpa_play for back bg and white bg both. but the size of its container is only the size of one of the buttons.
then you use the backgound-position in the css on different pages to show the correct part of the button


Q:

DocPad plugin: odd errors when testing, hangs when including in project

I'm trying to write a DocPad plugin to import MongoDB docs into the DocPad database for use in a static website. The source code is at https://github.com/nfriedly/docpad-plugin-mongodb and it's based on https://github.com/docpad/docpad-plugin-tumblr
When I run cake test, I get this output:
cake compile
cake install
npm install (for app)
npm install (for test)
npm install (for docpad tests)
coffee compile
npm test

> docpad-plugin-mongodb@2.0.0 test c:\Users\IBM_ADMIN\docpad-plugin-mongodb
> npm run prepare_test_db && node ./out/mongodb.test.js

> docpad-plugin-mongodb@2.0.0 prepare_test_db c:\Users\IBM_ADMIN\docpad-plugin-mongodb
> mongo test/prepare_database.mongo.js

MongoDB shell version: 2.6.5
connecting to: test
connecting to: docpad_plugin_mongodb_test
mongodb
mongodb > create
notice: If everyone who saw this message donated $1/week, maintaining DocPad would become sustainable: http://docpad.org/donate
error: An error occured:
Error: Didn't place the skeleton as the desired structure already exists
  at c:\Users\IBM_ADMIN\docpad-plugin-mongodb\node_modules\docpad\out\lib\docpad.js:4107:17
  at Object.cb [as oncomplete] (fs.js:168:19)
error: To report the above error, follow the guide at: http://docpad.org/bug-report
mongodb > create OK
mongodb > load plugin mongodb
mongodb > load plugin mongodb OK
mongodb > generate
mongodb > generate > action
warning: You have multiple files being written to c:\Users\IBM_ADMIN\docpad-plugin-mongodb\test\out\testData\1.json, they are:
  - testData/1.json:c7
  - testData/1.json:c5
  Rename one of them to avoid an over-write

FAILURE: 2/3 tests ran successfully; 0 failed, 1 incomplete, 0 errors

npm ERR! Test failed.  See above for more details.
npm ERR! not ok code 0

c:\Users\IBM_ADMIN\docpad-plugin-mongodb\Cakefile:99
      throw err;
            ^
Error: Process exited with error status code
  at ChildProcess.<anonymous> (c:\Users\IBM_ADMIN\docpad-plugin-mongodb\Cakefile:88:15)
  at ChildProcess.emit (events.js:98:17)
  at maybeClose (child_process.js:756:16)
  at Process.ChildProcess._handle.onexit (child_process.js:823:5)

And, when I include the module in my project, it just hangs after this:
$ docpad run
info: Welcome to DocPad v6.69.1 (local installation: c:\Users\IBM_ADMIN\watson-developer-cloud\node_modules\docpad
notice: If everyone who saw this message donated $1/week, maintaining DocPad would become sustainable: http://docp
info: Contribute: http://docpad.org/docs/contribute
info: Plugins: eco, mongodb
info: Environment: development
info: DocPad listening to http://0.0.0.0:9778/ on directory c:\Users\IBM_ADMIN\watson-developer-cloud\out

(And if I visit localhost:9778, it just hangs and never loads a page)
It seems like it only displays logs from plugins after the first pass is complete, so I started adding throw statements to see what it was doing. It seems that it imports things from mongo successfully, and it creates the document, but when the plugin calls document.action 'load', (err) ->, that callback is never fired.
Can anyone provide some guidance on what I'm messing up and how to get things working smoothly?

A:

Fixed it. The TaskGroup library (apparently) once had a .once('complete', callback) event that no longer works. Switching it to .done(callback) (and fixing a couple of other small bugs) got me working now.
It still gives me the "Error: Didn't place the skeleton as the desired structure already exists" but the tests all pass now, so I'll call it a win.


Q:

Careers Notification for a message keeps getting resent

I'm not sure wether or not this is the right place to post this, but I've clicked on the feedback is welcomed link on the Careers Stackoverflow site and arrived here.
I have a Careers profile which I don't really use. I got messaged by someone (a company) about a position, I chose to ignore the message (don't want to reply). I've read the message on the website, and it has been marked as read.
Following that, I get a notification weekly or once every two weeks titled:
Reminder: X is waiting to hear from you - Stack Overflow Careers 2.0.
I've checked several times, and even went out of my way to select the message and click the mark as read button, but the emails still come.
This must be a bug.

A:

The reason you are getting notifications is because you chose to ignore the message.  On Careers we expect you to respond to employer emails, even if you are not interested.  Simply marking the message as read will not prevent you from receiving these reminders, only responding to the message will.  If you want to ignore it, my best suggestion is that you respond not interested with an empty text response.  After 14 days of not responding to a message we will automatically mark your account not searchable.


Q:

Why don't I need the call operator to call functions in JavaScript?

Quite Simply, I'd like to now why is it that sometimes you don't require the call operator () for a Function invocation?
This is what I normally do:
function startUp() {
  alert("started");
}

// and later...
startUp(); //to call it, this will actually trigger the alert

//If I do this
startUp; //It prints the function in the a Browser's console, but won't call the function

Now, If I attach the function to a Browser event:
 <script>

    function startUp() {
      alert("started");
    }

    window.onload = startUp; //I don't need the () to call the Function! WHY is that??

  </script>

As I mention in the comment, why is it that I sometimes don't need the () to call a function? (like in this case)
Thank you in advance for your explanations.

A:

window.onload = startUp;

This is not you calling the function. Instead, you pass a reference to your function as a handler for the onload event of the window. When an event is fired, all the handlers associated with it get called (and that is when the function is executed).
Consider the following piece of code:
function foo() {
  console.log('I am fired');
}

function run(func){
  func();
}

var bar = foo; // nothing is called on this line
run(bar); // bar is not called on this line. It is called in run().
run(foo); // same thing.

For your example, window.onload = startUp, the browser is the one that triggers the callback (as with all the browser events, timeout callbacks, etc). The startUp function will be called by the browser when the page content has loaded (HTML, referenced CSS, referenced images, etc).
Also interesting to note is that the function can be called with parameters. Browser events usually call it with this being the element that triggered the event (in this case it should be window) and the first parameter the event that was fired. If you want to replicate that, it would look something like this:
function fireCallbacks(element,callbacks){
  var event = new Event();
  for (var i=0; i<callbacks.length; i++) {
    callbacks[i].call(element, event);
  }
}

fireCallbacks(window, [startUp]);

Function.prototype.call is used to execute a function with a specific this value and parameters.


Q:

Alternatives to CTEs in Microsoft Access

I work with MS Access 2010 on a daily basis and I want to know if there are alternatives to a Common Table Expression as it is used in SQL Server, and how it affects performance?
For example, is it better to create a subquery or is it better to call a query from another query, which essentially is very similar..
Example:
SELECT A.field1,A.Date
FROM (SELECT * FROM TABLE B WHERE B.Date = Restriction )

or
SELECT A.field1,A.Date
FROM SavedQueryB

SavedQueryB:
SELECT * FROM TABLE B WHERE B.Date = Restriction

I feel having multiple queries makes it easier to debug and manage, but does it affect performance when the data-set is very large?
Also, I've seen some videos about implementing the queries thru VBA, however I'm not very comfortable doing it that way yet.
Essentially. What is more efficient or a better practice? Any suggestion or recommendations on better practices?
I am mostly self taught, through videos, and books, and some programming background (VB.NET)

A:

For the simplest queries, such as those in your question, I doubt you would see a significant performance difference between a subquery and a "stacked query" (one which uses another saved query as its data source) approach.  And perhaps the db engine would even use the same query plan for both.  (If you're interested, you can use SHOWPLAN to examine the query plans.)
The primary performance driver for those 2 examples will be whether the db engine can use indexed retrieval to fetch the rows which satisfy the WHERE restriction.  If TABLE.Date is not indexed, the query will require a full table scan.  That would suck badly with a very large dataset, and the performance impact from a full scan should far overshadow any difference between a subquery and stacked query.
The situation could be different with a complex subquery as Allen Browne explains:

Complex subqueries on tables with many records can be slow to run.

Among the potential fixes for subquery performance problems, he suggests ...

Use stacked queries instead of subqueries. Create a separate saved
  query for JET to execute first, and use it as an input "table" for
  your main query. This pre-processing is usually (but not always)
  faster than a subquery. Likewise, try performing aggregation in one
  query, and then create another query that operates on the aggregated
  results. This post-processing can be orders of magnitude faster than a
  query that tries to do everything in a single query with subqueries.

I think your best answer will come from testing more complex real world examples.  The queries in your question are so simple that conclusions drawn from them will likely not apply to those real world queries.

A:

This is really context-dependent as a host of scenarios will decide the most efficient outcome including data types, join tables, indexes, and more. In essence and for simple queries like posted SELECT statmeents, the two queries are equivalent but the Jet/ACE's (underlying engine of MS Access) query optimizer may decide a different plan again according to structural needs of the query. Possibly, calling an external query adds a step in execution plan but then subqueries can be executed as self-contained tables then linked to main tables.
Recall SQL's general Order of Operations which differs from typed order as each step involves a virtual table (see SQL Server):
FROM clause       --VT1
ON clause         --VT2
WHERE clause      --VT3
GROUP BY clause   --VT4
HAVING clause     --VT5
SELECT clause     --VT6
ORDER BY clause   --VT7

What can be said is for stored query objects, MS Access analyzes and caches the optimized "best plan" version. This is often the argument to use stored queries over VBA string queries which the latter was not optimized before execution. Even further, Access' query object is similar to other RDMS' view object (though Jet/ACE does have the VIEW and PROCEDURE objects). A regular discussion in the SQL world involves your very question of efficiency and best practices: views vs subqueries and usually the answer returns "it depends". So, experiment on a needs basis.
And here CTEs are considered "inline-views" denoted by WITH clause (not yet supported in JET/ACE). SQL programmers may use CTEs for readibility and maintainability as you avoid referencing same statement multiple times in body of statement. All in all, use what fits your coding rituals and project requirements, then adjust as needed.
Resources

MS Access 2007 Query Performance
Tips - with note on subquery performance
Intermediate Microsoft Jet
SQL
- with note on subqueries (just learned about the ANY/SOME/ALL)
Microsoft Jet 3.5 Performance White
Paper
- with note on query plans


Q:

Javascript setTimeout function starts executing too many times

I created a loop with setTimeout function and it comes to a problem after 2nd or 3rd step it call's itself because it starts excecuting twice at the time. This is what my function looks like:
var value = 70,
    intervalID = null;

function interval() {
  intervalID = setTimeout(countDown, 1000);
}

function countDown() {
  value--;
  if(value > 0) {
    clearTimeout(intervalID);
    interval();
  } else {
    endInterval();
  }
}

function endInterval() {
  // do something
}

If I console the variable value its 69, 68 and after that it starts decreasing variable value twice in one function call. I'm not calling function countDown() anywhere but from one place.

What could be the problem?
Edit: this code works now.

A:

I'd recommend you to "sanitize" the timeouts by stopping previous one.
function interval() {
  clearTimeout(intervalID);
  intervalID = setTimeout(countDown, 1000);
}

However it looks like control of symptoms instead of sickness' cause. So it would be better to detect the cause of the issue.


Q:

Changing the voice used on Nexus 7 for Google Now search

I have recently bought a Nexus 7 from the Google Play UK store and it seems to be configured as a US tablet in that the voice on the Google Now search is an american woman, whereas on my Nexus S when I search the voice that responds is a man's which I prefer for this purpose, mainly due to the accent the woman has. Is it possible to change the voice that the tablet responds with? I'd prefer solutions that didn't require rooting.
I've already tried changing the language to English (UK).

A:

There's a separate section to choose the text-to-speech output speaker:
Goto settings and choose the UK voice:
Setting => Language & input => Text-to-speech output => Google Text-to-speech => Language
You can install german, spanish, french, italian voice data additionaly to the preinstalled english US/UK voices.


Q:

JavaScript library to type Hindi with international keyboards

I am developing a website using HTML5 and AngularJS. I want to develop a site in Hindi language. One requirement is that the site should allow to enter text in the Devanagari alphabet even in devices that do not have the appropriate keyboard.
Time ago I hot-linked a Microsoft bookmarklet that's no longer available (http://ilit.microsoft.com/Bookmarklet/Script/Hindi.js) which would convert from English to Hindi: you type "kya" and then get the corresponding Hindi characters.
Can you suggest tools to do the same, using this or other system?

A:

Download code from    http://www.gamabhana.com/?q=node/3
Extract downloaded folder. Now your folder have the following content

gamabhana_js have all js files that you need. Open the index.html in browser and enter something in textarea. Then you can see corresponding Hindi fonts instead of English. You can edit that index file and use according to your need.
Following is a sample code that I edited If I click on hindi then I will get Hindi fonts instead of English
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>

<script language="JavaScript" type="text/javascript" src="./gamabhana_js/GA1000.js"></script>
<script language="JavaScript" type="text/javascript" src="./gamabhana_js/GA0010.js"></script>
<script language="JavaScript" type="text/javascript" src="./gamabhana_js/GA0640.js"></script>
<script language="JavaScript" type="text/javascript" src="./gamabhana_js/gamabhanaLib.js"></script>
<script language="JavaScript" type="text/javascript" src="./gamabhana_js/fileio.js"></script>
<script language="JavaScript" type="text/javascript" >
gw1=null;
var hindi=false;
function myCustomOnInit()
{   try{

if(hindi==true){
                  gw1= new gamabhanaPhoneticHandler("elm1_ifr",'__devanagari__','__roman__','#gamabhana#');
                  gw1.MrAutoCor=true;
                  GphRegisterForMasterUpdates(gw1);
}
     }
     catch(e){}
}

function LanguageList_onchange() {
gw1.SetPriLanguage(document.getElementById('LanguageList1').value);
}

function arrangekbhelp()
{
document.getElementById('kbhelpdiv').style.left=(window.document.body.clientWidth-400) + "px";
if((window.document.body.clientWidth-400)<0)
 document.getElementById('kbhelpdiv').style.left=0 + "px";
}
function hindi1(){
hindi=true;
myCustomOnInit();
}

function togglekbhelp()
{
arrangekbhelp();
if(document.getElementById('kbhelpdiv').style.display=='block')
   document.getElementById('kbhelpdiv').style.display='none';
else
   document.getElementById('kbhelpdiv').style.display='block';

return;
}
window.onresize=arrangekbhelp;

</script>

<!-- TinyMCE -->
<script type="text/javascript" src="jscripts/tiny_mce/tiny_mce.js"></script>
<script type="text/javascript">
    tinyMCE.init({
        // General options
        mode : "textareas",
        theme : "advanced",
        plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,noneditable,visualchars,nonbreaking,xhtmlxtras,template",

        // Theme options
        theme_advanced_buttons1 : "newdocument,|,bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontselect,fontsizeselect,langselect",
        theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,help,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
        theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl",
        theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
        theme_advanced_toolbar_location : "top",
        theme_advanced_toolbar_align : "left",
        theme_advanced_statusbar_location : "bottom",
        theme_advanced_resizing : true,

        // Example content CSS (should be your site CSS)
        content_css : "css/content.css",
            oninit : "myCustomOnInit",
        // Drop lists for link/image/media/template dialogs
        template_external_list_url : "lists/template_list.js",
        external_link_list_url : "lists/link_list.js",
        external_image_list_url : "lists/image_list.js",
        media_external_list_url : "lists/media_list.js",

        // Replace values for the template plugin
        template_replace_values : {
            username : "omkar",
            staffid : "9383"
        }
    });
</script>
<!-- /TinyMCE -->

</head>
<body>

<form>

<textarea id="elm1" name="elm1" rows="15" cols="80" style="width: 80%">   </textarea>

</form>
<button onclick="hindi1()">Hindi</button>

</body>

</html>


Q:

How many rows in a mysql BEFORE fetch_assoc?

I am getting some data from the mysql through a select.
$result = mysqli_query($cxn, $query);

I then go through it with
if ($result!= false) {
    while ($row = mysqli_fetch_assoc($result)) {
        do_stuff();
    }
}

What I'd like to do is to add a line before the while ONLY if there is more than one line in the $result.
I understand that I could create an array of $row's first and then count them, but that would defeat the convenience of the while.
Question: is there a way to find out how many rows the mysqli_fetch_assoc would generate without running it twice?

A:

You should check this function: http://php.net/mysqli_num_rows
You can check the number of results by using it like this
if (mysqli_num_rows($result))
{
..
}


Q:

Can anybody provide any simple working example of the Conductor.Collection.AllActive usage?

It's a bit strange, but I really can't find a working example anywhere.
By the way, I'm using a ViewModel-first approach (in WPF) if this is important.
Thank you in advance.

A:

If you have a look at the discussion here you will see that the intent of AllActive is to compose several Views/ViewModels into a containing ViewModel. Judging from your previous comments it seems as if this is what you were expecting but I figured I'd at least reference it here.
You then mention activating 3 different ViewModels at different regions of the View. The way I've handled this in the past is to have separate properties for binding/referencing the ViewModels in the View, and then just adding all of them to Items to get the Conductor behavior.
public sealed class MyViewModel : Conductor<Screen>.Collection.AllActive
{
    public MyViewModel(IMagicViewModelFactory factory)
    {
        FirstSubViewModel = factory.MagicallyGiveMeTheViewModelIWant();
        SecondSubViewModel = factory.MagicallyGiveMeTheViewModelIWant();
        ThirdSubViewModel = factory.MagicallyGiveMeTheViewModelIWant();

        Items.Add(FirstSubViewModel);
        Items.Add(SecondSubViewModel);
        Items.Add(ThirdSubViewModel);
    }

    public Screen FirstSubViewModel { get; private set; }
    public Screen SecondSubViewModel { get; private set; }
    public Screen ThirdSubViewModel { get; private set; }
}

And in MyView you would have something like this. Of course you could put these ContentControls wherever you want to in the view.
<StackPanel>
    <ContentControl x:Name="FirstSubViewModel" />
    <ContentControl x:Name="SecondSubViewModel" />
    <ContentControl x:Name="ThirdSubViewModel" />
</StackPanel>

Another common use for AllActive is when you have a list of items. But the items are complex enough to warrant having their own View/ViewModels that require activation. In that case you would not have to have separate properties for the views as you would just set the x:Name of the list control to Items.


Q:

How to draw a vertical line table

I search here, Vertical lines in a table, it suggests something like:
 \begin{tabular}{cc|ccc|ccc}

I am using:
\toprule
 & & \multicolumn{5}{>{\centering\arraybackslash}p{8em}}{\textbf{Bootstrap}} \\
\cmidrule{4-8}

But does not fit in.
I wish to get the following:

My MWE:
\documentclass[12pt,oneside]{book}

\usepackage[showframe]{geometry}
\usepackage{amsmath}
\usepackage{ragged2e}
\usepackage{makecell, multirow, tabularx}
\renewcommand\theadfont{\small\bfseries} % for bold in table using \small
\renewcommand\theadgape{}
\usepackage[svgnames, table]{xcolor}
\usepackage{hhline, boldline}
\usepackage{seqsplit, caption} %for table spacing to second row
\usepackage{booktabs, ragged2e} % Use booktabs rules and get rid of vertical rules, ragged2e to ragged text
\usepackage{siunitx} %for table spacing to second row
\usepackage{threeparttable} %to add footnote below table
\usepackage{tabulary}
\usepackage{graphicx}

\begin{document}

\begin{table}[h!]
\centering
% \begin{center}
    %\begin{tabularx}{\textwidth}{@{}M*{6}{N}@{}}
\begin{tabularx}{\textwidth}{>{\RaggedRight\arraybackslash}cXcccccc}
\toprule
 & & \multicolumn{5}{>{\centering\arraybackslash}p{8em}}{\textbf{Bootstrap}} \\
\cmidrule{4-8}
    &
    &  \multirow{4.5}{*}{\textbf{Mean}}
    &  \multirow{4.5}{*}{\textbf{Bias}}
    & \multirow{4.5}{*}{\makecell{\textbf{Std.}\\ \textbf{Error}}}
    & \multirow{4.5}{*}{\makecell{\textbf{Sig.}\\ \textbf{(2-tailed)}}}
    & \multicolumn{2}{>{\centering\arraybackslash}p{8em}}{\textbf{95\% Confidence Interval of the Difference}}
    \\
\cmidrule{7-8}  %\cmidrule(lr){3-4}
     & & & & & & \multicolumn{1}{c}{\textbf{Lower}} &  \multicolumn{1}{c}{\textbf{Upper}} \\
\midrule
    Pair 1
    & \textit{Testing example dataset} (AA) - \textit{Testing puree Example Dataset} (BB)
    & 44.76\%
    &  0.19\%
    & 4.35
    & 0.001
    & 36.67\%
    & 53.33\%\\
    \bottomrule
    \end{tabularx}
\end{table}

\end{document}

A:

I would no add vertical line(s), rather use appropriate \cmidrule:

\documentclass[12pt,oneside]{book}
\usepackage[showframe]{geometry}
\usepackage{ragged2e}
\usepackage{booktabs, makecell, multirow, tabularx, tabulary}
\renewcommand\theadfont{\small\bfseries} % for bold in table using \small
\renewcommand\theadgape{}
\newcolumntype{L}{>{\RaggedRight}X}
\usepackage{threeparttable} %to add footnote below table
 \usepackage[svgnames, table]{xcolor}
\usepackage[skip=1ex]{caption} %for table spacing to second row
\usepackage{siunitx} %for table spacing to second row

    \begin{document}
        \begin{table}[ht]
\sisetup{round-mode = places,
         round-precision=2,
         detect-weight
         }
\setlength\tabcolsep{3pt}
    \begin{threeparttable}
\caption{Bootstrap for paired Samples Test}
\label{tab:blabla}
        \begin{tabularx}{\linewidth}
                {@{} l L *{3}{S[table-format=2.2,table-space-text-post={\,\%}]}
                              S[table-format=1.3]
                         *{2}{S[table-format=2.2,table-space-text-post={\,\%}]}
                 @{}}
        \toprule
        &   &               & \multicolumn{5}{c}{Bootstrap}                                 \\
        \cmidrule{4-8}
        &   &               &               &               &       & \multicolumn{2}{c}{\thead{\SI{95}{\%} Confidence\\ Interval}}                       \\
        \cmidrule{7-8}
        &   & {Mean}        & {Bias}        & {\thead{SE\tnote{a}}} & {\thead{STT\tnote{b}}}
                                                                    & {\thead{Lower}}
                                                                        & {\thead{Upper}}   \\
        \midrule
Pair 1  & Testing example dataset (BB) - Testing Example Dataset (AA)
            & 12.34567\%    & 12.34567\%    & 12.34567\%    & 1.234 & 12.34567\%    & 12.34567\%    \cr
        \bottomrule
    \end{tabularx}
\begin{tablenotes}[para, flushleft]
\item[a]    SE: Standard Error
\item[b]    STT: Signal (Two Tailed)
\end{tablenotes}
    \end{threeparttable}
        \end{table}
\end{document}

(MWE is based on my answer)
However, if you persist to have it:

\documentclass[12pt,oneside]{book}
\usepackage[showframe]{geometry}
\usepackage{ragged2e}
\usepackage{booktabs, makecell, multirow, tabularx, tabulary}
\renewcommand\theadfont{\small\bfseries} % for bold in table using \small
\renewcommand\theadgape{}
\newcolumntype{L}{>{\RaggedRight}X}
\usepackage{threeparttable} %to add footnote below table
 \usepackage[svgnames, table]{xcolor}
\usepackage[skip=1ex]{caption} %for table spacing to second row
\usepackage{siunitx} %for table spacing to second row

    \begin{document}
        \begin{table}[ht]
\sisetup{round-mode = places,
         round-precision=2,
         detect-weight
         }
\setlength\tabcolsep{3pt}
    \begin{threeparttable}
\caption{Bootstrap for paired Samples Test}
\label{tab:blabla}
        \begin{tabularx}{\linewidth}
                {@{} l L *{3}{S[table-format=2.2,table-space-text-post={\,\%}]|}
                              S[table-format=1.3]|
                              S[table-format=2.2,table-space-text-post={\,\%}]|
                              S[table-format=2.2,table-space-text-post={\,\%}]
                 @{}}
        \hline
        &   &               & \multicolumn{5}{|c}{Bootstrap}                                 \\
        \cline{4-8}
        &   &               &               &               &       & \multicolumn{2}{c}{\thead{\SI{95}{\%} Confidence\\ Interval}}                       \\
        \cline{7-8}
        &   & {Mean}        & {Bias}        & {\thead{SE\tnote{a}}} & {\thead{STT\tnote{b}}}
                                                                    & {\thead{Lower}}
                                                                        & {\thead{Upper}}   \\
        \hline
Pair 1  & Testing example dataset (BB) - Testing Example Dataset (AA)
            & 12.34567\%    & 12.34567\%    & 12.34567\%    & 1.234 & 12.34567\%    & 12.34567\%    \cr
        \hline
    \end{tabularx}
\begin{tablenotes}[para, flushleft]
\item[a]    SE: Standard Error
\item[b]    STT: Signal (Two Tailed)
\end{tablenotes}
    \end{threeparttable}
        \end{table}
\end{document}


Q:

Not skewed text in skewed class button

I've created a button for my website with a CSS class and I wanted it to have a parallelogram shape so I've used the skew function to create the shape. The code was right and the button has the shape that I wanted but the text inside the button resulted skewed as well following its wrap. There's a way to make the text not looking like the Leaning Tower inside my button?
Here's the html code:
<input type="submit" alt="submit" value="Login" class="button">

And that's the CSS for the button class:
.button {
    float: top;
    width: 275px;
    height: 40px;
    margin-top: 6px;
    display: inline-block;
    font-family: Impact;
    text-align: center;
    -webkit-transform: skewX(20deg);
    -moz-transform: skewX(20deg);
    -o-transform: skewX(20deg);
    transform: skewX(20deg);
}

A:

Partly seconding Sidharth, I think you won't get around the wrapper element to apply the CSS-transform on and then reset it for its child elements (the submit-input):
<div class="button-wrapper">
  <input type="submit" alt="submit" value="Login">
</div>

Sidharth's answer implies that you completely hide the original <input> and relies on JavaScript to trigger a click on it when the styled wrapper is clicked, but here's and easy way around that: Style the button-wrapper on :hover and remove all styles from the nested <input>-element and make it 100% wide (jsBin example):
.button-wrapper {
  background: #fff;
  border: 1px solid #bbb;
  border-color: #ddd #ccc #bbb;
  overflow: hidden;

  -webkit-transform: skewX(20deg);
  -moz-transform: skewX(20deg);
  -o-transform: skewX(20deg);
  transform: skewX(20deg);
}

.button-wrapper:hover {
  background: #efe;
  border-color: #090;
}

.button-wrapper input {
  background: transparent;
  border: 0;
  cursor: pointer;
  font-size: 20px;
  font-weight: bold;
  padding: 4px 0;
  margin: 0;
  width: 100%;

  -webkit-transform: skewX(-20deg);
  -moz-transform: skewX(-20deg);
  -o-transform: skewX(-20deg);
  transform: skewX(-20deg);
}

.button-wrapper input:hover {
  color: #060;
}


Q:

Difference between mail and mailx?

Whats the difference between mail and mailx?
I'm trying to troubleshoot a problem where I can send mail from server A with this echo $MESSAGE | mail -s "$SUBJECT" -r $FROM $RECIPIENTS command but executing the same command  from server B throws me this error (Both servers are RHEL)
mail: invalid option -- r
Usage: mail [-iInv] [-s subject] [-c cc-addr] [-b bcc-addr] to-addr ...
            [-- sendmail-options ...]
       mail [-iInNv] -f [name]
       mail [-iInNv] [-u user]

Now... going through mail manpages to ty to understand whats happening, man mail gives me this:
In Server A
MAILX(1)                         User Commands                        MAILX(1)

NAME
       mailx - send and receive Internet mail

SYNOPSIS
       mailx [-BDdEFintv~] [-s subject] [-a attachment ] [-c cc-addr] [-b bcc-addr] [-r from-addr] [-h hops]
              [-A account] [-S variable[=value]] to-addr . . .
       mailx [-BDdeEHiInNRv~] [-T name] [-A account] [-S variable[=value]] -f [name]
       mailx [-BDdeEinNRv~] [-A account] [-S variable[=value]] [-u user]

But in server B
MAIL(1)                   BSD General Commands Manual                  MAIL(1)

NAME
     mail - send and receive mail

SYNOPSIS
     mail [-iInv] [-s subject] [-c cc-addr] [-b bcc-addr] to-addr... [-- sendmail-options...]
     mail [-iInNv] -f [name]
     mail [-iInNv] [-u user]

Now... if I try man mailx in server B I get:
MAILX(P)                   POSIX Programmerâs Manual                  MAILX(P)

PROLOG
       This manual page is part of the POSIX Programmerâs Manual.  The Linux implementation of this interface may differ
       (consult the corresponding Linux manual page for details of Linux behavior), or the interface may not  be  imple-
       mented on Linux.

NAME
       mailx - process messages

SYNOPSIS
   Send Mode
              mailx [-s subject] address...

   Receive Mode
              mailx -e

              mailx [-HiNn][-F][-u user]

              mailx -f[-HiNn][-F][file]

Server B has a different version of mail than Server A? Mailx and Mail are different things? I would like to use the -r option I use in server A but in server B and I don't really know whats happening.

A:

Behold the confusing history of mail, nail, mailx.
Briefly, mail is the older program, mailx (formerly nail in some implementations) is a newer version , with an extended mostly-but-not-totally-compatible interface.
mailx is still quite old, created around 1986 and standarized as part of POSIX in 1992. There are several implementations (even in modern Linuxes), and some provide
extensions to the standard.
The -r option is one such extension. Depending on your Linux distribution, and the mail package you have installed, you might or not have that option. See eg here.
If you want to write portable scripts, it's better not to rely on it.


Q:

Is it good to utilize ~100% CPU by my application

I have an application written in C++ on Linux (Ubuntu 12.14), which decodes audio and finds the peak. This calculation is running on a background thread. From the main UI thread, I am calling the background thread several times. When this background thread runs, I see about 100% CPU utilization; that is, only the first core's usage goes 100%, and the remaining 3 cores are idle (quad core processor).
So is it good behavior for the application to utilize 100% CPU? I read some post which states, "Usually it's a good thing for a process to use 100% of the CPU. It means it finishes sooner."
Another statement I've read is, "75% to 100% cpu usage is not too bad if you're getting this under full load or when there's a major application running; however if this is a reading when idle or when you are not using the PC/laptop then this is a worry."

A:

It depends on whether your application is a computational one (like this) or interactive.
For a computational application, full utilisation of the CPU(s) is your goal, as that means that the result is ready sooner.  Anything that causes that utilisation to go down is an opportunity for improvement (e.g. waiting on I/O).
For an interactive application, any time used in CPU is time that's not spent ready to respond to user input.  You would like your usage to be low.
Some applications, such as multimedia editors, are both computational and interactive.  The good ones divide the work into different threads, so that they can be responsive to interaction, yet achieve high throughput.  This appears to be what you're doing.
One thing you might want to consider is using more threads for your workload (assuming it is divisible) so that you are keeping more cores busy with your computation.  If some of them are idle, that's a wasted resource!

A:

Of course it's good. The CPU's sole raison d'être is to be used by applications. The entire hw+os combo exists for this single purpose. Why wouldn't it be good to consume as much cpu as there is in the system?


Q:

Is there away to move between workspaces using trackpad?

I want to move to other workspaces using trackpad. How can I do that?

A:

The best "vanilla" solution I'm aware of is the following:
Go to System Preferences > Exposé & Spaces (Exposé tab) > Active Screen Corners and set one up as "Spaces".
Then when you quickly move your mouse into that corner it will bring up all available workspaces, and you can click the one you want.

A:

Not sure it's possible with the stock software. MagicPrefs and Better Touch Tool let you define trackpad gestures to do pretty much anything, including mapping them to the key sequences for switching between spaces (by default Cmd + arrow keys).


Q:

How can I use try... catch and get my script to stop if there's an error?

I'm trying to get my script to stop if it hits an error, and use try... catch to give me an easy way to handle the error. The easiest thing in the world I'd have thought, but I'm obviously doing something stupid. I have read for a couple of hours and I'm stuck, any help would be very handy, thanks!
Here's some example code, I've put erroraction all over the place, can't seem to stop the damn thing!
$ErrorActionPreference = "Stop"
try {
    get-content "c:\GarbageFileName.txt" -ErrorAction stop
}
catch {
    write-output "in catch, I want it to stop now"
}
write-output "try-catch finished, script is continuing"

 this text added next day *
Fantastic answers from people, I wish I could choose more than 1 answer or had enough reputation to vote for the ones which I reluctantly didn't choose as the answer, or say thanks somehow!

A:

The whole idea of a try/catch control is that you tell the script what to do if it encounters a terminating error, instead of the default action of throwing the error and stopping the script. If your catch block just displays a message to the terminal with Write-Host, that's all the error handling there will be, and the script will continue from there. If you think about it, it would partially defeat the purpose of try/catch if the script were stopped automatically whenever an error is caught.
In the catch block, $_ will be set to the ErrorRecord object representing the terminating error from the try block (the same one that gets stored in $error[0]). So the simplest way to end the script is to rethrow the error that would have been thrown if you hadn't used a try/catch:
try {
  Get-Content "c:\GarbageFileName.txt" -ErrorAction stop
} catch {
  # Custom action to perform before terminating
  throw $_
}

Or, if you want to display a custom message instead of the default ErrorRecord:
try {
  Get-Content "c:\GarbageFileName.txt" -ErrorAction stop
} catch {
  throw 'Custom error message'
}

Or you could use break as suggested in Joost's answer if you want to just quit after you're finished with your custom error handling without throwing an error to the error stream.
Or you could get more sophisticated and create your own ErrorRecord object. There's a lot you can do with that, it's too big a topic to cover comprehensively here, but you can get more info about the syntax by googling System.Management.Automation.ErrorRecord. Here's an example from one of my scripts to get you started (from a function that executes a SQL query defined in the $query variable against a SQL Server database):
} catch {
  $ErrorRecord = New-Object System.Management.Automation.ErrorRecord(
    (New-Object Exception("Exception executing the query: $($_.Exception.InnerException.Message)")),
    $query,
    [System.Management.Automation.ErrorCategory]::InvalidArgument,
    $null
  )
  $ErrorRecord.CategoryInfo.Reason = $_.CategoryInfo.Reason;
  $ErrorRecord.CategoryInfo.Activity = $_.InvocationInfo.InvocationName;
  $PSCmdlet.ThrowTerminatingError($ErrorRecord);
}

A couple of notes:

You'll see that in creating my custom ErrorRecord, I'm using $_, which I just said contains the ErrorRecord object associated by the terminating error that was caught in the try block. The idea is to customize some of the error output, while using parts of the default ErrorRecord by assigning them to the corresponding properties for the custom ErrorRecord.
$PSCmdlet is only available if you declare [CmdletBinding()] at the beginning of the function or script. Otherwise, you can just use throw $ErrorRecord to throw your custom error. However, the result will be more Cmdlet-style if you use $PSCmdlet.ThrowTerminatingError. (throw will spit back the line from the function that generated the error, whereas $PSCmdlet.ThrowTerminatingError will give you the line from the calling context where the function was used. It's hard to describe in a way that makes sense without getting too elaborate, but if you experiment with it you'll see what I mean.)

BTW, it's redundant to set $ErrorActionPreference = "Stop", and then use -ErrorAction Stop. The preference variable sets the default action for all cmdlets, and the -ErrorAction switch overrides the default action for a particular cmdlet, so there's no need to first specify the default, then use -ErrorAction to specify the same action you just set as the default. What you probably want to do is just leave out $ErrorActionPreference = "Stop".

A:

The only thing missing is your break-statement in the Catch-block.  Powershell won't stop the script if you don't instruct it to.
try {
    get-content "c:\GarbageFileName.txt" -ErrorAction stop
}
catch {
    write-output "in catch, I want it to stop now"
    break
}
write-output "try-catch finished, script is continuing"

And a small addendum, in case it helps you: with finally, you can add some lines of code that are always executed, regardless of wether an exception was thrown or not.
try {
    get-content "c:\GarbageFileName.txt" -ErrorAction stop
}
catch {
    write-output "in catch, I want it to stop now"
    break
}
finally {
    #do some stuff here that is executed even after the break-statement, for example:
    Set-Content -Path "f:\GarbageFileName.txt" -Value $null
}

#the line below is executed only if the error didn't happen
write-output "try-catch finished, script is continuing"


Q:

How to arrange words in this sentence?

I have this sentence in english:

Can I ask you one more question?

I am supposed to use eine Frage stellen instead of just fragen.
So I created this:

Darf ich euch eine Frage stellen?

Is the position of euch correct?

A:

Can I ask you a question? - Darf ich euch eine Frage stellen.
Can I ask you one more question? - Darf ich euch noch eine Frage stellen.
"Stellen" is a verb with 2 objects here, an accusative object (eine Frage) and a dative object (euch). Unless the accusative object is a personal pronoun or the accusative definite and the dative indefinite, the dative always comes before the accusative.
Beispiele:

Ich stelle euch eine Frage.
Ich stelle euch die Frage.
Ich stelle sie euch.

Ich stelle dem Mann eine Frage.
Ich stelle dem Mann die Frage.
Ich stelle die Frage einem Mann.
Ich stelle sie einem Mann.
Ich stelle sie dem Mann.

Also: "You" can be translated by "euch" (you guys), but also by "dir" (you, singular, informal) or "Ihnen" (you, singular or plural, formal).


Q:

Jquery - Append value to Paragraph

I have 4 groups of data that are tied to a click-bind event. I'm trying to add the value from a hidden field contained within each group to a paragraph later in the page, so that when the checkbox is clicked from one or more groups of data, the value from the hidden field displays within the paragraph area.
I'd also like to get it so that when the checkbox is unclicked, it removes the value from the paragraph, but for now I'm just trying to get the value to display when the checkbox is clicked.
Here's what I've tried:
This is the hidden field within the group of data that stores the value:
<input id="servicename_<?php echo $i;?>" name="servicename_<?php echo $i;?>"
type="hidden" value="<?php echo $service->PRODUCT;?>"></input>

This is the click-bind event:
$('input[id^=ckNow_]').each(function(){
    $(this).bind('click',function(){
      if($(this).prop('checked'))
        {

var servicename = '#servicename_'+$(this).attr('value').split("_");

ServiceName += servicename;

$('#lblServiceName').append($(ServiceName));

EDIT to add the checkbox that is within each group:
<input type="checkbox" id="ckNow_<?php echo $i;?>" name="ckNow[<?php echo $i;?>]">
</input>

And then the paragraph text:

Service Name
<input type="hidden" id="servicename" value="0"></input>

What am I doing wrong and how can I fix it? All responses are very appreciated and I'm completely open to any and all suggestions. Thank you.

A:

Try

Service Name

    <input type="hidden" id="servicename" value="0"></input>

then
jQuery(function ($) {
    var $checks = $('.group-data input[name^="ckNow["]').change(function () {
        var vals = $checks.filter(':checked').map(function () {
            return $(this).closest('.group-data').find('input[id^=servicename_]').val()
        }).get();
        $('#lblServiceName span').text(vals.join(', '))
    })
})

Demo: Fiddle


Q:

How to limit the number of failed attempts to call a function?

How rewrite this code in a pythonic way?
tried = 0

while tried < 3:
    try:
        function()
        break
    except Exception as e:
        print e
        tried += 1

Is there a built-in function I could use?

A:

A more pythonic way to do something N times is to use xrange with the _ variable:
for _ in xrange(3):
    try:
        function()
        break
    except Exception as e:
        print e

Also, consider catching a more specific exception instead of the root Exception class.


Q:

Equality of sum and direct sum of projection operators

I am reading the book "An introduction to Operator Algebras" by Kehe Zhu and I am confused by the proof of the following lemma:

$\textbf{Lemma 26.2}$ Let $\mathcal A$ be a von Neumann Algebra. The sum of centrally orthogonal abelian projections $\{P_i\}_{i\in I}$ in $\mathcal A$ is again abelian.

The proof starts like the following:
For each $i\in I$ let $Z_i := Z(P_i)$ be the central support of $P_i$ [that is, the smallest central projection projection majarizing/bigger than $P_i$]. Put $P:= \sum_{i\in I} P_i$. Since $P_i \leq Z_i$ and the $Z_i$'s are mutually orthogonal, we have $Z_iP_j =0$ and $P_i = Z_i P$ for all $i \neq j$. For each $T\in \mathcal A$
$$PTP = \left( \sum_{i\in I} Z_i PT\right) P = \sum_{i\in I} Z_iPTZ_iP = \bigoplus_{i\in I}Z_i PT Z_i P = \bigoplus_{i\in I}P_i T P_i.$$
I don't understand these last calculations. Why does the "normal" sum equal the direct sum? As far as I understand this, the direct sum acts on the Hilbert space $\bigoplus_{i\in I}\mathcal H$ while the normal sum acts on $\mathcal H$ so I don't see how equality there makes sense. Apart from that I don't understand the role of the $Z_i$ here, they should be the reason for equality. Can anyone enlighten me?
Some notes on terminology:
$1)$ "Projection" always means an orthogonal projection operator in the von Neumann Algebra $\mathcal A \subset B(\mathcal H)$,
$2)$ A projection $P \in \mathcal A$ is called abelian if and only if $P\mathcal A P$ is abelian,
$3)$ The sums are always taken to be in the strong operator topology on $B(\mathcal H)$,
$4)$ The $Z_i$ are defined as the smallest central projections such that $Z_i \geq P_i$, central meaning that $Z_i$ commutes with every operator in $\mathcal A$.

A:

The questions are two:

Why does the symbol $\bigoplus$ appear in the sum?
What is the role of the $Z_i$?

To answer lets go through the proof. What we want to do is to see that $P\mathcal A P$ is an abelian algebra. The proof starts by considering the expression $PTP$ for $T\in\mathcal A$ arbitrary. Now the $P$ on the left and the $P$ on the right can be expanded to get
$$PTP = (\sum_i P_i) T(\sum_j P_j)$$
where the sums converge in SOT.
It would be ideal if we could unify both sums to one summand, if that were the case then $PTP$ would be equal to $\sum_i (P_iTP_i)$ where the $P_i$ are mutually orthogonal projections and the sum converges in SOT. This means that the operator $PTP$ may be decomposed as a direct sum of operators $PTP = \bigoplus_i P_i TP_i \oplus 0_{P^\perp}$, where the individual $P_i$ have domain and image $\mathrm{im}(P_i)$ and $0_{P^\perp}$ is the zero operator on the orthogonal complement of $\bigoplus \mathrm{im}(P_i)$ in $\mathcal H$. This decomposition may then be done for the entire algebra: $P\mathcal A P = \bigoplus_i P_i \mathcal AP_i$ so $P\mathcal AP$ is a direct sum of abelian algebras and as such also abelian.
The $Z_i$ enter the proof as the mechanism that can perform this reduction from two sums to one sum. Here the properties $Z_i P_i =P_i$, $Z_iZ_j=0$ for $i\neq j$ and $Z_i$ being central are what we use. Then one calculates:
$$\sum_{ij} P_i T P_j = \sum_{ij} Z_iP_i T Z_j P_j = \sum_{ij} \underbrace{Z_iZ_j}_{=\delta_{ij}Z_i}\, P_i T P_j = \sum_i Z_iP_i TP_i = \sum_i P_iTP_i.$$


Q:

SQL Statement OR: show every row with the value in it malfunction

I have a very specific problem:
I have a List with Companies and different Roles to this companies in Access, everything in one Table, it look like this:
Company // Role 1 // Role 2 // Role 3 // Role 4 //
Comp1   // Ted    //        //        // Jimmy  //
Comp2   // Lin    //  Ted   // Andy   //        //
and so on...
I need now to make a sql statement which gives me every company (row) in which Ted, as an example, has a role.
I tried it like this in Access under SQL - Statement:
SELECT Firmen.Firma, Firmen.[Role1], Firmen.[Role2], Firmen.[Role3]
FROM Firmen
WHERE (((Firmen.[Role1])="Ted") AND ((Firmen.[Role2])="Ted") AND ((Firmen.[Role3])="Ted"));

But then it shows only rows where Ted is in the first column, I know there is a maybe stupid mistake in it and I had this problem already but I cant remember how I solved it last time.
Would be nice if you could help, because I really need it for work

A:

You are using the and logical operator instead of the or logical operator. Change it, and you should be OK. Or better yet, you could use the in operator:
SELECT Firmen.Firma, Firmen.[Role1], Firmen.[Role2], Firmen.[Role3]
FROM   Firmen
WHERE  "Ted" IN (Firmen.[Role1], Firmen.[Role2], Firmen.[Role3])


Q:

Is there a way to attach a custom validation message when extending the validator in laravel?

Currently I have implemented following custom validation, but I don't know how to attach a custom message if the validation fails. To clarify, I need to define the error message when extending validator
Validator::extend('phone_number', function($attribute, $value, $parameters)
    {
       // is there anyway I could define a error message here, if this validation fails,
        if (strlen($value) === 9)
        {
            if (substr($value, 0, 1) === '0')
            {
                return false;
            }
        }
        else
        {
            if (substr($value, 0, 1) != '0')
            {
                return false;
            }
        }

        return true;
    });

I have currently placed this code within boot method, and in documentation they say there's a way to define custom message as follows, but I really don't understand it.
public function boot()
{

Validator::extend(...);

Validator::replacer('foo', function ($message, $attribute, $rule, $parameters) {
    return str_replace(...);
});

}

A:

You can specify your message by adding a third parameter to the extend method like this :
Validator::extend('phone_number', function($attribute, $value, $parameters) {

    if (strlen($value) === 9)
    {
        if (substr($value, 0, 1) === '0')
        {
            return false;
        }
    }
    else
    {
        if (substr($value, 0, 1) != '0')
        {
            return false;
        }
    }

    return true;
}, 'Your custom message goes here'); // <--- HERE


Q:

LSTM many-to-many training in batches of independent examples

I'm still figuring out LSTMs and trying to come up with the optimal and appropriate training routine and data shape.
A time series represents musical notes. Let's call it a song. So I have data in the following form. The series consists of notes that are one-hot encoded. So they have shape (timesteps, features). A copy of this series is made twelve times by transposing (moving up notes of) the series. One song would then take shape (12, timesteps, features). Each of these twelve series should be trained on independently. In addition there are multiple songs that vary in length.
I'd like to train an LSTM such that a prediction is made at every step of a series. So training data of one of the twelve series would be X = series[:-1, :], Y = series[1:, :] and similarly for all twelve versions.
# Example data, numbers not one-hot encoded for brevity
series = [1, 3, 2, 4, 7, 7, 10]
X = [1, 3, 2, 4, 7, 7]
Y = [3, 2, 4, 7, 7, 10]   # Shifted 1 step back

The twelve variations would create a natural batch, as the length does not vary. But my question to you is: can the training be arranged such that these variants are fed to the network as a batch of twelve, but the training is performed as many-to many? (one time step per one prediction)
Currently I have what seems to be a naïve approach for one single example. It feeds the time steps to the network one by one, preserving state in between:
# X = (12 * timesteps, 1, features), Y = (12 * timesteps, features)
model = Sequential()
model.add(LSTM(256, input_shape=(None, X.shape[-1]), batch_size=1, stateful=True))
model.add(Dense(Y.shape[-1], activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['categorical_accuracy'])

for epoch in range(10):
    model.fit(X, Y, epochs=1, batch_size=1, shuffle=False)
    model.reset_states()

How might the mentioned training regime be achieved for a single song of twelve variations?

A:

As you mentioned in your comment you need to wrap a LSTM layer inside TimeDistributed. This way each of the 12 variations will be processed individually. Further, since each feature vector is one-hot encoded we add a Dense layer with a softmax activation as the last layer of our network:
from keras import models, layers

n_features = 20

model_input = layers.Input(shape=(12, None, n_features))
x = layers.TimeDistributed(layers.LSTM(64, return_sequences=True))(model_input)
model_output = layers.Dense(n_features, activation='softmax')(x)

model = models.Model([model_input], [model_output])
model.compile(loss='categorical_crossentropy', optimizer='rmsprop')
model.summary()

Here is the model summary:
Layer (type)                 Output Shape              Param #
=================================================================
input_1 (InputLayer)         (None, 12, None, 20)      0
_________________________________________________________________
time_distributed_1 (TimeDist (None, 12, None, 64)      21760
_________________________________________________________________
dense_1 (Dense)              (None, 12, None, 20)      1300
=================================================================
Total params: 23,060
Trainable params: 23,060
Non-trainable params: 0
_________________________________________________________________

Note that this model may be very simple for your problem. You may wish to stack more LSTM layers on top of each other and change parameters to get better accuracy depending on the specific problem you are trying to solve (at the end you must experiment!); but it gives you a rough idea of what a model may look like in this scenario. Although it may seem slightly irrelevant, I suggest you to read the Seq2Seq tutorial in Keras official blog to get more ideas in this regard.
As a side note, if you are using a GPU then you can use CuDNNLSTM layer instead of LSTM; it gives much better performance on GPU.


Q:

SonarQube REST APIs : Read Metrics for individual projects

My question:
I am using SonarQube version 7.1 and trying to extract the metrics and quality gate related to individual projects.
What we have tried
We were using Python SonarQube API to extract these data before our company upgraded to version 7.1. "api/resources" web service Deprecated since sonarqube5.4, so we cannot use it anymore.
I have also tried using getting data using CURL command via Web API using
curl -i -H "Content-Type: application/json" -H "x-api-key:token" -X GET 'http://MY_HOST/api/measures/component?metricKeys=key&component=project_key'
 We are able to get a json payload for individual metrics, but involves tedious task of creating the URL every single time.
But I wanted to know if there is a better/smarter way to access these "measures", be it any language or implementation.

A:

You could do this:
Call the API api/metrics/search first to get a (json) list of all the metrics and then iterate over that list and create a comma separated string of all the metric keys.
For example something like this: ncloc,complexity,violations .. as mentioned in the parameters example value in the API documentation here.
Then you could just add this comma separated list to the url as a parameter  something like: http://MY_HOST/api/measures/component?metricKeys=ncloc,complexity,violations&component=project_key
and call it once to get the response for all metrics.
Also, I haven't tried this, but as per the latest documentation, the parameter component is optional. So if you omit that, ideally you should get a response with metrics of all the projects.


Q:

How to avoid & popup when SQL query contain '&' letter?

I am writing a migration script where I replaced html encoded values by original values like & will get replaced by &. So my SQL query has & letter but when I execute this query it give me popup for every & to replace that character which is as shown below

After clicking on OK its giving anexpecetd result but actually this popup should not come for every &. What should have to do to avoid this popup?

A:

At the top of your script, add:
set define off;