Q:

Stata margins/marginsplot into R?

I am trying to replicate a Stata marginsplot into R, but have not been able to do so, even after browsing StackExchange and trying to figure it out for a couple of weeks.
Do you happen to know how can I recreate a plot created using marginsplot in R?
First, I generated a reproducible dataset using the following R code:
set.seed(96)
sampleData <- data.frame(
    ID = 1:200,
    outcome = sample(1:7, 200, replace = T),
    scale = sample(1:7, 200, replace = T),
    dummy1 = sample(0:1, 200, replace = T),
    dummy2 = sample(0:1, 200, replace = T))
write.dta(dataframe, "sampledata.dta")

Then, I read the data into Stata and run the following commands to get the attached graph:
   reg outcome dummy1##c.scale dummy2##c.scale

   margins dummy1 dummy2, at(scale=(1(1)7))

   marginsplot, recast(line) name(outcome, replace)

Essentially, when this code is run in Stata I get the graph that I am trying to replicate in R:

Do you have any pointers that would help me replicate this graph?

A:

# your data
set.seed(96)
sampleData <- data.frame(
    ID = 1:200,
    outcome = sample(1:7, 200, replace = T),
    scale = sample(1:7, 200, replace = T),
    dummy1 = sample(0:1, 200, replace = T),
    dummy2 = sample(0:1, 200, replace = T))

# all possible combinations
newData <- data.frame(scale=rep(1:7, each=4),
    dummy1=rep(c(0, 0, 1, 1), 7),
    dummy2=rep(0:1, 2*7))
newData$dummy <- paste(newData$dummy1, newData$dummy2)

a <- lm(outcome ~ dummy1*scale + dummy2*scale, data=sampleData)

b <- predict(a, newdata=newData, interval="confidence")

c <- cbind(newData, b)

require(ggplot2)

# one pane
d <- ggplot(c, aes(scale, fit, color=dummy))
d <- d + geom_line()
# d <- d + facet_grid(dummy1 ~ dummy2)
d <- d + geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.25)
d

# using facets
e <- ggplot(c, aes(scale, fit))
e <- e + geom_line()
e <- e + facet_grid(dummy1 ~ dummy2)
e <- e + geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=0.25)
e

I should include the plots.


Q:

Equation of a line passing through a point and forming a triangle with the axes

How can I find the equation of a line that;

is passing through the point (8, 6) and
is forming a triangle of area 12 with the axes

?
So I tried to start using $A = |{\frac{mn}{2}}|$ and got that $m\cdot n$ is either -24 or 24. What now?

A:

Equation of lines that passes through $(8,6)$ is $y=ax+6-8a$
and with axes that has common points $(0,6-8a),(8-\frac{6}{a},0)$. Then the surface of right triangle is
$$S=\frac{(8-\frac{6}{a})(6-8a)}{2}=12$$
after simplification we get equation
$$16a^2-30a+9=0$$
with solutions
$$a_1=6,a_2=24$$
there exists two lines with such proppertie
$$l_1:y=6x-42$$
$$l_2:y=24x-186$$


Q:

Octave to Java - InitializeThetas Function

Hi guys I´m new in java.
I'm trying to convert an octave function in to Java(using JBlas) but I´m not sure how to do this line:
OCTAVE: Thetas{i} = rand(sizes(i+1), sizes(i) + 1)*2*EPSILON-EPSILON;

My code in Java:
public class InitializeThetas {

    public static DoubleMatrix InitializeThetas(DoubleMatrix sizes, double epsilon)
    {
       int L= sizes.length;
       epsilon = 0.03;
       DoubleMatrix Thetas = new DoubleMatrix(new double[]{});
       Random r = new Random();

        for (int i = 1; i <= L - 1; i++)
        {
            //Thetas{i} = rand(sizes(i+1), sizes(i) + 1)*2*EPSILON-EPSILON;

            Thetas.data[i]= r.nextInt() * 2 * epsilon - epsilon;
        }
       return Thetas;
    }
}

A:

Is this close to what you want?
public class InitializeThetas {

    public static Collection<DoubleMatrix> InitializeThetas(DoubleMatrix sizes, double epsilon)
    {
        int L= sizes.length;
        epsilon = 0.03;
        Collection<DoubleMatrix> Thetas = new ArrayList<DoubleMatrix>();

        for (int i = 0; i < L - 1; i++)
        {
            Thetas.add(DoubleMatrix.rand(Double.valueOf(sizes.get(i + 1)).intValue(), Double.valueOf(sizes.get(i)).intValue() + 1).mul(2).mul(epsilon).sub(epsilon));
        }
        return Thetas;
    }

    public static void main(String[] args) {
        DoubleMatrix soze = new DoubleMatrix(10);
        for(int i = 0;i<10;i++){
            soze.put(i,i+1);
        }
        System.out.println(InitializeThetas(soze,1.1));
    }

}


Q:

Dialog is taking the whole screen width

I have made a custom Dialog
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical"
    android:id="@+id/dialog_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/dialog_text_padding"
    android:paddingRight="@dimen/dialog_text_padding"
    android:paddingTop="@dimen/dialog_text_padding">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dialog_heading"
        tools:text="Permissions"
        android:textStyle="bold"
        android:textColor="@color/brand_color"
        android:textSize="22sp"
        />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/dialog_text"
        android:clickable="true"
        android:layout_marginTop="@dimen/padding_large"
        android:textSize="18sp"
        tools:text="This app determines your phone location and shares it with Google to server personalized alters for you. This allows for a better app pferformance"/>

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="24dp"
        android:id="@+id/okCancelView"
        android:paddingTop="@dimen/dialog_text_padding"
        android:paddingLeft="@dimen/dialog_text_padding"

       >

        <TextView
            android:layout_width="wrap_content"
            android:layout_toLeftOf="@+id/dialog_cancel"
            android:layout_marginRight="@dimen/dialog_text_padding"
            android:gravity="center"
            android:layout_height="wrap_content"
             android:paddingTop="10dp"
            android:paddingBottom="10dp"
            android:paddingLeft="20dp"
            android:paddingRight="20dp"
            tools:text="OK"/>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            tools:text="CANCEL"
            android:padding="10dp"
            android:layout_alignParentRight="true"
            android:textColor="@color/dialog_heading"
            android:gravity="center"/>

        </RelativeLayout>

</LinearLayout>

I am showing it with simple
Dialog d=new Dialog(this);
d.setContentView(R.layout.custom_dialog);
d.show();

But my dialog is taking full width of the screen( image attached). Why is there no space between screen and dialog?

A:

Display display = ((Activity) ctx).getWindowManager()
                    .getDefaultDisplay();
            Point size = new Point();
            display.getSize(size);
            int width = size.x;
            alert_dialog.getWindow().setLayout((int) (width * .89),
                    LayoutParams.WRAP_CONTENT);


Q:

Should you use 'isEqual' or '=='?

I saw a couple of questions here on SO, with ansers including the function isEqual: instead of the standard ==.
So far, I have only learned to use the ==, so I'm wondering what's better to use, what are the pros and cons of each? When should you use them?
Thank you.

A:

They do different things; so you need to use the appropriate one:
Consider, if you will:
NSString *a = @"Hello!";
NSString *b = a;
NSString *c = [a mutableCopy];

if (a == b) NSLog(@"This prints");
if (b == c) NSLog(@"This doesn't");
if ([a isEqual:c]) NSLog(@"This does");

In other words; == merely checks if two pointers point to the same place, and therefore are the same object; isEqual: checks if the two objects are equal; in this case a and b are the same string, while c is a new string that is equal to a, in that it has the same characters in the same order; but it has a different class and a different address.
You'll almost always want to use isEqual: for objects, and, if they have it, a more specific comparator if they are of the same class (isEqualToString:, for example).
== on the other hand you should probably only use for integer data types. (They make little sense for objects, and less for floating point numbers.)


Q:

Delphi 10.3 Rio - Is initializaiton of inline declared record variables needed?

I am quite excited about Delphi 10.3 Rio inline variable declarations. However I ran into strange problem and it seems that I need to initialize record after it has been inline declared:
program Project8;
{$APPTYPE CONSOLE}
{$R *.res}

uses System.SysUtils,classes;

procedure DoEvil;
  //var sr:TSearchRec; //A
begin
  //var sr:= default(TSearchRec); //B
  var sr:TSearchRec; //C
  sr.Name := EmptyStr; //D
  FindFirst('*.*',faAnyFile,sr);
  while sr.Name<>EmptyStr do
  begin
    Writeln(sr.name);
    sr.Name := EmptyStr;
    FindNext(sr);
  end;
end;

begin
  try
     DoEvil;
    { TODO -oUser -cConsole Main : Insert code here }
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  readln;
end.

The code works fine if I declare sr on line:

//A (old style declaration) or on line
//B (inline declaration with initialization).

However if I declare sr on line

//C then it crashes on line //D, respective in system.pas on line  26222:
MOV     ECX,[EDX-skew].StrRec.refCnt    { fetch refCnt                 }

with exception:

Exception class $C0000005 with message 'access violation at
  0x0040ac98: read of address 0xfffffff9'. Process Project8.exe (18928)

I would assume from the address -6, that the string member sr.name is not initialized and is nil.
Just to be complete, Delphi is the new 10.3 release 1:
Embarcadero® Delphi 10.3 Version 26.0.33219.4899 - Installed Update 1

A:

I took a look in the CPU window and found a few oddities.
If I use the old-style var-block (your version // A), the CPU window shows a call to System._InitializeRecord, as it should. All is fine and normal.
If I use the inline declaration with Default() (your version // B), the local record is nilled out, then finalized using System._FinalizeRecord and then nilled out again. That is pretty weird and useless, but it works.
But if I use your version // C, nothing is done to initialize the record: no nilling out, no _InitializeRecord. When I tested your code, things did work, but I was probably just lucky.
So this is clearly a bug. Please report it to the Embarcadero Quality Portal.

I guess this is a remainder of the changes made to the compiler when default constructors, default destructors and overloaded assignment operators were tested (but then removed and postponed to a next release). Some of these changes were rather braindead (like the nilling, finalization and nilling again, as in version B), and I guess some of these changes were forgotten.
Update
Obviously this was already reported to QP:

https://quality.embarcadero.com/browse/RSP-21632
https://quality.embarcadero.com/browse/RSP-23417
https://quality.embarcadero.com/browse/RSP-23747


Q:

Compiling libavcodec with emscripten (with hardware acceleration)

I am trying to compile libavcodec library with emscripten to generate a wasm to be used in a web project. It works, but I wanted to enable hardware acceleration (at least for OSX) but I cannot make it working.
I am using this configuration:
--cc=emcc \
    --enable-cross-compile \
    --target-os=none \
    --arch=x86 \
    --disable-runtime-cpudetect \
        --disable-asm \
    --disable-stripping \
        \
        --disable-bzlib \
    --disable-iconv \
    --disable-libxcb \
    --disable-lzma \
    --disable-sdl \
    --disable-securetransport \
    --disable-xlib \
    --disable-zlib \
        --disable-network \
    --disable-d3d11va \
    --disable-dxva2 \
    \
        --disable-all \
        --disable-everything \
        --enable-ffmpeg \
        --enable-avcodec \
        --enable-avformat \
    --enable-avutil \
    --enable-avfilter \
    --enable-swresample \
    --enable-swscale \
    --enable-decoder=h264 \
    --enable-decoder=hevc \
    --enable-encoder=mjpeg \
    --enable-vda \
    --enable-hwaccel=h264_vda \
    --enable-vaapi \
        --enable-shared
but the result is: no hwaccels enabled. Is there something I am missing in the configuration?
Thanks

A:

Incompatible requirements. WASM does not (and can not) support vaapi, h264_vda or anything else that requires low level kernel/driver integration.


Q:

*Simple* FLV player (no logo, no advertisement)

I'm looking for a simple FLV player for my flv videos on Drupal.
I just want Play / Pause Button, mute volume option and eventually progress bar... (without logo or commercials)
thanks

A:

flowplayer is GPL


Q:

Kelly criterion for SnG

This paper has the correct formula for the Kelly criterion for SNG's where there are multiple outcomes. It stated it is more correct than the one given on sitandgoplanet.

The problem is I do not know how to do the maths. Can someone give a clear step-by-step calculation on how that x value is derived?

A:

If you have a little background in calculus, you'll notice that the dg(x)/dx line is the derivative of g(x) and then is set equal to 0 to find the critical point which in this case will be a maximum point and thus the optimal fraction of the bankroll to bet.  Here is a little background/refresher on performing derivatives with log functions.
Whether or not you understand how to arrive at the derivative of log functions yourself, these particular ones boil down to a simple formula:
the derivative of a*log(b+cx) = ac/(b+cx), where a, b, and c are constants.
With this example, you have three terms with their respective a, b, and c values being: (0.62, 1, -1); (0.24, 1, 1);  (0.14, 1, 3). Plugging these into the above formula gets you to the dg(x)/dx line and from there you'll use some algebra to combine terms and solving for x.


Q:

Sharing an object through several classes

I need to share 1 instance between several classes.
The Connect class has methods to create a URL and to download data, and the ui is the interface (swing form) through which I get the data to build the url (dates theat comprise the url).
What's the best way to do it?
Thought of:
1) Making it global by:
public class Global {

public static  Connect c;
}

2) Making the instance in main(), and passing it through objects.
public static void main(String[] args) throws IOException {

           Connect c = new Connect();   // get url to download from
           ui form = new ui(c);         // the form to get data from
.
.
.

What seems more reasonable, if any?
Thank you.

A:

The preferred way is usually to pass the instance into the constructor of whatever class needs it. That way, it's not a guess whether or not someone has set up Global.c and when it should be available to use. It also clearly documents that each class requires a Connect object. Another benefit is that if your code ever changes and you want your UI class to no longer rely on the same Global Connect instance, you no longer have to change all your code that pulls a magic instance from this global context, and you can just pass in a different object.
Do a search for something along the lines of "why are global variables bad" or "why are singleton accessors bad" and you'll get a lot more detail than my explanation. There are uses for them, but if you can avoid them up front you may save some headache down the line. As with everything, there are trade-offs for each.


Q:

How to append elements to multiple arrays on the same line?

I know it is possible to set mulitple variables to the same value on the same line :
$a, $b = "value"

My question is, Is it possible to do the same thing with Arrays and "+=" operators ?
I've tried this :
 $a = @()
 $b = @()
 $a, $b += "test"

But i get the following error :
Au caractère Ligne:1 : 1
+ $a, $b += test
+ ~~~~~~
L'expression d'affectation n'est pas valide. Vous devez placer un élément affectable, comme une variable ou une propriété, à gauche d'un opérateur
d'affectation.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : InvalidLeftHandSide

Thanks for your help !

A:

Here's one way to do it in the same line:
$a,$b | foreach {$_ += 'test'}

Edit: that actually doesn't work.  This does
$a,$b = $a,$b |% {,($_ += 'test')}

Not sure if that's any better than the iex or not.......


Q:

SAS check field by field

I try build little check process. One proc sql generated one row table (and 13 fields) and next step I need check that chosen field in the table has value <> 0.
Below my current (not completed) code with example table "have":
data Have;
   input REFERENCE_DATE
         L_CONTRACT
         L_CONTRACT_ACTIVITY
         L_LFC
         L_CONTRACT_CO_CUSTOMER
         L_CONTRACT_OBJECT
         L_CUSTOMER
         L_CUSTOMER_RETAIL
         L_DPD
         L_GL_ACCOUNT
         L_GL_AMOUNT
         L_EXTRA_COST
         L_PRODUCT;
   datalines;
450 1 9 8 6 0 4 3 0 0 0 0 0
;

Data work.Collect_data2;
    set work.have;
ARRAY tab(13) _temporary_ (0,0,0,0,0,0,0,0,0,0,0,0,0) ;
ARRAY tab_check(*) L_CONTRACT-L_CUSTOMER_RETAIL;
input id L_CONTRACT-L_CUSTOMER_RETAIL;

do j= 2 to 7;

end;

run;

I need to check field by field since L_CONTRACT to L_CUSTOMER_RETAIL (field 2 to 7).
If anyfield from this pieces has value = 0 - I need return info that something is not ok.
Thanks for help!
Best regards

A:

length flag $10.;
if whichn(0, of L_contract -- l_customer_retail) then flag='Not Ok';
else flag='Ok';

You can use the WHICHN() function to test if any value is 0 in a series of variables. No array declarations needed.  I'm confused as to why you have an INPUT statement along with a SET statement but no INFILE or 'CARDS` though.  That doesn't make sense to me.
Edit: change single dash to two dashes.


Q:

Is it possible to install Linux packages on OS X?

I know that the Mac commandline is very similar to that of Linux operating systems, so it would be nice to use some features of Linux in my Mac, specially installing Linux packages. For example, in Linux we can install a package by simply typing sudo apt-get install "package name" at the prompt. Is it possible to do something like this on Mac?

A:

Yes, it is possible to install and run a variety of UNIX applications on OS X. There are a few solutions out there, my choice and recommendation is Homebrew. I've found other solutions to be overly complex and unwieldy.


Q:

Jquery AJAX if/else based on (this).attr()

My goal is to load a recaptcha only when the user clicks on the contact page link.
I have successfully built a site that uses navigation links to load external HTML content into the index page's main content div based on the following function:
$('div#index_content').load($(this).attr('href') + ' #content');

When user clicks a navigation link, content from one of 6 individual .html or .php files is loaded into the index.html container:

Home

Fine Art

Sketches

Props

Contact

This all functions 100%.
The next step was to appended a function to the .load statement which loads a recaptcha into an empty div with id="captcha" for my contact form:
$('div#page_content').load(($(this).attr('href') + ' #contentB'),
   function() {
     Recaptcha.create("my public key", "captcha");
   }
 );

The site is still functioning at this point, but the function calling the captcha runs every time one of the navigation links is clicked, and I would like to create an if() statement that only runs the recaptcha load function if the $(this).attr('href') is loading the contact.php content. In other words, I would like it to only load the captcha when the user clicks on "Contact" in the navigation bar.
I tried these two versions of my function but the captcha doesn't load in either case:
$('div#page_content').load(($(this).attr('href') + ' #contentB'),
   function() {
       if ($(this).attr('href') == 'contact.php') {
               Recaptcha.create("my public key", "captcha");
       }
   }
 );

and...
$('div#page_content').load(($(this).attr('href') + ' #contentB'),
   function() {
       var ifContact = $(this).attr('href');
       if (ifContact == 'contact.php') {
               Recaptcha.create("my public key", "captcha");
       }
   }
 );

Can anyone tell me what's wrong with my if() statement? Does the $(this).attr('href') actually hold a value that can be equal to something?

A:

this in the inner and outer function does not represent the same object, store the value of href outside the inner function and use that value in the inner function.
var href = $(this).attr('href');
$('div#page_content').load(href + ' #contentB',
   function() {
       if (href == 'contact.php') {
               Recaptcha.create("my public key", "captcha");
       }
   }
 );


Q:

Веб программирование для новичков

Доброго времени суток, с недавних пор углубился в понимание вопросов смм и понял ,что без веб программирования заняться тем, что мне интересно не выйдет.
Итак созрел конкретный вопрос: с чего начать? Я никогда не имел дел с программированием в общем в том числе и с веб. Не велика ли пропасть и можно ли научится веб программированию не зная основ бэсика, СС+ итд? Если да, то хотелось бы услышать советов матерых девелоперов и программеров с чего начать! Ссылочки на бд,учебники и материалы для нубов:)Заранее всем огромное спасибо!:)

A:

Основа любого сайта - это html, css потом можно заняться javascript, php, кроме того после того как более менее познакомишься с html, css то осваивай и движки такие как joomla, wordpress


Q:

How to pass a url as a parameter to a handler in Django?

A project I'm currently working on has a sort of proxy functionality where users can browse to another URL through the site. I was hoping the URL could be something like this:

www.mydomain.com/browser/[URL here]

However I'm having trouble capturing a URL as a parameter like this. I think my inexperience with regex is failing me here :( My URL conf looks like this:
urlpatterns += patterns('',
    url(r'^browser/(?P<url>\w+)/$', browser_proxy, name='browser_proxy'),
)

I'm thinking the \w+ isn't sufficient to capture an arbitrary URL. Anyone know what I should be using here to capture a URL as a parameter like this?
Thanks for any help.

A:

\w means a "word" character, i.e. alphanumeric and underscore. It is equivalent to the set [a-zA-Z0-9_]. You can match any character with a period. I.e.:
urlpatterns += patterns('',
   url(r'^browser/(?P.+)/$', browser_proxy, name='browser_proxy'),
)


Q:

MVC 5 view not autoupdating partial view

I have a controller
public class AccountDetailsController : Controller
{
    private readonly IAccountStatsRepository _accountStatsRepository;

    public AccountDetailsController(IAccountStatsRepository accountStatsRepository)
    {
        _accountStatsRepository = accountStatsRepository;
    }

    public ActionResult Details(string accountEmail)
    {
        var stats = _accountStatsRepository.Get(accountEmail);

        var accountDetailsViewModel = new AccountDetailsViewModel
        {
            Email = accountEmail,
            Money = stats.TotalCredits
        };

        return View(accountDetailsViewModel);
    }

    [OutputCache(NoStore = true, Location = OutputCacheLocation.Client, Duration = 3)] // every 3 sec
    public ActionResult GetLatestLogging(string email)
    {
        //if (email == null || email != null)
        //{
            var list = new List<LogViewModel>();

            return PartialView("LatestLoggingView", list);
        //}

    }
}

And a View
@using FutWebFrontend.ViewModels
@model AccountDetailsViewModel

@{
    ViewBag.Title = "Details";
}

@Model.Email

Account details

    Money @String.Format("{0:0,0}", Model.Money)

    @Html.Partial("LatestLoggingView", new List<LogViewModel>())

    @Html.ActionLink("Back to List", "index", "AccountControl")

But when I go to my page and put a breakpoint in GetLatestLogging then nothing happens
If I hit F12 in chrome I get "Uncaught ReferenceError: $ is not defined "Details:67
From what I can gather, this should hit my Get method every 3 seconds, but I must have made a simple error somewhere

A:

Try this
$( document ).ready(function() {
setInterval(function () {$('#loggingstream').load('/AccountDetails/GetLatestLogging/@Model.Email'); }, 3000);
});


Q:

sed - how to replace meta character

In the following example I am looking to include the * metacharacter in the string replacement. If I understand correctly, I should be able to escape the character using \ but after doing that this is the result I am seeing:
❯ echo 'foo(*)' | sed s/foo\(\*/bar/g
bar*)

I was expecting to see the following:
❯ echo 'foo(*)' | sed s/foo\(\*/bar/g
bar)

A:

You need to quote your sed command:
echo 'foo(*)' | sed 's/foo(\*/bar/g'
bar)


Q:

Initialize a dynamic C array within a C++ initializer list

Most people will probably recommend that I use a std::vector or even a std::array but the custom array class below uses a C array and it works, I just need some explanation as to why it works.
For reference, here is a common way to initialize a dynamic C style array:
int* elements = new int[size];

Now below, we have our own custom array class that initializes a dynamic C style array within the initializer list.  The problem is that I don't understand how the C array is being initialized within the initializer list.
class myArray
{
public:

    myArray(int size) : size(size), elements(new int[size])
    {
        std::cout << "Constructed array of size " << size << std::endl;
    }

    ~myArray()
    {
        delete[] elements;
        std::cout << "Deleted elements" << std::endl;
    }

    int getSize() const { return size; }

private:
    int size;
    int* elements;  // our C style array
};

Thank you
UPDATE
I would like to clarify my question a little more.  Below is the old fashioned "assignment" way that I would normally initialize the dynamic C array:
myArray(int size)
{
    elements = new int[size];
    // elements(new int[size]); // why will line only work in initializer list?
    std::cout << "Constructed array of size " << size << std::endl;
}

But please see the commented line.  Why does that not work but it does work within the initializer list?

A:

I don't understand how the C array is being initialized within the initializer list.

here:
myArray(int size) : size(size), elements(new int[size])

elements are basicly assigned value returned by new int[size]
You could rewrite it as :
myArray(int size)
{
    this->size = size;
    elements = new int[size];
    std::cout << "Constructed array of size " << size << std::endl;
}

[edit]
This:
// elements(new int[size]); // why will line only work in initializer list?

will not work in the function body, because in this place compiler thinks that you want to call a function named elements, but there is no such function.
The fact that it works in the initializer list is because that is how the language syntax was made.


Q:

Make disabled Flex Spark Button more readable using CSS

I have a Flex Spark Button that I've changed the background to a dark color using
s|Button {
    color: #66ffff;
    chromeColor: #333333;
}

The problem is that when the button is disabled, it's very hard to read (the text color and background color are very close). I've tried setting the disabled color to something lighter
s|Button:disabled {
    color: #ffffff;
}

But the disabled text's color is not #ffffff. It's some combination of the text color and the background. Is there someway to disable this behavior (ie, specify the exact disabled state's text color)?

A:

You are battling with the default skin of the button.  If you were to create a new button skin based on ButtonSkin, you would see that the alpha for the entire skin is set: alpha.disabled="0.5".
Setting the value to 1.0 solves your problem, but it seems overkill to define this entire skin just to modify this single value.
Hopefully, there is a more elegant way.  I tried setting alpha: 1.0; in the disabled style, but it doesn't take.  The only thing I have been able to do is create a new button style, set alpha.disabled="1.0" and telling the button to use that slightly modified style.


Q:

java.lang.NullPointerException when using EntityManager's persist() func (Spring 4 ORM)

I have gone through numerous questions similar to this, but still stuck at a dead end.
I created my model, dao, and service classes. I am writing my JUnit test suite, however when I try to test my persisting functionality, I get a java.lang.NullPointerException. I did try to set up a few breakpoints and debug within my IDE but it is puzzling as to why this is happening.
My code for my model, dao, and service are below along with my spring.xml file.
Model (I avoided the constructor and other fields for brevity)
@Entity
public class Request implements Serializable {

    @Id
    private Integer restRequestId;

    private Timestamp restRequestTimestamp;

    private String restRequestParameters;
}

Dao
@Component
public class RequestDAO {

    @PersistenceContext
    private EntityManager entityManager;

    public void persist(Request request) {
        entityManager.persist(request);
    }

    public void update(Request request) {
        entityManager.getTransaction().begin();
        entityManager.merge(request);
        entityManager.getTransaction().commit();
    }

    public Object findById(Serializable id) {
        Request request = entityManager.find(Request.class, id);
        if (request == null) {
            throw new EntityNotFoundException("Cannot find Request for ID " + id);
        }
        return request;
    }

    public void delete(Request request) {
        entityManager.getTransaction().begin();
        entityManager.remove(request);
        entityManager.getTransaction().commit();
    }

    public void deleteById(Serializable id) {
        Request request = entityManager.find(Request.class, id);
        if (request == null) {
            throw new EntityNotFoundException("Cannot find Request for ID " + id);
        } else if (request != null) {
            entityManager.getTransaction().begin();
            entityManager.remove(request);
            entityManager.getTransaction().commit();
        }
    }

    public List<Request> findAll() {
        Query query = entityManager.createQuery("SELECT e from Request e");
        List<Request> requests = query.getResultList();
        return requests;
    }

    public void deleteAll() {
        List<Request> requests = findAll();
        for (Request request : requests) {
            delete(request);
        }
    }

}

RequestService
@Component
public class RequestService {

    @Autowired
    private RequestDAO requestDAO;

    @Transactional
    public void add(Request request) {
        requestDAO.persist(request);
    }

    @Transactional
    public void update(Request request) {
        requestDAO.update(request);
    }

    @Transactional
    public Object findById(Serializable id) {
        return requestDAO.findById(id);
    }

    @Transactional
    public void delete(Request request) {
        requestDAO.delete(request);
    }

    @Transactional
    public void deleteById(Request request) {
        requestDAO.delete(request);
    }

    @Transactional
    public void deleteAll() {
        requestDAO.deleteAll();
    }

    @Transactional
    public void addAll(Collection<Request> requestCollection) {
        for (Request request : requestCollection) {
            requestDAO.persist(request);
        }
    }

    @Transactional(readOnly = true)
    public List<Request> findAll() {
        return requestDAO.findAll();
    }
}

spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-4.2.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

    <context:component-scan base-package="com.company"/>
    <mvc:annotation-driven/>
    <context:annotation-config/>

    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver"/>
        <property name="url" value="jdbc:hsqldb:mem://requestDb"/>
        <property name="username" value="user"/>
        <property name="password" value="pass"/>
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
          p:packagesToScan="com.company"
          p:dataSource-ref="dataSource">
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="generateDdl" value="true"/>
                <property name="showSql" value="true"/>
            </bean>
        </property>
    </bean>

    <bean id="transactionManger" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManger"/>

</beans>

JUnit test class
public class RequestServiceTest {

    @Autowired
    RequestDAO requestDAO;

    @Before
    public void setUp() throws Exception {
    }

    @After
    public void tearDown() throws Exception {

    }

    @Test
    public void add() throws Exception {
        RequestService requestService = new RequestService();
        Request requestObject = new Request();
        requestObject.setRestRequestId(1);
        requestObject.setRestRequestParameters("hello");
        requestService.add(requestObject);
        Request requestResponseFromDatabase = (Request) requestService.findById(1);
        assertEquals("hello", requestResponseFromDatabase.getRestRequestParameters());
    }
}

A:

How does your unit test know that should be driven by Spring? In order to use Spring in JUnit tests, you should run with Spring (use the @RunWith(SpringJUnit4ClassRunner.class) annotation and provide some additional configuration).
Otherwise, JUnit doesn't even process the @Autowire.
You can read more on this here.


Q:

Property List Vs. NSDictionary

So I'm working on a GPA calculator app. Right now, I have my grading scale stored as an NSDictionary with a string for the key and a number for the value(i.e. @"A" --> 4.0).
I've been realizing that I often need to access the data in different ways that NSDictionary does not allow. For instance, I might like to add a tag to each entry for sorting purposes. Is this the type of things a property list is designed for? Could I have a key @"A" with a tag 1 and a value 4.0 associated with it?
I was thinking something like this:
<dict>
    <key>GradeScale</key>
    <array>
        <dict>
            <key>A_grade</key>
            <string>A</string>
            <key>point_value</key>
            <number>4.0</number>
           <key>tag</key>
           <number>1</number>
        </dict>
        <dict>
            <key>B_grade</key>
            <string>B</string>
            <key>point_value</key>
            <number>3.0</number>
           <key>tag</key>
           <number>2</number>

        </dict>
    </array>
</dict>

Is this the right track or am I not even close?
Edit:
So I've gone for an array of dictionaries with something like:
<dict>
    <key>Grade_Scale</key>
    <array>
        <dict>
            <key>string_value</key>
            <string>A</string>
            <key>point_value</key>
            <real>4</real>
            <key>Tag</key>
            <integer>1</integer>
        </dict>
        <dict>
            <key>string_value</key>
            <string>A-</string>
            <key>point_value</key>
            <real>3.7</real>
            <key>Tag</key>
            <integer>2</integer>
        </dict>

All I really wish to do is be able to reference a certain value by string_value, point_value, or tag. Does the above allow me to do this?

A:

A property list is just a file format.  NSDictionary is a class.  They are not interchangeable.

It's not clear (to me at least) the relationship between what you want to store. (so there might be a better structure)
If this dictionary is to hold not the numerical values of letter grades (i.e. "an 'A' is worth 10 points in my GPA") and instead the actual grades for courses:  then maybe what you need is an array holding dictionaries.
Array            // Holding each 'courses'.
of Dictionaries  // Where everything about the courses is stored:
                 //     {"name" => "Biology"
                 //      "grade" =>  ...
                 //      "tag"  => "science"
                 //      "scoreWeight"  =>   0.8  // this is worth 80% of my total score

You can then easily sort the course array however you please.


Q:

Using a super-cap with a PIC24F to keep time in case of supply failure

I want to use a 0.1F 5.5V supercap to keep time with a PIC24FJ64GA004 device. Does anyone have any idea on how to implement this?
I was thinking of using the supercap on the +3.3V supply line and monitoring the battery input. When the main supply drops below say 5V I would put the micro into ultra low power sleep mode (~400-500nA with RTCC.)
Does anyone know how long a 0.1F cap lasts with <1µA current draw? It'll be charged up to 3.3V and 2.0V is the terminal voltage, though it would probably work down even lower.

A:

According to page 4 this document, a 0.047F 5.5V supercap will drop from 3.3v to 2.0v in about 18 hours with a 3.75M load (<1µA).  So I would expect your 0.1F cap to do about twice that.


Q:

Keras fit_generator with pandas iterator object

I've got a csv too big to read into memory at once so I want to chunk it out and fit a keras model with it piece by piece. I think I'm misunderstanding how the fit_generator function works though since I keep getting StopIteration errors even though the chunksize & steps_per_epoch correctly account for how many rows are in my csv.
Code:
import pandas as pd
import numpy as np
from keras.models import Sequential
from keras.layers import Dense, Dropout

np.random.seed(26)
x_train_generator = pd.read_csv('X_train.csv', header=None, chunksize=150000)
y_train_generator = pd.read_csv('Y_train.csv', header=None, chunksize=150000)
x_test_generator = pd.read_csv('X_test.csv', header=None, chunksize=50000)
y_test_generator = pd.read_csv('Y_test.csv', header=None, chunksize=50000)

model = Sequential()
model.add(Dense(500, input_dim=1132, activation='tanh'))
model.add(Dense(1, activation='sigmoid'))

model.compile(loss='binary_crossentropy', metrics=['accuracy'],
              optimizer='adam')

model.fit_generator((x_train_generator.get_chunk().as_matrix(),
                     y_train_generator.get_chunk().as_matrix()),
          steps_per_epoch=37,
          epochs=1,
          verbose=2,
          validation_data=(x_test_generator.get_chunk().as_matrix(),
                           y_test_generator.get_chunk().as_matrix()),
          validation_steps=37
            )

Error output:
Exception in thread Thread-107:
Traceback (most recent call last):
  File "/usr/lib/python2.7/threading.py", line 801, in __bootstrap_inner
    self.run()
  File "/usr/lib/python2.7/threading.py", line 754, in run
    self.__target(*self.__args, **self.__kwargs)
  File "/home/user/myenv/local/lib/python2.7/site-packages/keras/utils/data_utils.py", line 568, in data_generator_task
    generator_output = next(self._generator)
TypeError: tuple object is not an iterator

---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
/home/user/tmp_keras.py in <module>()
     22           verbose=2,
     23           validation_data=(x_test_generator.get_chunk().as_matrix(), y_test_generator.get_chunk().as_matrix()),
---> 24           validation_steps=37
     25                 )
     26

/home/user/myenv/local/lib/python2.7/site-packages/keras/legacy/interfaces.pyc in wrapper(*args, **kwargs)
     85                 warnings.warn('Update your `' + object_name +
     86                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 87             return func(*args, **kwargs)
     88         wrapper._original_function = func
     89         return wrapper

/home/user/myenv/local/lib/python2.7/site-packages/keras/models.pyc in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weight, max_$ueue_size, workers, use_multiprocessing, initial_epoch)
   1119                                         workers=workers,
   1120                                         use_multiprocessing=use_multiprocessing,
