Q:

Testing WebServiceCallout with HttpCalloutMock

I am trying to use the new HttpCalloutMock following the guide here.
This is a new feature, and I was hoping to make some better test cases for using web-service callouts that respond with a SOAP Message.
However, after setting up the HttpCalloutMock response, I've since discovered that the TestMethod continues to throw: TypeException: Methods defined as TestMethod do not support Web service callouts, test skipped
I would assume this is being thrown from the imported on the WS Callout definition at WebServiceCallout.invoke(), since this isn't a simple HTTPRequest is it even going to be possible to test my web-service callouts?
    @isTest
global class ApiListMtgListMeetingsResultTest implements HttpCalloutMock {
    // Implement this interface method

global HTTPResponse respond(HTTPRequest req) {
    system.debug('Mock ApiListMtgListMeetingsResult');
    HttpResponse res = new HttpResponse();
    res.setHeader('Content-Type', 'text/xml;charset=UTF-8');
    res.setBody('<soap:Envelope>...</soap:Envelope>');
    res.setStatusCode(200);
    return res;
}

}

In the guide, setting the Test.Mock seems to capture any HTTP callouts via HttpRequest.send(), no explicit settings required.
Update
I guess I should clarify, I am trying to use HttpCalloutMock to respond to a call from:
WebServiceCallout.invoke()

A:

Without delving too deep, I've found such new feature errors to be stemming from old Api version on the class. Make sure you set the api version to 26.
None of the new features will be available unless the class is on the latest Api version. Try using the new String methods in a class with Api version less than 26!

A:

Thanks to this blog post from @metadaddy - I realized there is ANOTHER INTERFACE specifically for Webservices callouts.


Q:

How to extract a tar.gz file to two destinations concurrently?

I have some tar.gz files. I need to extract these tar.gz files to two USB harddisks. With the command tar -xvzf I can only extract the tar.gz to one harddisk at a time.
Grateful if I can be advised how can I extract the tar.gz file to two harddisks concurrently. Since the total size of the files I need to migrate are about 4.5TB, this can help to save much time for me.

A:

With zsh, using process substitution and its tee-like behaviour when you redirect a file descriptor several times:
zcat file.tar.gz > >(cd /media/disk1 && tar xf -) > >(cd /media/disk2 && tar xf -)

With other shells with support for process substitution (ksh, bash):
{
  zcat file.tar.gz 4>&- |
    tee >({ cd /media/disk1 && tar xf -; } >&4 4>&-) |
    { cd /media/disk2 && tar xf -; } 4>&-
} 4>&1

POSIXly on systems with /dev/fd/x:
zcat file.tar.gz | {
  {
    tee /dev/fd/3 |
      { cd /media/disk1 && tar xf -; } 3>&-
  } 3>&1 >&4 4>&- |
    { cd /media/disk2 && tar xf -; } 4>&-
} 4>&1

To do if for several tar.gz files, that's just (still in zsh)
for f (*.tar.gz) zcat -- $f > >(cd /media/disk1 && tar xf -) > >(cd /media/disk2 && tar xf -)

Note that the files will be extracted at the speed of the slowest destination drive.
Another approach could be to run extractions for both drives in parallel (here using POSIX sh syntax):
for f in *.tar.gz; do zcat -- $f | (cd /media/disk1 && tar xf -); done &
for f in *.tar.gz; do zcat -- $f | (cd /media/disk2 && tar xf -); done
wait

However note that:

it means uncompressing each file twice which is using more CPU resource
if one destination drive is significantly slower than the other one, some tar.gz file could end up being read twice from the source disk as it could end up being evicted from the cache which would result in more I/O on your machine.


Q:

Having multiple Regex in Java 8 Stream to read text from Line

I want to have more than one regex as below, how can I add that to flatmap iterator to put all matching values of the line to List during a single stream read?
static String reTimeStamp="((?:2|1)\\d{3}(?:-|\\/)(?:(?:0[1-9])|(?:1[0-2]))(?:-|\\/)(?:(?:0[1-9])|(?:[1-2][0-9])|(?:3[0-1]))(?:T|\\s)(?:(?:[0-1][0-9])|(?:2[0-3])):(?:[0-5][0-9]):(?:[0-5][0-9]))";
static String reHostName="host=(\\\")((?:[a-z][a-z\\.\\d\\-]+)\\.(?:[a-z][a-z\\-]+))(?![\\w\\.])(\\\")";
static String reServiceTime="service=(\\d+)ms";

private static final PatternStreamer quoteRegex1 = new PatternStreamer(reTimeStamp);
private static final PatternStreamer quoteRegex2 = new PatternStreamer(reHostName);
private static final PatternStreamer quoteRegex3 = new PatternStreamer(reServiceTime);

public static void main(String[] args) throws Exception {
    String inFileName = "Sample.log";
    String outFileName = "Sample_output.log";
    try (Stream<String> stream = Files.lines(Paths.get(inFileName))) {
        //stream.forEach(System.out::println);
        List<String> timeStamp = stream.flatMap(quoteRegex1::results)
                                    .map(r -> r.group(1))
                                    .collect(Collectors.toList());

        timeStamp.forEach(System.out::println);
        //Files.write(Paths.get(outFileName), dataSet);
    }
}

This question is a extension from Match a pattern and write the stream to a file using Java 8 Stream

A:

You can simply concatenate the streams:
String inFileName = "Sample.log";
String outFileName = "Sample_output.log";
try (Stream<String> stream = Files.lines(Paths.get(inFileName))) {
    List<String> timeStamp = stream
        .flatMap(s -> Stream.concat(quoteRegex1.results(s),
                        Stream.concat(quoteRegex2.results(s), quoteRegex3.results(s))))
        .map(r -> r.group(1))
        .collect(Collectors.toList());

    timeStamp.forEach(System.out::println);
    //Files.write(Paths.get(outFileName), dataSet);
}

but note that this will perform three individual searches through each line, which might not only imply lower performance, but also that the order of the matches within one line will not reflect their actual occurrence. It doesn’t seem to be an issue with your patterns, but individual searches even imply possible overlapping matches.
The PatternStreamer of that linked answer also greedily collects the matches of one string into an ArrayList before creating a stream. A Spliterator based solution like in this answer is preferable.
Since numerical group references preclude just combining the patterns in a (pattern1|pattern2|pattern3) manner, a true streaming over matches of multiple different patterns will be a bit more elaborated:
public final class MultiPatternSpliterator
extends Spliterators.AbstractSpliterator<MatchResult> {
    public static Stream<MatchResult> matches(String input, String... patterns) {
        return matches(input, Arrays.stream(patterns)
                .map(Pattern::compile).toArray(Pattern[]::new));
    }
    public static Stream<MatchResult> matches(String input, Pattern... patterns) {
        return StreamSupport.stream(new MultiPatternSpliterator(patterns,input), false);
    }
    private Pattern[] pattern;
    private String input;
    private int pos;
    private PriorityQueue<Matcher> pendingMatches;

    MultiPatternSpliterator(Pattern[] p, String inputString) {
        super(inputString.length(), ORDERED|NONNULL);
        pattern = p;
        input = inputString;
    }

    @Override
    public boolean tryAdvance(Consumer<? super MatchResult> action) {
        if(pendingMatches == null) {
            pendingMatches = new PriorityQueue<>(
                pattern.length, Comparator.comparingInt(MatchResult::start));
            for(Pattern p: pattern) {
                Matcher m = p.matcher(input);
                if(m.find()) pendingMatches.add(m);
            }
        }
        MatchResult mr = null;
        do {
            Matcher m = pendingMatches.poll();
            if(m == null) return false;
            if(m.start() >= pos) {
                mr = m.toMatchResult();
                pos = mr.end();
            }
            if(m.region(pos, m.regionEnd()).find()) pendingMatches.add(m);
        } while(mr == null);
        action.accept(mr);
        return true;
    }
}

This facility allows to match multiple pattern in a (pattern1|pattern2|pattern3) fashion while still having the original groups of each pattern. So when searching for hell and llo in hello, it will find hell and not llo. A difference is that there is no guaranteed order if more than one pattern matches at the same position.
This can be used like
Pattern[] p = Stream.of(reTimeStamp, reHostName, reServiceTime)
        .map(Pattern::compile)
        .toArray(Pattern[]::new);
try (Stream<String> stream = Files.lines(Paths.get(inFileName))) {
    List<String> timeStamp = stream
        .flatMap(s -> MultiPatternSpliterator.matches(s, p))
        .map(r -> r.group(1))
        .collect(Collectors.toList());

    timeStamp.forEach(System.out::println);
    //Files.write(Paths.get(outFileName), dataSet);
}

While the overloaded method would allow to use MultiPatternSpliterator.matches(s, reTimeStamp, reHostName, reServiceTime) using the pattern strings to create a stream, this should be avoided within a flatMap operation that would recompile every regex for every input line. That’s why the code above compiles all patterns into an array first. This is what your original code also does by instantiating the PatternStreamers outside the stream operation.


Q:

Accordion on Sharepoint 2010 content query

I am now trying to implement the accordion function for a content query webpart.
Basically, the content query structure looks like this:

     Title
     Content I want to expand collapse

 Title

 Content I want to expand collapse

 Title

 Content I want to expand collapse

 Title

 Content I want to expand collapse

and I have 3-5 of them.
What I want to do now is to expand collapse the description div whenever I click on the corresponding link-item (title) div.
Here is my JS code:
$(document).ready(function () {
    //ACCORDION BUTTON ACTION
    $('#MSOZoneCell_WebPartWPQ3 .link-item').click(function () {
        //MAKE THE ACCORDION CLOSE ON THE SECOND CLICK
        if ($('#MSOZoneCell_WebPartWPQ3 .description').hasClass('openDiv')) {
            $('#MSOZoneCell_WebPartWPQ3 .description').toggle('normal');
            $(this).next().removeClass('openDiv');
        } else {
            $('#MSOZoneCell_WebPartWPQ3 .description').toggle('normal');
            $(this).next().toggle('normal');
            $(this).next().addClass('openDiv');
        }
    });
    //HIDE THE DIVS ON PAGE LOAD
    $("#MSOZoneCell_WebPartWPQ3 .description").hide();
});

The problem I have now is that whenever I click on any one of the titles, ALL the description div expands, which is not what I want because I want only that particular description under the title I clicked to expand.
Any help here will be much appreciated here ! Thanks!!

A:

Check these, I think one of them should be what you want. You were right to use this when adding/removing classes, you just needed to do that for the toggle as well:
http://jsfiddle.net/7dcj4/
$(document).ready(function () {
    //ACCORDION BUTTON ACTION
    $('#MSOZoneCell_WebPartWPQ3 .link-item').click(function () {
        //MAKE THE ACCORDION CLOSE ON THE SECOND CLICK
        var $content = $(this).siblings('.description');

        var visible = $content.is(':visible');

        $("#MSOZoneCell_WebPartWPQ3 .description:visible").toggle('normal');

        if (!visible)
            $content.toggle('normal');

    });
    //HIDE THE DIVS ON PAGE LOAD
    $("#MSOZoneCell_WebPartWPQ3 .description").hide();
});

