text:
Q: Drawing point geometry with StreamGeometryContext Trying to draw a polar type chart using GeometryContext in C#. I have input of direction as an xRange (start & stop) which is in degrees. I'm converting this to Radians. All good. The yRange is cut in & cut out wind speed currently in m/s as a double. I'm trying to acheive a simplified version of the image below without the axis labels etc.

For each object to be charted I am returning an XY range:
 public IEnumerable<Styled2DRange> Query()
    {
        SolidColorBrush brush = new SolidColorBrush(Colors.Maroon);
        brush.Freeze();
        Pen linePen = new Pen(brush, 3);
        linePen.Freeze();
        SolidColorBrush fillBrush = new SolidColorBrush(Colors.Maroon);
        fillBrush.Freeze();

        foreach (var range in this.Charts)
        {
            Range xRange = new Range(ConvertToRadians(range.StartDirection), ConvertToRadians(range.EndDirection));
            Range yRange = new Range(range.CutInWindSpeed, range.CutOutWindSpeed);

            yield return new 2DRange()
            {
                Range = new XYRange()
                {
                    XRange = xRange,
                    YRange = yRange
                },

                Line = linePen,
                Fill = fillBrush
            };
        }

        yield break;
    }

This method is called from my override of Onrender. Obviously my points to be drawn by the StreamGeometryContext don't make sense as the Range.Y values are just wind speeds in m/s:
  protected override void OnRender(DrawingContext dc)
    {
         Point origin = new Point(0, 0);
         double maxR = 0;

         SweepDirection outerSweep = SweepDirection.Clockwise;
         SweepDirection innerSweep = SweepDirection.Counterclockwise;

         outerSweep = SweepDirection.Counterclockwise;
         innerSweep = SweepDirection.Clockwise;

         foreach (Styled2DRange range in Query())
         {
             maxR = Math.Max(maxR, range.Range.YRange.End);

                Point outerScreenPointBefore = new    Point(range.Range.XRange.Start, range.Range.YRange.End);
                Point outerScreenPointAfter = new Point(range.Range.XRange.End, range.Range.YRange.End);

                Point innerScreenPointBefore = new Point(range.Range.XRange.Start, range.Range.YRange.Start);
                Point innerScreenPointAfter = new Point(range.Range.XRange.End, range.Range.YRange.Start);

                StreamGeometry sectorGeometry = new StreamGeometry();
                sectorGeometry.FillRule = FillRule.Nonzero;

                using (StreamGeometryContext geometryContext = sectorGeometry.Open())
                {

                    geometryContext.BeginFigure(innerScreenPointBefore, true, true);
                    geometryContext.LineTo(outerScreenPointBefore, true, false);

                    double outerCircleRadius = Math.Sqrt(Math.Pow(outerScreenPointBefore.X - origin.X, 2) + Math.Pow(outerScreenPointBefore.Y - origin.Y, 2));
                    geometryContext.ArcTo(outerScreenPointAfter, new Size(outerCircleRadius, outerCircleRadius), 0, false, outerSweep, true, false);

                    geometryContext.LineTo(innerScreenPointAfter, true, false);

                    double innerCircleRadius = Math.Sqrt(Math.Pow(innerScreenPointBefore.X - origin.X, 2) + Math.Pow(innerScreenPointBefore.Y - origin.Y, 2));
                    geometryContext.ArcTo(innerScreenPointBefore, new Size(innerCircleRadius, innerCircleRadius), 0, false, innerSweep, true, false);
                }

                sectorGeometry.Freeze();
                dc.DrawGeometry(range.Fill, range.Line, sectorGeometry);
            }
       }

So how do I reference the wind speed to create an actual point within the bounds of the drawing?

A: The four points of your chart sector are lying on two concentric circles, where the radius of the inner circle is given by the start wind speed, and that of the outer circle by the end wind speed. The position of the points on each circle is directly given by the wind directions in radians.
Provided that you have the variables startDirection and endDirection for the wind directions and startSpeed and endSpeed for the wind speeds, a sector would be constructed like this:
var pStart = new Point(Math.Sin(startDirection), -Math.Cos(startDirection));
var pEnd = new Point(Math.Sin(endDirection), -Math.Cos(endDirection));
var isLargeArc = Math.Abs(endDirection - startDirection) > Math.PI;
var geometry = new StreamGeometry();

using (var sgc = geometry.Open())
{
    sgc.BeginFigure( // start point on inner circle
        new Point(startSpeed * pStart.X, startSpeed * pStart.Y),
        true, true);

    sgc.ArcTo( // end point on inner circle
        new Point(startSpeed * pEnd.X, startSpeed * pEnd.Y),
        new Size(startSpeed, startSpeed), // radius of inner circle
        0d, isLargeArc, SweepDirection.Clockwise, true, true);

    sgc.LineTo( // end point on outer circle
        new Point(endSpeed * pEnd.X, endSpeed * pEnd.Y),
        true, true);

    sgc.ArcTo( // start point on outer circle
        new Point(endSpeed * pStart.X, endSpeed * pStart.Y),
        new Size(endSpeed, endSpeed), // radius of outer circle
        0d, isLargeArc, SweepDirection.Counterclockwise, true, true);
}


text:
Q: Event selection cuts and cross section relation I was working on experimental HEP project where I am bit confused. I generated 1000 MC events with say "x" cross section and without selection cuts. Now suppose I put some selection cuts while writing the C++ code for the data analysis of these events. Because of this, the number of events now drops down, say "y" (<1000) which is logical but while doing any computation should I write the cross section now as (y.x)/1000 ?

A: The particular cross section is fixed by the physics of the interaction. A Monte Carlo modelling the data has all the possible channels and phase space defined by construction. In the experiment one cannot access all the phase space, due to the experimental limitations.

The transition probability per unit time for the interaction under study is given by the specific quantum mechanical model ,used in the generator of the MC events.
When the MC data fit the part of the cross section available to the detectors, one extrapolates to the full cross section , assuming that the model is perfect.
So if your experiment covers lets say an angle between two particles of 90 degrees, the Monte Carlo is used to extrapolate to the full crossection 360 degree phase space.   Suppose you found 2 events within the experiment's phase space, and the MC extrapolates another 3. Then the cross section for the interaction gives five events, of which two detectable by the experiment. Thus the theoretical cross section is measured by the use of the Monte Carlo events.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to clone an iterator? Suppose I have an iterator:
val it = List("a","b","c").iterator

I want a copy of it; my code is:
val it2 = it.toList.iterator

It's correct, but seems not good. Is there any other API to do it?

A: The method you are looking for is duplicate.
scala> val it = List("a","b","c").iterator
it: Iterator[java.lang.String] = non-empty iterator

scala> val (it1,it2) = it.duplicate
it1: Iterator[java.lang.String] = non-empty iterator
it2: Iterator[java.lang.String] = non-empty iterator

scala> it1.length
res11: Int = 3

scala> it2.mkString
res12: String = abc

A: Warning: as of Scala 2.9.0, at least, this leaves the original iterator empty.  You can val ls = it.toList; val it1 = ls.iterator; val it2 = ls.iterator to get two copies.  Or use duplicate (which works for non-lists also).
Rex's answer is by the book, but in fact your original solution is by far the most efficient for scala.collection.immutable.List's.
List iterators can be duplicated using that mechanism with essentially no overhead. This can be confirmed by a quick review of the implementation of iterator() in scala.collection.immutable.LinearSeq, esp. the definition of the toList method, which simply returns the _.toList of the backing Seq which, if it's a List (as it is in your case) is the identity.
I wasn't aware of this property of List iterators before investigating your question, and I'm very grateful for the information ... amongst other things it means that many "list pebbling" algorithms can be implemented efficiently over Scala immutable Lists using Iterators as the pebbles.


text:
Q: Share Extension not uploading full size images i am developeing share extension for my iOS application. i had really done every thing but the problem is that my code is only working for small images but when i upload image taken from device camer then uploading fails and only text get uploded.
- (void)performUploadWith:(NSDictionary *)parameters imageFile:(UIImage *)image{

NSString *boundary = @"SportuondoFormBoundary";

//    NSURLSessionConfiguration *configuration= [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationName];

//    NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
//    NSMutableURLRequest *request;//[NSURLRequest pho]

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.HTTPAdditionalHeaders = @{
                                        @"api-key"       : @"55e76dc4bbae25b066cb",
                                        @"Accept"        : @"application/json",
                                        @"Content-Type"  : [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary]
                                        };

NSURLSession *session=[NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];

NSMutableData *body = [NSMutableData data];

for (NSString *key in parameters)
{
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n\r\n", key] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"%@\r\n", [parameters objectForKey:key]] dataUsingEncoding:NSUTF8StringEncoding]];

}

NSData *imageData = UIImageJPEGRepresentation(image, 0.8);
NSLog(@"imageDATE, %@", imageData);
if (imageData)
{
    [body appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"image.jpg\"\r\n", @"file"] dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:[@"Content-Type: image/jpg\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [body appendData:imageData];
    [body appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
}
[body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];

// Data uploading task. We could use NSURLSessionUploadTask instead of NSURLSessionDataTask if we needed to support uploads in the background
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kURLBase,kURLAddPostDL]];
NSLog(@"url %@",url);
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:10000];
request.HTTPMethod = @"POST";
request.HTTPBody = body;

NSURLSessionUploadTask *upload=[session uploadTaskWithRequest:request fromData:request.HTTPBody];
[upload resume];
}

i update my code to this and i check on server my request never reaches to server. I am using this code
        NSInteger randomNumber = arc4random() % 1000000;
    NSURLSessionConfiguration *config = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[NSString stringWithFormat:@"testSession.foo.%d", randomNumber]];
    config.sharedContainerIdentifier=kGroupNameToShareData;
  session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
  NSURLSessionUploadTask  *uploadTask = [session uploadTaskWithRequest:request fromFile:[NSURL        URLWithString:[NSString stringWithFormat:@"file://%@", dataSrcImagePath]]];

   [uploadTask resume];