-> 1121                                         initial_epoch=initial_epoch)
   1122
   1123     @interfaces.legacy_generator_methods_support

/home/user/myenv/local/lib/python2.7/site-packages/keras/legacy/interfaces.pyc in wrapper(*args, **kwargs)
     85                 warnings.warn('Update your `' + object_name +
     86                               '` call to the Keras 2 API: ' + signature, stacklevel=2)
---> 87             return func(*args, **kwargs)
     88         wrapper._original_function = func
     89         return wrapper

/home/user/myenv/local/lib/python2.7/site-packages/keras/engine/training.pyc in fit_generator(self, generator, steps_per_epoch, epochs, verbose, callbacks, validation_data, validation_steps, class_weig
ht, max_queue_size, workers, use_multiprocessing, shuffle, initial_epoch)
   2009                 batch_index = 0
   2010                 while steps_done < steps_per_epoch:
-> 2011                     generator_output = next(output_generator)
   2012
   2013                     if not hasattr(generator_output, '__len__'):

StopIteration:

Weirdly, if I wrap the fit_generator() in a while 1: try: ... except StopIteration: it manages to run.
I've tried using x/y_train_generator in the fit_generator arguments without the get_chunk().as_matrix() functions but it fails since I'm not passing keras a numpy array.

A:

As mentioned in the comments, your issue is that Pandas .get_chunk() returns an iterator, which is what the .as_matrix() method is called on (and not what you want to happen - you want the iterator returned by .get_chunk() to be transformed into a DataFrame first, then .as_matrix() to be called).
To restructure your code, you'll need a loop, and you'll need to update your model inside the loop. I have two suggestions for you:

(Easiest) Re-structure the program above: have a loop over each chunk from Pandas as a DataFrame, before you call .as_matrix() on it. That way, you are actually getting a concrete DataFrame for your X_train, y_train, X_test, y_test data, instead of an IO iterator. You can then update your trained model using the new chunk of data. (If you already have a trained model, and you call .fit() again, it will update the existing model.)
(Using Keras functionality instead of Pandas functionality) Utilize built-in Keras utilities for reading large data sets - specifically, a Keras utility called HDF5Matrix (link to Keras documentation)  to read data from an HDF5 file in chunks, and that data will be transparently treated as a Numpy array. Something like this:
def load_data(path_todata, start_ix, n_samples):
    """
    This works for loading testing or training data.
    This assumes input data have been named "inputs",
    output data have been named "outputs" in HDF5 file,
    and that you are grabbing n_samples from the file.
    """
    X = HDF5Matrix(path_to_training_data, 'inputs', start_ix, start_ix + n_samples)
    y = HDF5Matrix(path_to_training_data, 'outputs', start_ix, start_ix + n_samples)
    return (X,y)

X_train, y_train = load_data(path_to_training_h5, train_start_ix, n_training_samples)
X_test,  y_test  = load_data(path_to_testing_h5, testing_start_ix, n_testing_samples)

Like solution #1, this would be structured within an overarching for loop that updates start_ix and n_samples within each iteration, in addition to updating (re-fitting) the model within each iteration. For another illustration of how to use HDF5Matrix see this example from Github user @jfsantos.


Q:

Python: Sort an array

I have a class that's sole purpose is to sort an array that's given as a parameter, however first of all, I'm getting an error "int not iterable." My question is what is this error and am I doing my sorting correctly?  Thanks.  Here is my sorter class being called by the other class below.
class Sorter:
    def reverseWackySort(self, vals):
        i = 0
        j = 0
        temp = 0
        length = len(vals)
        for i in length:
            for j in (length -1):
                if vals[j] > vals[j+1]:
                    temp = vals[j]
                    vals[j] = vals[j+1]
                    vals[j+1] = temp;
        return vals

Code -
from Sorter import Sorter

def TestSorter():
    rws = Sorter()

    nums = [88, 1, 7, 32, 18, 77, 34, 99, 54, 22]

    print "\nBefore Sort: ", nums

    rws.reverseWackySort(nums)

    print "After Sort:   {}\n".format(nums)

TestSorter()

A:

You are trying to iterate over an integer:
for i in length:
    for j in (length -1):

Perhaps you wanted to iterate over the range instead:
for i in range(length):
    for j in range(length -1):

range() produces a sequence of integers up to (but not including) length for you.
Note that you can swap variables in place in Python without a temporary intermediary:
vals[j], vals[j+1] = vals[j+1], vals[j]

and you don't need to 'pre-declare' variables either; the i = 0, j = 0 and temp = 0 lines are redundant.


Q:

Change slave's IP

Had an existing slave node that performed jobs perfectly.
Recently replaced said slave node with a new machine and different IP address.
I want to edit the IP of the old slave node to use the IP of the new slave node, but keep all the old configuration.  However, when I go to Jenkins -> Manage Jenkins -> Manage Nodes -> myNode, -> configure...I don't see anywhere to edit the IP.
What am I missing?

A:

Ensure that you have installed SSH Slaves plugin.
1) Go to
Jenkins -> Manage Jenkins -> Manage Nodes -> myNode -> configure

2) Check the Launch method option,
Select Launch slave agents on on Unix machines via SSH option.
Check the Host option is present.You can edit your IP Address.
3) Also Click on Advanced you can get more options regarding slave node like port etc.


Q:

Views Dependent Filter showing when no controller value selected

I'm using Views Dependent Filters to have a filter show based on the value of a filter above it. It is working for the most part but it is showing the field by default (when no controller value is selected.)
When my multiple select filter  being used as the controller, the dependent field shows even when no value is selected. For example:
Vehicle:

Car (Set as controller)
Boat
Plane

Tire Size (Dependent Filter)

Small
Med
Large

Tire size shows when "car" is selected but also shows when no value is selected. I believe this the module is not intended to function this way.
Is there a solution to this or a possible alternative?

A:

This was a bug relating the default views multiple select filter. I used the Better Exposed Filters checkboxes and now the dependent filter works as intended.


Q:

Bootstrap 4: Always display the mobile menu button no matter screen size

How can I get always display the mobile menu button no matter screen size? I do not want the links to appear until a person clicks the mobile button. Thank you!
I realize there is a post here on Bootstrap 3, however it does not work with Bootstrap 4. Will you please advise?

A:

Update Bootstrap 4.1.x
Exclude the navbar-expand* class.
As of beta, the navbar-toggleable-* class was replaced with navbar-expand-*, but now everythings moves up a tier. Since the default state of the navbar is always collapsed/mobile (xs) you'd simply exclude the navbar-expand-* class so that the menu is always collapsed on all tiers.
Beta demo: https://www.codeply.com/go/HiMQd9taEd
Bootstrap 4.1.3: https://www.codeply.com/go/ugmj6XKY79

Original Answer (Bootstrap 4 alpha)
In Bootstrap 4 the navbar is very different than 3.x, and it is always collapsed unless overriden by one of the navbar-toggleable-* classes. You just need to make sure your navbar doesn't include navbar-toggleable-*.

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#collapsingNavbar">

    </button>
    Navbar

                Home

                Features

                Wow

Alpha demo: http://www.codeply.com/go/LN6szcJO53


Q:

Gson deserialisation generates NULL value

I was trying to read and convert a JSON file to an array but getting null values from the array after reading the JSON file. I am using the default constructor for my ShipDetail class.
  BufferedReader detailReader = new BufferedReader( new  FileReader(shipDetails));
  // Buffered passed to convert json array to java array
  ShipDetail[] shipDetail  = gson.fromJson(detailReader, ShipDetail[].class );

  System.out.println( shipDetail[0].toString());

  // Convert  array to arrayList
  ArrayList<ShipDetail> detailArray = new ArrayList<ShipDetail>(Arrays.asList(shipDetail));

The JSON file:
[
   {
      "idmessage":"27301",
      "idsession":"362",
      "time_stamp_system":"2017-01-20 14:51:14",
      "NMEA_string":"xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx",
      "processed":"1",
      "MMSI":"0000000001",
      "AIS_version":"0",
      "IMO_number":"xxxxxxxxxx",
      "callSign":"ODLK1",
      "name":"ODLXJ KWW",
      "type_of_ship_and_cargo":"0",
      "bow_to_possition_unit":"212",
      "stern_to_possition_unit":"71",
      "port_to_possition_unit":"22",
      "starboard_to_possitio_unit":"22",
      "type_of_position_fixing_divice":"1",
      "ETA":null,
      "destination":"",
      "last_static_draught":"0",
      "DTE":"127"
   }
]