http://jsfiddle.net/uBnrV/
$(document).ready(function () {
    //ACCORDION BUTTON ACTION
    $('#MSOZoneCell_WebPartWPQ3 .link-item').click(function () {
        //MAKE THE ACCORDION CLOSE ON THE SECOND CLICK
        $(this).siblings('.description').toggle('normal');
    });
    //HIDE THE DIVS ON PAGE LOAD
    $("#MSOZoneCell_WebPartWPQ3 .description").hide();
});


Q:

Can I express these conditionals with a single math formula?

Not sure of the best way to ask this question other than:
I'm writing a function that will accept a variable called 'x'.
function doIt(x){
  var y = someformula; //this is just a placeholder for the correct formula
  return y;
}

And here's what I expect returned:
if (x is between 0 and 9){ y = 0; }

if (x is between 10 and 19){ y = 32; }

if (x is between 20 and 29){ y = 64; }

if (x is between 30 and 39){ y = 96; }

and so on....
Any help is appreciated.
I'm doing it in JavaScript if it matters.

A:

return Math.floor(x/10) * 32;


Q:

Error with sessions in CodeIgniter

The following snippet is returning an error, however the error goes away when there is no SESSION.
Here is the line that is referred to by the error:
$user_id = $this->session->userdata('user_id');

Here is the class definition that the previous line is contained within:
class Dashboard extends CI_Controller
{

    public function _construct()
    {
        parent::_construct();
        $user_id = $this->session->userdata('user_id');
        if(!user_id){
            $this->logout();
        }
    }

    public function index()
    {
          $this->load->view('dashboard/inc/header_view');
          $this->load->view('dashboard/dashboard_view');
          $this->load->view('dashboard/inc/footer_view');
    }

    public function logout()
    {
        $this->sess_destroy();
        redirect('/');
    }

}

What am I doing wrong?

A:

On your log out function
Where $this->sess_destroy(); is
Replace with $this->session->sess_destroy(); because you are missing the session
Make sure $this->load->library('session'); is loaded.
public function _construct() {
    parent::_construct();

    $this->load->library('session'); // Or Autoload it.

    if ($this->session->userdata('user_id') == FALSE) {
        $this->logout();
    }
}


Q:

Detect if a device goes out of a wifi range

Is there any event or any other way to detect when a iPad or iPhone goes out of a specific WiFi range. I searched for this and could only find Reachability class and that also i will have to check continuously in the background for the connectivity, which is not preferred in my case. Any help will be appreciated...

A:

This is the sample code you can use to find wifi/internet conncetivity
.h file
@class Reachability;

@interface AppDelegate : UIResponder <UIApplicationDelegate>
{
    Reachability* wifiReach;
}

.m file
**
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
    // Override point for customization after application launch
    if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
        self.viewController = [[HPViewController alloc] initWithNibName:@"HPViewController_iPhone" bundle:nil];
    } else {
        self.viewController = [[HPViewController alloc] initWithNibName:@"HPViewController_iPad" bundle:nil];
    }

    _navCon =[[UINavigationController alloc] initWithRootViewController:self.viewController];
    self.window.rootViewController = _navCon;

    // Observe the kNetworkReachabilityChangedNotification. When that notification is posted, the
    // method "reachabilityChanged" will be called.
    [[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(reachabilityChanged:) name: kReachabilityChangedNotification object: nil];
    //Change the host name here to change the server your monitoring
    wifiReach = [[Reachability reachabilityForLocalWiFi] retain];
    [wifiReach startNotifier];
    [self showAlertOfInternetConncetion: wifiReach];

    return YES;
}
//Called by Reachability whenever status changes.
- (void) reachabilityChanged: (NSNotification* )note
{
    Reachability* curReach = [note object];
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    [self showAlertOfInternetConncetion: curReach];
}
- (void)showAlertOfInternetConncetion : (Reachability*) curReach
{
    NetworkStatus netStatus = [curReach currentReachabilityStatus];
    switch (netStatus)
    {
        case NotReachable:
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"No Internet connection" message:@"Your internet connection has stopped working. Please check it." delegate:self cancelButtonTitle:nil otherButtonTitles:@"Exit App", nil];
            [alert show];
            [alert release];
        }
        case ReachableViaWWAN:
        {
            NSLog(@"ReachableVia WWAN");
        }
        case ReachableViaWiFi:
        {
            NSLog(@"ReachableVia WiFi");
        }
    }
}
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        exit(0);
    }
}

**


Q:

How to pass PHP $variables in cURL array

I would like to pass some simple PHP variables (such as $name1 and $email1) to the following cURL block (PHP-Curl)
CURLOPT_POSTFIELDS =>"{\n\"email\": \"percy.jackson@gmail.com\",\n\"name\": \"Percy Jack\",}"

Basically replace:

percy.jackson2290@gmail.com with $email1
Percy Jack with $name1

Is this possible? Please help!

A:

Don't try to create JSON by hand, create an array and use json_encode()
CURLOPT_POSTFIELDS => json_encode(["email" => $email1, "name" => $name1]),

For the more complex version in the comment:
CURLOPT_POSTFIELDS => json_encode([
    "sequence" => 1,
    "recipients" => [
        "signers" => [
            ["email" => $email1, "name" => $name1, "recipientId" => "1", "roleName" => "Client"]
        ],
    ]
]),

Edited version:
CURLOPT_POSTFIELDS => json_encode([
    "emailSubject" => "DocuSignAPI-CompositeTemplates",
    "emailBlurb" =>"CompositeTemplatesSample1",
    "status" => "sent",
    "compositeTemplates"=>
    ["serverTemplates"=>
     ["sequence"=>"1",
      "templateId"=>"ff32490f-58ab-4e26-a505-b32c863b2398"]],
    ["inlineTemplates"=>
     ["sequence"=>"1",
      "recipients"=>
      ["signers"=> [
       ["email" => $email1, "name" => $name1,"recipientId"=>"1","roleName"=>"Client"]]]]]]),


Q:

Why is getting a value from a variable preferred than getting it from an array?

Consider the below program:
int []array = {10, 20, 30, 40, 50};
int x = array[0];
for(int i = 0; i < array.length; i++)
{
 System.out.println(x * array[i]);
 System.out.println(array[0] * array[i]);
}

When an array is declared, it is stored in the memory which reside together.
array:     [0]    [1]    [2]    [3]   [4]
Value:     10     20     30     40    50
Location:  100   102     104    106   108

Now when x is assigned a value which is the first element of the array(10).
x is stored a value in the memory with value 10.
variable :  x
Value :     10
Location :  120

Now when we call the for loop,
The first print statement will refer to the value at location 120 and say that I have a value 10.
The second print statement will also refer to a location 100 and say it has a value 10.
When both the statements have to look for the memory location every time, why would the first statement be more optimal?
EDIT
In the same program if x is used multiple times.
int []array = {10, 20, 30, 40, 50};
int x = array[0];
for(int i = 0; i < array.length; i++)
{
 System.out.println(x * array[i] + (x + 1) * array[i] - ( x + 2));
 System.out.println(array[0] * array[i] + (array[0] + 1) * array[i] - (array[0] + 2));
}

Here x is used many times. So people prefer using x than calling array[0] everytime.
Both have to be looked up though.

A:

When accessing array[i], the processor has to look up the memory address for array and then add i to that address to get to the variable you requested.
When accessing x the processor can get the variable directly from x.
In Java, only primitives are stored on the stack so array will be a pointer to something on the heap whereas x will be stored on the stack. This only applies if x is a primitive though. If array contains objects (and x is thus a pointer to an object), both will be stored on the heap.
So the main difference is that when accessing array[i] you'll be accessing location-of-array-plus-i, but when accessing x you'll be accessing location-of-x. It's worth noting that array[0] (or any other fixed index) can usually be optimised into a single instruction.
Now, should you worry about this? No, absolutely not. There is unlikely to even be a measurable performance difference between these two ways and even if there is it is extremely unlikely that the performance difference will affect you - your application is probably doing a lot more time-consuming work than just accessing variables in memory. The compiler will also very likely optimise this to reduce the number of memory lookups required and the processor caches will play a role too.
The real reason it is preferable to write something like:
int x = array[0]
int y = array[1]
int result = x + y + x * y + x * (x - y)

Is that it is a lot more readable than:
int result = array[0] + array[1] + array[0] * array[1] + array[0] * (array[0] - array[1])


Q:

Official Kinect SDK vs. Open-source alternatives

Where do they differ?
What are the advantages of choosing libfreenect or OpenNI+SensorKinect, for example, over the Official SDK, and vice-versa?
What are the disadvantages?

A:

Please note that the below answer is per date and some facts may very well be outdated in the near future. Current state of the Official Kinect SDK is beta 1.00.12.
The first obvious difference is that the official SDK is maintained by the Microsoft Research team while OpenKinect is an open source SDK maintained by the open source community. Both has its cons and pros.

The Official SDK is developed by Microsoft which also develops the hardware and therefore should know internal information about the device that the open source society must reverse engineer. Obviously this is to Microsoft's advantage.
Microsoft is pouring a lot of money into this device and I am sure that they will do what they feel is necessary to keep their SDK up to par. Having economy behind it gives many advantages.
On the other hand, never underestimate the force of the open source society: "The OpenKinect community consists of over 2000 members contributing their time and code to the Project. Our members have joined this Project with the mission of creating the best possible suite of applications for the Kinect. OpenKinect is a true "open source" community!" - http://openkinect.org/wiki/Main_Page.
OpenKinect was released long before the official SDK as the kinect device was hacked on the first or second day of its release. Kudos to OpenKinect!

Programming languages supported:

Official SDK: C++, C#, or Visual Basic by using Microsoft Visual Studio 2010.
OpenKinect: Python, C, C++, C#, Java, Lisp and more! Obviously not requiring Visual Studio.

Operating systems support:

Official SDK: only installs on Windows 7.
OpenKinect: runs on Linux, OS X and Windows

Clearly advantage OpenKinect.
License:

The Official SDK is in its current beta state only for testing. The SDK has been developed specifically to encourage wide exploration and experimentation by academic, research and enthusiast communities. commercial applications are not permitted. Note however that this will probably change in future releases of the SDK. Visit the FAQ for more information
OpenKinect appers to be open for commercial usage, but online sources state that it may not be that simple. I would take a good look at the terms before releasing any commercial apps with it. Read Kinect – Licensing implications of open hardware projects for more info.

Documentation and support:

Official SDK: well documented and provides a support forum
OpenKinect: appears to have a mailing list, twitter and irc. but no official forum/QA? Documentation on website is not as rich as I would like it to be.

Device calibration:
Different Kinect devices may differ slightly depending on the batch that they were produced in. Thus device calibration is sometimes required. But:

the Official SDK does not provide any calibration settings but I have so far not had to calibrate the device I am working on. According to something I read online (link lost) at production time the calibration parameters are written to the kinect device, so with the Official SDK calibration is not needed.
OpenKinect features device calibration: http://openkinect.org/wiki/Calibration. Thus I believe that you should calibrate your device if you go with OpenKinect.

If its true that calibration is only needed for OpenKinect that is a big advantage for the official SDK as it is easier to distribute and install applications without such need.

Personally, after a failed try with the OpenKinect SDK I went with the official SDK, which