A: Extensions aren't allowed their own cache disk space. Need to share with application
Uploading  large image need cache disk space,so you upload failed.
You need create url session with following codes:
let configName = "com.shinobicontrols.ShareAlike.BackgroundSessionConfig"
let sessionConfig = NSURLSessionConfiguration.backgroundSessionConfigurationWithIdentifier(configName)
// Extensions aren't allowed their own cache disk space. Need to share with application
sessionConfig.sharedContainerIdentifier = "group.ShareAlike"
let session = NSURLSession(configuration: sessionConfig)

and then setting the app group both extension target and containing app.
and more infomations you can refer following link:
http://www.shinobicontrols.com/blog/posts/2014/07/21/ios8-day-by-day-day-2-sharing-extension

A: The problem is i am not using background session
  NSURLSessionConfiguration *configuration= [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:configurationName];

- (void)performUploadWith3:(NSDictionary *)parameters imageFile:(UIImage *)image

{
NSString *fileName = @"image.file";
NSString *boundary= @"Boundary+2EB36F87257DBBD4";

NSURL *storeURL = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:kGroupNameToShareData];

storeURL=[storeURL URLByAppendingPathComponent:fileName];
NSLog(@"sotre url %@",storeURL);

NSData *imageData =  UIImageJPEGRepresentation(image, 0.8);

imageData =[self appendParams:parameters andImage:image bondary:boundary];

if (!([imageData writeToFile:[storeURL path] atomically:YES]))
{
    NSLog(@"Failed to save file.");
}

NSString *string=@"URL here";

NSURL *url = [NSURL URLWithString:string];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:@"POST"];

NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
[request setValue:contentType forHTTPHeaderField:@"Content-Type"];

for (NSString *key in parameters)
{
    [request setValue:[parameters objectForKey:key] forHTTPHeaderField:key];

}

if (session == nil)
{
    //If this is the first upload in this batch, set up a new session

    //Each background session needs a unique ID, so get a random number
    NSInteger randomNumber = arc4random() % 1000000;

    sessionConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[NSString stringWithFormat:@"and unique name"]];
    sessionConfiguration.sharedContainerIdentifier=kGroupNameToShareData;
    // config.HTTPMaximumConnectionsPerHost = 1;

    session = [NSURLSession  sessionWithConfiguration:sessionConfiguration delegate:self delegateQueue:nil];

    //Set the session ID in the sending message structure so we can retrieve it from the
    //delegate methods later
    //            [sendingMessage setValue:session.configuration.identifier forKey:@"sessionId"];
    NSLog(@"config %@",sessionConfiguration.sharedContainerIdentifier);
}

if([[NSFileManager defaultManager]fileExistsAtPath:[storeURL path]])
{

    NSURLSessionUploadTask  *uploadTask = [session uploadTaskWithRequest:request fromFile:storeURL];
    [uploadTask resume];
}
else
    NSLog(@"file does not exsit");

    NSLog(@"desc %@",[session sessionDescription]);

    //   NSLog(@"state %ld", [uploadTask state]);

    }

A: You should be using a background NSURLSession since you are meant to dismiss the sharing UI as soon as possible by calling completeRequestByReturningItems on your NSExtensionContext instance.


text:
Q: Making use of idle cores in a parallel pipeline? I've been going through this tutorial on parallel pipelines and noticed that, while there is definitely a considerable difference in throughput, couldn't it be even better if the compression stage also took on a read job since it's just waiting around anyway? The same thing goes for the write stage... I mean, why not take on a third compression and then switch over to writing two, and then have one of those cores go back to compressing while the other wraps up the third write, and so on?
I apologize if this is obvious. I imagine this is standard practice and is called something, I'm just not sure what. Is their any overhead involved with switching jobs like this?
And I know this might be the wrong forum for this last question, but can the GPU switch jobs like this or should the programmable shaders/CUDA cores pretty much be left alone after being programmed?
EDIT: I guess I also don't understand how taking the same six-cores used in the 2 cores/stage example would be faster than just giving each of the six cores all three stages. Sure, there would be two cores that would do two, but that's still faster than the top scenario. I would understand it better in the GPU's case since there is specialized hardware involved for certain computations, but generally speaking, I don't see it. Maybe this example is weak or something because I know the parallel processing is here to stay.

A: This is definitely an issue with pipelining and there are a number of different ways to try and mitigate it.
With specialized hardware the hardware will often be tuned to try and balance the time taken in each stage for typical workloads. Fixed function stages in GPUs for example are typically balanced around the needs of a sample of representative game rendering workloads with transistors being allocated to try and balance the time taken in each stage. With static balancing like this there will usually be some wasted performance still however.
An alternative approach that can be used in both software and hardware to balance a pipeline is to break the longer stages down into multiple shorter steps. This is a common strategy in CPU instruction pipelines but can also be useful in software. In your example, the longer running compression step could potentially be broken down into multiple shorter pipeline stages. Depending on the task this may be difficult or impossible to do efficiently however.
Task scheduling systems can be used to help balance workloads across CPUs in a software pipeline. In a task scheduling system, you have a number of worker threads (usually around one per hardware thread) and any task can run on any worker thread. You have an API to set up dependencies between tasks and the task scheduler is responsible for scheduling tasks to run wherever CPU time is available once their dependencies are satisfied. In your example, the cores with idle time running the Read and Write tasks could help out with Compress tasks rather than sitting idle as long as the Compress tasks had their Read task dependencies satisfied.
Traditional OS thread schedulers can give some of the same benefits of a task scheduling system. In your example, if the Read threads waited on a semaphore when their work queues were empty (to be signalled when new work was added to the queues), the OS could schedule Compress threads to run on those idle cores. This can work reasonably well for relatively long running pipeline stages (10s of milliseconds) but for shorter pipeline stages (sub 1ms) the overhead of the OS thread scheduling and the length of the thread time slice will likely mean a task scheduling system would give better performance.

A: Your points are valid. The tutorial is lacking.
If the read, compress, and write operations can all occur at once, independently, the simple non-pipelined case would be the fastest for the six cores.    Also notice that in the six core diagram, the reads and writes never overlap, so they could be the same ones.  You only need four cores.
But consider a case where the reads all access the same disk so issuing too many read operations in parallel makes the reads take longer because they interfere with each other.  In this case you can gain by pipelining the reads since you start the first compress steps sooner and they limit
the overall performance.


text:
Q: Overloading by return type I read few questions here on SO about this topic which seems yet confusing to me. I've just begun to learn C++ and I haven't studied templates yet or operator overloading and such.
Now is there a simple way to overload
class My {
public:
    int get(int);
    char get(int);
}

without templates or strange behavior? or should I just
class My {
public:
    int get_int(int);
    char get_char(int);
}

?

A: It's possible, but I'm not sure that it's a technique I'd recommend for
beginners.  As in other cases, when you want the choice of functions to
depend on how the return value is used, you use a proxy; first define
functions like getChar and getInt, then a generic get() which
returns a Proxy like this:
class Proxy
{
    My const* myOwner;
public:
    Proxy( My const* owner ) : myOwner( owner ) {}
    operator int() const
    {
        return myOwner->getInt();
    }
    operator char() const
    {
        return myOwner->getChar();
    }
};

Extend it to as many types as you need.

A: Resurrecting an old thread, but I can see that nobody mentioned overloading by ref-qualifiers. Ref-qualifiers are a language feature added in C++11 and I only recently stumbled upon it - it's not so widespread as e.g. cv-qualifiers. The main idea is to distinguish between the two cases: when the member function is called on an rvalue object, and when is called on an lvalue object. You can basically write something like this (I am slightly modifying OP's code):
#include <stdio.h>

class My {
public:
    int get(int) & { // notice &
        printf("returning int..\n");
        return 42;
    }
    char get(int) && { // notice &&
        printf("returning char..\n");
        return 'x';
    };
};

int main() {
    My oh_my;
    oh_my.get(13); // 'oh_my' is an lvalue
    My().get(13); // 'My()' is a temporary, i.e. an rvalue
}

This code will produce the following output:
returning int..
returning char..

Of course, as is the case with cv-qualifiers, both function could have returned the same type and overloading would still be successful.

A: You can think this way:
You have:
  int get(int);
  char get(int);

And, it is not mandatory  to collect the return value of the function while invoking.
Now, You invoke
  get(10);  -> there is an ambiguity here which function to invoke.

So, No meaning if overloading is allowed based on the return type.

A: While most of the other comments on this problem are technically correct, you can effectively overload the return value if you combine it with overloading input parameter.  For example:
class My {
public:
    int  get(int);
    char get(unsigned int);
};

DEMO:
#include <stdio.h>

class My {
public:
    int  get(         int x) { return 'I';  };
    char get(unsinged int x) { return 'C';  };
};

int main() {

    int i;
    My test;

    printf( "%c\n", test.get(               i) );
    printf( "%c\n", test.get((unsigned int) i) );
}

The resulting out of this is:
I
C

A: There is no way to overload by return type in C++. Without using templates, using get_int and get_char will be the best you can do.

A: You can't overload methods based on return types. Your best bet is to create two functions with slightly different syntax, such as in your second code snippet.

A: As stated before, templates are overkill in this case, but it is still an option worth mentioning.
class My {
public:
    template<typename T> T get(int);
};

template<> int My::get<int>(int);
template<> char My::get<char>(int);

A: No there isn't. You can't overload methods based on return type.
Overload resolution takes into account the function signature. A function signature is made up of:

*

*function name

*cv-qualifiers

*parameter types

And here's the quote:
1.3.11 signature

the information about a function that participates in overload
  resolution (13.3): its parameter-type-list (8.3.5) and, if the
  function is a class member, the cv-qualifiers (if any) on the function
  itself and the class in which the member function is declared. [...]