The ShipDetail class:
public class ShipDetail {

    private String IdMessage, IdSession, Time_Stamp_System, Nmea_String, Processed;
    private String Mmsi, Ais_Version, Imo_Number, Callsign, Name, Type_Of_Ship_And_Cargo;
    private String Bow_To_Position_Unit, Stern_To_Position_Unit, Port_To_Position_Unit, Starboard_To_Position_Unit,
            Type_Of_Position_Fixing_Device;
    private String Eta, Destination, Last_Ship_Draught, Dte;

    public String getMmsi() {
        return Mmsi;
    }

    public String toString() {
        return "\n Id Message : " + IdMessage + "\n Id Session : " + IdSession + "\n Time Stam System : "
                + Time_Stamp_System + "\n NMEA String : " + Nmea_String + "\n Processed : " + Processed + "\n MMSI : "
                + Mmsi + "\n AIS Version : " + Ais_Version + "\n IMO Number : " + Imo_Number + "\n Call Sign : "
                + Callsign + "\n Name : " + Name + "\n Type Of Ship And Cargo : " + Type_Of_Ship_And_Cargo
                + "\n Bow To Position Unit : " + Bow_To_Position_Unit + "\n Stern To Position Unit : "
                + Stern_To_Position_Unit + "\n Port To Position Unit : " + Port_To_Position_Unit
                + "\n Starboard To Position Fixing Device : " + Starboard_To_Position_Unit
                + "\n Type Of Position Fixing Device : " + Type_Of_Position_Fixing_Device + "\n ETA : " + Eta
                + "\n Destination : " + Destination + "\n Last Ship Draught : " + Last_Ship_Draught + "\n DTE : " + Dte;
    }
}

A:

Your Gson mapping does not match the given JSON. By default, Gson maps JSON properties to their appropriate fields in the target mapping by exact name. Take a look at:
"idmessage":"27301"

and
private String IdMessage

The property name case and the field name case do not match. What you need is map your JSON correctly. Either:
private String idmessage

or by overriding the name match (and that's more appropriate for the Java naming conventions):
@SerializedName("idmessage")
private String idMessage;

Note one field per line. This is required in order to annotated each field separately. Or, if possible, use camelCase both in Java and JSON.


Q:

Best way to get underlying data from MemoryStream?

The bytes are written to MemoryStream object and there is a need to get underlying buffer to save it to file
MemoryStream ms = new MemoryStream();
// ms.Write(...)
// ms.Write(...)
// etc... some bytes are written to the stream

byte[] data = ms.GetBuffer();
int length = data.Length;

However the returned data is of ms capacity rather than the real ms length.
Is it better (faster, safer, ...) to set ms capacity to its length or allocate a data and copy ms contents into it?

A:

just use the member-method ms.ToArray()


Q:

Is there an authentic hadith where a woman is forbidden from leaving the house while her father dies, but they're forgiven for her obedience?

From ImamReza.net we have the following hadith (listed as by Hojjat al-Islam Shaykh Husain Ansariyan):

Imam Sadiq said: One of the men from the Helpers (Ansar) went on a trip and ordered his wife not to leave the house until he returned home. Her father got ill while her husband was away. She sent a messenger to the Prophet (S.A.W.) asking him if she could visit her father. The Prophet (S.A.W.) replied that she should obey her husband and stay at home. Her father got worse and she sent another message but received the same reply. Her father passed away and she sent another messenger to go and pray for her father, but she received the same reply. They buried her father but the woman stayed at home. The Prophet (S.A.W.) sent a messenger to her and he said that God forgave you and your father for obeying your husband.

I also found it included at erfan.ir, at duas.org, and in a comment at BabyCenter.com.  I've seen hadith with this meaning mentioned before (a woman is forbidden by her husband from leaving the house as her father dies), but I can't seem to pinpoint a reliable reference currently.
Question: Is there an authentic hadith where a woman is forbidden from leaving the house while her father dies, but they're forgiven for her obedience?

A:

This hadith is included in One Hundred Weak or Fabricated Traditions by Shaykh Ihsan Al-‘Utaibi (pdf).  It is described as:

41 - ((There was once a certain man who set out on a journey after having covenanted with his wife not to leave their house. Her father was downstairs, and she was upstairs. When he (her father) fell ill, the woman sent for the Messenger of Allah asking his permission to go down to see her father. The Messenger of Allah said, 'Obey your husband.' The father died. She sent to Prophet Mohammed once again [to get permission to see her father], but he said again, 'Obey your husband.' Her father was buried. The Messenger of God sent a message to her that her father was forgiven on account of her obedience to her husband)).

In this work, it's classified as weak:

Weak; Al-Haythami said: [it is] narrated by Al-Tabari in "Al-Awsaat", and in it (i.e. the chain) is 'Aismah ibn Al-Mutawakil and he is weak. Al-Albani said: narrated by Al-Tabari in "Al-Awsaat" from the way of 'Aismah ibn Al-Mutawakil … and he is weak, and his shaykh Zafir ibn Sulaiman Al-Quhistani is also weak. Also narrated by 'Abd ibn Hameed (1369), from another way, but in the chain is Yousif ibn 'Atiyah and he is Matrouk, "Irwaa' Al-'Galeel" (7/76), and "Majmaa' Al-Zawaid" (4/313)


Q:

What is the Funko Pop! Howard the Duck bobble-head holding?

The Funko Pop! Howard the Duck bobble-head is carrying some sort of brown rectangular object. Does anyone who is more familiar with the character than I am know what it is?

A:

The official blurb mentions only his hat and trademark suit, clearly implying that he's simply holding his lapel.
It does however mention that because they're hand-painted, they may not always be perfect, which appears to be the case with your figure:

The perfect addition to your Funko collection this official Guardians
  of the Galaxy Howard the Duck vinyl figure is a cool option for any
  fan Marvel fan! Series 64 this figure sees Howard the Duck as featured
  within the much loved end credits scene of the 2014 Guardians of the
  Galaxy movie. This figure is packed with detail showcasing Howard the
  Duck with his distinguished suit and hat as featured within the after
  credits collectors scene. This Funko Pop! Guardians of the Galaxy
  Howard The Duck vinyl figure measures 3.75 inches and is presented in
  a window box packaging. Perfect for any Marvel fans this official
  Guardians of the Galaxy Howard the Duck figure is a must-have addition
  to your Funko Pop! collection. The anthropomorphic funny guy character
  Howard the Duck is seen within the end credits of the 2014 summer
  blockbuster Guardians of the Galaxy; after being freed from his cage,
  Howard is seen sipping a martini after the destruction of Taneleer
  Tivan's museum. Please note each Funko Pop! vinyl figure is hand
  painted allowing for a unique finish, meaning the figure may be
  subject to imperfections.

A:

It's his lapel.
You can see that there's nothing else in his hands by watching some unboxing videos, but I think the official sales images show it clear enough.

The gesture/affectation matches the style of the clothing Howard is wearing.


Q:

Any alternative to Python pickle?

When i try to use pickle to load a dumped file, python crashes with code CLR20r3 !! I wanna know if there are any alternatives to pickle, that can dump a python object and load it back. 3rd party libraries are acceptable.

A:

I think the best answer you are going to get for the information you have provided is this...
No other serialization format is going to make your situation better. pickle handles native Python objects a lot more gracefully than something like JSON. Any other format will require you to define handlers to help it serialize objects it can't handle.
The best route for you is to try and solve why pickle is failing.


Q:

Keepalived load balancing MySQL. Backup server time-out

Dear beloved people at ServerFault. I'm trying (and failing) to setup a load balanced MySQL server array. Please enlighten me, show me the error in my ways.
Current setup: two MySQL servers with dedicated fixed IP's (10.116.219.47 & 10.116.219.48) and one virtual IP that is shared using keepalived (10.116.219.12). This setup is successful in providing failover. DB2-server quickly takes over if we turn off DB1-server. It's only when adding a virtual_server block to the config, that things start to break.
DB1
vrrp_instance VI_2 {
    state MASTER

    interface eth0
    virtual_router_id 60
    priority 150

    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 3S83hbt200SbwY6
    }
    virtual_ipaddress {
        10.116.219.12
    }
}

DB2
vrrp_instance VI_2 {
    state BACKUP

    interface eth0
    virtual_router_id 60
    priority 100

    advert_int 1
    authentication {
        auth_type PASS
        auth_pass 3S83hbt200SbwY6
    }
    virtual_ipaddress {
        10.116.219.12
    }
}

We've been trying to add load balancing to the keepalived config, but here DB2 stops responding.
virtual_server 10.116.219.12 3306 {
  delay_loop 2
  lb_algo rr
  lb_kind DR
  protocol TCP

  real_server 10.116.219.47 3306 {
    weight 10
    TCP_CHECK {
      connect_port    3306
      connect_timeout 1
    }
  }

  real_server 10.116.219.48 3306 {
    weight 10
    TCP_CHECK {
      connect_port    3306
      connect_timeout 1
    }
  }
}

Trying to connect to the virtual ip (10.116.219.12) will alternate on a successful response from DB1, or a time-out from DB2.
Debugging so far:

MySQL connecting to the fixed ip's works on both DB1 and DB2. Firewall/MySQL binding is not blocking incoming connections.
Set net.ipv4.ip_forward=1 on both DB1 and DB2
Listening for TCP inbound connections on DB2 will show up the attempt. (20:46:08.385786 IP 10.116.219.44.46211 > 10.116.219.12.mysql)

So it appears that DB2 MySQL-server refuses to respond, my guess is because the incoming packet destination (the shared virtual ip) is not known to the DB2 server, because DB1 is carrying it as keepalived master.

A:

Since you are using direct routing the virtual IP will need to be configured on both servers at the same time.  You can accomplish this by having a second vrrp instance which configures the VIP (10.116.219.12) on the loopback interface of the secondary server.  When the connection is forwarded from the load balancer to the secondary server it will respond back out on eth0 as normal.
If you do this you'll need to disable source routing via sysctl. For example:

# Do not accept source routing
net.ipv4.conf.default.accept_source_route = 0

Additionally you'll need to change how ARP is announced and responds to requests (more information):

net.ipv4.conf.eth0.arp_ignore = 1
net.ipv4.conf.eth0.arp_announce = 2
net.ipv4.conf.all.arp_ignore = 1
net.ipv4.conf.all.arp_announce = 2

Also, configure rp filtering:

net.ipv4.conf.eth0.rp_filter = 1 # Works for CentOS 5
or
net.ipv4.conf.eth0.rp_filter = 2 # Works for CentOS 6+

The default rp_filter setting can vary between kernel versions, so make sure you choose the correct setting.  More information.


Q:

SCCM report to return KB status on servers