came with drivers that installed out of the box
came with examples and code for easy getting into business
All-in-all: I could start my own development within 15 minutes or so.
Now, after working with the Kinect for a few months, I have to say that I am quite satisfied with the API provided. I cannot however compare it to the OpenKinect SDK as I in fact never got it working (but perhaps it didn't give it a fair try).

UPDATE: As of February 1st 2012 there is a commercial license for the official SDK:
"The commercial license for this release authorizes development and distribution of commercial applications. The prior SDK was a beta, and as a result was appropriate only for research, testing and experimentation, and was not suitable for use with a final, commercial product. The new license will enable developers to create and sell their Kinect for Windows applications to end user customers using Kinect for Windows hardware on Windows platforms."
Developer Frequently Asked Questions

A:

As explained by Avada Kedavra in his/her answer, these are some interesting differences:

supported operating systems: you can only use Microsoft SDK on Windows, while open source solutions are usually able to work on other operating systems;
programming languages: you have a wider choice with open source solutions, while Microsoft only supports C++ and C# (Visual Basic is no more supported with SDK 2.0);
documentation and support: Microsoft offer a good forum and a well done documentation (with a lot of samples); but there are several open source solution well documented;
license: Microsoft is less or more proprietary, open source is less or more free. Consider also that open source ideas have sometimes been bought by big companies, and transformed in something that is no more open. Probably yours will not be the case, but keep in mind this additional eventuality.

In my personal opinion, the most significant difference between open source solutions and Microsoft SDKs is strictly related to the skeletal tracking algorithm.
While depth and RGB data can be effectively provided by both open/free APIs and Microsoft SDKs, implementing skeletal tracking capabilities is not only a matter of reverse engineering.
To implement such an algorithm, developers must have strong competences in pattern recognition and machine learning areas, and I am quite sure that such kind of knowledge is available among the open source community. But the implementation of skeletal tracking is based on a "trained" algorithm, that requires a lot of experiments to collect very large amount of data. These data are then used to "train" the algorithm, that can recognize the skeletal joints.
Getting enough data, but also adjusting and properly using them, requires a lot of time and money. Microsoft researchers and developers are in the best conditions to work on this kind of stuff, simply because it is their job.
In my previous experiences, I noticed that open source solutions provide good skeletal tracking capabilities, but they are not at the same level of what Microsoft offers with its SDK.
Remember also that Microsoft SDK provide a lot of additional capabilities, like facial recognition or joint orientation, and several widgets very useful if you want to fastly build a gestural GUI.
So what I suggest is: if you are working on a project in which you simply need depth and/or RGB data, or if you have the necessity to use a programming language that is not supported by Microsoft SDK, then you should opt for open source solution. Otherwise, Microsoft SDK would be my best choice.

A:

I would strongly recommend the Cinder framework. (libcinder.org)
It supports both OpenNI and Kinect develoment, if you're using C++. It now supports Kinect SDK 1.7 and OpenNI 2, via these Cinderblocks:
MS Kinect SDK 1.7 (stable)
https://github.com/BanTheRewind/Cinder-MsKinect
OpenNI 2 / NITE 2.2 (alpha)
https://github.com/wieden-kennedy/Cinder-OpenNI
Both can do skeletal tracking out of the boz, OpenNI being capable of tracking up to six skeletons simultaneously. OpenNI 2 is gaining rapidly on the Kinect, although the new Kinect will probably change that when it comes out next month. However the basic underlying principles are unlikely to change.
The main drawback with the initial release of OpenNI was that it required a full body activation pose to recognise a user, which was a deal breaker for a lot of applications - however this seems to have been solved in the newer versions and OpenNI 2 also supports robust hand tracking at close range, although it still requires a focus gesture initially. If you work on Mac or Linux, it's pretty much your only choice.


Q:

How to make two controllers perform same action in Angular, but change visual aspect of site?

I would like to replicate Google's home page functionality in Angular, and it's causing me grief. I've gone through the Egghead videos and read the entire API, but there's no particular example for that exact behavior. What I'd like it to do is the following:

user comes to home page, main search bar is present and generic black header bar
user searches for something, and only when he presses "search" does the main search bar disappear, the url changes to mysite.com/q/searchTerm and a new sub-header appears under the black header bar much like with Google's home page, where the main search field is removed and placed in a grayish bar under the main header bar (if you have instant-search off)
the results of the search appear in place of the now gone main search bar, just like with Google, but this part I can handle with routes and views. The layout switch between two identical controllers is what bothers me.

So far what I've tried was:

make a parent controller for both MainCtrl sub controllers, and set its scope.data = {searchHeaderDisplay: false}
have both sub controllers share the same name (MainCtrl) because they share the exact same functionality
make the one in the header bar ng-show="data.searchHeaderDisplay" and the main one ng-hide="data.searchHeaderDisplay" and then try switching the data.searchHeaderDisplay on ng-click of Search Button. This didn't work - no effect was produced.

I'm still coming to terms with AngularJS, so I'm sure it's quite simple, I just need a practical example or two to learn from.
Edit: would it be better to shove the secondary header (with the smaller search field) into a separate view template along with the search results, and just have the root view be the main search field? The documentation is very lax on best practices regarding views and routes, especially routes that will have multiple controllers doing something.

A:

If I understand you correctly, you set scope.data = {searchHeaderDisplay: false} on the parent controller of the two MainCtrl controllers, with the intention to enable the MainCtrl controllers to share the same model data. That's all fine.
Without seeing your code, my guess is that the problem lies in how you switch data.searchHeaderDisplay on ng-click. You might have set data.searchHeaderDisplay at the child scope level (ie. the scopes that corresponds the MainCtrl controllers) when you should have assign the value to their parent scope level. Let me know if you need me to elaborate.
UPDATE:
After taking a look of the provided code, the problem is indeed as what I suspected earlier (above).
mainProductSearch() is what needs to be changed. Instead of scope.data.searchHeaderVisible = true;, you need scope.$parent.data.searchHeaderVisible = true for the reason briefly explained earlier. If the rationale behind is still not clear to you, then you probably need to familiarize yourself with prototypal inheritance chain of AngularJS scope (and/or Javascript object in general). Scope prototypal inheritance an essential part of AngularJS. Here is a great article on the topic.

A:

Instead of an AppCtrl (which is essentially acting like $rootScope), and using $parent (which is a fragile solution because changing the HTML structure could cause this to break -- e.g., you might find you need to use $parent.$parent... if you add an intermediate ng-controller), I suggest a service for storing model data related to your header.  Let's call it searchService.
Controllers that need to affect this model can inject the service.  This has the additional advantage that the dependencies are clear (vs controller $scope inheritance, where the dependencies are not clear).  E.g., when the user presses "search", the controller can call a notification method defined on the service:  searchService.newSearchTerm(searchTerm).  Now, all views (like the header view) that are watching for changes in the model will notice the change and can update accordingly.
You might consider using ng-view for the main content area of your page.
See also https://stackoverflow.com/a/14619122/215945, where a very similar layout is discussed.  In that SO post, a shopping basket with an item count is in the header.  The item count needed to be updated by multiple controllers, so we put it into a service.


Q:

JavaScript-based quiz application called Quizz

I've been spending lot of time reading through this site and found plenty of resources that shaped up my code.
I am working on an open source project known as Quizz. It is in a primitive stage as I work only during my spare time I cannot concentrate much. For this JavaScript to work, I have a huge objects and array's of topics and questions in a variable called qbank (read question bank).
var qbank   = {};

qbank['js'] = [];
qbank['html']   = [];

qbank['js'].push({
    level:  'basic',
    questions:  [
        {
            title:  'One JS BASIC A question statement?',
            type:   'single',
            anss:   [
                'Answer 1',
                'Answer 2',
                'Answer 3'
            ],
            ans:    [1],
            comments:   'If there is a wrong answer, a justification is needed'

        },

    ]
});

I guess from the above code it is understandable that the topics may be JavaScript/HTML/PHP or Java, and each JavaScript array holds set of questions based on levels (basic, intermediate,... advanced).
The idea is to iterate over array and hold each levels and topics in a separate array variable.
Do you think this approach is good? I really feel there is something wrong with this.
var digest  = function() {
        for( var q in qbank ) {
            //  q   is js/html/php/..... topic names
            var
                topic,
                t,
                qns     = 0,
                i   = 0,
                questions,
                question,
                level
            ;

            topic   = qbank[q];

            //  Initializing instance topics
            _instance.topics[q]= [];

            for(
                var
                    l = levels.length
                ; i < l; i++ ) {

                if( typeof _instance.topics[q][i] === 'undefined' ) {
                    _instance.topics[q][i]  = {
                        'level': levels[i],
                        'questions': []
                    };
                }
            }

            for( t in topic ) {
                questions   = topic[t].questions;
                level       = topic[t].level;

                for( qns in questions ) {
                    for( var
                            inst = 0,
                            l = _instance.topics[q].length; inst < l; inst++ ) {

                        if( _instance.topics[q][inst].level === level ) {
                            _instance.topics[q][inst].questions.push( questions[qns] );
                        }
                    }
                }
            }
        }
    };

Secondly, I have this digest function where it will pull out and merge all the questions based on levels and topics. I really hate to see my code with plenty of for loops. Please help in suggesting a good practice or approach I need to take.

A:

I can understand your frustration of nested for loops.
However, your data structure is full of nested arrays. How else can you handle them?
One way to have pretty code is to separate each loop in its own function, with clear names.
This way, the main logic remains readable. And if you want to go in detail, the only scope you have to care about is a small function.
You can refactor more than in the example given above, it's all up to you.
Example:
var digest  = function() {
        for( var q in qbank ) {
            //  q   is js/html/php/..... topic names
            var
                topic,
                t,
                qns     = 0,
                i   = 0,
                questions,
                question,
                level
            ;

            topic   = qbank[q];

            initInstance( _instance, q );

            for( t in topic ) {
                initTopics( _instance, t, q );

            }
        }

        //  Initializing instance topics
        function initInstance( _instance, q ) {
            _instance.topics[q]= [];

            for(
                var
                    l = levels.length
                ; i < l; i++ ) {

                if( typeof _instance.topics[q][i] === 'undefined' ) {
                    _instance.topics[q][i]  = {
                        'level': levels[i],
                        'questions': []
                    };
                }
            }
        }

        function initTopics( _instance, t, q ) {
            var
                questions   = topic[t].questions,
                level       = topic[t].level
            ;

            for( qns in questions ) {
                for( var
                        inst = 0,
                        l = _instance.topics[q].length; inst < l; inst++ ) {

                    if( _instance.topics[q][inst].level === level ) {
                        _instance.topics[q][inst].questions.push( questions[qns] );
                    }
                }
            }
        }
};


Q:

Deleting rows from a collection using ef code first

I have the following domain model:
public class Campaign
{
    public virtual long Id { get; set; }
    public virtual string Name { get; set; }
    public virtual ICollection<Content> Content { get; set; }
}

public class Content
{
    public virtual long Id { get; set; }
    public virtual string Body { get; set; }
}

This is configured:
modelBuilder.Entity<Campaign>().HasMany(x => x.Content).WithOptional();

In my service I have the following code:
Campaign campaign = campaignRepository.GetById(id);

This loads the campaign and any associated content items into the collection which is great. The issue comes with the following code:
 campaign.Name = "new value";
 campaign.Content.Clear();

 unitOfWork.Commit();

This does not delete the content rows from the database. It actually sets the foreign key in the content table to null for the affected rows but it does not delete the rows.
I then tried to modify the configuration to:
modelBuilder.Entity<Campaign>().HasMany(x => x.Content).WithRequired();

This would simply give me the following exception: A relationship from the 'Campaign_Content' AssociationSet is in the 'Deleted' state. Given multiplicity constraints, a corresponding 'Campaign_Content_Target' must also in the 'Deleted' state.
There must be a way to delete rows from the content collection. I must be missing something. Any help is appreciated.

A:

You will have call the Remove method on the corresponding DbSet for each entity instance.
foreach(var content in campaign.Content)
{
    dbContext.Contents.Remove(content);
}


Q:

How can I simply modify the path for the entire requests package within a libraries folder in my appengine project

I've been working with AppEngine for a little while now and always have a bit of friction when using external libraries where I need to modify each import statement to reflect the fact that the library is not in the base directory of the project.
For example, my directory structure might look like (with the requests library installed)
/myapp/app.yaml
/myapp/main.py
/myapp/libraries/requests/packages/
/myapp/libraries/requests/__init__.py
/myapp/libraries/requests/adapters.py
etc...

However appengine expects something like
/myapp/app.yaml
/myapp/main.py
/myapp/requests/packages/
/myapp/requests/__init__.py
/myapp/requests/adapters.py
/myapp/requests/api.py
etc...

I then need to go in to each of the requests files to modify the imports to something like
from libraries.requests import adapters

rather than simply
import adapters

which may be within api.py. If I do not modify it I get an import error e.g.
ImportError: No module named adapters

I have looked at the following How to import modules in Google App Engine? which suggests modifying the path (though the application is different in their code) using
sys.path.append(os.path.join(os.path.dirname(__file__), 'libraries'))

To translate this to my issue I could put something like
sys.path.append(os.path.dirname(__file__))

at the start of each __init__.py file within libraries. However it strikes me that there must be a more efficient way, and in keeping with DRY - but I cannot seem to find it. I've tried simply including it in the top most __init__.py file within libraries and then again in the top most __init__.py file within each package. This does not work for sub-packages though unfortunately. Is there a way to make one change to fix this?

A:

I have all my third party libs in a lib dir
The I just  include
sys.path.insert(0,'./lib')
in appengine_config.py which is loaded before any of your code.
If find it needs to be inserted at the beginning of sys.path rather than at then end if you use specific versions of libs like webob that are not part of the appengine available versions.
Then you don't have to modify any of the libraries etc....
This is pretty standard python behaviour.  In a normal desktop install situation you are installing vie easy_install which sticks stuff in places like site-packages and setups paths etc....  but if you aren't using any of that, and you can't with appengine you have to do the path manipulation yourself.


Q:

Prove that $ 1+2q+3q^2+...+nq^{n-1} = \frac{1-(n+1)q^n+nq^{n+1}}{(1-q)^2} $

Prove:

$$ 1+2q+3q^2+...+nq^{n-1} = \frac{1-(n+1)q^n+nq^{n+1}}{(1-q)^2} $$

Hypothesis:
$$ F(x) = 1+2q+3q^2+...+xq^{x-1} = \frac{1-(x+1)q^x+xq^{x+1}}{(1-q)^2} $$
Proof:
$$ P1 | F(x) = \frac{1-(x+1)q^x+xq^{x+1}}{(1-q)^2} + (x+1)q^x = \frac{1-(x+2)q^{x+1}+xq^{x+2}}{(1-q)^2} $$
$$ P2 | \frac{1-(x+1)q^x+xq^{x+1}+[(x+1)(1-q)^2]q^x}{(1-q)^2} = \frac{1-(x+2)q^{x+1}+xq^{x+2}}{(1-q)^2} $$
$$ P3| \frac{x\color{red}{q^{x+1}}+[-(x+1)]\color{red}{q^x}+1+[(x+1)(1-q)^2]\color{red}{q^x}}{(1-q)^2} = \frac{x\color{red}{q^{x+2}}-(x+2)\color{red}{q^{x+1}}+1}{(1-q)^2} | $$
Here I just reorganize both sides of the equation, so LHS is explicity an expression with a degree of x+1, while the degree of RHS is x+2. Both LHS' $\color{red}{q^x}$ are added next.
$$P4| \frac{xq^{x+1}+[-(x+1)+(x+1)(<1^2q^0+\binom{2}{1}1q-1^0q^2>)]q^x+1}{(1-q)^2}=\frac{xq^{x+2}-(x+2)q^{x+1}+1}{(1-q)^2} $$
$$P5 | \frac{xq^{x+1}+[2xq-xq^2+2q-q^2]q^x+1}{(1-q)^2} = \frac{xq^{x+2}-(x+2)q^{x+1}+1}{(1-q)^2} $$
I get stuck at this point. I don't know if i'm approaching  the problem the right way. So, any help would be appreciated.
Thanks in advance.

A:

Hint:
$1+2q+3q^2+\ldots+nq^{n-1}= (q+q^2+\ldots+q^{n})'$

A:

$$\begin{align}
S&=1+2q+3q^2+\qquad\cdots\qquad  \qquad+nq^{n-1}\\
qS&=\qquad q+2q^2+3q^3+\cdots +\quad(n-1)q^{n-1}+nq^n \\
\text{Subtracting,}&\\
(1-q)S&=1+\;\ q \ +\ q^2 +\ q^3+\cdots \qquad \qquad +q^{n-1}-nq^n\\
&=\frac {\;\ 1-q^n}{1-q}-nq^n\\
S&=\frac{1-q^n-nq^n(1-q)}{(1-q)^2}\\
&=\frac{1-(n+1)q^n+nq^{n+1}}{(1-q)^2}\qquad\blacksquare\end{align}$$

A:

You can also prove by induction. Assume true for $n$, and show for $n+1$.
$$1+2q+3q^2+\cdots+nq^{n-1} = \frac{1-(n+1)q^n+nq^{n+1}}{(1-q)^2}.$$
Then,
$$1+2q+3q^2+\cdots+nq^{n-1}+(n+1)q^n = \frac{1-(n+1)q^n+nq^{n+1}+(n+1)q^n(1-q)^2}{(1-q)^2}=  \frac{1-(n+2)q^{n+1}+(n+1)q^{n+2}}{(1-q)^2}.$$
Thus the result holds for $n+1$. Since the result holds for $n=1$, the proof is complete.


Q:

Flex 4 - How to set alternate value for a spark Image control and Spark BitmapImage

How to set alternate value for Image and BitmapImage controls in flex 4 like HTML img tag
   <img src="url" alt="some_text">

But I want to display alternate image if the image is not correct.
Is it possible?

A:

This will help you.
The catch here is IOErrorEvent. If images not loading correctly it throws IO_ERROR EVENT (might be incorrect path). Also aware of Cross Domain Security issue.
protected function img_creationCompleteHandler(event:FlexEvent):void
{
    img.addEventListener(IOErrorEvent.IO_ERROR, function(event:IOErrorEvent):void
    {
        img.source = "url";//Make sure it should be Right path;
    });
}

<s:Image id="img" toolTip="Hey tooltip here" creationComplete="img_creationCompleteHandler(event)" />


Q:

npm install -g @vue/cli @vue/cli-init errors

I am busy setting up NativeScript and I am also adding in Vue.js support for it. Well, I get this error when installing. Should I use --unsafe-perm or is there a better way to do this?
npm install -g @vue/cli @vue/cli-init
npm WARN deprecated vue-cli@2.9.6: This package has been deprecated in favour of @vue/cli
npm WARN deprecated coffee-script@1.12.7: CoffeeScript on NPM has moved to "coffeescript" (no hyphen)
/usr/local/bin/vue -> /usr/local/lib/node_modules/@vue/cli/bin/vue.js

> fsevents@1.2.9 install /usr/local/lib/node_modules/@vue/cli/node_modules/fsevents
> node install

node-pre-gyp WARN Using request for node-pre-gyp https download
node-pre-gyp WARN Pre-built binaries not installable for fsevents@1.2.9 and node@10.16.0 (node-v64 ABI, unknown) (falling back to source compile with node-gyp)
node-pre-gyp WARN Hit error EACCES: permission denied, mkdir '/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/lib'
gyp WARN install got an error, rolling back install
gyp ERR! configure error
gyp ERR! stack Error: EPERM: operation not permitted, utime '/Users/chris/.node-gyp/10.16.0'
gyp ERR! System Darwin 18.7.0
gyp ERR! command "/usr/local/Cellar/node@10/10.16.0/bin/node" "/usr/local/Cellar/node@10/10.16.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "configure" "--fallback-to-build" "--module=/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node" "--module_name=fse" "--module_path=/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64" "--napi_version=4" "--node_abi_napi=napi" "--napi_build_version=0" "--node_napi_label=node-v64"
gyp ERR! cwd /usr/local/lib/node_modules/@vue/cli/node_modules/fsevents
gyp ERR! node -v v10.16.0
gyp ERR! node-gyp -v v3.8.0
gyp ERR! not ok
node-pre-gyp ERR! build error
node-pre-gyp ERR! stack Error: Failed to execute '/usr/local/Cellar/node@10/10.16.0/bin/node /usr/local/Cellar/node@10/10.16.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node --module_name=fse --module_path=/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64 --napi_version=4 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
node-pre-gyp ERR! stack     at ChildProcess.<anonymous> (/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/node_modules/node-pre-gyp/lib/util/compile.js:83:29)
node-pre-gyp ERR! stack     at ChildProcess.emit (events.js:198:13)
node-pre-gyp ERR! stack     at maybeClose (internal/child_process.js:982:16)
node-pre-gyp ERR! stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:259:5)
node-pre-gyp ERR! System Darwin 18.7.0
node-pre-gyp ERR! command "/usr/local/Cellar/node@10/10.16.0/bin/node" "/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/node_modules/node-pre-gyp/bin/node-pre-gyp" "install" "--fallback-to-build"
node-pre-gyp ERR! cwd /usr/local/lib/node_modules/@vue/cli/node_modules/fsevents
node-pre-gyp ERR! node -v v10.16.0
node-pre-gyp ERR! node-pre-gyp -v v0.12.0
node-pre-gyp ERR! not ok
Failed to execute '/usr/local/Cellar/node@10/10.16.0/bin/node /usr/local/Cellar/node@10/10.16.0/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js configure --fallback-to-build --module=/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64/fse.node --module_name=fse --module_path=/usr/local/lib/node_modules/@vue/cli/node_modules/fsevents/lib/binding/Release/node-v64-darwin-x64 --napi_version=4 --node_abi_napi=napi --napi_build_version=0 --node_napi_label=node-v64' (1)
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 (node_modules/@vue/cli/node_modules/fsevents):
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: fsevents@1.2.9 install: `node install`
npm WARN optional SKIPPING OPTIONAL DEPENDENCY: Exit status 1