Options:
1) change the method name:
class My {
public:
    int getInt(int);
    char getChar(int);
};

2) out parameter:
class My {
public:
    void get(int, int&);
    void get(int, char&);
}

3) templates... overkill in this case.

A: No, you can't overload by return type; only by parameter types, and const/volatile qualifiers.
One alternative would be to "return" using a reference argument:
void get(int, int&);
void get(int, char&);

although I would probably either use a template, or differently-named functions like your second example.

A: you can't overload a function based on the return type of the function.
you can overlead based on the type and number of arguments that this function takes.

A: I used James Kanze's answer using a proxy:
https://stackoverflow.com/a/9569120/262458
I wanted to avoid using lots of ugly static_casts on a void*, so I did this:
#include <SDL_joystick.h>
#include <SDL_gamecontroller.h>

struct JoyDev {
    private:
        union {
            SDL_GameController* dev_gc = nullptr;
            SDL_Joystick*       dev_js;
        };
    public:
        operator SDL_GameController*&() { return dev_gc; }
        operator SDL_Joystick*&()       { return dev_js; }

        SDL_GameController*& operator=(SDL_GameController* p) { dev_gc = p; return dev_gc; }
        SDL_Joystick*&       operator=(SDL_Joystick* p)       { dev_js = p; return dev_js; }
};

struct JoyState {
    public:
        JoyDev dev;
};

int main(int argc, char** argv)
{
    JoyState js;

    js.dev = SDL_JoystickOpen(0);

    js.dev = SDL_GameControllerOpen(0);

    SDL_GameControllerRumble(js.dev, 0xFFFF, 0xFFFF, 300);

    return 0;
}

Works perfectly!


text:
Q: Validate time slots are overlaping with each other - javascript I have a page where we can add available time slots for a given item. These time slots can be added to any order, but a selected slot should not overlap with other slots. So, before I save I need to validate all the added time slots are overlapping or not with each other. My plan is to add two forloops for this. But I'm wondering there is another way of doing this more efficiently with less coding. Please share your thoughts on this.
In the given image 09:00 - 11:00 is overlapping with 08:00 - 10:00. So it should not allow saving.
I'm trying to add a for loop like below which is not completed. I wonder there is another way of doing this easily.
    function isAnOverlapEvent (inputs) {
    var i;
    var matchingList;

    for (i = 0; i < inputs.length; i++) {
        var item = inputs[i];
        matchingList = inputs;

        matchingList.splice(item.index, 1);

        for (k = 0; k < matchingList.length; k++) {

        }
    }
    return false;
}

Can someone help me with this?

A: Long story short, when a timeslot is added you should compare it to the timeslots that already exist and make sure that it ends before the start of each existing timeslot, or that it starts after the end of existing timeslots.
If you want more details on date (or time) comparison, you can read this very detailed answer.

const existingTimeslots = [{start: 8, end: 10}, {start: 12, end: 14}, {start: 14, end: 16}];

const isNewSlotValid = (newSlot) => {
  let isValid = true;

  for(let i = 0; i < existingTimeslots.length; i++) {
    if((existingTimeslots[i].end > newSlot.start) && (existingTimeslots[i].end <= newSlot.end)) {
      isValid = false;
    }
  }

  return isValid;
}

console.log(isNewSlotValid({start: 9, end: 11})); // Should return false
console.log(isNewSlotValid({start: 16, end: 18})); // Should return true


text:
Q: How do I create recovery discs on a Compaq 615 I am trying to create recovery discs on a Compaq 615 running Windows 7, but I can not find the Recovery Manager that is supposed to be used for this purpose. See this official page for reference. It is a Swedish laptop, so most programs have Swedish names, but there is nothing even resembling "Recovery Manager".
There is a recovery partition, but I can not find anything useful there. How do I create recovery disks in this situation?

A: The HP Recovery Disc restores you computer to its initial state, erasing any changes and all of your data. It's really only to be used only in case of absolute necessity. Only one copy of the recovery disk can be created, so your first attempt to create it must succeed.
In English, the Start menu entry is called something like HP Backup and Recovery Manager. If you enter "HP" you should find it in the list. Another possible name is the "PC Help and Tools" menu group. If you still can't find it, go to C:\Program Files (or whatever it is in Swedish) and search for a directory whose name starts with "HP" and may look similar to one of the above names, where you can find this program.
The Windows 7 Recovery Disk is much less destructive and can recover some computer errors. It's best to have both discs, just in case.
From Create a system recovery disk in Windows 7 :

*

*In Control Panel, click System and Security, and then click Backup and Restore

*In the left pane, click Create a system recovery disk

*Insert a blank CD in the DVD, and then click Create Disk.

A: Usually, you can create recovery disks of your system with a CD/DVD provided with the laptop. I mean should have got a disk when you bought the laptop. But this is not a general rule, so if you don't have a disk for "Recovery Manager" probably HP/Compaq thought that you don't need one. This usually happens when you have that recovery partition, so you don't need a recovery manager to do a recovery disk for yourself.
However, Windows 7 install disk may have an option for creating for you a recovery disk, I don't know for sure, if you have a Windows 7 install DVD, try to boot from it and see if you have an option.

A: Search your hard drive for "CDCreator.exe" then execute it.
It may be found here
C:\Program Files (x86)\Hewlett-Packard\Recovery
If it is not on your hard drive then you cannot create the discs.
You can download and attempt installation of Recovery manager.
http://h10025.www1.hp.com/ewfrf/wc/softwareDownloadIndex?softwareitem=ob-75985-1&cc=us&lc=en&dlc=en
If this does not work, order a set of recovery discs
http://h10025.www1.hp.com/ewfrf/wc/document?docname=c00810334&cc=us&lc=en&dlc=en
If HP cannot supply them, then contact this company
http://www.computersurgeons.com/Default.aspx
.

A: Try looking inside the recovery partition. It's possible that it has been wiped out.
Furthermore, the site you linked to (http://h10025.www1.hp.com/ewfrf/wc/document?lc=en&dlc=&cc=us&docname=c01867124) refers to Windows 7. A previous poster noted that the laptop did not originally have Windows 7 so the instructions on that page do not apply to you.
I suggest following the steps outlined by harrymc and outlined in detail at http://forums.techarena.in/guides-tutorials/1114725.htm.

A: Is this a new laptop? Sometimes when you buy a new laptop, the place you buy it from will advertise services for your new laptop like "removing unnecessary software" and "software optimization". If you accepted these services, they may have deleted the link to the recovery manager or the executable itself in order to "serve your needs". You can check the recycle bin for the link. Also look around in c:/Program Files and c:/Program Files(x86) for anything that relates to HP or Compaq. The recovery manager executable might still be lying somewhere in there. You might also like to try recuva to see if it was deleted from the recycle bin (and still recoverable).
If it is completely gone, I would recommend doing a disk image backup with something like Acronis, Macrium Reflect, Norton Ghost, or CloneZilla.


text:
Q: Why the difference between type signatures of the same F# function in module vs class? Closely related to my question here, but actually a different question...
Consider the following F#:-
type TestClass() =
    let getValFromMap m k = Map.find k m
    let mutable someMap : Map<string,int> = Map.empty
    let getValFromMapPartial key = getValFromMap someMap key
    let getValFromMapPartialAndTacit = getValFromMap someMap

module TestModule =
    let getValFromMap m k = Map.find k m
    let mutable someMap : Map<string,int> = Map.empty
    let getValFromMapPartial key = getValFromMap someMap key
    let getValFromMapPartialAndTacit = getValFromMap someMap

In both the class case and the module case, getValFromMapPartial and getValFromMapPartialAndTacit behave in very different ways, and are compiled to IL differently.  In both the class and module case, the former behaves like a true syntactic function, and the latter behaves like a lambda-computing function (I know this thanks to user Marc Sigrist).
In the module case, the type signatures seem to be correct:-
getValFromMapPartial : key:string -> int
getValFromMapPartialAndTacit : (string -> int)

But in the class case, the type signatures are identical:-
getValFromMapPartial : (string -> int)
getValFromMapPartialAndTacit : (string -> int)

Why would this be so?
Since getValFromMapPartial acts as a true syntactic function in both cases, why would it be typed as a lambda-computing function in the class case?

A: I can only think of a few times you'd ever need to worry about the distinction between A -> B and (A -> B) (see the F# spec's section on signature conformance for related commentary):

*

*When you want to implement a module signature, only a syntactic function can serve as the implementation of something with the signature A -> B, while either a syntactic function or any other function value could implement the signature (A -> B).  That is, the latter signature is a superset of the former.

*When you care about the way your code appears to other .NET languages, functions with signature A -> B are implemented as methods, while functions with signature (A -> B) are implemented as values of type Microsoft.FSharp.Core.FSharpFunc<A,B>.

Otherwise, the difference doesn't matter.  And in this case, as @ildjarn notes, let-bound values in a type definition are private, so the above two considerations don't come into play for TestClass and it's just an implementation detail of no consequence.


text:
Q: What are the cases when AJAX should not be used? It seems that the sites and applications that use AJAX are growing rapidly.  And probably one of the major reasons for using AJAX is to enhance the user experience. My concern is that just because the project CAN use AJAX, doesn't mean that it SHOULD.
It could be that AJAX is exposing more security threats to the site/app for the sake of UX. Maybe you have other reasons for not using AJAX.
When should the use of AJAX be avoided?

A: Getting Data Already Available Or Data Easily Obtainable
I usually see that on car websites, where there are makes and models. Their usual <select> (without JavaScript) include <optgroup>'s as such:
<select>
    <optgroup label="Ford">
        <option value="21">Escape</option>
        <option value="21">F-150</option>
    </optgroup>
    <optgroup label="Toyota">
        <option value="51">Corolla</option>
        <option value="52">Yaris</option>
    </optgroup>
</select>