I am trying to create a custom report in SCCM which will tell me if a specific KB is installed on a pool of servers, and return a binary answer (in this case, yes or no).
The problem I have is I cannot get it to return the status of just one KB. I am running this:
SELECT
 SYS.Name0 'Computer',
 SYS.operatingSystem0 'OS',
 UIN.Title 'Update',
 CASE
  WHEN UIN.Title LIKE '%KB3092627%' THEN 'Yes'
  ELSE 'No'
  END 'KB Installed'

FROM v_R_System SYS
 INNER JOIN v_UpdateComplianceStatus UCS ON SYS.ResourceID = UCS.ResourceID
 INNER JOIN v_UpdateInfo UIN ON UCS.CI_ID = UIN.CI_ID

WHERE SYS.operatingSystem0 LIKE '%Server 2008%'

ORDER BY SYS.Name0

but I get hundreds of results for each SYS.Name0, one for every detected update. All records for updates which arent the desired KB have a value of 'No' for KB Installed, but they are still listed. I tried SELECT DISTINCT to see if it got me different results, but it does not.
What I want is to determine if the KB is present, and return if it is or not. I feel like I'm not even asking the fundamental question of "Is  installed or not" with this code, but I can't think of a way to ask this differently. Is this something I should be doing in Report Builder instead of the query?

A:

Disclaimer: I haven't tested this on a representative data set as you didn't provide one, but I think this should do what you're trying to achieve:
SELECT DISTINCT
    s1.Name0 'Computer',
    s1.operatingSystem0 'OS',
    CASE WHEN matches.Computer IS NULL THEN 'No' ELSE 'Yes' END 'KB Installed'
FROM v_R_System s1
LEFT JOIN
(
    SELECT s2.Name0 'Computer',
    FROM v_R_System s2
    INNER JOIN v_UpdateComplianceStatus UCS ON s2.ResourceID = UCS.ResourceID
    INNER JOIN v_UpdateInfo UIN ON UCS.CI_ID = UIN.CI_ID
    WHERE UIN.Title LIKE '%KB3092627%'
) AS matches ON s1.Name0 = matches.Computer
WHERE s1.operatingSystem0 LIKE '%Server 2008%'
ORDER BY s1.Name0

So this effectively returns the distinct list of all Computers and LEFT JOINs this to result set of just records for the update in question for each given Computer. Therefore, when the field returned from the LEFT JOIN is NULL, the update hasn't been installed and vice-versa.
And to answer your question, I personally think it's fine to be doing this in the query (as opposed to in your report somehow) - it's where I would do it.


Q:

IBM i (AS400) JVM - Is it possible to define where the JVM looks for .jar files?

We bought a solution from a provider a couple of years ago, droped the .jar file in the standard location in IFS /QIBM/UserData/Java400/ext/ and we have been working correclty ever since with this.
However a couple of months ago the provider released a new .jar with some new functions we would like to use. However they also changed the names of several classes and methods that we are using.
So what we were thinking of doing, if possible, is define a path on which the old programs when they need to use that .jar look for that .jar in the defined path. And for the new programs that we want to use the new .jar file we wanted to have different path for that.
At this point I don't know if this is possible to do. I have been searching everywhere for this information without luck. So if someone around here as some clue it would be fantastic.
Thank you for your time.
Edit: So I was reading through your advices and I have these coments.
I already asked the supplier for assistance but since this wasn't designed for AS400 they don't provide support.
I tested the possibility of the classpath. I deleted the files from the /QIBM/UserData/Java400/ext/ and put them in /QIBM/JARS/old/ then I created a CL that did this:
ADDENVVAR  ENVVAR(CLASSPATH) VALUE('/QIBM/JARS/old') REPLACE(*YES)
After I first executed this new CL then I tried a program that would use the .jar that I had in the location /QIBM/JARS/old and I got the error of the class not found. So either I did something wrong or this isn't actually a solution.
HotLicks do you mean that it is not possible to have users A1 and B1, and A1 using /QIBM/JARS/old/A.jar and B1 using /QIBM/JARS/new/A.jar at the same time?

A:

You can adjust the Java classpath.


Q:

Issues running haxe application in osx terminal with createjs library

When running this command
haxe -main Main.hx

I'm getting this error
Main.hx:2: characters 7-33 : Type not found : createjs.easeljs.Container

Main.hx
package ;
import createjs.easeljs.Container;
import createjs.easeljs.Shape;
import createjs.easeljs.Stage;
import createjs.easeljs.Text;
import createjs.easeljs.Ticker;
import js.Browser;
import js.html.CanvasElement;
import js.html.Element;

I've included the javascript file for the createjs library and I also installed the library using the command
haxe install createjs

A:

You have to include the createjs haxelib with the -lib argument during compilation:
haxe -main Main.hx -lib createjs


Q:

24 hour Countdown timer using Javascript and PHP

I need a 24 hour countdown timer like the image in the link. I need to implement the timer to my wordpress site. The timer should reset every night at midnight EST.
This is my current JS Code but it restarts each time i refresh the page. Can I somehow integrate it with EST?

A:

I'll take another look at this when I am home, your problem however is that every time your page loads you are calling the startTimer() method, what you need to do is get the current system time (in EST format) and convert that to seconds
That way when your page refreshes you will have the current time and not your current defined constant - I hope this is a basis for you to find a solution.


Q:

MimeType to encoded files

i need to return a encoded PDF, but i need the MIME type to do it. What i should use it?
Thank's!
ExternalContext ec = fc.getExternalContext();

    ec.responseReset();
     ec.setResponseContentType("??")
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + this.fileName + ".pdf" + "\"");

    OutputStream output = ec.getResponseOutputStream();
    output.write(encrypted);
    output.flush();
    output.close();

    fc.responseComplete();

A:

I'm not entirely sure what an encoded PDF is and how it differs from a regular one. Since you export it as a .pdf file though, I'd have thought the standard PDF mime type of application/pdf would apply.


Q:

How do you select using a range of strings in SQL?

I have a table of vehicles with registration numbers, and want to select a subset of them that are between some user-supplied 'from' and 'to' values.
So lets say the table looks like this:
id       reg_num
1        DD1111
2        DD1112
3        DE2245
4        EE5678
5        EF6547

The SQL I have so far looks like this:
select *
from vehicles
where reg_num >= 'DD'   -- this value is user supplied
and reg_num <= 'DE'     -- and so is this one

Which should (by my thinking) return:
1        DD1111
2        DD1112
3        DE2245

But instead, only returns:
1        DD1111
2        DD1112

I imagine that SQL server sees 'DE2245' as greater than 'DE', and so excludes the row.
My question: How do I get SQL server to include all rows that start with 'DE'?

A:

You have to add 'zzzz's at the end as many as necessary to match your column width definition.
 select * from vehicles
 where reg_num  >= 'DD' and reg_num <= 'DE' + 'ZZZZZZZZZZZZ'

A:

where reg_num >= @userValueFrom
and left(reg_num,char_length(@userValueTo) <= @userValueTo

but please note that this where does not utilize any index because of a function on the column in SARG.


Q:

CSS - select th tags only within the tbody of a table

I would like to use a css selector to get only the th tags with the tbody.  There are also th tags in the thead section, which I don't want included by the selector.  Here's the markup I'm working with.  Is there a selector to accomplish this?

Grade 4
Grade 8
Grade 12

Civics (2010)
769K
577K
1179K

A:

.bgtable tbody th {
   color: red;
}

A:

table.bgtable tbody th {
 /* CSS rules here */
}

A:

tbody>tr>th {color:red;}


Q:

How to run multiple commands on docker container on startup?

I have Flask application container which has to run on port 5000.
I also have a background process which is related to queue. This process has an infinite loop which is why I want to run it in background.
I'm using docker-compose.yml file for creating container. For now, I'm able to run only one command which is to make the flask server up.
flask run --host=0.0.0.0 --port 5000. I'm using the command option in docker-compose .
This is the command I want to run in background python app/workload/services/queue_services.py > qlog.txt.
When I put the background command first in command, the server is not coming up and I'm only seeing the output from background script.
When I put the flask run command first, the background script is not starting at all.
Is there any proper way to run these two commands on container start up?

A:

create a script.sh
#!/bin/bash
python app/workload/services/queue_services.py > qlog.txt &
flask run --host=0.0.0.0 --port 5000

and set it as your command


Q:

What is a G-Set Graph?

I keep finding references to $G$-Set graphs and I cannot find a definition anywhere.
They are usually mentioned at the same time as the random graph generator "rudy," so I believe they refer to a method of generating graphs but I cannot find out any more than that.
I apologise in advance if I have missed something obvious.

A:

I believe these are the 57 graphs labelled $G_1$ to $G_{57}$ in Table 7 of a preprint by Helmberg and Rendl (http://opus4.kobv.de/opus4-zib/files/306/SC-97-37.pdf). As you thought, they were generated by rudy, and the table lists the data needed to get them from that program.
Apparently, these graphs are accepted as standard test cases for some kinds of problems.  In particular, a paper by S.J.Benson, Y.Ye, and X.Zhang http://dx.doi.org/10.1137/S1052623497328008 says: "Our experiments used a machine-independent graph generator, called rudy, created by G.Rinaldi. We tested the maximum cut semidefinite program on the G set of graphs used by Helmberg and Rendl [12]. This set of problems becomes a standard test set for graph optimization."


Q:

Custom code to display current time not working

//<![CDATA[
var displayCurrentTime = new function() {
  // Get values...
  var sysHour = getHours(); // Get Hours
  var curHour = 0; // Initialize current hour (12 hr format)
  var morningEvening = "AM"; // Initialize AM/PM notation

  if (sysHour < 13) { // If it's in the morning, set time as is.
    curHour = sysHour;
    morningEvening = "AM"
  } else {
    curHour = sysHour - 12; // If it's in the evening, subtract 12 from the value and use "PM"
    morningEvening = "PM"
  }
  var curMins: getMinutes; // Get current minutes...

  // Capture the ID of the notification bar div, and compose a string from the above values.
  var notificationBar = document.getElementById("notificationBar");
  var dateTimeString = curHour + ":" + curMins + " " + morningEvening;

  // All that code above files into this fun stuff.
  notificationBar.innerHTML = dateTimeString;
}

window.setInterval(function() {
  displayCurrentTime();
}, 1000);
//]]>

I've been reading up some information and I wanted to create a simple script that grabs the hour and minute, does some calculations to determine if it's AM or PM, creates a string variable from those results, and then slips it inside of a specific DIV element.  It does this every second.
Most of the code I've written seems to make sense based on what I've read.  In the beginning I've tried using function displayCurrentTime() {} as well as what you see below (var displayCurrentTime = new function() {}) and neither seem to work.  I cannot get my text to display in the page.  Note: the ID of the div is notificationBar, just as it is here.
Is there anything in this code that makes no sense, or does this actually warrant posting the full HTML?

A:

You don't need new in front of function that you newly define, you don't instantiate  class.
You have few syntax errors, like var curMins : ... instead of var curMins = ....
Also, you cannot use getHours() and getMinutes() methods, outside of Date object:

var displayCurrentTime = function() {
                // Get values...
                var d = new Date();
                var sysHour = d.getHours();    // Get Hours
                var curHour = 0;             // Initialize current hour (12 hr format)
                var morningEvening = "AM";   // Initialize AM/PM notation

                if (sysHour < 13) {          // If it's in the morning, set time as is.
                    curHour = sysHour;
                    morningEvening = "AM"
                } else {
                    curHour = sysHour - 12;  // If it's in the evening, subtract 12 from the value and use "PM"
                    morningEvening = "PM"
                }
                var curMins = d.getMinutes();     // Get current minutes...

                var curSecs = d.getSeconds(); //optionally get seconds too
                // Capture the ID of the notification bar div, and compose a string from the above values.
                var notificationBar = document.getElementById("notificationBar");
                var dateTimeString = curHour + ":" + curMins + ":" + curSecs + " " + morningEvening;

                // All that code above files into this fun stuff.
        notificationBar.innerHTML = dateTimeString;
            }

            window.setInterval(function(){ displayCurrentTime(); }, 1000);
<div id='notificationBar'>
Time Here
</div>

See about Date object:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date
About functions and anonymous function expression:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions#The_function_expression_(function_expression)
Also:
https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Howto


Q:

persist node state between postbacks with jquery cookie plugin

I have the following html table

This table is autogenerated by a sharepoint xsltlistviewwebpart (didnt post in sharepoint as the question is more jquery+html related).
this is a treeview with nodes, when i expand a collapsed node it changes style from
style="display: none;"

to
style=""

The problem: the webpart does not remember which nodes were collapsed, so on each postback it resets all to expanded. What I need to do, is to remember the node state (expanded or collapsed) in a jquery cookie, and to retrieve it on postbacks (so, to persist the node state).
So far I got:

Can anyone please provide some pointers on how to do this. Im a bit dazed and confused about the events themselves, on page_load I should save the cookie but also retrieve it somehow.
Also "items" array stored all 7 elements which is good, but when i try alert(items[0]); I get undefined.
Thank you

A:

I suggest you to create string of this and then parse this string back... kind of like that:
var items = '';
function RememberClickedState() {
    $('.ms-listviewtable tbody').each(function(){
        tid = $(this).attr('id');
        tvisible = $(this).is(':visible');
        items += tid+':'+tvisible+','
    })
    //$.cookie("itemListState", items);
    $('body').append(items+'
');
}
function RestoreClickedState() {
    //string = $.cookie("itemListState")
    var string = items; //temporary
    var cookies = string.split(',');
    $.each(cookies, function(i, val){
        val = val.split(':');
        show = (val[1] == 'true' ? true:false);
        item = $('.ms-listviewtable').find('#'+val[0]);
        show ? item.show() : item.hide();
        $('body').append('#'+val[0]+' is '+ 'display:'+show+'
');
    })
}
$(document).ready(function(){
    RememberClickedState();
    RestoreClickedState();
})

Here is DEMO:
http://jsfiddle.net/MYexv/3/


Q:

Powerpoint: Copying individual slides into new powerpoint files

I want to save each slide in a powerpoint-file into seperate powerpoint-files, as well as store png images of each slide. In the end I want to create an archive of individual unique slides, so that all slides that are shown on some info screens are stored in this archive. This is what I have to far:
function exportSingleSlides(pathname, filename){
    var app = new ActiveXObject("PowerPoint.Application");
    app.Visible = true;

    // Open the presentation
    var presentation = app.Presentations.Open(pathname+filename, true);
    var tmpPresentation; // Used to store a new presentation for each slide.

    var e = new Enumerator(presentation.Slides);
    var slide;
    e.moveFirst();
    var i = 0;
    while (!e.atEnd()) {
        i++;
        slide = e.item(); // gets this slide

        // Export slide to png
        slide.Export(pathname + 'slide' + (i < 10 ? '0' + i : i) + '.png', 'PNG', 1920, 1080);

        // Open new presentation
        tmpPresentation = app.Presentations.Add();

        // Copy current slide and paste into new presentation
        slide.Copy();
        tmpPresentation.Slides.Paste(1);

        tmpPresentation.SaveAs(pathname + 'slide' + (i < 10 ? '0' + i : i));
        tmpPresentation.Close();
        e.moveNext();
    }

    // Close the presentation. (But how do I close powerpoint entirely?)
    presentation.Close();
    app.Quit();
}

// Which file are we looking at?
var pathname = 'C:\\Users\\Stian\\Dropbox\\jobb\\RB\\powerpoint parser\\';
var filename = 'test.pptx';

exportSingleSlides(pathname, filename);

This saves the slides to png as I want, and it also saves each slide as it's own powerpoint-file. But it's not copying it as it should. I think it might be missing the template, because headers and footers aren't included in the new copy. I'm using the powerpoint developer reference pages, but I can't seem to find a good way to copy/duplicate a slide as-is. Any suggestions?

A:

I've figured it out. Doing as below instead of just copying will do the trick.
// Get the layout from the source slide
layout = slide.CustomLayout;

// Copy current slide and paste into new presentation
slide.Copy();
tmpPresentation.Slides.Paste(1);

// Set the layout
tmpPresentation.Slides(1).CustomLayout = layout;

Now I'm getting an unspecified error when trying to save the new file, but that's a whole other problem.


Q:

GENY MOTION Virtualization engine not found ERROR

I am having this problem for a while,
I searched a lot on the internet,
The problem is when I emulate hybird app in the android geny motion emulator it say 'Virtualization engine not found'.
what I found on the internet is to enable Hyper-V in windows feature and reinstall VB host network adapter but noting works for me. And also Virtual Box is not showing any Host Only Networks.

And when I create any Host Network in VBox it is not there on
  reopening the VBox.

GenyMotion version 2.5.3.
VBox version 5.
OS Windows 10 pro Updated.
(the problem is same on other OSs)

A:

I solved this issue. It's working fine now.
I'm using:
+ Window 10
+ VirtualBox-5.0.2-102096-Win
+ Genymotion-2.5.3

Step 1: We should set Run as this program as an administrator & Compatibility mode Windows 8 for those file.
C:\Program Files\Oracle\VirtualBox
    + VBoxHeadless.exe
    + VBoxManage.exe
    + VirtualBox.exe
C:\Program Files\Genymobile\Genymotion
    + genymotion.exe

Step 2: My Computer -> Manage-> Device Manager-> Network adapters
Remove all items with name: VirtualBox Host-Only Ethenet Adapter #...
Step 3: Open Virtual Box and go to File -> Preferences -> Network -> Host Only Networks
Remove all and create new host with information:
Adapter Tab:
    IPv4 Address:        192.168.1.201
    IPv4 Network Mask:   255.255.255.0
DHCP Server Tab:
    Server Address:      192.168.1.100
    Server Mask:         255.255.255.0
    Lower Address Bound: 192.168.1.101
    Upper Address Bound: 192.168.1.199

Step 4: Run Genymotion again. It's will work.
> Screenshots


Q:

Find $\log_{p}X^2$?

Given that $\log_{p}X=5$ and $\log_{p}Y=2$, find
i) $\log_{p}X^2$
I did this, $X=p^5$ and $Y=p^2$
But how do I use them? Should I find $p$?

A:

Hint:Just use the identity:
$$\log_{\,b}x^n=n\log_{\,b}x .$$


Q:

How do I disable Android @IntDef annotation checks in special cases?

One such case is reading an int from a Bundle and storing it into the variable restricted by @IndDef annotation:
public class MainActivity extends ActionBarActivity {

@IntDef({STATE_IDLE, STATE_PLAYING, STATE_RECORDING})
@Retention(RetentionPolicy.SOURCE)
public @interface State {}

public static final int STATE_IDLE = 0;
public static final int STATE_PLAYING = 1;
public static final int STATE_RECORDING = 2;

@MainActivity.State int fPlayerState = STATE_IDLE;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (savedInstanceState != null)
        fPlayerState = savedInstanceState.getInt(BUNDLE_STATE); //Causes "Must be one of: ..." error

There must be some way of suppressing the check or casting from int to @MainActivity.State int in order to set the variable in the last line.
The other case is to write a negative test that calls a function with annotated parameter intentionally passing the wrong parameter in order to test that the Exception is thrown in such case. There must be a way to suppress annotation check in order to compile such test.

A:

I've found the way to suppress the annotation checks. Actually, there are three of them:

Add @SuppressWarnings("ResourceType") before the definition of your class. In my case:
@SuppressWarnings("ResourceType")
public class MainActivity extends ActionBarActivity {
    ...
}

Add @SuppressWarnings("ResourceType") before the definition of your method. In my case:
@Override
@SuppressWarnings("ResourceType")
protected void onCreate(Bundle savedInstanceState) {
    ...
}

These two approaches do not work for me, because I want annotation checks on all of my code, except for just one statement.

To suppress a check on a single line add a specially formatted comment (!!!).
//noinspection ResourceType
fState = savedInstanceState.getInt(BUNDLE_STATE);

A:

@Status int state1=bundle.getInt(STATE_ELEMENT1);
setStatus1(state1);
//instead of direct setStatus1(bundle.getInt(STATE_ELEMENT1);


Q:

why servlet name appending to requesting map url ? is it possible to have URL without servlet name prefix?

I have servlet xml file  personDetails-servlet.xml
<bean>
<mvc:annotation-driven />
<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix" value="/WEB-INF/jsp/yyy/config/" />
    <property name="suffix" value=".jsp" />
</bean>
<context:component-scan base-package="com.ddd.config.controller" />
</beans>

And Web.xml entry
 <servlet>
      <servlet-name>personDetails</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
     <load-on-startup>1</load-on-startup>
 </servlet>
 <servlet-mapping>
    <servlet-name>personDetails</servlet-name>
     <url-pattern>/personDetails/*</url-pattern>
 </servlet-mapping>

and below is PersonDetailsController
 package com.ddd.config.controller;
 @Controller
 public class PersonDetailsController {
 @RequestMapping(value="/personDetails/personAddressDetails.html",            method=RequestMethod.GET)
 public String abc(ModelMap model) throws Exception{
 }
 }

And i am trying to hit with http://localhost:8080/myapp/personDetails/ConfgurationDetails.html
it's not working
when i tried with below one it is working
http://localhost:8080/myapp/personDetails/personDetails/ConfgurationDetails.html
can some one tells, how i can do without adding servlet name to request mapping ulr, and also tell me how name is adding.
thank you

A:

According to your web.xml config file, you tell your application to use the org.springframework.web.servlet.DispatcherServlet class to handle requests that match <application_context>/personDetails/*.
The previous URL is the starting point of all URLs you'll use with Spring MVC. So, if you declare the following handler @RequestMapping(value="/personAddressDetails.html"), then the URL you need to call will be <application_context>/personDetails/personAddressDetails.html.
In other words, you don't need the add the servlet mapping prefix to your Controller's RequestMapping annotation.


Q:

JQuery validation on not existing checkbox

I have a JQuery DataTable that has checkboxes to select items in it. I added j
JQuery validation such that you can't submit the form without having at least selected one checkbox. Here is what my validation looks like:
jQuery.validator.addMethod("noApplicationSelected", function(value, element, params) { return $('.cbDisplay').length != 0; },'{0}');
$('[name="cbDisplay"]').rules('add', { noApplicationSelected: ['No checkbox selected'] });

Everything works fine but my problem is that if I for example add a filter in my DataTable search such that no entries are present (empty DataTable), and I try to submit the form, it submits even though I haven't selected any checkboxes.
The reason for that I think is because the validation can't bind the rules on the checkboxes because they do not exist.
How can I fix this problem?
Edit 1:
Would adding some validation that checks for whether the DataTable is empty and a checkbox is selected fix my problem? But the issue I see with that is what do I bind this validation to? I guess I could bind it to the select all/deselect all checkbox but that doesn't make sense
Edit 2:
Demo of the probelm: https://jsfiddle.net/mu79L32w/14/

A:

If you try to find the inputs/checkboxes inside the displayed document, you only get the rendered elements of the datatables-element. This means it is possible that you will not find any checkbox-element in the document if the filter of datatables is used. If a row is not displayed in the datatables-element it is removed from the rendered table and as a result all elements inside that row are also not available for a wrapping form-element.
But you can iterate over the data/rows of the DataTable-Object with javascript.
Here is an example on how to test if any checkbox is checked when the form submits by using jquery-validates submitHandler.

$(document).ready(function() {

  let table = $('#example').DataTable({
    "columns": [
      { "data": "column_a" },
      { "data": "column_b" }
    ]
  });

  function isAnythingChecked() {
    let foundChecked = false;
    let inputs = table.rows().nodes().to$().find('input');
    for (let input of inputs) {
      if (input.checked) foundChecked = true;
    }
    return foundChecked;
  }

  $("#myForm").validate({
    submitHandler: function(form) {
      if (isAnythingChecked()) {
        alert('Yeah! A checkbox is selected');
        //form.submit();
      } else {
        alert('Oh no! No checkbox selected');
      }
    }
  });

});

<link href="https://cdn.datatables.net/v/dt/dt-1.10.18/datatables.min.css" rel="stylesheet"/>

<form id="myForm">

        Column A
        Column B

        <input type="checkbox"> Checkbox 1
        Test

        <input type="checkbox"> Checkbox 2
        Lorem

        <input type="checkbox"> Checkbox 3
        ipsum

  <button id="btn" type="submit">Submit</button>

</form>


Q:

How can you tell if an iPhone camera photo has been fully uploaded to the Photo Stream without using a computer?

I'd like to know if the photos were uploaded yet, but an indicator isn't apparent. I'd like to know without resorting to checking a desktop/laptop. Is there one I'm missing?

A:

It's quite easy to see indeed. If the two images match (left), all photos were uploaded to the Photo Stream. If they don't match (right), some pictures haven't uploaded yet.

NB: Photo Stream will only work over Wi-Fi, syncing only the latest 1,000 pictures taken in the last 30 days.


Q:

In what specific order do I have to put the modules on the temporal communication system?

Very early in the game you have to put together an Antenna to talk to your people in the  future. The cubic modules are supposed to make for one plane Area. I can't quite figure it out. So how exactly and in what order do you have to put the cubes on the antenna to solve this puzzle?
The antenna:

The modules:

A:

The objective is to form a 3x3 panel on each side of the antenna once you've finished arranging the cubes.
To achieve this, arrange the cubes as follows. On one side, place the following cubes from the case;

bottom left
top middle
bottom middle

On the other side, place the remaining cubes as follows;

top left
top right
bottom right

Once you've got them in the right order, a red light will start flashing on the antenna. Press the main switch on the antenna (red button/light) to activate and your antenna should look like this:

Here is a video on YouTube of the cubes being placed correctly;


Q:

Switching a circuit from a 2 wire dc motor to 3 wire motor

I am an extreme newbie (having done software all my life, hardware is making me feel super dumb), and big picture is I am trying to replicate this work:
http://words.iame.li/post/112091812552/buttonpusher
Although he seems to be taking some shortcuts which I don't quite understand (where does the yellow and green wire go on the pi? How does he join the green wire up to the power supply?)
As part of my learning, I decided to do it by steps on an established kit. I have just completed this circuit:
As you can see from that rather complicated chart (which i assume is for protecting the RaspPi) the motor is ultimately powered by two wires, positive and negative.
I now want to take this setup, WHICH WORKS!, and apply it to the Futaba servo which he uses (https://www.amazon.com/Futaba-FUTM0031-S3003-Standard-Servo/dp/B0015H2V72) but simply plugging in my wires to the red and black receptors of the Futaba servo didnt work, presumably because I need a neutral wire to ground the new white wire from the Futaba? I must be sounding so retarded now to you guys, but I appreciate any and all tips as to fundamental concepts i must go and learn and terms and things i need to google. Please help!

A:

The standard motor they use, and a standard Futaba servo, work in different ways.
A standard permanent magnet DC motor just turns continuously when you apply power to it, speed more or less proportional to voltage, or in the case of PWM, to duty cycle. It's just dumb physics-obeying hardware. The L293 is a power switch, a full H-bridge, which takes the low power logic levels from the Pi, and switches higher currents capable of turning the motor. It can drive +/-, or -/+ to the motor to make it turn in either direction, those wires to the motor are not power supplies or always +ve or -ve. U2 and 3 are opto isolators, for bomb-proof isolation between the Pi and the motor and its power supplies, but not absolutely necessary for function.
A standard servo contains a motor in it somewhere, but has a very different function. It is intended to go to a specific shaft angle within an angular range of about half a turn. It is used for controlling rudder and throttle position on radio controlled models. It contains a gearbox, position sensor, and some comparator and drive electronics. The desired angle of the shaft is encoded in the length of logic pulses sent into the white wire. A 1.5mS pulse is central, 1mS full left, 2mS full right. Typically, pulses are delivered every 20mS or so. In the absence of a pulse, it will hold the last position.
If you want to drive it directly from your Pi, connect red and black supply wires to +5 and gnd respectively. Connect the white wire directly to the one of the GPIOs, or to the output of either U2 or U3 if you want the opto-isolation for safety, or via the 1k resistor (some protection) that your first project uses.  Use your software skills to generate a stream of pulses on the GPIO, length 1mS to 2mS, 20mS apart.
I've not looked myself, but I would not be surprised at all if you googled 'pi servo open source', and found stuff ready to run that would put the right sort of pulses onto the GPIO.
The author of the first project was misleading slightly when he said 'the servo spins for a few seconds', because it doesn't, it just changes position (noisily, over a second or so) to push the button.
If you connected red and black from your servo to the output of the 293, I hope it didn't go bang when you applied reverse voltage to it. I would hope that as servos are designed to be supplied by batteries (which can be reversed) and used by youngsters, they would be designed to survive supply reversal.
In software terms, what you're trying to do is plug a USB lead into a 3.5mm audio jack! Both have their standards and levels of complexity, but you're lacking the experience at the moment to anticipate how different.
If you have got your existing L293 drive working, then this is the way to modify it to use your new servo, with full bomb-proof opto-isolation of any spikes from the motor to the Pi.

A number of things to note. The 5v servo supply is totally isolated from the Pi's. All the GND symbols are for this 5v supply. There is no ground connection between the Pi's supply and the servo's 5v supply. I've taken the servo 5v supply to the output of the optos. The +3.3v supply to the input of the optos is still the Pi +3.3v supply.
I've replaced the functionality of the L293 with that of the servo, note that it only needs one logic input, where the L293 used 3. I've coloured the 3 servo connections appropriately.


Q:

Validation Summary with JQuery in MVC 2

I'm trying to get client validation working on my asp.net mvc 2 web application (Visual Studio 2010). The client side validation IS working. However the validation summary is not.
I'm including the following scripts

Have this before this form is started
<% Html.EnableClientValidation(); %>

and inside the form is
<%: Html.ValidationSummary("There are some errors to fix.", new { @class = "warning_box" })%>

    <%: Html.LabelFor(m => m.Name) %>

    <%: Html.TextBoxFor(m => m.Name) %>
    <%: Html.ValidationMessageFor(m => m.Name, "*") %>

I have that latest version of MicrosoftMvcJQueryValidation.js from the MvcFutures download, but it doesn't look like it supports Validation Summary. I've tried correcting this by setting extra options such as errorContainer and errorLabelContainer, but it looks like there's some more underlying issues with it.
Is there an updated / better version of this file around?

A:

The best solution I've found so far is a patch by Since Ince that can be found at jQuery.validate, and Html.ValidationSummary playing nice together.


Q:

Regex to match specific values from from an Apache virtualhost file

I want to match the values defined as ServerName, ServerAlias and DocumentRoot with regex.
Anything with a preceding # can be ignored.
I also would like to keep each virtualhost's definitions separate so in the example below I'd have two arrays.
Example:
<VirtualHost *:80>
  ServerName foo.com
  ServerAlias stage.foo.com new.foo.com
  DocumentRoot /var/www/foo.com
</VirtualHost>

<VirtualHost *:80 *:443>
  ServerName bar.com
  ServerAlias store.bar.com
  #ServerAlias new.bar.com us.bar.com
  DocumentRoot /var/www/bar.com
</VirtualHost>

My work:
<VirtualHost(?: \*\:[0-9]*)+>\s* will match each virtual hosting opening "tag" plus trailing white space.
[^\#](?:ServerName|ServerAlias|DocumentRoot) ((?:(?:[\w\/\._-]+) ?)+) will match the values I need but not as separate virtualhosts/sets/arrays.
I'm having trouble connecting them together.

A:

It required more code than I initially thought. Consider this code:
$s = <<< EOF
<VirtualHost *:80>
  ServerName foo.com
  ServerAlias stage.foo.com new.foo.com
  DocumentRoot /var/www/foo.com
</VirtualHost>

<VirtualHost *:80 *:443>
  ServerName bar.com
  ServerAlias store.bar.com
  #ServerAlias new.bar.com us.bar.com
  DocumentRoot /var/www/bar.com
</VirtualHost>
EOF;
$vh = array();
if (preg_match_all('~<VirtualHost ([^>]+)>(.+?)</VirtualHost>~is', $s, $arr)) {
   for($i=0; $i < count($arr[1]); $i++) {
       if (preg_match_all('/^ *(ServerName|ServerAlias|DocumentRoot) +(.+)$/im',
                               $arr[2][$i], $m)) {
          $entries = array();
          for($j=0; $j < count($m[1]); $j++)
             $entries[$m[1][$j]] = $m[2][$j];
          $vh[$arr[1][$i]] = $entries;
       }
   }
}
print_r($vh);

OUTPUT:
Array
(
    [*:80] => Array
        (
            [ServerName] => foo.com
            [ServerAlias] => stage.foo.com new.foo.com
            [DocumentRoot] => /var/www/foo.com
        )

    [*:80 *:443] => Array
        (
            [ServerName] => bar.com
            [ServerAlias] => store.bar.com
            [DocumentRoot] => /var/www/bar.com
        )
)