+ @vue/cli@3.10.0
+ @vue/cli-init@3.10.0
updated 2 packages in 42.488s

A:

you can solve this problem with --unsafe-perm : npm install -g @vue/cli @vue/cli-init --unsafe-perm
ref.
https://github.com/mapbox/node-pre-gyp/issues/439#issuecomment-462821780


Q:

Como escrever a data e hora de um erro no log do Django?

Eu iniciei um projeto no Django 1.4, e todo erro que eu pegava via try..except eu imprimia no sys.stderr - fazendo ele cair no mesmo arquivo de log do Apache (error.log). Funcionava, mas só pros erros que eu explicitamente pegava, e além disso os erros de todas as instâncias em execução iam pro mesmo arquivo. Mas a vantagem é que o Apache prefixava todos os erros com a data e hora do erro.
Quando fiz upgrade pro Django 1.9, comecei a usar o sistema de logging baseando-me nesse primeiro exemplo (no settings.py):
LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'handlers': {
        'file': {
            'level': 'ERROR',
            'class': 'logging.FileHandler',
            'filename': '/var/www/vhosts/example.com/statistics/logs/django_errors.log',
        },
    },
    'loggers': {
        'django.request': {
            'handlers': ['file'],
            'level': 'ERROR',
            'propagate': True,
        },
    },
}