Then usually then proceed to hide that <select> and create 2 new select, one for makes and one for models.
All is fine up to that point. They start messing up here.
They then process to query the server to get a list of makes, and then do another query to get the list of models, when they could of simply parsed the original element try to get their information. Then, everytime you change make, another request is made...
The above is a excellent example of when NOT to use AJAX. Consider this: a request is longer than parsing available data, so they make the user wait. They probably query their database each time, so it has a hit on their server CPU usage. And it incurs more bandwidth. Terrible waste of resources.
What they should have done
They should of have simply parsed the DOM try under the <select> to fetch the relevant information. Each <optgroup> is an item in the makes <select> while each child <option> from the <optgroup> is an item in the models <select>.
Other examples

*

*Using AJAX for simple static DOM modifications (you don't need AJAX to switch from one tab to another in most cases, just include the data in your original request).

*Using AJAX to retrieve data on load (why not include it with the original request?)

*Using AJAX for an image gallery (why not include the images and manipulate them after the request is done?)

A: You definitely should avoid AJAX when you are sure that your clients will be using "not javascript enabled" browsers

A: Actually, AJAX should be used to enhance user interaction. If not it, then Flash or what have you.
Naturally, if there's no possible enhancement, there's no reason to go that way. I tag that as highly unlikely. If you find such a case, blog about it: it'll probably make interesting read.
There are situations, of course, where AJAX is contra-indicated. Basically, when you don't have people using the site. If you expect the site to work with SOFTWARE driving the requests, then you must make sure it works fine without AJAX.
And if you don't expect software to drive the requests, I sure hope you have an alternate API for it, one that can do everything the site can. Otherwise you are just deluding yourself and failing your clients.

A: If your development time is limited or your team lacks sufficient expertise, then you could make a good case for staying away from AJAX programming.
But otherwise:

[AJAX calls are] no more-or-less safe
  than a normal HTTP POST request issued
  by a browser as in from a -form-.
The "fix" for this is the same "fix"
  for non-AJAX requests - use SSL.

A: I hear this a lot - just because you can make it pretty with Ajax doesn't mean you should.
I don't think you should necessarily put the UI on the backburner though.  It shouldn't be the last thing you think about, particularly in certain cases.
The UI is what the user sees - they don't see any of the complexity behind it, so they'll judge the quality of your site/application based on how easy it is to use and how it makes sense to them.
With that in mind, decide on Ajax based on the user's point of view.  Does it make sense that when I click on this button the page slides to the left to reveal a new section?  Would it comfort me or confuse me to see the page grayed out and a "Working..." image displayed in front?

A: When redirecting a user to a new page which the user might want to bookmark - i.e. if clicking on a link causes the content to be updated using AJAX, the user can't bookmark the page.

A: AJAX should be avoided when the same functionality can be implemented entirely client-side without an additional round-trip to the server.
For example, it may be more efficient to seed the client with a list of zip codes for all US States and scope zip code selection to the appropriate set rather than going to the server for a list of valid zip codes for the given state.

A:
It could be that AJAX is exposing more security threats to the site/app for the sake of UX. Maybe you have other reasons for not using AJAX.

How? What security threats?


text:
Q: Laravel - Change query dependend from the results of a form at the moment I am struggling a bit with a SQL Query in Laravel.
I have a form with 6 Dropdowns which I send to a Image Controller via get. In dependency of what I will send to the controller, the query should change.
If a  is "empty"  (value="leer") this should be excluded from the query.
This is my html:
<form action="/filter" method="get">

                                                {{csrf_field()}}

                                                    Brand
                                                    <select class="form-control" id="brand" name="brand">
                                                        <option value="leer"></option>
                                                        @foreach($brands as $brand)

                                                            <option value="{{$brand->brand}}">{{$brand->brand}}</option>

                                                        @endforeach

                                                    </select>

                                                    Color
                                                    <select class="form-control" id="color" name="color">
                                                        <option value="leer"></option>

                                                        @foreach($colors as $color)

                                                            <option value="{{$color->color}}">{{$color->color}}</option>

                                                        @endforeach
                                                    </select>

                                                    Style
                                                    <select class="form-control" id="style" name="style">
                                                        <option value="leer"></option>
                                                        @foreach($styles as $style)

                                                            <option value="{{$style->style}}">{{$style->style}}</option>

                                                        @endforeach
                                                    </select>

                                                    Material
                                                    <select class="form-control" id="material" name="material">
                                                        <option value="leer"></option>
                                                        @foreach($materials as $material)

                                                            <option value="{{$material->material}}">{{$material->material}}</option>

                                                        @endforeach
                                                    </select>

                                                    Shape
                                                    <select class="form-control" id="shape" name="shape">
                                                        <option value="leer"></option>
                                                        @foreach($shapes as $shape)

                                                            <option value="{{$shape->shape}}">{{$shape->shape}}</option>

                                                        @endforeach
                                                    </select>

                                                    Year
                                                    <select class="form-control" id="year" name="year">
                                                        <option value="leer"></option>
                                                        @foreach($years as $year)

                                                            <option value="{{$year->year}}">{{$year->year}}</option>

                                                        @endforeach

                                                    </select>

                                                <input type="submit" class="btn" value="Filter">

                                                <button type="button" class="btn" data-dismiss="modal">Close
                                                </button>

                                            </form>

I send this form via a route
Route::get('/filter', 'ImagesController@filter');

And this is my controller function, the where clause should be empty by defaultif nothing is chosen in the form. If you choose for example somtehing from the brand dropdown and the color dropdown, The query should look like where([['brand', $brand],['color',$color]])->paginate(12);
    public function filter(Request $request){

    $brand = $request->brand;
    $color = $request->color;
    $style = $request->style;
    $material = $request->material;
    $year = $request->year;
    $shape = $request->shape;

  $images = DB::table('images')->select('brand', 'color', 'style', 'material', 'shape', 'year', 'id', 'path', 'created_at')->where('year',$year)->paginate(12);

    if ($brand == 'leer') {
        $images->where('brand', '=', $brand);
    }

    if ($color == 'leer') {
        $images->where('color', '=', $color);
    }

    if ($style == 'leer') {
        $images->where('style', '=', $style);
    }

    if ($material == 'leer') {
        $images->where('material', '=', $material);
    }

    if ($shape == 'leer') {
        $images->where('shape', '=', $shape);
    }

    if ($year == 'leer') {
        $images->where('year', '=', $year);
    }

    return view('index')->with(compact('images'));

Sometimes it works but I think its by accident, obviously it doesnt work.
I would really appreciate your help.
Many thanks in advance Lars.

A: You need to call paginate after the where clauses. A paginate on the builder object results in a LengthAwarePaginator object. A where call on this paginator results in a where on the pagination collection (through the magic method __call) which isn't the expected response.
Try:
$imagesQuery = DB::table('images')->select('brand', 'color', 'style', 'material', 'shape', 'year', 'id', 'path', 'created_at')->where('year',$year);

        if ($brand == 'leer') {
            $imagesQuery->where('brand', '=', $brand);
        }

        if ($color == 'leer') {
            $imagesQuery->where('color', '=', $color);
        }

        if ($style == 'leer') {
            $imagesQuery->where('style', '=', $style);
        }

        if ($material == 'leer') {
            $imagesQuery->where('material', '=', $material);
        }

        if ($shape == 'leer') {
            $imagesQuery->where('shape', '=', $shape);
        }

        if ($year == 'leer') {
            $imagesQuery->where('year', '=', $year);
        }

$images = $imagesQuery->paginate(12);

return view('index')->with(compact('images'));


text:
Q: Error in doing interval task using BroadcastReceiver and AlarmManager in Android I am absolute beginner to Android. So now I am trying to develop a to-do list app on my own to improve my skills. My app is offline. But in my app I need to notify the user of the to-do tasks everyday. So I need to fire event for it in the background even my app is not running.
So I am trying to integrate AlarmManager with BroadcastReceiver by creating a simple project to show a simple toast message at every interval. But it is throwing error. This code is not the to-do app code. I am just testing to do background event firing even my app is not running. But when I run this code. It is throwing error.
This is my Android manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.bgnotification.bgnotification" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <receiver android:name=".RemainderReceiver"></receiver>
    </application>

</manifest>

This is the activity class
public class MainActivity extends AppCompatActivity {
    private RemainderReceiver remainderReceiver;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        remainderReceiver = new RemainderReceiver();
        remainderReceiver.startRemainder(this.getApplicationContext());
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

This is the Broadcast Receiver
public class RemainderReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "YOUR TAG");
        //Acquire the lock

        wl.acquire();

        Toast.makeText(context,"my message", Toast.LENGTH_SHORT).show();
        wl.release();
    }

    public void startRemainder(Context context)
    {
        AlarmManager am = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context,RemainderReceiver.class);

        PendingIntent pi = PendingIntent.getBroadcast(context,0,intent,0);
        am.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(),1000*2,pi);
    }
}