E ele passou a logar no arquivo especificado todos os erros 500, inclusive os que eu não pegava explicitamente. O único problema é que ele só loga o erro em si, não dá nenhuma indicação da data e da hora do erro, nem nenhuma informação adicional:
Internal Server Error: /admin/example/projeto/add/
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 132, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/usr/local/lib/python2.7/dist-packages/django/contrib/admin/options.py", line 618, in wrapper
    return self.admin_site.admin_view(view)(*args, **kwargs)
  ...
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/usr/local/lib/python2.7/dist-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
IntegrityError: (1048, "Column 'area' cannot be null")

Existe um jeito simples de logar a data e hora do erro, pra ficar mais fácil correlacionar com a entrada no access.log (onde é escrito algo como "POST /meu/caminho HTTP/1.1" 500)? Eu imagino que eu tenha de mexer no formatters, mas lendo a documentação não entendi muito bem como ele funciona. O mais importante pra mim é o stack trace, é claro, mas essa informação adicional seria muito útil (se não for possível, ou for algo mais complicado, posso viver sem isso - afinal esse tipo de erro é relativamente raro).
P.S. Estou usando mod_wsgi, se isso for de alguma relevância.

A:

Eu testei aqui e realmente não estava mostrando a data e hora, mas basta indicar o formato do log que funcionou, neste caso coloquei formatter: 'verbose', esse verbose está formatado com a data:
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'verbose': {
            'format': "[%(asctime)s] %(levelname)s [%(name)s:%(lineno)s] %(message)s",
            'datefmt': "%d/%b/%Y %H:%M:%S"
        },
        'simple': {
            'format': '%(levelname)s %(message)s'
        },
    },
    'handlers': {
        'file': {
            'level': 'DEBUG',
            'class': 'logging.FileHandler',
            'filename': '{0}/errors.log'.format(BASE_DIR),
            'formatter': 'verbose'  # aqui você indica o formato definido em formatters
        },
    },
    'loggers': {
        'django': {
            'handlers': ['file'],
            'level': 'DEBUG',
            'propagate': True,
        },
    },
}

Eu atualmente utilizo sentry para organizar melhor os erros, uso o serviço getsentry.com, me atende bem e é bem fácil de usar, se não me engano permite até 200 erros por dia de forma gratuita.


Q:

Zero Day Policies implementation

I'm new here, and sorry if my english is a little bit broken it's not my main language.
I'm trying to put together a document/ppt for my startup with a Zero Day policy structure.
But I'm not finding real implemented flows, information, or something I can base this from (anything is helpfull)
What I found on my research mainly focus on specific discussing how heartbleed or the cve work.
I want to put something very straightforward but would love different point of views or examples if there are like:

We will be suscribed to receive every update automatically from the different applications, OS that we own
Critical updates will be reviewed, researched and implemented at top on 48 hours on all the servers
Medium/Urgent updates will be reviewed, researched and implemented at top on 1 week on all servers
Low Updates will be reviewed and implemented at most on the same month
A Team will monitor the audits logs of ports that are reporting status that are receiving suspected activity once a week on a internal meeting and define if new meassures have to be implemented
ETC

A:

The point of zero-day attacks is that they use vulnerabilities which are not known at the time they get exploited. You can thus not create a policy specifically for zero-days. But hardening the security in general also reduces the risk or at least the impact of a zero-day. Because the zero-day exploit is just the way the attacker enters the network or takes over a system or account. The actual harm against the network is not done by the exploit itself, but by the attacker using other tools and methods from its achieved privileges on the computer and in the network for espionage, sabotage, ransom etc.
Therefore the protection you add must be based on the assumption that the attacker has already successfully entered your network using the zero-day exploit, i.e. that he is actually inside your network and that you need to reduce the harm he can do there.
This means of course being up-to-date with patching since otherwise you likely have problems already with the way more common known attacks than just with the uncommon zero-day attacks. This means monitoring your infrastructure for suspicious activity, which of course means that you know what should be normal and what is suspicious in the first place. Strict and narrow separation and segmentation at network and application level and proper user permissions can help a lot to restrict the harm a successful attacker could do in your network - no matter if he came in by using a zero-day or not. And for the harm you could not prevent you need recovery strategies, like having a backup with a working restore.
In other words: know what should happen in your network and implement techniques (like microsegmentation, zero-trust, ...) to enforce and monitor the expected behavior. Expect some harm and be able to recover from it. The better you understand what should happen and the better you enforce it, the less harm an attacker can do in your network even if he has successfully infiltrated some computer/user in the network. It is not that firewalls, IDS, antivirus, SIEM etc don't help - but these are tools to enforce and monitor expected behavior and not magic wands you just need to wave. Don't expect to successfully fight zero-days by adding security on top of a chaotic network you don't understand or which behaves differently than you believe.


Q:

AJAX call from jQuery UI dialog

I'm working on a user login system using jQuery UI modal dialogs to interact between my html and PHP scripts.  Recently, I moved all of my user functionality to one PHP file, from where I had them before in my header markup.
I was able to get the login functionality to work if someone puts in a valid username/password, but now I am trying to account for other possibilities, i.e. someone enters a valid username but incorrect password, or if they enter a username that does not exist.
The problem I'm having is with the AJAX call on the Dialog script.  I want to submit the login form to the same page, user.php, and either log a user in, or return an error message that would populate a div on the same dialog.
Right now, my code will return an error message, but it also returns a copy of the user form.  Not really sure what I am doing wrong here...
Any input would be appreciated.
EDIT:  Decided to go ahead and post the entirety of user.php, since making changes based on one answer made the html added by this file disappear entirely.  I'm now guessing that there are probably several things I'm doing wrong:

                <?php
                    //if user is logged in, show name and Log Out option, else show Log In and Sign Up options
                    if(isset($_COOKIE["user"])) {
                        setSessionUserData($_COOKIE["user"]);
                        echo "
Logged in as {$_SESSION["username"]}
";
                        echo "
 |
";
                        echo "
Log Out
";
                    } else {
                        echo "
Log In
";
                        echo "
 |
";
                        echo "
Sign up
";
                    }
                ?>

        <form id="login_form">
            <fieldset>
                Username
                <input type="text" name="username" id="username" />
                Password
                <input type="password" name="pw" id="pw" />
            </fieldset>
        </form>

Are you sure you want to log out?

<?php

function setSessionUserData($cookie) {
    $con = connect();

    $query = "SELECT * FROM practice_user WHERE userid = '$cookie'";
    $result = mysqli_query($con, $query);
    $userData = mysqli_fetch_array($result);

    $_SESSION["username"] = $userData["username"];
    $_SESSION["fname"] = $userData["first_name"];
    $_SESSION["lname"] = $userData["last_name"];
}

?>

...and the PHP:
if($_SERVER["REQUEST_METHOD"] == "POST") {
$user = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);

//check if correct login
if (chkLogin($user, $pass)) {
    $id = getUser($user, $pass);
    setUserCookie($id);
    header("Location: Practice.php");
}
//check if username exists but incorrect password entered
else if (chkUser($user)) {
    echo "Username and password do not match";
}
//Or else return that username doesn't exist
else {
    echo "Username does not exist";
}

}
There are other functions in my code to handle validation and such.
If I need to post those, please let me know.

A:

Can you try this,
You can't able to redirect the page in ajax calling php file itself, So redirection section moved into the javascript side.
Jquery,
    $("#login_dialog").dialog({
            autoOpen: false,
            height: 200,
            width: 250,
            resizeable: false,
            modal: true,
            buttons: {
                Submit: function() {
                    $.post("auth.php",
                            {
                            username: $("#username").val(),
                            password: $("#pw").val()
                            },
                            function(result) {
                                if(result=='success'){
                                    window.location='Practice.php';
                                }else{
                                   $(".error").html(result);
                                   }
                               }
                          )
                    },
                Cancel: function(){
                    $(this).dialog("close");
                }
            },
            close: function() {
                loginFields.val("");
            }
        });

Create new page called auth.php, Included your dependency php function.
   <?php

    if($_SERVER["REQUEST_METHOD"] == "POST") {
    $user = test_input($_POST["username"]);
    $pass = test_input($_POST["password"]);

    //check if correct login
    if (chkLogin($user, $pass)) {
        $id = getUser($user, $pass);
        setUserCookie($id);
        echo "success";
    }
    //check if username exists but incorrect password entered
    else if (chkUser($user)) {
        echo "Username and password do not match";
    }
    //Or else return that username doesn't exist
    else {
        echo "Username does not exist";
    }
}
?>


Q:

Generating ECDSA signature with Node.js/crypto

I have code that generates a concatenated (r-s) signature for the ECDSA signature using jsrsasign and a key in JWK format:
const sig = new Signature({ alg: 'SHA256withECDSA' });
sig.init(KEYUTIL.getKey(key));
sig.updateHex(dataBuffer.toString('hex'));
const asn1hexSig = sig.sign();
const concatSig = ECDSA.asn1SigToConcatSig(asn1hexSig);
return new Buffer(concatSig, 'hex');

Seems to work. I also have code that uses SubtleCrypto to achieve the same thing:
importEcdsaKey(key, 'sign') // importKey JWK -> raw
.then((privateKey) => subtle.sign(
    { name: 'ECDSA', hash: {name: 'SHA-256'} },
    privateKey,
    dataBuffer
))

These both return 128-byte buffers; and they cross-verify (i.e. I can verify jsrsasign signatures with SubtleCrypto and vice versa). However, when I use the Sign class in the Node.js crypto module, I seem to get something quite different.
key = require('jwk-to-pem')(key, {'private': true});
const sign = require('crypto').createSign('sha256');
sign.update(dataBuffer);
return sign.sign(key);

Here I get a buffer of variable length, roughly 70 bytes; it does not cross-verify with jsrsa (which bails complaining about an invalid length for an r-s signature).
How can I get an r-s signature, as generated by jsrsasign and SubtleCrypto, using Node crypto?

A:

The answer turns out to be that the Node crypto module generates ASN.1/DER signatures, while other APIs like jsrsasign and SubtleCrypto produce a “concatenated” signature. In both cases, the signature is a concatenation of (r, s). The difference is that ASN.1 does so with the minimum number of bytes, plus some payload length data; while the P1363 format uses two 32-bit hex encoded integers, zero-padding them if necessary.
The below solution assumes that the “canonical” format is the concatenated style used by SubtleCrypto.
const asn1 = require('asn1.js');
const BN = require('bn.js');
const crypto = require('crypto');