This is the Logcat when I run this app
01-23 09:45:33.853 2029-2029/? D/AndroidRuntime: Shutting down VM
01-23 09:45:33.853 2029-2029/? W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0xa615a908)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime: FATAL EXCEPTION: main
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime: java.lang.RuntimeException: Unable to start receiver com.example.bgnotification.bgnotification.RemainderReceiver: java.lang.SecurityException: Neither user 10058 nor current process has android.permission.WAKE_LOCK.
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2383)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.access$1500(ActivityThread.java:141)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:  Caused by: java.lang.SecurityException: Neither user 10058 nor current process has android.permission.WAKE_LOCK.
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Parcel.readException(Parcel.java:1425)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Parcel.readException(Parcel.java:1379)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.IPowerManager$Stub$Proxy.acquireWakeLock(IPowerManager.java:271)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.PowerManager$WakeLock.acquireLocked(PowerManager.java:717)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.PowerManager$WakeLock.acquire(PowerManager.java:686)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.example.bgnotification.bgnotification.RemainderReceiver.onReceive(RemainderReceiver.java:22)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.handleReceiver(ActivityThread.java:2376)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.access$1500(ActivityThread.java:141)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1310)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.os.Looper.loop(Looper.java:137)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at android.app.ActivityThread.main(ActivityThread.java:5041)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at java.lang.reflect.Method.invokeNative(Native Method)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at java.lang.reflect.Method.invoke(Method.java:511)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
01-23 09:45:33.853 2029-2029/? E/AndroidRuntime:     at dalvik.system.NativeStart.main(Native Method)
01-23 09:45:33.853 476-1662/? W/ActivityManager:   Force finishing activity com.example.bgnotification.bgnotification/.MainActivity
01-23 09:45:33.909 476-1662/? D/dalvikvm: GC_FOR_ALLOC freed 2598K, 47% free 6995K/13080K, paused 9ms, total 9ms
01-23 09:45:33.937 476-492/? D/dalvikvm: GC_FOR_ALLOC freed 57K, 40% free 7894K/13080K, paused 19ms, total 19ms
01-23 09:45:33.957 476-479/? D/dalvikvm: GC_CONCURRENT freed 100K, 31% free 9117K/13080K, paused 1ms+5ms, total 19ms
01-23 09:45:33.969 476-492/? I/dalvikvm-heap: Grow heap (frag case) to 11.451MB for 2536932-byte allocation
01-23 09:45:33.993 476-484/? D/dalvikvm: GC_FOR_ALLOC freed <1K, 26% free 11594K/15560K, paused 25ms, total 25ms
01-23 09:45:34.021 476-479/? D/dalvikvm: GC_CONCURRENT freed 69K, 25% free 11770K/15560K, paused 2ms+1ms, total 30ms
01-23 09:45:34.413 476-488/? W/ActivityManager: Activity pause timeout for ActivityRecord{532d55cc u0 com.example.bgnotification.bgnotification/.MainActivity}
01-23 09:45:34.441 679-679/? W/EGL_genymotion: eglSurfaceAttrib not implemented
01-23 09:45:34.513 476-544/? I/qtaguid: Failed write_ctrl(s 0 10058) res=-1 errno=1
01-23 09:45:34.513 476-544/? W/NetworkManagementSocketTagger: setKernelCountSet(10058, 0) failed with errno -1
01-23 09:45:44.513 476-488/? W/ActivityManager: Activity destroy timeout for ActivityRecord{532d55cc u0 com.example.bgnotification.bgnotification/.MainActivity}

How can I debug this?

A: you missed WAKE_LOCK permission in manifest.XML:
<uses-permission android:name="android.permission.WAKE_LOCK"/>

Your manifest.xml will like this:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bgnotification.bgnotification" >
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.NoActionBar" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".RemainderReceiver"></receiver>
</application>

</manifest>


text:
Q: html list add and remove using and js I am trying to make a simple list using html input box and js. the list are creating on clicking "add skill" and get removed when click on "remove". But when I try to add some skill after remove, the last removed item also get back.

   var skillList="";
   var i = 0;
   function addSkill(){
    var skills= document.getElementById("addSkill").value;
    if(skills != ""){
     skillList += "
" + skills + " " +
     "remove
";
     i++;
     document.getElementById("skill").innerHTML = skillList;
     document.getElementById("addSkill").value="";
    }
   }

   function removeSkill(){
    skillList="";
    var items = document.querySelectorAll("#skill li"),index,tab = [];
    for(var j = 0; j < items.length; j++){
     tab.push(items[j].innerHTML);
    }
    for(var j = 0; j < items.length; j++){
     items[j].onclick = function(){

      index = tab.indexOf(this.innerHTML);
      items[index].parentNode.removeChild(items[index]);
      tab.splice(j,1);
     };
    }
    console.log(tab);
    for(var j=0; j<tab.length;j++){
     skillList += "
" + tab[j] + "
";
    }
   }
skills:

          <input type="text" name="skill" id="addSkill"/>
          add skill

A: Just delete this piece of code
                for(var j=0; j<tab.length;j++){
                skillList += "
" + tab[j] + "
";
            }

Your were adding it again...
Working now...

var skillList="";
   var i = 0;
   function addSkill(){
    var skills= document.getElementById("addSkill").value;
    if(skills != ""){
     skillList += "
" + skills + " " +
     "remove
";
     i++;
     document.getElementById("skill").innerHTML = skillList;
     document.getElementById("addSkill").value="";
    }
   }

   function removeSkill(){
    skillList="";
    var items = document.querySelectorAll("#skill li"),index,tab = [];
    for(var j = 0; j < items.length; j++){
     tab.push(items[j].innerHTML);
    }
    for(var j = 0; j < items.length; j++){
     items[j].onclick = function(){

      index = tab.indexOf(this.innerHTML);
      items[index].parentNode.removeChild(items[index]);
      tab.pop(j,1);
     };
    }

   }
skills:

          <input type="text" name="skill" id="addSkill"/>
          add skill

A: You got all lost in the loops and indexes in your removeSkill function and it's way easier than what you are doing - one single line of code. No loops and no arrays are needed.
You've also got a bunch of other styles of coding that are ancient and should be avoided.

*

*You don't need to use a hyperlink just because you want to give
someone something to click on. All visible elements support a click
event. Only use hyperlinks when you are actually navigating
somewhere.

*You can't use table cells without a table.

*Don't use inline HTML event attributes (onclick). Separate all your
JavaScript from your HTML and do the event binding with
.addEventListener().

*Don't create new HTML by concatenating strings together. It becomes a
nightmare fast and requires you to use .innerHTML, which has
performance and security implications. Instead, create new DOM
objects, configure their properties as needed and then append them
into the document.

See the comments inline below:

// Get all the element references you'll need just once:
var skillList = document.querySelector("#skillList");
var newSkill = document.querySelector("#newSkill");
var btnAddSkill = document.querySelector("input[type='button'");

// Do all of your event binding in JavaScript, not with inline HTML event attributes
btnAddSkill.addEventListener("click", addSkill);

function addSkill(){
 if(newSkill.value !== ""){
   // Don't build new HTML by concatenating strings. Create elements and configure them as objects
   var li = document.createElement("li");
   li.textContent = newSkill.value;

   // Only use hyperlinks for navigation, not to have something to click on. Any element can be clicked
   var span = document.createElement("span");
   span.classList.add("remove");
   span.textContent = "remove skill";
   span.addEventListener("click", removeSkill);
   li.appendChild(span);  // Add the span to the bullet
   skillList.appendChild(li); // Add the bullet to the list
   newSkill.value = "";
 }
}

function removeSkill(){
  // Just remove the closest
 ancestor to the  that got clicked
  skillList.removeChild(this.closest("li"));
}
.remove { display:inline-block; margin-left:10px; padding:2px 4px; background:rgba(200,0,225,.7); color:#ff0; cursor:pointer; }

li {margin:8px 0; border-bottom:1px dashed #e0e0e0; }

Skills:

<input type="text" name="skill" id="newSkill">
<input type="button" value="add skill">


text:
Q: Transform an array into a string while keeping the [ ] inside the string I have an array of integers
element= [12,456]

I would like to transform this into
desired_output = "[12,456]"

I tried toString but it fails. For example element.toString() outputs "12,456" which is not what I want.
It's tricky, I want to keep the [ and the ] inside the string.

A: This might work:
JSON.stringify(YourArray);

A: a = [1, 2, 3]
desired = `[${a.join(',')}]`
console.log(desired) //"[1,2,3]"


text:
Q: check radio button again in radio group android I am using a radio group containing two radio buttons like below:
  <RadioGroup
                    android:layout_width="match_parent"
                    android:layout_marginStart="@dimen/dp_16"
                    android:layout_marginEnd="@dimen/dp_16"
                    android:layout_height="wrap_content"
                    app:layout_constraintTop_toTopOf="parent">

                <RadioButton
                        android:id="@+id/rbDebitCard"
                        android:fontFamily="@font/sf_ui_regular"
                        android:textColor="@color/txt_color_heading"
                        android:layout_width="match_parent"
                        android:drawableEnd="@drawable/debit_card"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:text="Pay with Card"/>

                <View
                        android:layout_width="match_parent"
                        android:layout_height="@dimen/dp_1"
                        android:layout_marginTop="@dimen/dp_16"
                        android:background="@color/divider_line"/>

                <RadioButton
                        android:id="@+id/rbCash"
                        android:fontFamily="@font/sf_ui_regular"
                        android:textColor="@color/txt_color_heading"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_weight="1"
                        android:checked="true"
                        android:drawableEnd="@drawable/cash"
                        android:layout_marginTop="@dimen/dp_16"
                        android:text="Cash"/>

            </RadioGroup>

In my kotlin code I am showing a bottom sheet when rbDebitCard is clicked and changing the check by ischecked=false when closing the bottom sheet.
which perfectly unchecks the radio button.
The issue is, when I am clicking on the same radio button again, it is not getting checked. However, the bottom sheet is opening.
If i click on the other radio button(which obviously gets checked) and then again clicking on the first button then it is getting checked and opening the bottom sheet. But once again I close the bottom sheet and click on the radio button, it is not getting checked.
For reference, below is the kotlin code:
//pay with card
        rbDebitCard.setOnClickListener {
            rbDebitCard.isChecked = true
            paymentMode = "Card"
            onBraintreeSubmit(clContainer)
        }

        //Cash
        rbCash.setOnClickListener {
            paymentMode = "Cash"
        }

 override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    if (requestCode == BundleConstants.REQ_CODE_PAYMENT) {
        if (resultCode == Activity.RESULT_OK) {
            // use the result to update your UI and send the payment method nonce to your server
            val result: DropInResult = data!!.getParcelableExtra(DropInResult.EXTRA_DROP_IN_RESULT)
            Log.e("payment result nonce", result.paymentMethodNonce?.nonce)

            makePayment(result.paymentMethodNonce?.nonce)
        } else if (resultCode == Activity.RESULT_CANCELED) {
            // the user canceled
            rbDebitCard.isChecked = false
        } else {
            // handle errors here, an exception may be available in
            val error = data!!.getSerializableExtra(DropInActivity.EXTRA_ERROR) as Exception
            rbDebitCard.isChecked = false
        }
    }
}

adding the check change listener to the radio button looks like below:
 rgPayment.setOnCheckedChangeListener { group, checkedId ->
        when(checkedId){
            R.id.rbDebitCard->{
                rbDebitCard.isChecked = true
                paymentMode = "Card"
                onBraintreeSubmit(clContainer)
            }

            R.id.rbCash->{
                paymentMode = "Cash"
            }
        }
    }

A: You have to take the id of the Radio Group and use radio group checkedchangedlistener like this -
val checkedRadioButton = group?.findViewById(group.checkedRadioButtonId) as? RadioButton
        checkedRadioButton?.let {

            if (checkedRadioButton.isChecked)
                Toast.makeText(applicationContext, "RadioGroup: ${group?.contentDescription} RadioButton: ${checkedRadioButton?.text}", Toast.LENGTH_LONG).show()
}

A: the issue is with  rbDebitCard.isChecked = false
I replaced this with rgPayment.clearCheck().
With this i think in a radiogroup some check must be maintained by the radio group also which is independent of the check assigned to a radio button manually.
However, this thing solved the issue :)