const EcdsaDerSig = asn1.define('ECPrivateKey', function() {
    return this.seq().obj(
        this.key('r').int(),
        this.key('s').int()
    );
});

function asn1SigSigToConcatSig(asn1SigBuffer) {
    const rsSig = EcdsaDerSig.decode(asn1SigBuffer, 'der');
    return Buffer.concat([
        rsSig.r.toArrayLike(Buffer, 'be', 32),
        rsSig.s.toArrayLike(Buffer, 'be', 32)
    ]);
}

function concatSigToAsn1SigSig(concatSigBuffer) {
    const r = new BN(concatSigBuffer.slice(0, 32).toString('hex'), 16, 'be');
    const s = new BN(concatSigBuffer.slice(32).toString('hex'), 16, 'be');
    return EcdsaDerSig.encode({r, s}, 'der');
}

function ecdsaSign(hashBuffer, key) {
    const sign = crypto.createSign('sha256');
    sign.update(asBuffer(hashBuffer));
    const asn1SigBuffer = sign.sign(key, 'buffer');
    return asn1SigSigToConcatSig(asn1SigBuffer);
}

function ecdsaVerify(data, signature, key) {
    const verify = crypto.createVerify('SHA256');
    verify.update(data);
    const asn1sig = concatSigToAsn1Sig(signature);
    return verify.verify(key, new Buffer(asn1sig, 'hex'));
}

Figured it out thanks to

https://crypto.stackexchange.com/questions/1795/how-can-i-convert-a-der-ecdsa-signature-to-asn-1
ECDSA signatures between Node.js and WebCrypto appear to be incompatible?


Q:

Calculate your stack exchange reputation

Background:
I often find that, when browsing a Stackexchange site, I begin to wonder how people get the amount of reputation that they have. I know I can always count on codegolf SE to solve my problems, so here it is:
Create a program that will accept a positive integer which represents a person's reputation. We will ignore bounties, and say that these are the only ways to gain/lose rep on SE (full table here):

Every account starts out with 1 rep and cannot go below that
Your question is upvoted = +5
Your answer is upvoted = +10
Your question is downvoted = -2
Your answer is downvoted = -2
You downvote an answer = -1
Your answer is accepted = +15
You accept an answer = +2

Your program must figure out how many of those actions occurred on that user's account to get to the rep they have. It must figure out the shortest number of actions to get to this level of rep. Examples:

Input: 11
Output: 1 answer upvote
Input: 93
Output: 6 answer accepts, 1 answer accepted

In these examples when I say 'question upvote', it means that person's queston got upvoted. When I say 'answer downvoted', it means they downvoted someone else's answer.
Rules:
code-golf, so the shortest code that can do this wins.

A:

Bash, 247 202 192 bytes
n=$1 bash <(sed 's/E/)echo /;s/C/ Aaccept/;s/A/answer /
s/.*)/((&)\&\&/'<<<'a=(n+1)/15,a-1)s=s;q=question
aE$aC$s
r=n%5,r-4)d=d&&
r>1E1Ced
1-r%2E1 Adownvote$d
n-=15*a,n>8)q=A
n>3E1 $q upvote')

How it works
After the sed command does it job, the following bash script gets executed:
((a=(n+1)/15,a-1))&&s=s;q=question
((a))&&echo $a answer accept$s
((r=n%5,r-4))&&d=d&&
((r>1))&&echo 1 answer accepted
((1-r%2))&&echo 1 answer downvote$d
((n-=15*a,n>8))&&q=answer
((n>3))&&echo 1 $q upvote

To obtain the optimal solution (minimal number of events to get n reputation), it suffices to compute the number of accepted answers (a) necessary to get to a reputation below 16 (1 answer accept) and handle the residue as follows:
1  (no rep change)
2  answer accepted, answer downvoted
3  answer accepted
4  question upvote, answer downvote
5  question upvote, answer downvoted
6  question upvote
7  question upvote, answer accepted, answer downvoted
8  question upvote, answer accepted
9  answer upvote, answer downvote
10 answer upvote, answer downvoted
11 answer upvote
12 answer upvote, answer accepted, answer downvoted
13 answer upvote, answer accepted
14 answer accept, answer downvote
15 answer accept, answer downvoted

A:

Perl, 500 263 256 208 bytes
Script rep.pl:
$_=1+pop;sub P($){print$=,@_,$/}$;=" answer ";$:="$;downvote";($==$_/15)&&P"$;accept"."s"x($=>1);$_%=15;$==1;P"$;upvote",$_-=10if$_>9;P" question upvote",$_-=5if$_>4;P"$;accepted"if$_>2;P$:."d"if$_%2;P$:if!$_

Usage
The input is expected as positive integer, given as argument to the script. The different actions are output as lines.
Tests
perl rep.pl 11
1 answer upvote

perl rep.pl 93
6 answer accepts
1 answer accepted

perl rep.pl 1

perl rep.pl 4
1 question upvote
1 answer downvote

perl rep.pl 12
1 answer upvote
1 answer accepted
1 answer downvoted

perl rep.pl 19
1 answer accept
1 question upvote
1 answer downvote

perl rep.pl 34
2 answer accepts
1 question upvote
1 answer downvote

perl rep.pl 127
8 answer accepts
1 question upvote
1 answer accepted
1 answer downvoted

perl rep.pl 661266
44084 answer accepts
1 question upvote

Ungolfed
$_ = pop() + 1; # read the reputation as argument,
                # remove the actionless start reputation
                # and add a bias of two to calculate
                # the answer accepts in one division.

# Actions
# -------
# answer accepts:      Your answer is accepted    = +15
# answer upvotes:       Your answer is upvoted     = +10
# question upvotes:     Your question is upvoted   = +5
# answers accepted:     You accept an answer       = +2
# answers downvoted:    You downvote an answer     = -1
# answer downvotes:     Your answer is downvoted   = -2
# (questions downvoted: Your question is downvoted = -2) not used

# Function P prints the number of actions in $= and
# the action type, given in the argument.
# The function is prototyped "($)" to omit the
# parentheses in the usage.
sub P ($) {
    print $=, @_, $/ # $/ is the line end "\n"
}
# abbreviations,
# special variable names to save a space if a letter follows
$; = " answer ";
$: = "$;downvote";

# Calculation and printing the result
# -----------------------------------
($= = $_ / 15) && # integer division because of the special variable $=
P "$;accept" .
  "s" x ($= > 1); # short for: ($= == 1 ? "" : "s")
$_ %= 15;
$= = 1;           # now the action count is always 1 if the action is used
P "$;upvote",         $_ -= 10 if $_ > 9;
P " question upvote", $_ -=  5 if $_ > 4;
P "$;accepted"                 if $_ > 2;
P $: . "d"                     if $_ % 2;
P $:                           if ! $_

Older version
$_ = pop() + 1; # read the reputation as argument
                # subtract start reputation (1)
                # add bias (2)

# Actions
# -------
# $= answer accepts:      Your answer is accepted    = +15
# $b answer upvotes:      Your answer is upvoted     = +10
# $c question upvotes:    Your question is upvoted   = +5
# $d answers accepted:    You accept an answer       = +2
# $e answers downvoted:   You downvote an answer     = -1
# $f answer downvotes:    Your answer is downvoted   = -2
# -- questions downvoted: Your question is downvoted = -2

# Calculaton of answer accepts by a simple division that is
# possible because of the bias.
$= = $_ / 15; # integer division because of the special variable $=
$_ %= 15;

# The older version of the calculation can be simplified further, see below.
# Also the older version did not use the bias.
#
# function E optimizes the construct "$_ == <num>" to "E <num>"
# sub E {
#     $_ == pop
# }
#
# $d = $e = 1 if E 1;       #  1 =     +2 -1
# $d++ if E 2;              #  2 =     +2
#
# $c = $f = 1 if E 3;       #  3 =  +5 -2
# $c = $e = 1 if E 4;       #  4 =  +5 -1
# $c++ if E 5;              #  5 =  +5
# $c = $d = $e = 1 if E 6;  #  6 =  +5 +2 -1
# $c = $d = 1 if E 7;       #  7 =  +5 +2
#
# $b = $f = 1 if E 8;       #  8 = +10 -2
# $b = $e = 1 if E 9;       #  9 = +10 -1
# $b++ if E 10;             # 10 = +10
# $b = $d = $e = 1 if E 11; # 11 = +10 +2 -1
# $b = $d = 1 if E 12;      # 12 = +10 +2
#
# $=++, $f++ if E 13;       # 13 = +15 -2
# $=++, $e++ if E 14;       # 14 = +15 -1

$b++, $_ -= 10 if $_ > 9;
$c++, $_ -=  5 if $_ > 4;

# Now $_ is either 0 (-2), 1 (-1), 2 (0), 3 (1), or 4 (2).
# The number in parentheses is the remaining reputation change.

# The following four lines can be further optimized.
# $f++        if ! $_;    # "! $_" is short for "$_ == 0"
# $e++        if $_ == 1;
# $d = $e = 1 if $_ == 3;
# $d++        if $_ == 4;

# Optimized version of the previous four lines:

$f++ if ! $_;
$e++ if $_ % 2;
$d++ if $_ > 2;

# function P optimizes the printing and takes the arguments for "print";
# the first argument is the action count and the printing is suppressed,
# if this action type is not needed.
sub P {
    print @_, $/ if $_[0]
    # $/ is "\n"
}

# some abbreviations to save some bytes
$; = " answer ";
$D = "$;downvote";

# output the actions

P $=, "$;accept", ($= == 1 ? "" : "s");
P $b, "$;upvote";
P $c, " question upvote";
P $d, "$;accepted";
P $e, $D, "d";
P $f, $D

Edits

Case 4 is fixed.
This also simplifies the calculation that is now done without a loop.
Unreachable plural "s" removed, function S no longer needed.
Calculation optimized, function E no longer needed.
Bias of 2 added for optimized calculation.
Larger rewrite to remove most variables some other tricks to save some bytes.

A:

R, 454 421
r=as.integer(commandArgs(T)[1])-1;p=function(...){paste(...,sep='')};a='answer ';b='accept';e='ed';f='d';v='vote';d=p('down',v);u=p('up',v);q='question ';z=c();t=r%/%15;if(t>0){z=c(p(t,' ',a,b));r=r%%15;};if(r%in%(8:12))z=c(z,p(a,u));if(r%in%(3:7))z=c(z,p(q,u));if(r%in%c(1,2,6,7,11,12))z=c(z,p(a,b,e));if(r%in%(13:14))z=c(z,p(a,b));if(r%in%c(3,8,13))z=c(z,p(a,d));if(r%in%c(1,4,6,9,11,14))z=c(z,p(a,d,f));cat(z,sep=', ')

Thanks to Dennis for his answer which helped me a lot.
Ungolfed version
# read input
r = as.integer(commandArgs(T)[1]) - 1

# shortcut to join strings (... will pass the parameter to paste() *as is*)
p = function(...) {paste(..., sep = '')}