text:
Q: How to get Node status HighLevelRESTClient ElasticSearch I am using the Java HighLevelRestClient to connect to my ElasticSearch.I was working on a task to get the health status of each nodes.
Tried with :
private string getHighLevelClientInfo(){
try{
ClusterHealthResponse res=restHighLevelClient.cluster().health(new ClusterHealthRequest(),RequestOptions.DEFAULT);
return res.getStatus.name();
}
catch(Exception e){
return "Error";
}
}

While doing so, i was getting all Cluster related information with Status as "Green" and number of nodes=3.
Any help, how to get the node specific information with node status.
Thanks

A: There is no concept of node health status, it's a cluster health status which is made up of all the indices health status which again in turn made of shard health status.
I guess, you are looking for node stats API, which will print each node stats like, how CPU, memory, various queue size, and several other information.


text:
Q: Breakpoints being moved Visual Studio 2010 I use breakpoints in debugging my C#/.Net programs.  Very often I use many "When hit" breakpoints to display messages in the Output window and keep going, so I can examine what the program is doing  while it's executing.
But I often find that after editing code my breakpoints get moved, producing spurious or incorrect results and I have to go and delete my old breakpoints and make new ones.
Searching for this on Stack Overflow I find other programmers having this problem when building in Release mode, but I'm building with a Debug configuration.
How do I make my breakpoints stay put?

A: *

*Do you "share" files such as .csproj.user, .suo... with other developers of the project ?

If you are using a SCM exclude them from it, these files are not intended to be shared between different machines. To send them to another user with slightly different sources may cause this kind of funny mess.
More details about these files here :
Best practices for Subversion and Visual Studio projects

*

*This kind of thing could also happen if you manually edit files, outside of VS (with Notepad++ for example) : try to avoid this when you want to keep breakpoints at the right place, VS doesn't like it at all.

A: There are many ways to examine the execution of program. Make sure you are generating full Debug Info for your project. Also check that csproj.user, .suo files aren't set as Read Only.

If these thing doesn't work, for your case I suggest you to use some console based output providing methods.
Try this one
Console.WriteLine("Currently executing this...");

The console here is the output window of VS. Select Debug from 'Show output from:'.

If you want to halt the execution, use this code
Console.WriteLine("Currently executing this...");
System.Diagnostics.Debugger.Break();

You should do conditional compilation of your code so that this doesn't get released with the final product. Console.WriteLine() will not cause any problem but System.Diagnostics.Debugger.Break() will break application.


text:
Q: Using multiple identical flags in curl with Python's sh module I'm using the sh module in Python to convert my curl commands into Python, but I get an error because I'm using multiple F flags in the curl call in Python.
Here is the original curl code:
curl -u admin:admin -F x=y http://localhost:8080/foo
curl -u admin:admin -F :operation=copy -F :dest=/foo/bar http://localhost:8080/foo

My code is here:
def exploit(url, username, password):
    sh.curl(url, F = "x=y", u = "%s:%s" %(username, password))
    sh.curl(url, F = ":operation=copy", F = ":dest=/foo/bar", u = "%s:%s" %(username, password))

def main():
    #default username and password is admin:admin
    username = "admin"
    password = "admin"
    exploit("http://localhost:8080/foo", username, password)

Here's the error message:
  File "/Users/Winston/Desktop/sling_exploit.py", line 7
sh.curl(url, F = ":operation=copy", F = ":dest=/foo/bar", u = "%s:%s" %(username, password))
SyntaxError: keyword argument repeated

Can anyone help me find a solution? Any help would be appreciated. Thanks.

A: I figured it out using PyCurl for those who are interested
def exploit(url, username, password):
    c = pycurl.Curl()
    c.setopt(c.URL, url)
    data = [
         ('x', 'y')
    ]
    c.setopt(c.HTTPPOST, data)
    c.setopt(pycurl.USERPWD, username + ':' + password)
    c.perform()
    data_2 = [
         (':operation', 'copy'),
         (':dest', '/foo/bar')
    ]
    c.setopt(c.HTTPPOST, data_2)
    c.perform()
    c.close()

def main():
    #default username and password is admin:admin
    username = "admin"
    password = "admin"
    exploit("http://localhost:8080/foo", username, password)


text:
Q: When is ViewTreeObserver.OnGlobalLayoutListener notified in Android I am trying to detect screen rotation for a view I have. I realized when there is a screen rotation, both View.OnLayoutChangeListener and ViewTreeObserver.OnGlobalLayoutListener are notified.
To determine which one I shall use for detecting screen rotation, I need to understand the circumstanced under which either of them are notified.
For View.OnLayoutChangeListener, it's clear from the documentation that it is notified when the view's bound changes.
However, the documentation for ViewTreeObserver.OnGlobalLayoutListener is unclear to me. So my question is that when exactly is ViewTreeObserver.OnGlobalLayoutListener be notified?
Having answered that question, then shall I use ViewTreeObserver.OnGlobalLayoutListener or View.OnLayoutChangeListener for detecting screen rotation?

A: Submersed's comment is the correct answer.  You should override onConfigurationChanged() to react to orientation changes.
Additionally, to prevent your Activity from restarting when the device is rotated, you should specify something like android:configChanges="orientation|keyboardHidden|screenSize" in your manifest.
@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
        // landscape
    } else {
        // portrait
    }
}

See: prevent activity restarting when orientation changes
To answer your specific question, you might examine the source code.


text:
Q: AttributeError: module 'pysynth' has no attribute 'make_wav' AttributeError: module 'pysynth' has no attribute 'make_wav'
import pysynth as ps
test = (('c', 4), ('e', 4), ('g', 4), ('c5', -2), ('e6', 8), ('d#6', 2))
ps.make_wav(test, fn = "test.wav")

A: pip version pysynth of pysynth is outdated. If you installed pysynth through pip, uninstall it, and install from github repository.
pip uninstall pysynth

git clone https://github.com/mdoege/PySynth.git

cd PySynth

python3 setup.py install


text:
Q: Setting a maximum on a number column based on a column from the same list I have a list with 3 columns. Title, amount and progress.
Amount and progress are both number types. Is it possible for the progress column's maximum value to be the value of the amount column of the same item?
If not, is there a way to achieve what I'm trying to do?

A: You can do that using the Validation Settings.
Go to List Settings -> Validation Settings and add a formula for this:
=progress<amount

And add a User Message telling the user that Progress cannot be larger than the Amount or something.


text:
Q: Subdomain on localhost ASP.NET webform project My team is creating a project that allows different users to use the web application based on different sub-domain. That is to say. http://P1.example.com will has its own set of P1's user and http://P2.example.com will has its own set of P2's user.
We do not have the structural issues with the database and the code but we have questions regarding the project's setup. I have read similar questions and answers here but they are not leading me to the right direction:
Add subdomain to localhost URL and
Apache vhost not working for subdomains as they are not windows-based.
Question:

*

*How do I setup such that I can test subdomains on visual studio on localhost settings. What are the setup we need to do?

*What should I do to trick the computer and tell it to "redirect" the requests all P1.localhost to localhost and P2.localhost to localhost but maintaining the URL in the browser?

A: You can set up a normal site in IIS and assign it a binding of subdomain.localhost
Then in your hosts file (c:\windows\system32\drivers\etc\hosts) add an entry
127.0.0.1     subdomain.localhost

Sorry for this being quite short, I assume that you already know how to set up a site in IIS.


text:
Q: Multiple date selecte in single input field? I want to be a create date picker calender . Which having  option to select multiple dates with single input field . Please help me if someone have do before.
 <script>
    var drp;
    function makedatepicker(){
        drp = $("#myDate").datepicker({});
    }
    function getRange(){
        $("#myOutput").html("");
        $(drp.getDateRange()).each(function() {
            $("#myOutput").append($("<li>").html($.datepicker.formatDate("dd/MM/yy",this)));
        });
    }

    $( document ).ready(function() {
        makedatepicker();
    });
</script>

Thanks

A: To select multiple date from one input you can use the datepick.js Which allow you to select multiple date at a time.
Here is the link for the demo and download
To see the demo for multiple date select click on "Multiple" tab on this page
You can select multiple dates using :
<input type="text" id="multi999Picker" size="60" class="is-datepick">

$('#multi999Picker').datepick({
    multiSelect: 999, monthsToShow: 2,
    showTrigger: '#calImg'});


text:
Q: List index out of range when appending text from files The code below throws an IndexError saying list index out of range but when I print the item on that index, it shows that there is text there.
So why am I getting an index error?
code:
paths = []
formats = []

with open("config.cf","r") as config_file:

    global sort_mode
    sort_mode = config_file.readline().replace("\n","").split(":")

    if sort_mode[1] == "custom":

        for line in config_file:

            temp = str(line).replace("\n","").split("/")

            if temp[0] == "mode:":
                continue

            format_list = str(temp[0]).split(",")

            paths.append(temp[1]) # <---- Error
            formats.append(format_list)

the first line of the "Config file" is mode:custom and the second is .txt/text
When i do  print(temp[1]) i get "text" and the "index error" at the same time.

A: You file contains a \n at the end of it - the line after is "empty".
This temp = str(line).replace("\n","").split("/") returns a list with 1 element.
Afterwards you access this list with temp[1] - this causes the indexing error.
Next time you get such an error, replace the access-line with a print of the list, this gives you a good idea whats wrong.
Use
if len(temp) < 2 or temp[0] == "mode:":
    continue

Empty lists are falsy and it would continue afterwards.
The other thing you can always do if you encounter exceptions: catch them.
try:

    print( [][20])
except IndexError as e:
    print(e)

Code to test it (use first the one then the other create-code for config.cf):
# works
with open("config.cf","w") as f:
    f.write("""mode:custom
.txt/text""")

# fails
with open("config.cf","w") as f:
    f.write("""mode:custom
.txt/text
 """)


text:
Q: Plugin 'org.apache.maven.plugins:maven-dependency-plugin:' not found on m1 macbook I just started using the MacBook with the M1 chip and I just git-cloned my spring boot project through IntelliJ and I have installed the same java version and set its path and SDK. Everything is great actually and it runs but I get an error in my pom.xml file that says "Plugin 'org.apache.maven.plugins:maven-release-plugin:' not found". I have installed maven through homebrew. I have set its path and I have tried the different solutions provided online but the error stays the same. Can you helpThe result I'm getting
Can you please help me out


text:
Q: Error: Call to a member function setPayrollperiodid() on null I'm trying to count the number of payroll week that matches the payroll period entered. It returns the correct number but won't add to the database but instead says there's no match in the database. When I make changes I get this error:

Error: Call to a member function setPayrollperiodid() on null.

I have outlined what I have thus far. Can someone tell me where I went wrong.
I have made some updates to the question I no longer get that error but record isn't adding instead it's saying that it doesn't match where did I go wrong in the controller.
Repository
class PayrollweekRepository extends EntityRepository
{
    public function findBystartdateAndenddate($startdate, $enddate)
    {
        $repository = $this->getEntityManager()
            ->getRepository('comtwclagripayrollBundle:Payrollweek');

        $qb = $repository->createQueryBuilder('pw');
        $qb->select('pw');
        $qb->where('pw.startdate=:startdate');
        $qb->Andwhere('pw.enddate=:enddate');
        $qb->setParameter('startdate', $startdate);
        $qb->setParameter('enddate', $enddate);
        $qb->getquery()->getResult();
    }

    public function countBystartdateAndenddate($startdate, $enddate)
    {
        $repository = $this->getEntityManager()
            ->getRepository('comtwclagripayrollBundle:Payrollweek');

        $qb = $repository->createQueryBuilder('pw');
        $qb->select('count(pw.id)');
        $qb->where('pw.startdate=:startdate or pw.enddate=:enddate');
        $qb->setParameter('startdate', $startdate);
        $qb->setParameter('enddate', $enddate);

        $count = $qb->getQuery()->getSingleScalarResult();

        var_dump($count);
        return $count;
    }
}

Controller
public function createAction(Request $request)
{
    $entity = new Payrollperiod();

    $form = $this->createCreateForm($entity);
    $form->handleRequest($request);

    if ($form->isSubmitted() && $form->isValid()) {
        $em = $this->getDoctrine()->getManager();

        $payrollperiod = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')
            ->findOneBy([
                'startdate' => $form->get('startDate')->getData(),
                'enddate' => $form->get('endDate')->getData()]
            );

        $payrollweek = $em->getRepository('comtwclagripayrollBundle:Payrollweek')
            ->findBystartdateAndenddate($entity->getStartDate() , $entity->getEndDate());

        $counter = $em->getRepository('comtwclagripayrollBundle:Payrollweek')
            ->countBystartdateAndenddate($entity->getStartDate() , $entity->getEndDate());

        //If entity exists
        if ($payrollperiod){
            $this->addFlash('error', 'Error: A payroll period is already present with the same start and end date.');
            return $this->redirect($this->generateUrl('payrollperiod'));
        }
        //If PayrollWeek matches the Payrollperiod entered
        elseif ( $counter==2){
           $payrollweek->setPayrollperiodid($entity);
        }

        $em->persist($entity);
        $em->flush();

        $this->addFlash('success', 'Payroll Period was added.');
        $this->addFlash('success', 'Payroll week was updated.');
        return $this->redirect($this->generateUrl('payrollperiod'));
        //return $this->redirect($this->generateUrl('payrollperiod_show', array('payrollperiodid' => $entity->getpayrollperiodid())));
    }
    else{
        $this->addFlash('error', 'Payroll Period does not match a payroll week.');
        return $this->redirect($this->generateUrl('payrollperiod'));
    }

    //return $this->render('comtwclagripayrollBundle::new.html.twig',array('form' => $form->createView()));
    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

UPDATES
public function countBystartdateAndenddate($startdate, $enddate)
{
    $repository = $this->getEntityManager()
        ->getRepository('comtwclagripayrollBundle:Payrollweek');

    $qb = $repository->createQueryBuilder('pw');
    $qb->select('count(pw.id)');
    $qb->where('pw.startdate=:startdate or pw.enddate=:enddate');
    $qb->setParameter('startdate', $startdate);
    $qb->setParameter('enddate', $enddate);

    $count = $qb->getQuery()->getResult();

    var_dump($count);
    return $count;
}

public function createAction(Request $request)
{

    $entity = new Payrollperiod();

    $form = $this->createCreateForm($entity);

    $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

        $em = $this->getDoctrine()->getManager();

        $payrollperiod = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')->findOneBy(['startdate'=>$form->get('startDate')->getData(), 'enddate'=>$form->get('endDate')->getData()]);

        //$payrollweek = $em->getRepository('comtwclagripayrollBundle:Payrollweek')->findBystartdateAndenddate($form->get('startDate')->getData(), $form->get('endDate')->getData());

        $counter = $em->getRepository('comtwclagripayrollBundle:Payrollweek')->countBystartdateAndenddate($form->get('startDate')->getData(), $form->get('endDate')->getData());

        //If entity exists
        if ($payrollperiod){
                $this->addFlash('error', 'Error: A payroll period is already present with the same start and end date.');
                return $this->redirect($this->generateUrl('payrollperiod'));
            }
            //If PayrollWeek matches the Payrollperiod entered
           elseif ($counter==2){
            foreach ($counter as $pWeek) {

                $pWeek->setPayrollperiodid($entity);

            }

          $em->persist($entity);
          $em->flush();

            $this->addFlash('success', 'Payroll Period was added.');
            $this->addFlash('success', 'Payroll week was updated.');
            return $this->redirect($this->generateUrl('payrollperiod'));
           //return $this->redirect($this->generateUrl('payrollperiod_show', array('payrollperiodid' => $entity->getpayrollperiodid())));
             }
             else{
               $this->addFlash('error', 'Payroll Period does not match a payroll week.');
            return $this->redirect($this->generateUrl('payrollperiod'));
             }
       }

       //return $this->render('comtwclagripayrollBundle::new.html.twig',array('form' => $form->createView()));
       return array(
           'entity' => $entity,
           'form'   => $form->createView(),
       );

        }

Further Updates
public function createAction(Request $request)
{

    $entity = new Payrollperiod();

    $form = $this->createCreateForm($entity);

    $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {

        $em = $this->getDoctrine()->getManager();

        $payrollperiod = $em->getRepository('comtwclagripayrollBundle:Payrollperiod')->findOneBy(['startdate'=>$form->get('startDate')->getData(), 'enddate'=>$form->get('endDate')->getData()]);

        $payrollweek = $em->getRepository('comtwclagripayrollBundle:Payrollweek')->findBystartdateAndenddate($form->get('startDate')->getData(), $form->get('endDate')->getData());

        //If entity exists
            if ($payrollperiod){
                    $this->addFlash('error', 'Error: A payroll period is already present with the same start and end date.');
                    return $this->redirect($this->generateUrl('payrollperiod'));
                }
            //If PayrollWeek matches the Payrollperiod entered
            elseif ($payrollweek){
            $count = count($payrollweek);
            foreach ($payrollweek as $pWeek) {
            $pWeek->setPayrollperiodid($entity);
            }

            $em->persist($entity);
            $em->flush();

            $this->addFlash('success', 'Payroll Period was added.');
            $this->addFlash('success', 'Payroll week was updated.');
            return $this->redirect($this->generateUrl('payrollperiod'));
           //return $this->redirect($this->generateUrl('payrollperiod_show', array('payrollperiodid' => $entity->getpayrollperiodid())));
             }
             else{
               $this->addFlash('error', 'Payroll Period does not match a payroll week.');
            return $this->redirect($this->generateUrl('payrollperiod'));
             }
}

       //return $this->render('comtwclagripayrollBundle::new.html.twig',array('form' => $form->createView()));
       return array(
           'entity' => $entity,
           'form'   => $form->createView(),
       );

        }

A: You're not checking that $payrollweek exists before trying to use it.  In your case, it didn't find a value when you ran this function:
$payrollweeks = $em->getRepository('comtwclagripayrollBundle:Payrollweek')
    ->findBystartdateAndenddate($entity->getStartDate() , $entity->getEndDate());

Since it didn't find anything, $payrollweek is NULL instead of an instance of your Payrollweek entity.  You could add another check like this:
if (!$payrollweeks) {
    $this->addFlash(
        'error',
        'Error: No payroll week found with the given start and end date'
    );

    return $this->redirect($this->generateUrl('payrollperiod'));
}