# strings
a = 'answer '; b = 'accept'; e = 'ed'; f = 'd'
v = 'vote'; d = p('down',v); u = p('up',v)
q = 'question '

z = c()

# +15
t = r %/% 15;
if (t > 0) {
    z = c(p(t,' ',a,b))
    r = r %% 15
}

if (r %in% (8:12))              z = c(z,p(a,u));    # answer upvote
if (r %in% (3:7))               z = c(z,p(q,u));    # question upvote
if (r %in% c(1,2,6,7,11,12))    z = c(z,p(a,b,e));  # answer accepted
if (r %in% (13:14))             z = c(z,p(a,b));    # answer accept
if (r %in% c(3,8,13))           z = c(z,p(a,d));    # answer downvote
if (r %in% c(1,4,6,9,11,14))    z = c(z,p(a,d,f));  # answer downvoted

# print operations
cat(z,sep = ', ')


Q:

Failed to init angularjs, included ng-controller

Not sure why I coulnd't run angularjs. I've created a repo here https://github.com/eldyvoon/temp/blob/master/app/index.html
Am I doing anything wrong? I've included angulajs, put ng-app and ng-controller, but the $scope.test doesn't work..

A:

in your sample you didn't declare an ng-app
try add it in the body tag of you'r index html
 <body ng-app="main">

hope this helps


Q:

An error when specify range for RangeValidator

I try to specify range from 4 to 13. But it keeps error "The MaximumValue 13 cannot be less than the MinimumValue 4 of RangeValidator1." How can I solve this. Here's my code:

     <asp:TextBox ID="TextBox2" runat="server" ValidationGroup="Group1"></asp:TextBox>
     <asp:RequiredFieldValidator ID="RequiredFieldValidator3" runat="server"
                ControlToValidate="TextBox2" ErrorMessage="กรุณากรอก Password" ForeColor="Red"
                ValidationGroup="Group1">*</asp:RequiredFieldValidator>
     <asp:RangeValidator ID="RangeValidator1" runat="server"
                ControlToValidate="TextBox2"
                ErrorMessage="Password ต้องมีความยาวตั้งแต่ 4-13 ตัวอักษร" ForeColor="Red"
                MaximumValue="13" MinimumValue="4" Type="String" EnableClientScript="false">*</asp:RangeValidator>

This is the code in Button:

    protected void Button2_Click1(object sender, EventArgs e)
    {
        try
        {
            if (Page.IsValid)
            {

            }
            else
            {
                Insert();
            }
        }
        catch (Exception ex)
        {

        }
    }

Any help appreciated.

A:

Set the type Integer when you are using RangeValidator for integer type values.
<asp:RangeValidator ID="RangeValidator1" runat="server"
                ControlToValidate="TextBox2"
                ErrorMessage="Password ต้องมีความยาวตั้งแต่ 4-13 ตัวอักษร" ForeColor="Red"
                MaximumValue="13" MinimumValue="4" Type="Integer" EnableClientScript="false">*</asp:RangeValidator>

But I am surprised that you are using RangeValidator with Password field. In this case you are restricting user to put value between 4-13.
You probably wants to check the length of input. For that you use Regular Expression validator.
<asp:RegularExpressionValidator ID="RegexVal" ValidationExpression="^.{4,13}$"  runat="server" ErrorMessage="Password must be 4-13 character long" ControlToValidate="TextBox2"  />

A:

RangeValidator validates the value of the control, not the value length. For string comparison "13" is less than "4", so you are getting the "max < min" error.
You should use RegularExpressionValidator to check the input length:
 <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server"
            ControlToValidate="TextBox2"
            ErrorMessage="Password ต้องมีความยาวตั้งแต่ 4-13 ตัวอักษร" ForeColor="Red"
            ValidationExpression="^.{4,13}$" ValidationGroup="Group1" EnableClientScript="false">*</asp:RegularExpressionValidator>


Q:

Listen power key press when device's keyguard locked

Assuming a service is running in background for three to four hours. In that particular time:
When Android device's keyguard is in locked state, I want to listen to an event, for example a power key press three times subsequently, and open an activity that will be a pattern lock.
Summary

Start a service for 3 - 4 hours.
Keyguard Lock.
Press power button 3 times subsequently.
Open Lock pattern as an activity.

How to do this? Any help will be appreciated.

A:

take a look at this answer about hooking the power button with a BroadcastReceiver.
all you need to add is the counter and make the Activity with the lock pattern. (try reading this answer)


Q:

Could the Marauder's map show two sets of Harry and Hermione?