EDIT based on discussions:
You should be able to get rid of your countBystartdateAndenddate() function and just use PHP's count() function to get the results you want, then loop over your payroll weeks:
$count = count($payrollweeks);

foreach ($payrollweeks as $payrollweek) {
    $payrollweek->setPayrollperiodid($entity);
}


text:
Q: Dividing space with spheres I heard that maximum number of spaces that can be divided with n spheres is $\frac{1}{3}(n^3-3n^2+8n)$, as cited by this site: http://mathworld.wolfram.com/SpaceDivisionbySpheres.html
I tried to solve this but was unsuccessful, and also failed in searching for the proof. Any help would be very apperciated. Thank you.


text:
Q: Как оптимизировать вставку в БД вложенной древовидной структурой? Есть многоуровневая древовидная структура, получаемая с клиента
[
    'name' => 'text1'
    'children' => [
        ['name' => 'text2', 'children' => []],
        [
            'name' => 'text3'
            'children' => [
                ['name' => 'text4', 'children' => []],
                ['name' => 'text5', 'children' => []],
                ['name' => 'text6', 'children' => []],
            ]
        ],
    ]
]

Стандартная: узел дерева и его потомки, с бесконечной вложенностью.
Как можнозанести все эти записи в БД оптимизированно? Наибольшей эффективностью.
У меня на уме только два способа:

*

*Делать вставки рекурсивно в БД. Т.е. вставляется родитель, берётся у него id, потом вставляются его потомки с parent_id, который только что получили, у них тоже получаем id и вставляем их потомков с parent_id указывающим на них.
Это легко сделать, но, боюсь, что это очень неэффективно, т.к. по сути, на 100 узлов будет 100 INSERT'ов (ну или каждую пачку детей можно через один INSERT записывать, но всё равно неэффективно).

*Взять последний id в базе, даже заблокировать таблицу для записи, рассчитать все идентификаторы заранее и вписать их в массив. И уже одним инсертом вставить в БД.
Этот способ мне не нравится, потому что надо блокировать всю таблицу на время рассчёта идентификаторов на сервере и их вставки.
Есть ли ещё способы вставки такой структуры?


text:
Q: Where do I learn to manage a Mac OS Server network? I inherited a network with 2 Mac OS Servers and 20+ Macbook Pros. My background is all Windows server so I get the concept of Open Directory, Server Admin, and Workgroup Manager, but the nuts and bolts are more difficult to pick up.
Can someone recommend a starting point to learn all of this? So much of the resources I found out there are for home users and not necessarily for a work environment.

A: Ifskills has a great tutorial of Mac OS X Server. I'm still going through it myself. It is massively helpful.

A: Apple has a certification program analogous to Microsoft's MCSE (Microsoft Certified Systems Engineer) certification. They have classroom training at authorized training centers, but they are offered in far fewer cities and less often than those for Microsoft or Cisco. If your employer is willing to pay for it, it would be a good idea to pursue this.
I hold three Apple certifications (see my Ask Different profile here on this site) although none of mine are in network administration.
You might want to pursue the Apple Certified Technical Coordinater certification. If not, at least look at the training materials and third-party books that cover preparation for the Apple OS X Server Essentials 10.7 Exam (9L0-515), or the previous exam for 10.6, which is still available.
Look at Apple's Training and Certification web site to learn about their program.
In the meantime, I would steer you to the Apple-authorized training books from Peachpit Press.

A: If you are looking for a learning place you can check:
http://www.certifiedtraining.com/coursedesc.php?id=101
http://www.learningtree.com/search/search.aspx?Submit.x=0&Submit.y=0&Submit=Submit&q=Mac
http://training.apple.com/classes
http://www.lynda.com/Mac-OS-X-10-7-tutorials/Mac-OS-X-Lion-Essential-Training/85081-2.html
If looking to learn on your own at your own pace... there are great resources/books out there. A few listed below:
Mac OS X Lion Server For Dummies (For Dummies (Computer/Tech))
Mac OS X Lion Bible
Apple Pro Training Series: OS X Lion Support Essentials: Supporting and Troubleshooting OS X Lion


text:
Q: Pandas:Passing a delimiter value to read_csv(), such that, it is ignored for 1 of the columns I've got the Titanic train dataset from Kaggle and I am trying to import it in a pandas data frame. Following is some records from the dataset:
PassengerId,Survived,Pclass,Name,Sex,Age,SibSp,Parch,Ticket,Fare,Cabin,Embarked

*

*2,1,1,"Cumings, Mrs. John Bradley (Florence Briggs
Thayer)",female,38,1,0,PC 17599,71.2833,C85,C

*3,1,3,"Heikkinen, Miss. Laina",female,26,0,0,STON/O2.
3101282,7.925,,S
I want to import it to pandas dataframe such that the commas in the Name field values(which are included under double quotes) are not considered as a delimiter and the column is not split at that comma.
E.g.- for the second record in the example above the Name field having value- "Heikkinen, Miss. Laina" is taken as a single value and is not split at the comma between Heikkinen and Miss. Laina

A: From https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_csv.html pandas documentation:

quotechar : str (length 1), optional
The character used to denote the start and end of a quoted item. Quoted items can include the delimiter and it will be ignored.
quoting : int or csv.QUOTE_* instance, default 0
Control field quoting behavior per csv.QUOTE_* constants. Use one of QUOTE_MINIMAL (0), QUOTE_ALL (1), QUOTE_NONNUMERIC (2) or QUOTE_NONE (3).
doublequote : boolean, default True
When quotechar is specified and quoting is not QUOTE_NONE, indicate whether or not to interpret two consecutive quotechar elements INSIDE a field as a single quotechar element.

So I suggest specifying quotechar in your call of read_csv.


text:
Q: Bot reply In DM on a specific message. Discord.net I'm trying to make a bot that sends a private message when triggered by a specific word.
For example, it would trigger if I type 'send_me_dm'
After the bot sends me a dm message, if I were to dm back 'hiiii", the bot will reply in the dm 'hi'
My code :
If message.Content.Contains("send_me_dm") Then
    Dim user = TryCast(message.Author, SocketGuildUser)
    Await user.SendMessageAsync("you can talk with me") 'now it send as dm
End If

Dim channell As SocketTextChannel = discord.GetChannel(message.Channel.Id)

If message.Channel.Id.Equals(channell) Then
    If message.Content.Contains("hiiii") Then
        Await channell.SendMessageAsync("hi")
    End If
End If


text:
Q: What is the difference between a constructor having super() and not having super() function call in a Java Class What is the difference between these two constructors.
public Students(String name, String address) {
    super();
    this.name = name;
    this.address = address;
}

/*Here is constructor without super function call.*/
public Students(String name, String address) {
    this.name = name;
    this.address = address;
}

A: If there is no explicit call to a super class constructor, the compiler will generate a call to super(). Because of this there is no difference between your examples.

A: No Difference, Its just a matter of explicit and implicit. In the second case, it implicitly calls the super constructor of this Students class if it is inherited from a parent class.  Read more on this. You can find more info if you google it.
public class A {
    //there is a hidden constructor. Even if you explicitly write it
    //public A(){
    //}
}

public class B extends A {
 private int i;

public B(int x){
   this.i = x;
}

}

when you create an Object form B you first call A's constructor implicitly. You can explicitly specify it though.
as
public B(int x){
       super();
       this.i = x;
}

A:
what is difference between a construct having super function and without it.

Well, it can be easily tested. They are actually the same for this case.
More importantly, you probably want to know when and how to use super.
Running the following codes:
public class Test
{
    public static void main(String[] args)
    {
        new Students("a", "b");
    }
}

class Parent
{
    public Parent(){
        System.out.println("Parent class constructor invoked");
    }
}

class Students extends Parent
{
    String name;
    String address;

    public Students(String name, String address) {
        super();
        this.name = name;
        this.address = address;
    }
}

OUTPUT:
Parent class constructor invoked
Now we remove the super();
class Students extends Parent
{
    String name;
    String address;

    public Students(String name, String address) {
        this.name = name;
        this.address = address;
    }
}

OUTPUT:
Parent class constructor invoked
Just like how classes are implicitly extending to Object even when you don't extend them to something. "By default" a super(); will be called in every constructor if one is not given by you.

A: super() just calls the parent constructor of the function and lets you either pass arguments such as super(someArgument) or can be used to call methods of the parent constructor such as super.someMethod().
super() alone just calls the parent constructor without passing any arguments or referencing any methods of the parent. The actual decision on when to call super() depends on the purpose of the overridden method and also the behaviour expected by the base class when you are overriding a certain method.
Check out The Java™ Tutorials or JavaTPoint to learn more.

A: Java implicitly calls the constructor of the super class, if you haven't called it explicitly (constructor chaining - search this term on google for more info). Even if your class is not explicitly inherited from any class, java implicitly makes it inherit the Object class (and makes a call to the constructor of the Object class).
So, there's no difference between them.


text:
Q: Opposite of lastUnique() New to Esper and EPL in general, i have two use cases which are basically the opposites of oneanother. First I need to catch all unique events in a timewindow, using firstunique(*parameters*).win:time(*time*).
Now what I need to do is the exact opposite, basically catch all events that arrive in that window and that are NOT thrown by that statement, basically all the duplicates.
How can I achieve this ? Thanks !

A: You could use a subquery and "not exists". For example:
select * from Event e1 where not exists (select * from Event#firstunique(*parameters*)#time(*time*) e2 where e1.parameters = e2.parameters)

A: I've actually found a solution, it involves using unique id's for incoming events on top of comparing their parameters.
The query looks something like this :
select * from Event a where exists (select * from Event.std:firstUnique(*parameters*).win:time(*time*) b where a.eventId <> b.eventId)

This solves the problem I had where the exists method would return every event (duplicates and unique events) because the window in the subquery would be filled first.