Prof. Lupin explains to Harry in the Shrieking Shack that he was looking at the map when they went to meet Hagrid before the execution of Buckbeak. Three people went in, but four came out. Why didn't he see Pettigrew's dot (as Scabbers) inside Hagrid's cabin?  I do not think Hagrid's hut was unplottable, because even the insides of the castle aren't. Even the Professors' personal study rooms are visible (Harry was relieved to see Prof. Snape back in his study, I don't remember which book, though; maybe Prisoner of Azkaban).
But my main question is, when the Harry/Ron/Hermione come out of Hagrid's hut with Pettigrew, the Harry/Hermione pair from the future were hiding nearby, close enough to be able to see themselves (their past versions) coming out of the cabin. Given the size of Hogwarts and the scale of the map, shouldn't both the past and future versions appear relatively close to each other? Shouldn't someone watching the versions come out of the cabin see the ones hiding near the forest as well?
Incidentally, would the map show Buckbeak too?

A:

I think the map would show two sets of Harry/Hemione, because in the Harry Potter universe, time travel means that you end up having two versions of yourself at the same time. Which is why Harry and Hermione are warned not to be seen by anyone. The main point is that the map always shows the truth so it would show two versions of them moving about.
I doubt that the map shows animals because when you think about it lots of people have pets in Hogwarts but they don't show on the map. So Buckbeak, maybe not but only because she's an animal and not to do with the time travel.


Q:

how to use a resource in a storyboard using TargetName

As below I would like to set the TargetName to movingImage so that the image moves across the screen left to right. Visual Studio throws an error and am not sure how to reference it correctly. I would like to keep the image in a resource dictionary and bring it in programmatically as required.
I have the following resource:
            <Canvas.Resources>

            <Storyboard x:Key="myStory">
                <DoubleAnimation Storyboard.TargetName="movingImage"
                                 Storyboard.TargetProperty="(Canvas.Left)"
                                 Duration="0:0:5"
                                 From="-157"
                                 To="78"/>
            </Storyboard>

            <Image x:Key="movingImage"
                   Canvas.Left="-157"
                   Source="Resource\myImage.png"/>

            </Canvas.Resources>

And have brought the Storyboard and Image as follows in MainWindow.xaml.cs:
myCanvas.Children.Add(myCanvas.FindResource("movingImage") as UIElement);
sb = myCanvas.FindResource("myStory") as Storyboard;
sb.Begin();

The error I am getting is:

An unhandled exception of type 'System.InvalidOperationException' occurred in PresentationFramework.dll
Additional information: 'movingImage' name cannot be found in the
  name scope of 'System.Windows.Controls.Canvas'.

A:

Do these changes :

Change Key of Image control to movingImageKey, and name to movingImage.
   <Image x:Key="movingImageKey" x:Name="movingImage"
           Canvas.Left="-157"
           Source="Penguins.jpg"/>

Code :
    NameScope.SetNameScope(myCanvas, new NameScope());

    Image img = (myCanvas.FindResource("movingImageKey") as Image);
    myCanvas.RegisterName(img.Name, img);
    myCanvas.Children.Add(img);

    Storyboard sb = myCanvas.FindResource("myStory") as Storyboard;
    sb.Begin();


Q:

How do you find the angle of intersection between two given polar curves?

How does one find the angle of intersection between two given polar curves?
For example, between
$a^2=r^2\sin(2\theta)$ & $b^2=r^2\cos(2\theta)$

A:

For a curve given with $y(x)$ in Cartesian coordinates, $\frac{dy}{dx}$ is a slope of the curve with respect to the $y=\mathrm{const.}$ line (a tangent of the angle between the curve and the 'horizontal' line).
In polar coordinates, $\frac 1r\frac{dr}{d\theta}$ is a slope of the curve given with $r(\theta)$ with respect to the $r=\mathrm{const.}$ circle.
So you need to

convert equations to the $r=f(\theta)$ form,
solve a system of equations to find an intersection point (or points),
then calculate $\frac 1r\frac{dr}{d\theta}$ for both functions at $\theta$ corresponding to the intersection point,
apply $\arctan$ to them to obtain angles
and finally calculate the difference between angles.


Q:

How to display all product prices on the page at once with Drupal commerce?

I have several products related to a single product display node using Drupal Commerce.
Currently this page only shows a single price (related to the product option currently selected in the dropdown). The only way you can see the prices of the other products is to change the dropdown, which invokes an AJAX request to reload the current product options (including price).
Obviously this is counter-intuitive for customers, who are used to seeing all of the prices available at one time, and not having to change to a new option with the dropdown just to see the price of that option.
How do I change this display so it functions like a traditional e-commerce website? By that I mean either a dropdown that contains the product name AND product price, or (far more preferably) a table with the list of available products, with their prices in one of the columns?
I can only assume that this very basic functionality must exist somewhere in the Commerce configuration settings somewhere, but as yet I haven't been able to find it.
I could easily write a module to code round this problem, but I'm currently evaluating Commerce to see whether it's good enough for our agency to use in future e-commerce projects, without having to re-invent the wheel over and over again. To that end, answers involving code probably won't be too useful.
Muchas gracias

A:

If themeing is considered "involving code", then you could create a view block.
Using Contextual Filters and Relationships, a View will be able to list all the referenced products on a node (including their fields).

Start by creating a View listing all the nodes that have a product
reference field (ex: Product Display).
Add a Contextual Filter for the Nid that defaults to use the Nid from the URL
Next add a Relationship (Product) using the product reference field of the Product Display node
Then add another Relationship (Line Item) for the Commerce Line Item of the referenced product

After that is all setup, you can add fields that use the Line Item relationship to get product titles, calculated prices, etc.


Q:

how to use getlinecount() in textview android

i want to know how many line in my text view.
i already set mytextview text, then i want to get how many line it take in mytextview.
i use mytextview.getLineCount() but it didn't work.
it always return 0.
can someone helpme.

A:

You need to post method for fetching the lines counts. Here is the sample code
imageCaption.setText("Text Here");
imageCaption.post(new Runnable() {

    @Override
    public void run() {

        int lineCount    = imageCaption.getLineCount();

        Log.v("LINE_NUMBERS", lineCount+"");
    }
});

A:

thanks for all. i solved it already. i use thread to get the linecount just like this
@Override
public void run() {
    // TODO Auto-generated method stub
    while(textView.getLineCount() == 0){

    }
    countLine = textView.getLineCount();

}

hope this will help if you have same problem.
best regard.


Q:

How to convert multiple perl programs into a ready to install software?

I have multiple perl programs written myself, which calculate genomic parameters, change headers, extract specific sequences from genome data or fasta sequences. Is there any way to build a package/ software which will calculate above things on clicking buttons in a menu and using my perl programs to do so.

A:

PAR::Packer is an utility which bundles an entire Perl project into a distributable executable with no external dependencies. It does so packing the Perl interpreter itself plus used modules (with XS binaries) into a single file. When user executes such a file, everything is unpacked to a temporary location, executed, and cleaned up on finish.


Q:

Cannot invoke $function with object of type *

I'm having trouble with a type error that seems to be incorrect. The following code produces the error:
"Cannot invoke baz with argument list of type (f: (A) -> (), g: (String) -> ())" As indicated, the "incorrect" type is the exact type of baz, which is being called.
NB: I pulled out 'succeed' and 'fail' for type clarity, but the same thing happens when using the functions as closures.
class Foo<A> {
  ..
  func baz(f: (A) -> (), g: (String) -> ()) {
    .. do some stuff
  }
  func bar<A, B>(f: (A -> B)) -> Foo<B> {
    func succeed(a: A) -> () {
      .. do some stuff
    }
    func fail(s:String) -> () {
      .. do some stuff
    }
    baz(f: succeed, g: fail)
    .. do some stuff
  }
}

A:

Your generic parameter A declared for function bar overrides the generic type declared for class Foo, you need to remove it:
class Foo<A> {
    func baz(f: (A) -> (), g: (String) -> ()) {}

    func bar<B>(f: (A -> B)) -> Foo<B> {
        func succeed(a: A) -> () {}

        func fail(s:String) -> () {}

        baz(succeed, g: fail)

        return Foo<B>()
    }
}


Q:

How Can I Clean Up My CSS?

I have a ton of css validation errors because of css3 and a ton of warnings.  What is the best way to deal with this?  Here is the validation:
http://jigsaw.w3.org/css-validator/validator?uri=http%3A%2F%2Fbrainbuzzmedia.com%2Fthemes%2Famplify%2Fwordpress%2F&profile=css21&usermedium=all&warning=1&lang=en

A:

Since you are validating your CSS against the CSS2.1 specification, you can expect to get a series of errors for any CSS3 properties you've included in your styles (e.g. your rounded corners).  You should validate against the highest spec you're writing against: CSS3 in your case.
If we run the validator again with CSS3, you straight away halve the number of errors you see.  Again, you can discount the errors given for vendor-specific attributes such as -moz-border-radius since the CSS specifications do not discriminate based on the type of browser, its only concern is the standard border-radius declaration.  Browser vendors have adopted their own prefixes as a hedge against an as-yet unratified standard (although border radius should really be supported by all browsers by now IMHO).
Once you've taken out these issues your error list is actually looking pretty manageable, with only a few star hacks that the validator doesn't like.  If you can fiddle your CSS better to achieve the same results in IE without as many hacks (or perhaps include a separate IE stylesheet with a conditional comment in your Wordpress template) your styles should all be looking good.
The bottom line is essentially, if you're using CSS3 and vendor-specific prefixes, you can expect the W3C Validator to call you out on what it considers to be non-standard declarations.


Q:

What happens if you skip the practice games?

I haven't played any league games yet in StarCraft 2. When I go to the league page, there is a  button that suggests something like "test skills". As far as I know it will be 5 games to determine my level and to put me in the most appropriate group (bronze, silver, etc).
But there is also "Skip" button. What will be if I skip those testing? Will I be able to play few games and than go back to tests? Or I will be put into "Bronze" league instead?

A:

I believe this "test skills" option you are referring to is your practice games.  You get  50 practice games, and they are optional. These games don't count for anything in your profile. I'm not sure exactly whom they are against (whether other practice league players or regular league players).
Once you run out of your 50 practice games (or skip them), you will not be able to go back.
After the practice games, you will then be put into your placement matches.  From this point on, your games record goes into your profile. The placement matches are to determine in what league you will best be placed (Bronze, Silver, etc.).  Once your placement matches are over, you will be in one of those leagues. You won't be able to choose to go back to the placement matches again - the matchmaking system will only be matching you up against people it thinks are evenly matched with you.
Personally, I skipped the practice games.  I wanted to start playing against people the system thinks are evenly matched with me as soon as possible.

A:

You start out in the practice league. In this league you play unranked matches against other practice league players, on special maps designed to prevent early rushes. Matches in the practice league also take place at a slower game speed.
You can play 50 games in the practice league before you have to move on. You can also choose to leave the practice league early, but if you do so you won't be able to go back. (This is the "Skip" button you mentioned)
Once you leave the practice league, you begin a series of 1v1 placement matches to determine which 1v1 league you will be placed in (Bronze, Silver, Gold, etc.) You can't play any ranked games (1v1, 2v2, etc) until you leave the practice league.


Q:

Подключение js/css в Symfony4

Помогите разобраться с подключением js/css в Symfony4 с Webpack Encore.
Пытаюсь подключить adminlte для админки.
Скачиваю его через npm в node_modules и ... как действовать дальше, чтобы использовать скрипты и стили в шаблонах?
Со скриптами, если понимаю правильно, просто - создаем в assets/js файл, подключаем в нем
var adminlte=require('admin-lte');

и в шаблон подключаем сгенерированный через webpack файл.
А вот как подключать стили?

A:

В шаблоне подключаем собранные вебпаком файлы (public/build):
<link rel="stylesheet" href="{{ asset('build/app.css') }}">
<script src="{{ asset('build/app.js') }}"></script>

В app.js и app.css будут включены все файлы используемые в проекте, в том числе и из node_modules.
Подключить css в app.js можно примерно так:
require('admin-lte/dist/AdminLTE.min.css')


Q:

How can I speedup this Julia code?

The code implements an example of a Pollard rho() function for finding a factor of a positive integer, n. I've examined some of the code in the Julia "Primes" package that runs rapidly in an attempt to speedup the pollard_rho() function, all to no avail. The code should execute n = 1524157897241274137 in approximately 100 mSec to 30 Sec (Erlang, Haskell, Mercury, SWI Prolog) but takes about 3 to 4 minutes on JuliaBox, IJulia, and the Julia REPL. How can I make this go fast?
pollard_rho(1524157897241274137) = 1234567891
__precompile__()
module Pollard

export pollard_rho

function pollard_rho{T<:Integer}(n::T)
    f(x::T, r::T, n) = rem(((x ^ T(2)) + r), n)
    r::T = 7; x::T = 2; y::T = 11; y1::T = 11; z::T = 1
    while z == 1
        x  = f(x, r, n)
        y1 = f(y, r, n)
        y  = f(y1, r, n)
        z  = gcd(n, abs(x - y))
    end
    z >= n ? "error" : z
end

end # module

A:

There are quite a few problems with type instability here.

Don't return either the string "error" or a result; instead explicitly call error().
As Chris mentioned, x and r ought to be annotated to be of type T, else they will be unstable.

There also seems to be a potential problem with overflow. A solution is to widen in the squaring step before truncating back to type T.
function pollard_rho{T<:Integer}(n::T)
    f(x::T, r::T, n) = rem(Base.widemul(x, x) + r, n) % T
    r::T = 7; x::T = 2; y::T = 11; y1::T = 11; z::T = 1
    while z == 1
        x  = f(x, r, n)
        y1 = f(y, r, n)
        y  = f(y1, r, n)
        z  = gcd(n, abs(x - y))
    end
    z >= n ? error() : z
end

After making these changes the function will run as fast as you could expect.
julia> @btime pollard_rho(1524157897241274137)
  4.128 ms (0 allocations: 0 bytes)
1234567891

To find these problems with type instability, use the @code_warntype macro.


Q:

Get total value of a particular column in multiple row table

I created a table where I can dynamically add multiple rows to it. There's a column to add cost. Now I want to
get total cost value of each row at the bottom of the table. How can I get this using JavaScript?
Here is my html code for dynamic table.

            No
            Title
            <th cost

            1

                <input type="text"  id="title" name="title[]" />

                <input type="text"  id="cost" name="cost[]" />

Javascript function:
$(function(){
        $('.addrow').click(function(){
            addrow();
        });

        function addrow()
        {

            var row =($('#body tr').length-0)+1;
            var tr ='
'+
                ''+row+'	'+
                '<input type="text" id="title" name="title[]" >	'+
                '<input type="text"  id="cost" name="cost[]" />	'+
                '
';
            $('#body').append(tr);
        }
    });

A:

You should iterate the input tags that belong to the table and have an id starting with "cost".
Also, you can not add the row directly to the body, you want to add it after the last row already created.
Try out this (edit:) fiddle (old habits die hard) snippet .

$(document).ready(function(){
        $('#addRow').click(function(){
            addRow();
        });
        $('#totalRow').click(function(){
            totalRow();
        });

        function addRow()
        {
            var rowId = $('#myTable tr').length;
   $('#myTable > tbody:last-child').append(
       '
' + rowId + ' 	' +
       '<input type="text"  id="title' + rowId + '" />	' +
                '<input type="text"  id="cost' + rowId + '"
'
   );
    }

        function totalRow()
        {
            var rowId = $('#myTable tr').length;
            var val = 0;
             $("#myTable [id^=cost]").each(function() {
       val += parseFloat($(this).val());
    });
   $('#myTable > tbody:last-child').append(
       '
T	' +
       '<input type="text" id="totalRow" value="TOTAL" />	' +
                '<input type="text" id="totalCost" value="' + val +'" />
'
   );
  }
    });

Add row

Calculate total row

            No
            Title
            Cost

            1

                <input type="text"  id="title1" value="Example" />

                <input type="text"  id="cost1" value="25" />

Hope it helps!


Q:

How to use an ICollection navigation property with include()

I am trying to get each user with its projects using entity framework core in a web api project in the controller with linq
I tried with this query but it gave me an empty object
var users = _context.Users.Include(x => x.userProjects.Select(up => up.UserId == x.Id)).ToListAsync();

I also tried this one and got the same result
var users = _context.Users.Include(x => x.userProjects.Where(up => up.UserId == x.Id)).ToListAsync();

This is the User class
public class User
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<UserProject> userProjects { get; set; }
}

This is the Project class
public class Project
{
    public int Id { get; set; }
    public string Name { get; set; }

    public ICollection<User> Users { get; set; }
    public ICollection<UserProject> UserProjects { get; set; }
}

and this is the UserProject class
public class UserProject
{
    [ForeignKey("User")]
    public int UserId { get; set; }
    public User User { get; set; }

    [ForeignKey("Project")]
    public int ProjectId { get; set; }
    public Project Project { get; set; }
}

I want to get a json with each user and an array of its projects

A:

For multiple level of includes, you need ThenInclude.
var users = _context.Users
                    .Include(x => x.userProjects)
                        .ThenInclude(y => y.Project)
                    .ToListAsync();


Q:

I'm getting strange error during debugging in Visual Studio

When I debug my web apps and WCF srvices I often get such error. This happens randomly (I suppose). But after that - I must to start debugging anew from beginning.
PS. Script debugging in IE is disabled.
PPS. Google searching didn't help me.

A:

Did you try setting your executable project as a start up project (in case of multiple projects in the solution)?
Editing to add the solution that solved the problem mentioned in the comments already:
If you want to run the projects simultaneously, you can use the "Start multiple projects" option in VS. Goto Solution Explorer -> solution properties -> Common properties -> Startup Project and select Multiple startup projects
But, if your projects are dependent on each other and you want to use same debugger, you might want to consider this solution:
https://stackoverflow.com/a/32132756/5434084