text:
Q: How to get the value of input type checkbox in RepeaterItems (ASP.NET)? i have button delete message from database but i cant get value from checked checkbox in repeateritem. how can i do that?
this my btndelete:
protected void btnDelete_Click(object sender, EventArgs e)
{
    foreach (RepeaterItem aItem in rptInbox.Items)
    {
        HtmlInputCheckBox chk = (HtmlInputCheckBox)aItem.FindControl("chkRow");

        if (chk.Checked == true)
        {
            string id = chk.Value.ToString();

            SqlConnection con = new SqlConnection(conStr);
            SqlCommand cmd = new SqlCommand("delete from mailbox where mailboxid='"+id+"'", con);
            try
            {
                con.Open();
                cmd.ExecuteNonQuery();
            }
            catch (Exception er)
            {

            }
            finally
            {
                con.Close();
            }
        }
    }
}

this my html:
<asp:Repeater ID="rptInbox" runat="server">
    <ItemTemplate>

            <input type="checkbox" ID="chkRow" value='<%#Eval("mailboxid")%>' runat="server"/>
            <%#Eval("from") %>
            <a href="InboxDetail.aspx?MailboxId=<%#Eval("mailboxid") %>"><%#Eval("subject") %>
            <%#Eval("date") %>

    </ItemTemplate>
</asp:Repeater>

A: You can store the value in a hidden field:
<asp:Repeater ID="rptInbox" runat="server">
    <ItemTemplate>

                <input type="checkbox" ID="chkRow" runat="server"/>
                <input type="hidden" ID="hiddenMailBoxID" value='<%# Eval("mailboxid") %>' runat="server"/>

                <%#Eval("from") %>

            ...

    </ItemTemplate>
</asp:Repeater>

And retrieve it in code-behind:
HtmlInputHidden hiddenMailBoxID = aItem.FindControl("hiddenMailBoxID") as HtmlInputHidden;
string id = hiddenMailBoxID.Value;


text:
Q: Sencha Cmd unable to parse custom code in app.js For some reason, Sencha Cmd fails when it parses app.js with custom code.  Below, is a snippet from an application I'm deploying to testing (unminified JavaScript but in a single file) or to production (minified JavaScript).
The browser throws the following JavaScript exceptions from the deployed folder (with all-classes.js):
(note: the folder with all js source code runs fine)
GET http://localhost/App/App/model/app/CheckTreeNode.js?_dc=1396967410158 404 (Not Found) all-classes.js:10841
GET http://localhost/App/App/store/app/UserPreferenceNodes.js?_dc=1396967410159 404 (Not Found) all-classes.js:10841
GET http://localhost/App/app/controller/ViewportAdmin.js?_dc=1396967410177 404 (Not Found) all-classes.js:10841

...

Uncaught Error: [Ext.Loader] Failed loading 'App/model/app/CheckTreeNode.js', please verify that the file exists all-classes.js:11259
Uncaught Error: [Ext.Loader] Failed loading 'App/store/app/UserPreferenceNodes.js', please verify that the file exists all-classes.js:11259
Uncaught Error: [Ext.Loader] Failed loading 'app/controller/ViewportAdmin.js', please verify that the file exists

I tried fixing things by adding a "requires" config in my Ext.application class, but that didn't help.  How can I force these files to be seen by Sencha Cmd?  Sencha Touch has a solution by allowing you to add files to "app.json".  Perhaps there is a similar solution for ExtJS applications that I'm unaware of?
If there are more elegant solutions, I'm open to them.  I needed the user preferences in the constructor of a bunch of my classes, so this was the only place I could get it to load and be ready when those are called.  If there is a different way to load data that can be available when building classes within MVC, I'm fine with a different solution for that.  As for having two viewports, this is what I found to work, so that's what ViewportAdmin is.  Just a second viewport.
app.js source code:
Ext.application({
    name: 'App',
extend: 'App.Application',
requires: [
    'App.store.app.UserPreferences',
    'App.view.ViewportAdmin'
],
autoCreateViewport: false,
launch: function () {

    Ext.StoreManager.lookup('App.store.app.UserPreferences').on('load', function () {

        if (window.location.href.indexOf('/App/index.aspx?admin=true') > -1) {
            Ext.create('App.view.ViewportAdmin');
        }
        else if (window.location.href.indexOf('/App/index.aspx') > -1) {
            Ext.create('App.view.Viewport');
        }
    });

}

});

A: The problem wasn't due to what I suspected.  After deploying the app to testing (ran command "sencha app build testing", I put a breakpoint on the two lines of code below.  It turns out that the controller that it errored on had the store which was not being used.  It failed because of that.  The CheckTreeNodes.js was the model being used in that store.  I just removed it from the stores list to resolve it.
code in all-classes.js (generated from YUI compressor I think):
script.src = url;
(Loader.documentHead || document.getElementsByTagName('head')[0]).appendChild(script);

I looked at the call stack in Google Chrome and found that the anonymous function call (in the call stack) was showing the list of stores from the ViewportAdmin controller.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как получить значения после определенного элемента? Есть список -
a = ['test','test1','test2','test3','test4','test5','test6','test7','test8','test9','test10']

И переменная -
b = test4

Как получить значения которые идут после переменной b из списка a.
Результат должен быть таким
['test5','test6','test7','test8','test9','test10']

A: Вот так вот:
a = ['test','test1','test2','test3','test4','test5','test6','test7','test8','test9','test10']
b = 'test4'

print(a[a.index(b) + 1:])


text:
Q: Run Git commands in microservice I'm implementing microservice (in Spring Cloud) which acts as facade for Git operations invoked by UI layer. I'm trying to use jgit, but the problem is that it requires filesystem. So I have to clone remote repository to local filesystem. Problem is that then microservice is not stateless, and also other problems arises:

*

*cloning before every operation takes too much time so is not an option

*having multiple instances of such microservice can lead to different repositories (push take some time)

*commits on different nodes at the same time can lead to conflicts

I would like to treat Git repository in similar way to database, so all operations should be done without using filesystem, cloning etc. - just invoke command on remote and it's done.
I would like to add that it's quite hard to search for solution, because "Git microservice" phrase is quite common but in other sense (storing sources in repository).
Edit: I've just found
Are there any restful interfaces to git?
but any other ideas would be nice

A: Try Locked Working Copy from scm4j API. It can create locked folder in shared network folder which can not be used by another microservices until release. Do any checkout and other work within Working Copy. Then it will be reused if the same repository url is provided so you need to execute just switch+pull, not clone. If another microservice is currently working with the Working Copy then another available will be taken and locked or new one will be created and locked and so on..
public static final String WORKSPACE_DIR = System.getProperty("java.io.tmpdir") + "scm4j-vcs-workspaces"; // or provide network shared folder path
public static void main(String[] args) {
    IVCSWorkspace workspace = new VCSWorkspace(WORKSPACE_DIR);
    String repoUrl = "https://github.com/scm4j/scm4j-vcs-api";
    IVCSRepositoryWorkspace repoWorkspace = workspace.getVCSRepositoryWorkspace(repoUrl);
    try (IVCSLockedWorkingCopy wc = repoWorkspace.getVCSLockedWorkingCopy()) {
        // wc.getFolder() is locked folder where you can do any checkouts. Another microservices can not use this folder
    }
    // here folder is unlocked and can be reused if the same repository url is provided

}


text:
Q: How to prohibit making a copy of a public field or property in C# Is it possible to prohibit making a reference copy of a public field or property like in the following example?
Foo foo = new Foo();

foo.bar.DoSomething(); // That's fine
Bar myRefToBar = foo.bar; // Don't allow this!

When "bar" gets exchanged inside "foo", "myRefToBar" will still point to the original "bar".
What I'm trying to achive is that either:

*

*"myRefToBar" automatically Points to the new "bar" object, or

*prohibit making a copy of "bar" in the first place.

The obvious solution would be to make "bar" private and write a wrapper function like:
class Foo
{
  private Bar bar;

  public void DoSomethingWithBar()
  {
    bar.DoSomething();
  }
}

But lets say "Bar" has hundreds of functions and I want all of them available, do I have to write hundreds of wrappers, or is there a simpler way of achiving this?

A: All you're doing by writing foo.Bar is exposing a reference to that object.  What they do with the object at that point is up to them.  They can store it for later use (as var bar = foo.Bar) or operate on it directly (as foo.Bar.DoSomething()).  The only way to keep them from doing this would be to, as you said, not expose it at all.

A:
When "bar" gets exchanged inside "foo", "myRefToBar" will still point
  to the original "bar".

Yes, that's true. Are you likely to swap bar a lot? Is there some kind of indication that bar is going to become invalid? If I'm using a class that exposes references I don't necessarily expect them to change unless I call a method such as ReplaceBar(newBar)

What I'm trying to achive is that either:
  • "myRefToBar" automatically Points to the new "bar" object, or
  • prohibit making a copy of "bar" in the first place.

I'm not sure why you have this goal, make it obvious that bar can change, when it has changed and preferably when it will change.

The obvious solution would be to make "bar" private and write a
  wrapper function

Actually to me the most obvious solution is to name bar CurrentBar or use a method GetTemporaryBar() which indicates it changes.
The second step I'd make is if Bar can be invalid I'd make it IDisposable and dispose the old Bar when I swapped it out. Any method called on an invalid Bar should now raise an ObjectDisposedException; I would still be surprised if my reference to bar became invalid halfway through a local method without me calling something that made it clearly my fault.


text:
Q: How to customize a face on Emacs, but only when hl-line is active? I am using Emacs 24, console (8 colors) with the Solarized theme.

I want to make the comments less intrusive using:
(set-face-foreground 'font-lock-comment-delimiter-face "black")
(set-face-foreground 'font-lock-comment-face "black")

That way the comments would be colored with the same color as the hl-line face we can see on the picture. However, when moving to a line containing comments, I would like them to be inverted (black background from the hl-line, normal foreground instead of black) so I can still read them.

A: As an alternative, you can also temporarily hide comments.  See command hide/show-comments-toggle in library hide-comnt.el.  Bind it to a handy key --- pretty simple.

A: Please see the code in the attached link:  Emacs colors. why it is gray on current line? zenburn theme


text:
Q: Why am I getting garbage characters? I keep getting garbage characters when I am outputing "123" and "0".
I was able to narrow it down to the baseout method, and I believe it may be one of my "for loop" conditions but I can't seem to get to be able to remove the garbage characters.
If you can help, please do. Program is in C.
Thank you in advance.
#include <stdio.h>

#define COUNT 8     /* number of hex digits to display */
#define DECIMAL 10  /* to indicate base 10 */
#define HEX 16      /* to indicate base 16 */

/* array used for ASCII conversion */
const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

void baseout (int number, int base, FILE * stream) {
int f1;
int f2;
int index = 0;
int result = number;
char store1[f2];

/*This condition outputs the digit "0" on Line 4*/
if (number == 0) {
    fputc(digits[0], stream);
}

/*This condition outputs the digit "0" after "0x"*/
if (base != DECIMAL){
    store1[f1] = '0';
    fputc(store1[f1], stream);

}

/*This condition outputs codes from bases 2-36*/
if (number != 0) {
   for(f2 = 1; f2 < COUNT && result != 0; f2++){
      index = result % base;
      store1[f2] = digits[index];
      result = result / base;
   }
}

for (f2 = COUNT; f2 > 0; f2--){
    fputc(store1[f2], stream);
}
}

void decout (unsigned int number, FILE * stream) {
    /*Passes DECIMAL to baseout algorithm*/
    baseout(number, DECIMAL, stream);
}

void hexout (unsigned int number, FILE * stream) {

    /* Output "0x" for hexidecimal. */
    writeline ("0x", stream);
    baseout (number, HEX, stream);
}
void newline (FILE * stream) {
    /* Output a newline character */
    fputc('\n', stream);
}
int writeline (const char * message, FILE * stream) {
    int index = 0;
    /*While "index<messagelength" output the each character of message*/
    while(message[index] != '\0'){
            fputc(message[index], stream);
        index++;
    }
    /*Return the message length*/
    return sizeof(message);
}

int main (int argc, char *const* argv) {
    writeline ("Hello World", stdout);
    fprintf (stderr, "Hola Mundo\n");
    newline(stdout);
    decout (123, stdout);
    newline(stdout);
    decout (0, stdout);
    newline(stdout);
    hexout (0xFEEDDAD, stdout);
    newline(stdout);
    return 0;
}

The Desired Output is:
Hola Mundo
Hello World
123
0
0x0FEEDDAD
The Current Output is:
Hola Mundo
Hello World
123
0123
0x0FEEDDAD

A: Your array store1 in the function baseout is not initialized.  Your function does not populate every element in that array, resulting in garbage being left in some of the higher elements.  One solution is to initialize the array to all spaces (or zeros or whatever character you want) at the start of the function:
for(index = 0; index < COUNT ; index++)
{
    store1[index] = ' ';
}

Another possibility is to remove the "if (result != 0)" check in your baseout function (around line 34).  This will store zero in the store1 array for every element that has a zero.  This will result in printing "0000123" instead of "    123"

A: This block of code is not well thought out.
    for(f2 = 1; f2 < COUNT; f2++){
        if (result != 0){
            index = result % base;
            store1[f2] = digit[index];
            result = result / base;
        }
    }

You are incrementing f2 even after result is 0 and not setting the value of store1[f2] for those values. Then you go ahead and try to print the contents of store1. Since store1 is not initialized to anything sensible, you are getting garbage.
Here's one way to fix those problems.
/*This condition outputs codes from bases 2-36*/
if (number != 0) {
   for(f2 = 1; f2 < COUNT && result != 0; f2++){
      index = result % base;
      store1[f2] = digits[index];
      result = result / base;
   }
}

for (f2--; f2 > 0; f2--){
    fputc(store1[f2], stream);
}


text:
Q: Ajax Load a html file and then add a value Hello I have a file here called personal.html:
<form id="form_personal">

                Username:

                <input type="text" name="username" id="us"/>

                <button id="submit" type="submit" class="success button">Submit</button>

    </form>

As you can see from the above code, I have an id called "us". So here is what I am trying to achieve via ajax but it does not work, my

is actually in a file called profile.html. So I am including personal.html via AJAX load into profile.html.
$.ajax({

    url: 'some params, ignore this',
    dataType: 'ignore this',
    success: function(r)
    {
        $('.atest').load('personal.html');

    }
}).done(append);

function append()
{
    // alert();
    $('#us').val('test');
}

I am trying to put in the value of "test" into my
<input type="text" name="username" id="us"/>

which is in the personal.html file, How do I achieve that?

A: you need to wait until personal.html loads completely,for that you should use complete call back of JQuery load method like this:
$('.atest').load('personal.html', function() {
    //this will run after personal.html has loaded.
    //Do your stuff here
});


text:
Q: EJB server error on Wildfly 8.0 I have just started learning EJB and just wanted to execute my first code.
However, I am unable to remove this error:

Error-11:24:22,065 INFO  [org.jboss.as.naming] (default task-3) JBAS011806:
  Channel end notification received, closing channel Channel ID 4fb1d052
  (inbound) of Remoting connection 6e42fa05 to null

I am using Java 1.8 with wildfly 8.0
Code ClientBean
public static void main(String[] args) throws CommunicationException {
    try {
         Context context = getInitialContext();
         Hello remote=(Hello)context.lookup("HelloBean/remote");
         System.out.println(remote.Hello());
    }
    catch (NamingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

public static Context getInitialContext() throws javax.naming.NamingException {
    Properties properties=new Properties();
    properties.put(Context.INITIAL_CONTEXT_FACTORY, "org.jboss.naming.remote.client.InitialContextFactory");
    properties.put(Context.PROVIDER_URL,"http-remoting://localhost:8080");
    properties.put("jboss.naming.client.ejb.context", true);
    return new javax.naming.InitialContext(properties);
}

A: Are you able to invoke your EJB and you see this error after that ?
Also please add credentials to InitialContext Properties ,like below
properties.put("java.naming.security.principal", "user");
properties.put("java.naming.security.credentials", "pass");
You can add this user to wildfly , using addUser.bat/sh scripts. It will ask for something like "use this user for EJB remote communication " , say yes for that.


text:
Q: eCatcher login error (peer not authenticated) I can no longer login in Talk2M using my good old eCatcher 3.x or 4.x.
I receive one of these error messages:

Written out:
Additional info I/O error while communicating with HTTP server:
sun.security.validator.ValidatorException PKIX path building failed:
sun.security.provider.certpath.SunCertPathBuilderException: unable to find certification path
to requested target

or

What can I do?

A: Some SSL certificates have expired in your eCatcher. You should either download new certificates from the eWON web site (eCatcher 4.x only). Or better still, you should upgrade to the latest version.
This page on the eWON web site contains the links to address your problem.
(Disclaimer: I am a member of the eWON R&D team.)


text:
Q: Tracking Changes of Data Refresh from Sharepoint List In Excel I have a excel sheet that is is connected to sharepoint List as data source. Every time I refresh the entire table is updated. The List is saved in a table format.
How would it be possible to track changes of the updates that are made every time it updates? The Track changes tab is greyed out in the review tab. If I remove query definitions by converting table into range the 'track changes' appears again but my connection is no longer functional.
I want to be able to just see the updates that occur. Is there is a better way to visualize such changes ? I already have versioning on in the sharepoint but that is not what I want.


text:
Q: Logitech K750 not working I brought new Logitech K750 keyboard. When I insert wireless unifying receiver to my laptop, I was expecting that some software utility will pop up for installation but all in vain. I rebooted the system, Nothing happened, I type key on keyboard but it doesn't take any input and system shows no response. I am using Ubuntu 11.10. Any suggestions on how to make it work ?

A: Logitech keyboards should work out of box with unifying transmitter. But if you have to configure it manually, you should install the "solaar" package.
Installation
sudo apt-get install solaar solaar-gnome3

If you are running Ubuntu before 16.04, you have to add repository before:
sudo add-apt-repository ppa:daniel.pavel/solaar
sudo apt-get update

How to use
The "solaar-gnome3" package provides a gnome application which can be used to add or remove devices from Logitech's Unifying dongle

A: You won't get any installation utility that pops up, since Logitech doesn't really support Linux.  But normally, their USB devices work fine with Linux (I use a Logitech standard infra-red USB mouse).  I have heard of at least one user who uses the K750 with Ubuntu in the past.
Is the one you have USB?  If so, do you get any indication at all when you plug it in?  Have you tried any other USB slots?  If you're using a USB-3 slot, you may need to switch to USB-2, as there are sometimes compatibility issues.
If it doesn't work, then you might be out of luck.  Logitech isn't too good about Linux support, I don't think.


text:
Q: Run multiple instances of NSOperation with NSURLConnection? We have a large project that needs to sync large files from a server into a 'Library' in the background. I read subclassing NSOperation is the most flexible way of multithreading iOS tasks, and attempted that. So the function receives a list of URLs to download & save, initialises an instance of the same NSOperation class and adds each to an NSOperation queue (which should download only 1 file at a time).
-(void) LibSyncOperation {
    // Initialize download list. Download the homepage of some popular websites
    downloadArray = [[NSArray alloc] initWithObjects:@"www.google.com",
                                                     @"www.stackoverflow.com",
                                                     @"www.reddit.com",
                                                     @"www.facebook.com", nil];

    operationQueue = [[[NSOperationQueue alloc]init]autorelease];
    [operationQueue setMaxConcurrentOperationCount:1]; // Only download 1 file at a time
    [operationQueue waitUntilAllOperationsAreFinished];

    for (int i = 0; i < [downloadArray count]; i++) {
        LibSyncOperation *libSyncOperation = [[[LibSyncOperation alloc] initWithURL:[downloadArray objectAtIndex:i]]autorelease];
        [operationQueue addOperation:libSyncOperation];
    }
}

Now, those class instances all get created fine, and are all added to the NSOperationQueue and begin executing. BUT the issue is when it's time to start downloading, the first file never begins downloading (using an NSURLConnection with delegate methods). I've used the runLoop trick I saw in another thread which should allow the operation to keep running until the download is finished. The NSURLConnection is established, but it never starts appending data to the NSMutableData object!
@synthesize downloadURL, downloadData, downloadPath;
@synthesize downloadDone, executing, finished;

/* Function to initialize the NSOperation with the URL to download */
- (id)initWithURL:(NSString *)downloadString {

    if (![super init]) return nil;

    // Construct the URL to be downloaded
    downloadURL = [[[NSURL alloc]initWithString:downloadString]autorelease];
    downloadData = [[[NSMutableData alloc] init] autorelease];

    NSLog(@"downloadURL: %@",[downloadURL path]);

    // Create the download path
    downloadPath = [NSString stringWithFormat:@"%@.txt",downloadString];
    return self;
}

-(void)dealloc {
    [super dealloc];
}

-(void)main {

    // Create ARC pool instance for this thread.
    // NSAutoreleasePool *pool = [[NSAutoreleasePool alloc]init]; //--> COMMENTED OUT, MAY BE PART OF ISSUE

    if (![self isCancelled]) {

        [self willChangeValueForKey:@"isExecuting"];
        executing = YES;

        NSURLRequest *downloadRequest = [NSURLRequest requestWithURL:downloadURL];
        NSLog(@"%s: downloadRequest: %@",__FUNCTION__,downloadURL);
        NSURLConnection *downloadConnection = [[NSURLConnection alloc] initWithRequest:downloadRequest delegate:self startImmediately:NO];

        // This block SHOULD keep the NSOperation from releasing before the download has been finished
        if (downloadConnection) {
            NSLog(@"connection established!");
            do {
                [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
            } while (!downloadDone);

        } else {
            NSLog(@"couldn't establish connection for: %@", downloadURL);

            // Cleanup Operation so next one (if any) can run
            [self terminateOperation];
        }
            }
    else { // Operation has been cancelled, clean up
        [self terminateOperation];
    }

// Release the ARC pool to clean out this thread
//[pool release];   //--> COMMENTED OUT, MAY BE PART OF ISSUE
}

#pragma mark -
#pragma mark NSURLConnection Delegate methods
// NSURLConnectionDelegate method: handle the initial connection
-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse*)response {
    NSLog(@"%s: Received response!", __FUNCTION__);
}

// NSURLConnectionDelegate method: handle data being received during connection
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [downloadData appendData:data];
    NSLog(@"downloaded %d bytes", [data length]);
}

// NSURLConnectionDelegate method: What to do once request is completed
-(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSLog(@"%s: Download finished! File: %@", __FUNCTION__, downloadURL);
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDir = [paths objectAtIndex:0];
    NSString *targetPath = [docDir stringByAppendingPathComponent:downloadPath];
    BOOL isDir;

    // If target folder path doesn't exist, create it
    if (![fileManager fileExistsAtPath:[targetPath stringByDeletingLastPathComponent] isDirectory:&isDir]) {
        NSError *makeDirError = nil;
        [fileManager createDirectoryAtPath:[targetPath stringByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:&makeDirError];
        if (makeDirError != nil) {
            NSLog(@"MAKE DIR ERROR: %@", [makeDirError description]);
            [self terminateOperation];
        }
    }

    NSError *saveError = nil;
    //NSLog(@"downloadData: %@",downloadData);
    [downloadData writeToFile:targetPath options:NSDataWritingAtomic error:&saveError];
    if (saveError != nil) {
        NSLog(@"Download save failed! Error: %@", [saveError description]);
        [self terminateOperation];
    }
    else {
        NSLog(@"file has been saved!: %@", targetPath);
    }
    downloadDone = true;
}

// NSURLConnectionDelegate method: Handle the connection failing
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"%s: File download failed! Error: %@", __FUNCTION__, [error description]);
    [self terminateOperation];
}

// Function to clean up the variables and mark Operation as finished
-(void) terminateOperation {
    [self willChangeValueForKey:@"isFinished"];
    [self willChangeValueForKey:@"isExecuting"];
    finished = YES;
    executing = NO;
    downloadDone = YES;
    [self didChangeValueForKey:@"isExecuting"];
    [self didChangeValueForKey:@"isFinished"];
}

#pragma mark -
#pragma mark NSOperation state Delegate methods
// NSOperation state methods
- (BOOL)isConcurrent {
    return YES;
}
- (BOOL)isExecuting {
    return executing;
}
- (BOOL)isFinished {
    return finished;
}

NOTE: If that was too unreadable, I set up a QUICK GITHUB PROJECT HERE you can look through. Please note I'm not expecting anyone to do my work for me, simply looking for an answer to my problem!
I suspect it has something to do with retaining/releasing class variables, but I can't be sure of that since I thought instantiating a class would give each instance its own set of class variables. I've tried everything and I can't find the answer, any help/suggestions would be much appreciated!
UPDATE: As per my answer below, I solved this problem a while ago and updated the GitHub project with the working code. Hopefully if you've come here looking for the same thing it helps!

A: In the interests of good community practice and helping anyone else who might end up here with the same problem, I did end up solving this issue and have updated the GitHub sample project here that now works correctly, even for multiple concurrent NSOperations!
It's best to look through the GitHub code since I made a large amount of changes, but the key fix I had to make to get it working was:
[downloadConnection scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

This is called after the NSURLConnection is initialized, and just before it is started. It attaches the execution of the connection to the current main run loop so that the NSOperation won't prematurely terminate before the download is finished. I'd love to give credit to wherever first posted this clever fix, but it's been so long I've forgotten where, apologies. Hope this helps someone!


text:
Q: Can you help me with a LINQ query? I got this MySQL query and I would like to change this to LINQ query.
MySQL:
SELECT
    id,
    cas_poziadavky,
    nazov_linky,
    stanica,
    cas_prichodu,
    meno_udrzbara,
    pricina_problemu,
    riesenie_problemu,
    cas_odchodu,
    bol_prestoj,
    poznamka,
    TIMESTAMPDIFF(MINUTE, cas_poziadavky, cas_odchodu) AS rozdiel',
    TIMESTAMPDIFF(MINUTE, cas_poziadavky, cas_prichodu) AS 'reakcia',
    TIMESTAMPDIFF(MINUTE, cas_prichodu, cas_odchodu) AS 'vyriesenie'
FROM
    monitor_linky

Can you help me please?

A: Just translate your query like this sample:
IQueryable<Customer> custQuery =
from cust in db.Customers
where cust.City == "London"
select cust;

This link may provide you more info: https://msdn.microsoft.com/en-us/library/bb397906.aspx
Hope this help you :)


text:
Q: Facebook sdk 11.0.0 cause crashes on android Environment

*

*Unity Editor Version: 2019.4.30f1

*Unity SDK Version: 11.0.0

In order to solve a crash problem on android caused by Unity, I upgraded my Unity from 2019.4.29f1 to 2019.4.30f1. Unfortunately this time I found a new crash problem. The details information for this problem is as follows:
Caused by java.lang.NullPointerException: Parameter specified as non-null is null: method kotlin.jvm.internal.Intrinsics.checkNotNullParameter, parameter args
       at com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper$BillingClientStateListenerWrapper.invoke(:12)
       at java.lang.reflect.Proxy.invoke(Proxy.java:1006)
       at $Proxy2.onBillingServiceDisconnected()
       at com.android.billingclient.api.zzah.onServiceDisconnected(com.android.billingclient:billing@@3.0.3:4)
       at android.app.LoadedApk$ServiceDispatcher.doDeath(LoadedApk.java:1811)
       at android.app.LoadedApk$ServiceDispatcher$RunConnection.run(LoadedApk.java:1826)
       at android.os.Handler.handleCallback(Handler.java:873)
       at android.os.Handler.dispatchMessage(Handler.java:99)
       at android.os.Looper.loop(Looper.java:205)
       at android.app.ActivityThread.main(ActivityThread.java:6991)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:884)

According to the information provided on the Firebase Crashlytics dashboard, all crashes occur in the background, and most of them occur on Android 11. After analyzing the information, it seems that the crash occurred on the callback of the onBillingServiceDisconnected event (com.facebook.appevents.iap.InAppPurchaseBillingClientWrapper$BillingClientStateListenerWrapper.invoke). Since I don't have an Android 11 device, there is no way to reproduce this crash, and I don't know how to reproduce it. Now onServiceDisconnected event, do you have any suggestions?

A: Try change your dependencies in Facebook Dependencies from
<androidPackage spec="com.facebook.android:facebook-core:[11.0, 12)" />
<androidPackage spec="com.facebook.android:facebook-applinks:[11.0, 12)" />
<androidPackage spec="com.facebook.android:facebook-login:[11.0, 12)" />
<androidPackage spec="com.facebook.android:facebook-share:[11.0, 12)" />
<androidPackage spec="com.facebook.android:facebook-gamingservices:[11.0, 12)" />

To
<androidPackage spec="com.facebook.android:facebook-core:[11.0, 11.3)" />
<androidPackage spec="com.facebook.android:facebook-applinks:[11.0, 11.3)" />
<androidPackage spec="com.facebook.android:facebook-login:[11.0, 11.3)" />
<androidPackage spec="com.facebook.android:facebook-share:[11.0, 11.3)" />
<androidPackage spec="com.facebook.android:facebook-gamingservices:[11.0, 11.3)" />

As temporary solution it will work

A: Root cause is a bug in the underlying facebook sdk: https://github.com/facebook/facebook-android-sdk/issues/1019
Downgrading to facebook-login 11.2 fixes this.


text:
Q: InvalidRequestException(why:No indexed columns present in by-columns clause with "equals" operator) I have created one keyspace and created the column family with some column names. And also added the records in that keyspace programmatically. Now I am going to add one more coulmn in that keysapce and added the new records. It was success... But while searching with that new column field value with equals operator.. I am getting the following exception me.prettyprint.hector.api.exceptions.HInvalidRequestException: InvalidRequestException(why:No indexed columns present in by-columns clause with "equals" operator)
I think there are the rows which does not have the new column field... Is That make an issue?..  Could you please anyone help me to how to solve this problem?.... In Normal Relational database we can add null values to the existing records if any new column is added in the table... Is there anyway like that we can do with cassandra to solve this problem?.... My Final Result should be I can able to search the records with the new column field....

A: yes...the reason you get exception is the newly added column in not indexed to perform equality or similar operations ; while altering column family you have to write e.g.
column_metadata = [{column_name : 'username',
    validation_class : UTF8Type,
    index_name : 'username_idx',
    index_type : 0}]

so your final alter query would be like this
UPDATE COLUMN FAMILY your_CF_name with column_type = 'Standard'
      and comparator = 'UTF8Type'
      and default_validation_class = 'UTF8Type'
      and key_validation_class = 'UTF8Type'
      and column_metadata = [
        {column_name : 'your_all_existing_columns',
        validation_class : your_all_existing_validation_class,
        index_name : 'user_defined_name',
        index_type : 0},
           .
           .
           .
    {column_name : 'your_new_additional_column',
        validation_class : your_validation_class,
        index_name : 'user_defined_name',
        index_type : 0}];


text:
Q: Magento checking order updated_at using Magento date and time we are trying to filter out orders that were created longer than 60 minutes ago with status pending. We are having some problems with the date/time functions
We tried:
 - date('Y-m-d H:m:s') and subtracting hours
 - and Mage::getModel('core/date')
But both are not giving me the correct date/time as I see is being used for the column updated_at.
Question: What date/time function or method should I use to find a date-time that corresponds to the date-time that is used for the updated_at column in orders? (so when I have the correct date-time I can subtract and select orders)
$date = $this->get_offset_hours();
$orders = Mage::getModel('sales/order')->getCollection()
    ->addFieldToFilter('state', 'new')
    ->addFieldToFilter('status', 'pending')
    ->addFieldToFilter('updated_at', array('lt' => $date));

A: All magento transaction data it's saved in UTC so you need to start with the UTC now not your store or server now.
To get the NOW in UTC you can use:
// Get Store ID
$store = $this->getCurrentStoreId(); // You can change it

// Get Store Now (Zend_Date)
$nowStore = Mage::app()->getLocale()
    ->storeDate($store, null, true);

// Get Store Now (String)
$nowStoreDatetime = $nowStore->toString('y-MM-dd HH:mm:ss');

// Get Now UTC
$nowUtc = Mage::app()->getLocale()
    ->utcDate($store, $date, true);

Now you can play with Zend_Date:
/** @var Zend_Date $nowUtc */

$nowUtc->subHour(1);
$finalDatetime = $nowUtc->toString('y-MM-dd HH:mm:ss');

Using $finalDatetimein your query you should get the orders you want.
Note that updated_at date can change if you add a comment to the order or some cron/payment gateway do something, so if you want to track the exactly moment that the order was set to 'pending' you should add a join with status_history table. If that were your case, just let me know and i'll update the answer.
EDIT
Adding a Join with Sales_Order_Status_History to filter by the date when the order was set as 'pending'.
    $orders = Mage::getModel('sales/order')->getCollection()
    $select = $orders->getSelect();
    $select->join(
        array('sfosh' => 'sales_flat_order_status_history'),
        'sfosh.parent_id = main_table.entity_id',
        array()
    )
    ->group('main_table.entity_id');

    $orders
        ->setOrder('sfosh.created_at', 'ASC')
        ->addFieldToFilter('sfosh.created_at', array('lteq' => $finalDatetime))
        ->addFieldToFilter('main_table.status', array('eq' => 'pending'))
    ;


text:
Q: How can I say a function $F:\mathbb{R}^n \longrightarrow \mathbb{R}^m$ $nMy doubts are about an application of the Implicit Function Theorem: I do not understand how a function $F: \mathbb{R}^n \longrightarrow \mathbb{R}^m$, with $n<m$ (!!!) can locally be an homeomorphism between a neighbourhood of $x$ and a neighbourhood of $F(x)$, for all $x$ such that $rnk(DF(x))=n$.
I just cannot understand how I can apply the Inverse Function Theorem (which I know for Banach spaces), given that $DF(x)$ cannot be invertible! I'm asking this because I found this result written in many texts, for example the solution of exercise 2.2.5 of Berkley-Problems in Mathematics.
To be precise, the exercise was:
$F: \mathbb{R}^n \longrightarrow \mathbb{R}$, $F\in C^2(\mathbb{R})$. Let0s say that a point $x$ is a nondegenerate critical point if $DF(x)=0$ and $rnk(D^2F(x))=n$. Show that every nondegenerate crytical point is isolated.
The solution provided from the book stated:
Define $G: \mathbb{R}^n \longrightarrow \mathbb{R}, G(y):= |DF(y)|^2 $, where $|.|$ is the Euclidean norm.Then, $G$ is $C^1$, $G'(x) != 0 $ and $G(x)=0$, so by the Inverse Function Theorem G is locally diffeomorphism to a neighbourhood of 0, hence injective.
I don't understand this solution!Thanks in advance to everybody who'll answer me!

A: The proposed solution is nonsense, you should complain to the people who wrote it. (In the 3rd edition of ``Berkeley Problems in Mathematics" that I have, this is a "solution" of Problem 2.2.10.) A correct solution is to consider the gradient function $G(x)=\nabla F(x), x\in {\mathbb R}^n$. This function is $C^1$ and has zero at some $x_0$. The assumption that the Hessian of $F$ has rank $n$ at $x_0$ amounts to the assumption that the derivative $DG(x)$ has (maximal) rank $n$ at $x_0$. Regarding $G$ as a map ${\mathbb R}^n\to {\mathbb R}^n$ we then can apply the IFT to $G$ at $x_0$ and conclude that $G$ is a local diffeomorphism at $x_0$, implying that $x_0$ is an isolated zero of $G$. In other words, $x_0$ is an isolated critical point of $F$.


text:
Q: Export results with outreg2 I am using the community-contributed command outreg2 in Stata to create a table with multiple regressions based on categorical variables:
bysort Sector: outreg2 using results_by_sectors.xls, replace dec(2) ///
keep(log_tfp_leader_growth years_schooling_normalized ///
tfp_gap_years_school_norm i_rd_go tfp_gap_i_rd) title("Regressions By Sectors") ///
label: reg log_tfp_growth log_tfp_leader_growth years_schooling_normalized ///
tfp_gap_years_school_norm, robust

Everything is well except one thing; the table instead of using the names/labels of the categorical variable Sector pops out as Sector 1, Sector 2, Sector 3 and so on:

However, the labels/names of each Sector are:
tab Sector

        ind |      Freq.     Percent        Cum.
------------+-----------------------------------
      10-12 |        236        3.88        3.88
      13-15 |        236        3.88        7.76
      16-18 |        236        3.88       11.64
         19 |        220        3.62       15.26
      20-21 |        220        3.62       18.88
      22-23 |        236        3.88       22.76
      24-25 |        220        3.62       26.38
      26-27 |        220        3.62       30.00
         28 |        220        3.62       33.62
      29-30 |        220        3.62       37.24
      31-33 |        220        3.62       40.86
          A |        284        4.67       45.53
          B |        284        4.67       50.20
        D-E |        252        4.14       54.34
          F |        284        4.67       59.01
          G |        284        4.67       63.68

How should I modify my outreg2 code so instead of getting Sector 1, Sector 2 in the column names of each regression to get the labels of each Sector as shown above (e.g. 10-12 etc.)?

A: You cannot do that with outreg2 because it is coded by its author to return the name of the variable plus the factor level number:
. sysuse auto, clear
(1978 Automobile Data)

. bysort foreign: outreg2 using myfile, side replace: quietly reg price weight mpg
dir : seeout

. type myfile.txt
        (1)     (2)     (3)     (4)
        foreign 0               foreign 1
VARIABLES       price   se      price   se

price
weight  4.415***        (0.948) 5.156***        (0.881)
mpg     237.7*  (139.0) -19.78  (57.68)
Constant        -13,285**       (5,726) -5,066  (3,203)

Observations    52              22
R-squared       0.483           0.785
Standard errors in parentheses
*** p<0.01, ** p<0.05, * p<0.1

You can see that this is indeed the case if you recode the variable you use for bysort:
. recode foreign (0 = 1) (1 = 2)
(foreign: 74 changes made)

. bysort foreign: outreg2 using myfile, side replace: quietly reg price weight mpg
dir : seeout

. type myfile.txt
        (1)     (2)     (3)     (4)
        foreign 1               foreign 2
VARIABLES       price   se      price   se

price
weight  4.415***        (0.948) 5.156***        (0.881)
mpg     237.7*  (139.0) -19.78  (57.68)
Constant        -13,285**       (5,726) -5,066  (3,203)

Observations    52              22
R-squared       0.483           0.785
Standard errors in parentheses
*** p<0.01, ** p<0.05, * p<0.1

However, you can get the desired output with the estout community-contributed command:
. sysuse auto, clear
(1978 Automobile Data)

. quietly bysort foreign: eststo: quietly reg price weight mpg

. esttab, label nodepvar

----------------------------------------------------
                              (1)             (2)
                         Domestic         Foreign
----------------------------------------------------
Weight (lbs.)               4.415***        5.156***
                           (4.66)          (5.85)

Mileage (mpg)               237.7          -19.78
                           (1.71)         (-0.34)

Constant                 -13285.4*        -5065.8
                          (-2.32)         (-1.58)
----------------------------------------------------
Observations                   52              22
----------------------------------------------------
t statistics in parentheses
* p<0.05, ** p<0.01, *** p<0.001

Obviously, you will have to play with the various options to get exactly what you need (e.g. specify the option cells(b se) in order to include standard errors in the table).


text:
Q: Is there a simple Bash command which just sets the exit code? When testing exit code handling it is often useful to trigger an arbitrary exit code anywhere within the script, as a sort of hack approximating a Python Mock with side_effect = Exception(). For exit codes 0 and 1 there are the true and false builtins, but for any other exit code it seems there are only clunky options:

*

*Using a subshell: (exit "$exit_code"). This is expensive and complex enough to possibly have unexpected side effects. Starting up a new shell probably invokes many thousands of lines of code, while a command specifically intended to set the exit code in line would probably be a handful of lines. Subshells are also a rare construct in production code, so a newbie could easily conclude that the code is equivalent to exit "$exit_code".

*Creating and invoking a custom function:
simulate_exit_code() {
    return "$1"
}
simulate_exit_code "$exit_code"

Cheap but additional complexity.
I'm asking whether there is a better option than either of the above, not which one of them is best (the first for brevity, the second for speed). Some dead simple builtin command like set_exit_code "$exit_code" would be ideal.

A: One convoluted option would be:
. /dev/stdin <<< 'return "$exit_code"'

(doesn't fork, but creates a temp file or a pipe in 5.1+)
For completeness,
Note that in ksh93, (exit "$ret") doesn't fork a subshell, so is relatively efficient there.
bash is one of the rare few Bourne-like shells where you can't write it set_status() return "$1" for short.
In zsh, you could use an anonymous function:
() return 3

When I have such a need, I personally use:
set_status() { return "$1"; }

Which seems the simplest to me.
But in conclusion, the answer to is there a simple Bash command which just sets the exit code is no AFAIK.

A: I believe a custom function is your best bet (option 2 in your question).


text:
Q: og:image not working, except when I try with "Open Graph Object Debugger" I have a website with all the og:image tags properly set and it does not work, except when I use the Open Graph Object Debugger, which shows me the expected preview.
Step by step (with an image for every step):
If I take a non-cached URL like...
http://club.ad/andorra-la-vella/ca/activitat/activitats-infantils and I try to share it on facebook, this is what I get:

As you can see there's no image shown on the preview. In this case the first thing I do is check that the og:image is properly set. Checking the sourcecode of that link, we can read:
<meta property="og:image" content="http://club.ad/files/thumbs/activities-illustrative/10557110_m.jpg" />

And if we check the image URL, we get this:
activity's illustrative image http://club.ad/files/thumbs/activities-illustrative/10557110_m.jpg
The og:image tag is inside the head tag, so everything seems to be ok. Here's when I go to Facebook's Open Graph Object Debugger and I try the previously checked link.
The first time it says that that URL has not been cached, but it shows the preview pretty well:

Now that the request has been done from here, if I go back to facebook the preview is properly loaded:

And if we go back again to the Open Graph Object Debugger and we click on "Fetch new scrape information" there aren't errors nor warnings shown:

So, what's wrong with my website? Or what's wrong with facebook?
If you want to check it by yourself, take any URL from the websites' activities index (there are some of them that have been checked and thus will return the cached content):
http://club.ad/andorra-la-vella/ca/activitats (click on any activity image)
Thanks in advance for any help given :)

A: Try specifying image dimensions in your OG meta tags as well.
https://developers.facebook.com/docs/sharing/best-practices#precaching:

There are two ways to avoid [image not being shown on first share] and have images render on the first Like or Share action:

*

*Pre-cache the image with the URL Debugger […]

*Use og:image:width and og:image:height Open Graph tags
Using these tags will specify the image to the crawler so that it can render it immediately without having to asynchronously. (sic)

A: From: http://developers.facebook.com/docs/sharing/best-practices#precaching

When content is shared for the first time, the Facebook crawler will
  scrape and cache the metadata from the URL shared. The crawler has to
  see an image at least once before it can be rendered. This means that
  the first person who shares a piece of content won't see a rendered
  image:

I use this script to update the facebook cache before the user shares the page:
<script>
        var fbShareLink = '<yourLink>';
        var d = new Date();
        $.post(
            'https://graph.facebook.com',
            {
                id: fbShareLink,
                scrape: true
            },
            function(response){
                console.log(response);
            }
        );
</script>

Currently I do it every time the page is loaded, because my images are live renderd and contain the current time.
There might be a better solution for static images. (Calling facebook from the backend, when new content is added)


text:
Q: Additional Columns with Other non Criteria Sorry the title isn't clear
I have a script (using Pl/Sql Oracle), i have created a report that will     optout a list of cities chosen by a user. I have a column that will list that     city but i wanted to include an additional column that list other cities     associated with the user (the cities list should not include his/her pick on     that column).
I am not exactly sure who to do that so that the additional column will not list the picked city or cities. Is there a function i can use?
I am also doing it on Crystal reporting 10 (if it possible there)
Iex: This is just an idea of what i am trying to do.
##Table Name: Giving Cities##
##Andrew - Peru##
##Andrew - Venezuela##
##Andrew - France##
##Paul - USA##

Pick cities where user = Andrew and  City = Peru

Output
User, City, Other Given Cities

A: In SQL adding extra additional columns:
select user,cities,'' as additional_columns from yourtable

A: I think this is what you are looking for: SQL Query to concatenate column values from multiple rows in Oracle
It looks like exactly what you are trying to do with concatenating the results of multiple rows together.
As for not selecting the "selected" city for the additional column, you would want to use a subselect. A subselect allows you to apply a different where clause to the additional column.
select t.user, t.city, t2.concatenated_cities
from table t
inner join
(
    select distinct <see above link for how to concatenate rows here> as concatenated_cities
    from table sub_t
    where sub_t.city <> 'CITY'
) t2
on t.user = t2.user
where t.city = 'CITY'


text:
Q: .load() jquery with JSP and Access Database I have got a situation where I call .load() with a jsp which returns a html table and values extracted from database.
Every time there is a change through insert, update or delete, .load() is called.
function showResponse(responseText, statusText, xhr, $form)
{
   var success = "Success";
   var updated = "Updated";
   var deleted = "Deleted";

   if(responseText.substr(0,7) == updated)
   {
      document.getElementById('editForm').reset();
      document.getElementById('editFormDiv').style.display = 'none';
      retrive();
      return;
   }
   if(responseText.substr(0,7) == success)
   {
      document.getElementById('addBeneficiary').reset();
      document.getElementById('otherBank').style.display = 'none';
      document.getElementById('bene_name').focus();
      document.getElementById('editFormDiv').style.display = 'none';
      retrive();
      return;
   }
   if(responseText.substr(0,7) == deleted)
   {
      retrive();
      return;
   }
}

function retrive()
{
   $('#updateEditResults').load('retriveBeneficiaryDetails.jsp?process=u');
   $('#updateDeleteResults').load('retriveBeneficiaryDetails.jsp?process=d');
}

Now whenever I call it after delete and update, the updated database (with record deleted / edited) is shown. But after insert sql statement the changes are not reflected.


text:
Q: Using simple JS within ionic sidemenu sample (AngularJS) I am currently porting a Javascript "app" into AngularJS and one part of this app would be too long to recode.
What I would like to do is to use a simple javascript instruction like alert("message") within the ionic sideMenu sample available here : http://ionicframework.com/getting-started/
I already tried by including this into indext.html as well as in search.html but nothing would help
<script src="js/test.js" type="text/javascript"></script>

This is my test.js (I get no output for the console.log neither)
function test()
{
   console.log('test');
   alert("Secon test");
}
test(); //first method for calling the function, won't work

And calling it within an attribute won't work neither :
<ion-content class="has-header"  scroll="false" onload="test()">

Could you please tell me why this is not working and how to fix it?
Thank you in advance

A: As mentioned Lucuma :
Ionic uses angular so this should be included inside a controller.


text:
Q: Cannot use the special principal 'sa' When I try to run the command:
EXEC master..sp_addsrvrolemember @loginame = N'sa', @rolename = N'serveradmin'
GO

I get the error:

Msg 15405, Level 11, State 1, Procedure sp_addsrvrolemember, Line 45
  Cannot use the special principal 'sa'.

Ideas/suggestions welcome.

A: 'sa' is a reserved login for the sysadmin; it's already a member of the sysadmin group, which trumps all other groups.  You don't need to add it to any roles, so why are you trying to do that?


text:
Q: Huge Array filtering I am using realm db and in my table I have 100000 record. After request for new data I need to check this data exist in my table or not.
I am getting the record in array from db. And every request I am checking new record exist in this array or not. I use first, map, filter, foreach and for loops. But all of them increase memory so much and then application freeze.
How can I search in huge array without any memory problem?
My table structure:
userName - UserPhone - userAddres
let users = [User]() --Filled from realm db.

let realm = try! Realm()

let userData = realm.objects(Users.self)
users = Array(userData)

let userItem = self.users.first(where: { $0.userName == item.Name && $0.userPhone == item.phone })

let userItem = self.users.filter(where: { $0.userName == item.Name && $0.userPhone == item.phone })


text:
Q: submitting multiple forms with javascript My script:

Submits the below form:
<form name="playsong" method="post" action="submit.php">
<input type="hidden" name="play" value="2009-05-19-3934.data">
Play 1
</form>

How can I change this so that I can have a series of links: Play 1 That will submit the correct form without having to build a function to submit each form.
That is how can I make the function submit different various forms on the page dependent the link clicked.

A: Consider:-
 function submitForm(form)
 {
      document[form].submit();
 }

 Play 1

A: Build several links like
<form action="act1">
    Play 1
</form>
<form action="act2">
    Play 2
</form>
<form action="act3">
    Play 3
</form>
<form action="act4">
    Play 4
</form>
<form action="act5">
    Play 5
</form>

And make a js:
function goForm(frm) {
    if (frm != null)
        frm.submit();
}

There you go! =´p


text:
Q: GraphQL client libraries for iOS I have a GraphQL service that I need to hit from an iOS app, and I'm trying to survey what my options are for client libraries geared towards this purpose. My initial impression is that there are not many good options out there, and I'm a little surprised by this since Facebook's mobile app is always cited among the motivational material for GraphQL itself.
What follows is my current understanding of my options. My questions is: what client library options am I overlooking?  I'm also curious if you were to imagine the ideal GraphQL client library for iOS, what might it look like?

*

*Just Alamofire, AFNetworking, or NSURLSession directly, passing in lovingly hand-crafted Query Documents and spelunking through a Dictionary representing the resulting JSON, or

*Chester

*GraphQLicious

*Swift-GraphQL

A: I would not build queries by hand, and I think both Chester and GraphQLicious would be fine for you.
If I had to imagine the perfect library, it should not only build queries but also parse the result into Swift objects. This, as you may know from JSON parsing libraries, is not a small task and that's why most of the GraphQL-Builder libraries don't do it.
Disclosure: I'm one of the guys behind GraphQLicious

A: This question was asked a long time ago - I think today the standard answer to this will be to use Apollo Client.
It uses a similar API as the Apollo Client on the web and has a couple of really nice features:

*

*Static type generation based on GraphQL Queries & Mutations

*Normalized cache

*Query watching & automatic UI updates

*Manual store updates

It has not yet reached 1.0 but overall is a super promising project!
Here are some resources that should help you get started:

*

*Apollo iOS Quickstart

*Apollo iOS on GitHub

*Ray Wenderlich GraphQL Tutorial

*Learn Apollo iOS Track


text:
Q: How do I make an outline or box around a download link? I tried looking online, but I couldn't find anything. Please help!
I tried some methods that were supposed to work, but they did not.

A: Use the attribute selector and apply the style

a[download] {
  outline: 2px solid orange;
}
Download


text:
Q: Sequential SQL inserts when triggered by CROSS APPLY This process has several steps which are reflected in various tables of a database:
Production --> UPDATE to the inventory table using something like
UPDATE STOR SET
    STOR.BLOC1 = T.BLOC1,
    STOR.BLOC2 = T.BLOC2,
    STOR.BLOC3 = T.BLOC3,
    STOR.PRODUCTION = T.PROD,
    STOR.DELTA = T.DELTA
FROM BLDG B INNER JOIN STOR S
ON S.B_ID = B.B_ID
CROSS APPLY dbo.INVENTORIZE(B.B_ID) AS T;

The above feeds a log table with a TRIGGER like this:
CREATE TRIGGER trgrCYCLE
ON STOR
FOR UPDATE
AS
INSERT INTO dbo.INVT
    (TS, BLDG, PROD, ACT, VAL)
    SELECT CURRENT_TIMESTAMP, B_ID, PRODUCTION,
        CASE WHEN DELTA < 0 THEN 'SELL' ELSE 'BUY' END,
        DELTA
    FROM inserted WHERE COALESCE(DELTA,0) <> 0

And finally, every update should INSERT a row into a financials table which I added to the TRIGGER above:
INSERT INTO dbo.FINS
    (COMPANY, TS, COST2, BAL)
    SELECT CORP, CURRENT_TIMESTAMP, COST,
    ((SELECT TOP 1 BAL FROM FINS WHERE COMPANY = CORP ORDER BY TS DESC)- COST)
    FROM inserted WHERE COALESCE(COST,0) <> 0

The problem is with this line:
((SELECT TOP 1 BAL FROM FINS WHERE COMPANY = CORP ORDER BY TS DESC)- COST)

which is meant to calculate the latest balance of an account. But because the CROSS APPLY treats all the INSERTS as a batch, the calculation is done off of the same last record and I get an incorrect balance figure. Example:
 COST    BALANCE
----------------
          1,000   <-- initial balance
 -150       850
 -220       780   <-- should be 630

What would be the way to solve that? A trigger on the FINS table instead for the balance calculation?

A: Understanding existing logic in your query
UPDATE statement will fire a trigger only once for a set or batch satisfying join conditions, Inserted statement will have all the records that are being updated. This is because of BATCH processing not because of CROSS APPLY but because of UPDATE.
In this query of yours
   SELECT CORP, CURRENT_TIMESTAMP, COST,
    ((SELECT TOP 1 BAL FROM FINS WHERE COMPANY = CORP ORDER BY TS DESC)- COST)
    FROM inserted WHERE COALESCE(COST,0) <> 0

For each CORP from an Outer query, same BAL will be returned.
(SELECT TOP 1 BAL FROM FINS WHERE COMPANY = CORP ORDER BY TS DESC)

That being said, your inner query will be replaced by 1000(value you used in your example) every time CORP = 'XYZ'
   SELECT CORP, CURRENT_TIMESTAMP, COST, (1000- COST)
    FROM inserted WHERE COALESCE(COST,0) <> 0

Now your inserted statement has all the records that are being inserted. So every record's cost will be subtracted by 1000. Hence you are getting unexpected result.
Suggested solution
As per my understanding, you want to calculate some cumulative frequency kind of thing. Or last running total
Data Preparation for problem statement. Used my dummy data to give you an idea.
--Sort data based on timestamp in desc order
SELECT PK_LoginId AS Bal, FK_RoleId AS Cost, AddedDate AS TS
, ROW_NUMBER() OVER (ORDER BY AddedDate DESC) AS Rno
INTO ##tmp
FROM dbo.M_Login WHERE AddedDate IS NOT NULL

--Check how data looks
SELECT Bal, Cost, Rno, TS FROM ##tmp

--Considering ##tmp as your inserted table,
--I just added Row_Number to apply Top 1 Order by desc logic

+-----+------+-----+-------------------------+
| Bal | Cost | Rno |           TS            |
+-----+------+-----+-------------------------+
| 172 |   10 |   1 | 2012-12-05 08:16:28.767 |
| 171 |   10 |   2 | 2012-12-04 14:36:36.483 |
| 169 |   12 |   3 | 2012-12-04 14:34:36.173 |
| 168 |   12 |   4 | 2012-12-04 14:33:37.127 |
| 167 |   10 |   5 | 2012-12-04 14:31:21.593 |
| 166 |   15 |   6 | 2012-12-04 14:30:36.360 |
+-----+------+-----+-------------------------+

Alternative logic for subtracting cost from last running balance.
--Start a recursive query to subtract balance based on cost
;WITH cte(Bal, Cost, Rno)
AS
(
    SELECT t.Bal, 0, t.Rno FROM ##tmp t WHERE t.Rno = 1
    UNION ALL
    SELECT c.Bal - t.Cost, t.Cost, t.Rno FROM ##tmp t
      INNER JOIN cte c ON t.RNo - 1 = c.Rno
)
SELECT * INTO ##Fin FROM cte;

SELECT * FROM ##Fin

Output
+-----+------+-----+
| Bal | Cost | Rno |
+-----+------+-----+
| 172 |    0 |   1 |
| 162 |   10 |   2 |
| 150 |   12 |   3 |
| 138 |   12 |   4 |
| 128 |   10 |   5 |
| 113 |   15 |   6 |
+-----+------+-----+

You have to tweet your columns little bit to get this functionality into your trigger.

A: I think you can try a trigger on the Fins.
You can use IDENT_CURRENT('Table')) to take the last primary key from the table and make a select.
I think it's better than "select top 1".
To to take the last balance value, set a variable last_bal = select bal from FINS where primary_key = Ident_Current("FINS")

A: well
first sql is a game where it work with groups or rather "set" so always you have think about that.
if you work with a simple item is correct, it maybe be better approach
declare @myinsert table(id int identity(1,1), company VArchar(35), ts datetime, cost2 smallmoney, bal smallmoney)

insert into @myinsert(company,ts, cost2, bal)
SELECT CORP, CURRENT_TIMESTAMP, COST,
FROM inserted WHERE COALESCE(COST,0) <> 0

declare @current int

select @current = min(id) from @myinsert

while exists(select * from @myinsert where id = @current)
begin
  INSERT INTO dbo.FINS
  (COMPANY, TS, COST2, BAL)
  SELECT COMPANY, CURRENT_TIMESTAMP, COST,
  ((SELECT TOP 1 BAL FROM FINS WHERE COMPANY = my.COMPANY ORDER BY TS DESC)- COST)
  from @myinsert my where id = @current

  select @current = min(id) from @myinsert where id > @current
end

A: i am not giving you exact query .For a moment forget trigger.Because you are unable to test your query .
I suggest to use Output clause .This will atleast help you to construct proper query and test it.
this query is running ok,(if you can use merge then that is best).
Declare @t table
(
  BLOC1,BLOC2,BLOC3 ,PRODUCTION ,DELTA --whatever column is require here
)

UPDATE STOR SET
    STOR.BLOC1 = T.BLOC1,
    STOR.BLOC2 = T.BLOC2,
    STOR.BLOC3 = T.BLOC3,
    STOR.PRODUCTION = T.PROD,
    STOR.DELTA = T.DELTA
Output inserted.BLOC1 ,inserted.BLOC2,  and so on into @t
FROM BLDG B INNER JOIN STOR S
ON S.B_ID = B.B_ID
CROSS APPLY dbo.INVENTORIZE(B.B_ID) AS T;

now you have inserted value in table variable @t
 SELECT CORP, CURRENT_TIMESTAMP, COST,
 BAL,Row_Number() over(partition by company order by TS desc) RN
FROM @t inner join FINS on COMPANY = CORP
WHERE COALESCE(COST,0) <> 0

Verify this query till here.Think of optimizing or trigger later on.
I think i gave good suggestion.and I guess subtraction is not a problem.I am telling to put everything in output clause and analyze the query and test it.
you can use CTE inside trigger also but how will you test it.
  ;With CTE as
    (
      SELECT CORP, CURRENT_TIMESTAMP, COST,BAL
   ROW_NUMBER()over(ORDER BY TS DESC )rn
    FROM inserted
        inner join FINS on COMPANY = CORP

     WHERE COALESCE(COST,0) <> 0
    )
    select * from CTE --check this what you are getting

A: Something like that, Isn't complete.
CREATE TRIGGER trgrCYCLE
ON STOR
FOR UPDATE
AS
begin

declare @last_bal int

declare @company varchar(50)
declare @ts  --type
declare @cost  int
declare @bal  --type
--etc whatever you need

select @company = company, @ts= ts , @cost = cost , @bal = bal from INSERTED

 --others selects  and sets

set @last_bal = select bal from dbo.FINS where you_primary_key = IDENT_CURRENT('FINS'))

set @last_bal = @last_bal - @cost

Insert INTO FINS (company, ts, cost2, bal) VALUES (@company, @ts, @cost, @last_bal) where --your conditions

end

A: If, similar to @Shantanu's method, you could associate a sequence with inserted, the virtual table associated with the trigger you could do this by subtracting all the COSTs that come before the current record.
This could be accomplished by adding a rowversion to STOR, which will be updated automatically with each delete.
Then instead of:
((SELECT TOP 1 BAL FROM FINS WHERE COMPANY = CORP ORDER BY TS DESC)- COST)
from inserted ...
make the rowversion RV, and:
(SELECT SUM(X.B) FROM
      (SELECT TOP 1 BAL B
           FROM FINS
           WHERE COMPANY = CORP
           ORDER BY TS DESC
       UNION
       SELECT -COST B
           FROM inserted ii
           WHERE ii.RV >= i.RV AND ii.CORP = i.CORP
       ) AS X)
    FROM inserted i WHERE COALESCE(COST,0) <> 0

Should do what you want. You could conceivably do this with a timestamp that was more find-grained than CURRENT_TIMESTAMP which, I believe, goes down only to seconds but that requires you update it in the UPDATE statement. The rowversion may cause problems with your STOR insert statements.


text:
Q: "sic" with "explicitly" (and other adverbs) I was reading a Wikipedia article on Fermat's principle that quoted some older English text, and one bit confused me:

The principle of Fermat, although it was assumed by that mathematician on hypothetical, or even imaginary grounds, is in fact a fundamental law with respect to undulatory motion, and is explicitly [sic] the basis of every determination in the Huygenian theory...

The use of "sic" is tied in the source code to the word "explicitly," by the way. I thought this might have been a one-off thing, but when you search "explicitly [sic]" you find a host of other examples, most of which seem fine to me:

...there is just one non-Hebrew document from Syria-Palestine which speaks explicitly [sic] of the Hebrews... [2]

'Velikovsky explicitly [sic] predicts the presence of frogs and flies in the clouds of Jupiter...' [3]

He does not claim, and in fact explicitly [sic] denies, that suppositions of like universality attach to critique or textual interpretation... [4]

What's going on here? Is there something wrong with these sentences, or is it some extension of usage?

A: There's nothing wrong with the sentences. It is rather an extension of usage.
[sic] can mean that something is not correct in a quote (typo etc) but you could also use it to emphasize some peculiarity of the quoted text (e.g. contradictory or
dubious assertions or a value that deviates heavily from the norm). By using [sic] you normally want to express that you are aware of this discrepancy and you want the reader of your text to know that you yourself find some fact or opinion somewhat shady, not convincing or maybe not trustworthy. The link between [sic] and "explicitly" derives from that. If you say that someone else explicitly said something then you imply that 1. this person really said this and believed it and 2. that it is not your interpretation but in the original text and can be verified, e.g. in the corpus of an author. By using [sic] you somewhat disavow the controversial statement.
Within the database of CliniPharm/CliniTox (https://www.vetpharm.uzh.ch/wir/varia/sic.htm) [sic] is mostly used to indicate that the immediately preceding statement or value can be found exactly like quoted in the original publication but that the validity of the info is very arguable.


text:
Q: Internet Explorer not loading js scripts in .new framework 4.7.2 application I've created and deployed an asp.net framework 4.7.2 mvc application.
It works well with all other browsers but when it's opened with IE the scripts do not run.
This must be a compatibility issue, how can I resolve this?
Note: the scripts are both jquery and javascript integrated together.


text:
Q: Custom notice based on cart item stock quantity in Woocommerce I am trying to create a function for wordpress/woocommerce to show an option in the cart page for split delivery.
What it should do is to check the stock status of all items in cart.
First case: If all items in cart are available output nothing.
Second case: If all items in cart are out of stock, output nothing.
Third case: The only condition when something should be shown is, when both cases (first and second) occurs.
So only if the cart has items in stock AND has items out of stock it should display a notification.

The previous version seemed to be the wrong way to go. So here is my new approach with a different code.

in functions.php:
add_action( 'woocommerce_after_cart_table', 'split_devliery_notification' );
function split_devliery_notification() {
    $all_items_in_stock = true; // initializing
    $all_items_out_of_stock = true;

    // Iterating through cart items (to get the stock info)
    foreach (WC()->cart->get_cart() as $cart_item) {

        # HANDLING SIMPLE AND VARIABLE PRODUCTS

        // Variable products
        $variation_id = $cart_item['variation_id'];
        if( 0 != $variation_id) {
            $variation_obj = new WC_Product_variation($variation_id);
            $stock = $variation_obj->get_stock_quantity();
        } else {
            // Simple products
            $product_id = $cart_item['product_id'];
            $product_obj = new WC_Product($product_id);
            $stock = $product_obj->get_stock_quantity();
        }

        if( $stock <= 0 ){
            // if an item is out of stock
            $all_items_in_stock = false;
            break; // We break the loop
        }
        elseif ( $stock >= 0 ) {
            $all_items_out_of_stock = false;
            break;
        }

    }

    // All items "in stock"
    if( $all_items_in_stock ) {
        echo 'All items in cart are in stock';
    }
    elseif ( $all_items_out_of_stock ) {
        echo 'All items in cart are out of stock';
    }
    else {
        echo 'Some items in cart are in stock and some are out of stock -> Show notification ON!';
    }

}

This function works for two cases:

*

*If all items in cart are in stock it echoes the right message (All items in cart are in stock
).

*If all items in cart are out of stock is echoes the right message (All items in cart are out of stock).

But if the cart contains items in stock AND items out of stock it echoes the first message (All items in cart are in stock).

A: I have revisited your code. For cart items, $cart_item['data']; is the WC_Product Object that is needed, so the code will be much more compact.
The code below will display a custom notice when there is mixed stock for cart items that are in stock and out of stock at the same time.
The first function is the conditional function that checks cart items.
The second function use the first function to display conditionally a custom notice.
// Conditional function: Checking cart items stock
function is_mixed_stock_items(){
    $enough_stock = $out_of_stock = false; // initializing

    // Loop through cart items
    foreach ( WC()->cart->get_cart() as $cart_item ) {
        // Get an instance of the WC_Product Object
        $product = $cart_item['data'];
        // Get stock quantity
        $stock_qty = $product->get_stock_quantity();
        // get cart item quantity
        $item_qty  = $cart_item['quantity'];

        if( ( $stock_qty - $item_qty ) >= 0 ){
            $enough_stock = true; // enough stock
        } else {
            $out_of_stock = true; // not enough stock
        }
    }
    // return true if stock is mixed and false if not
    return $enough_stock && $out_of_stock ? true : false;
}

// Display a custom notice
add_action( 'woocommerce_after_cart_table', 'display_delivery_notification' );
function display_delivery_notification() {
    if( is_mixed_stock_items() ){
        $message = __("Some items in cart are in stock and some others out of stock -> Show notification ON!");
        wc_print_notice( $message, 'notice');
    }
}

Code goes in function.php file of your active child theme (or active theme). Tested and works.

You can use the conditional function that check cart items stock in different hooks if needed

Related: Get in WooCommerce cart the product ID of a cart item

A: Although the solution from @LoicTheAztec works perfect and is coded really clearly, well and elegant I came up with my own solution as well. I will post it here too, just to show two different approaches to the problem.
add_action( 'woocommerce_after_cart_contents', 'split_devliery_notification' );
function split_devliery_notification() {
$all_items_in_stock = true; // initializing a true statement at beginning to be proved
$all_items_out_of_stock = true;

// Iterating through cart items (to get the stock info)
foreach (WC()->cart->get_cart() as $cart_item) {

    # HANDLING SIMPLE AND VARIABLE PRODUCTS

    // Variable products
    $variation_id = $cart_item['variation_id'];
    if( 0 != $variation_id) {
        $variation_obj = new WC_Product_variation($variation_id);
        $stock = $variation_obj->get_stock_quantity();
    } else {
        // Simple products
        $product_id = $cart_item['product_id'];
        $product_obj = new WC_Product($product_id);
        $stock = $product_obj->get_stock_quantity();
    }

    if ( $stock <= 0 ){
        // if an item is out of stock
        $all_items_in_stock = false;
        break; // We break the loop
    }
}
            // Continue with iterating if first iterating was stopped because one item has stock status below 0
            foreach (WC()->cart->get_cart() as $cart_item) {

                # HANDLING SIMPLE AND VARIABLE PRODUCTS

                // Variable products
                $variation_id = $cart_item['variation_id'];
                if( 0 != $variation_id) {
                    $variation_obj = new WC_Product_variation($variation_id);
                    $stock = $variation_obj->get_stock_quantity();
                } else {
                    // Simple products
                    $product_id = $cart_item['product_id'];
                    $product_obj = new WC_Product($product_id);
                    $stock = $product_obj->get_stock_quantity();
                }
                // check if stock status is 0 or above. If not it is proven that there are both types in cart
                if ( $stock >= 0 ) {
                    $all_items_out_of_stock = false;
                    break;
                }
            }

// All items "in stock"
if( $all_items_in_stock ) {
// commented out to prevent displaying a message in that case
//        echo 'All items in cart are in stock';
}
elseif ( $all_items_out_of_stock ) {
// commented out to prevent displaying a message in that case
//        echo 'All items in cart are out of stock';
}
else {
    ?>

                Delivery notification ON.

    <?php
     }

}

this goes in functions.php


text:
Q: Making API calls from a unit test in React? I am writing unit tests for my components using enzyme, mocha, chai, and sinon. In my components I import a library that constructs an API call with jQuery and use it in my component like so:
CategoryTree
_getCategoriesFromServer() {
        const _this = this;
        sdk.getJSON(_this.props.sdkPath, {
            itemsperpage: 10000
        }).done(function(data) {
            _this.setState({
                isLoaded: true,
                categories: _this.state.categories.concat(data)
            });
        }).fail(error => {
            console.log('ERROR', error);
        });
    }

Im calling this method in componentDidMount. The issue im having is with the testing. I am using Istanbul for test coverage, and I noticed that no matter what I do, the AJAX call is unsuccessful. Here is one of the tests:
it('should call componentDidMount', () => {
            sinon.spy(CategoryTree.prototype, 'componentDidMount');
            wrapper = mount(<CategoryTree {...props} />);
            expect(CategoryTree.prototype.componentDidMount.calledOnce).to.be.true;
            console.log(wrapper.props());
            console.log(wrapper.state());
            console.log(wrapper.debug());
        });

When this test runs it returns this error in the terminal:
ERROR { readyState: 0,
  getResponseHeader: [Function: getResponseHeader],
  getAllResponseHeaders: [Function: getAllResponseHeaders],
  setRequestHeader: [Function: setRequestHeader],
  overrideMimeType: [Function: overrideMimeType],
  statusCode: [Function: statusCode],
  abort: [Function: abort],
  state: [Function: state],
  always: [Function: always],
  then: [Function: then],
  promise: [Function: promise],
  pipe: [Function: then],
  done: [Function: add],
  fail: [Function: add],
  progress: [Function: add],
  complete: [Function: add],
  success: [Function: add],
  error: [Function: add],
  responseJSON: undefined,
  status: 0,
  statusText: 'error' }

The call works as expected in the application, just not in the test. Is there a reason for this?
EDIT: Forgot to mention that the _getCategoriesFromServer method is in the CategoryTree component.


text:
Q: Is there a state machine framework which implements UML semantics for the D programming language? Is there a state machine framework in the D programming language which implements UML semantics similar to boost.MSM, boost.statecharts, QP or Machine Objects ?

A: Ragel says it has a D backend.


text:
Q: UIScrollView - detecting scrolling vs orientation change in layoutSubviews? Question - In the "layoutSubviews" callback of a custom UIScrollView how could one detect the different of scrolling (which may not require subview re-layout) with other events such as an orientation change (which does require re-layout)?
Background - I want to add/remove subviews programmatically as scrolling occurs but in this case the existing views on the scrollview don't need re-layout, so I don't want to go through all these calculations.  However when an event such as orientation-change occurs I do want to recalc all positions.  So my question is aimed at finding the best approach to handle this.  In this case I do not want to use UIContainerView by the way.

A: let priorLayoutSize = CGSize.zero

func layoutSubviews() {
    super.layoutSubviews()

    let layoutSize = bounds.size
    if layoutSize != priorLayoutSize {
        priorLayoutSize = layoutSize
        // do full layout
    } else {
        // do incremental layout
    }
}


text:
Q: 502 Bad Gateway Internal Server error I'm trying to send notification's using FCM & serverless framework, making an HTTP POST request using API Gateway of AWS. The notification to the respective users are getting delivered but receiving below response from AWS with status code 502-Bad Gateway
{
    "message": "Internal server error"
}

Here is the code for the aws lambda function
'use strict';

const _ = require('lodash');
const bodyParser = require('body-parser');

const {sendFCMmany, sendFCMone} = require('./tools/sendFCM');
const {sliceData} = require('./tools/splitData');
const students = require('./tools/students');

module.exports.sendNotification = (event, context, callback) => {

    var reqBody = JSON.parse(event.body);

    var catag = 'announcement';

    // For Class
    if(reqBody.class_id != "" && reqBody.subclass_id == ""){
        var type = 'class';
        sendStudent(reqBody,type,catag);
    }

    // For Section
    if(reqBody.class_id != "" && reqBody.subclass_id != ""){
        var type = 'section';
        sendStudent(reqBody,type,catag);
    }

    // For Institute
    if(reqBody.class_id == "" && reqBody.subclass_id == ""){
        var type = 'Institute';
        sendStudent(reqBody,type,catag);
    }

  const response = {
    statusCode: 200,
    isBase64Encoded: false,
    headers: {
        "Content-Type": "*/*"
    },
    body: JSON.stringify({
      message: 'Announcement Sent'
    }),
  };

  //console.log(response);

  callback(null, response);

  // Use this code if you don't use the http event with the LAMBDA-PROXY integration
  //callback(null, { message: 'Go Serverless v1.0! Your function executed successfully!', event });
};

//-------------------------------------------- HELPER FUNCTIONS -------------------------------------------------

function sendStudent(body,type,catag) {

    students.getStudents(body,type,catag,(err,student) => {
        if(err){
           console.log(err);
        }
        else {

            var slicedFCM = sliceData(student,950);

            _.forEach(slicedFCM, function(value) {
                sendFCMmany(value,body,catag);
            });
        }
    });
}

Actually I'm not able to track the reason for "Internal Server error" how to rectify the same?


text:
Q: CakePHP behavior not working with bindModel I have a model named Users defined as:
class User extends AppModel {

...

public $actsAs = array(
    'Date' => array('date_birth')
);

...

The Date behavior converts the field date_birth from iso format ('yyyy-mm-dd') to locale format ('dd/mm/yyyy').
When from my controller I do a find such as
$this->User->find(...)

the behavior works fine and the field date_birth is formatted as dd/mm/yyyy.
Now, this is my problem:
I have a second model called Reviews.
In my controller I use the bindModel method to create the following relationship between the two models:
Review belongsTo User
When I do $this->Review->find() the User info are fetched along with the Review info. But the behavior defined in the User model is not applied and the field date_birth is formatted as yyyy-mm-dd.
Is there a reason for this?

A: For anyone interested, I solved the problem by changing the code in the Behavior so to accept fields of the form User.date_birth


text:
Q: Center align owner drawn checkbox in winform I have explored CheckBoxRenderer.DrawCheckBox method as well as DrawFrameControl method.
But could not find any way to replicate
CheckAlign = ContentAlignment.MiddleCenter.
Please suggest me how can I achieve the same.
Regards,
Anirban


text:
Q: 2 torsion part of real elliptic curve. Let $E$ be a real elliptic curve defined by $y^2+a_1xy+a_3y=f(x)$ where $f$ is a polynomial of degree 3 s.t. $E$ is non-singular with the point at infinite added.
(7.1) Assertion: An abelian, connected, compact Lie group is isomorphic to a product of $S^1$. The number of factors is equal to dimension of locally euclidean space.
There are 2 cases. $f(x)$ contains 1 real root and $f(x)$ contains $3$ real roots.
I do not understand the argument of $3$ real roots.
If $f$ has 3 real roots, then $E$ has 2 components. Then $E\cong S^1\times Z_2$.
$\textbf{Q:}$ How do I see $Z_2$ part of $E$ here? Where does $Z_2$ part entering the picture? I knew there is 2 torsion part for $E(Q)$. This had better be maintained by $E(Q)\subset E(R)$.
Ref: Elliptic Curves by Dale Husemoller Chapter on Introduction to Rational Points on Plane Curves, Sec 7.


text:
Q: java.security.KeyStoreException: Cannot store non-PrivateKeys I have generated a keypair of Public-private keys, and am trying to store the privatekey in Java keyStore.
But I am getting error everytime.
My piece of code:
            KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
            keyGen.initialize(2048);
            KeyPair pair = keyGen.generateKeyPair();
            PrivateKey privateKey = pair.getPrivate();
            PublicKey publicKey = pair.getPublic();
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.ENCRYPT_MODE, publicKey);
            String ss = Base64.encodeBase64String(cipher.doFinal(ppp.getBytes("UTF-8")));
            System.out.println(ss);

            // Creating the KeyStore object
            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());

            // Loading the KeyStore object
            char[] ksPassword = "changeit".toCharArray();
            String path = "C:/Program Files/Java/jre1.8.0_201/lib/security/cacerts";
            java.io.FileInputStream fis = new FileInputStream(path);
            keyStore.load(fis, ksPassword);

            // Creating the KeyStore.ProtectionParameter object
            KeyStore.ProtectionParameter protectionParam = new
            KeyStore.PasswordProtection(ksPassword);

            // Creating SecretKey object
            SecretKey mySecretKey = new SecretKeySpec(ppp.getBytes(), "RSA");

            // Creating SecretKeyEntry object
            KeyStore.SecretKeyEntry secretKeyEntry = new KeyStore.SecretKeyEntry(mySecretKey);
            keyStore.setEntry("mykeyalias", secretKeyEntry, protectionParam);

            // Storing the KeyStore object
            java.io.FileOutputStream fos = null;
            fos = new java.io.FileOutputStream("newKeyStoreName");
            keyStore.store(fos, ksPassword);

But i'm getting below exception at the line keyStore.setEntry while running:
java.security.KeyStoreException: Cannot store non-PrivateKeys
    at sun.security.provider.JavaKeyStore.engineSetKeyEntry(JavaKeyStore.java:261)
    at sun.security.provider.JavaKeyStore$JKS.engineSetKeyEntry(JavaKeyStore.java:56)
    at java.security.KeyStoreSpi.engineSetEntry(KeyStoreSpi.java:550)
    at sun.security.provider.KeyStoreDelegator.engineSetEntry(KeyStoreDelegator.java:179)
    at sun.security.provider.JavaKeyStore$DualFormatJKS.engineSetEntry(JavaKeyStore.java:70)
    at java.security.KeyStore.setEntry(KeyStore.java:1557)
    at com.sprint.neo.bc4j.util.TestMain.StoringKeys(TestMain.java:33)

Can anyone help to resolve this issue so that I can store Privatekeys to the java keyStore along with an alias name, to be used later. Where is the exact wrong in the above piece of code. Thanks a lot.


text:
Q: How can I show a "tr" tags content when I click a button? I am creating a chrome app and I need part of a table to show up when I click a button.
I have looked at various and answers but I keep getting an error from chrom when I click the button/
Here is my JavaScript:
    document.getElementById("newpull").style.visibility = "visible";
}
);
window.onload = function () {
        document.getElementById("newpull").style.visibility = "hidden";
};

And my HTML:
 <button id="click" style="float; left">Click</button>

A: display block and none on button click

function myFunc() {
  var disp = document.getElementById("newpull").style.display;
  console.log(disp);
  if (disp == 'block') {
    document.getElementById("newpull").style.display = 'none'
  } else {
    document.getElementById("newpull").style.display = 'block'
  }
}
<button id="click" style="float; left" onclick="myFunc()">Click</button>

    abc
    abc
    abc
    abc
    abc

A: just put function in script and fire from button click using put this onclick="showTR()" in <button>
<button id="click" style="float: left" onclick="showTR()">Click</button>

        1
        2
        3
        4
        5

this is your script

function showTR(){
   document.getElementById("newpull").style.visibility = "visible";
}
window.onload = function () {
   document.getElementById("newpull").style.visibility = "hidden";
};

OR you can also use like this

function showTR(){
var status = document.getElementById("newpull").style.visibility ;
  if (status == 'visible') {
     document.getElementById("newpull").style.visibility = "hidden";
  } else {
     document.getElementById("newpull").style.visibility = "visible";
  }
}
window.onload = function () {
   document.getElementById("newpull").style.visibility = "hidden";
};


text:
Q: Android TabLayout Indicator drawable color is not visible also unable to add custom width I want to use custom drawable for TabLayout indicator like this

but it is not showing the colors

also unable to add custom width. As you can see that design has width that is not more than width of text, how I could to do that?
 <com.google.android.material.tabs.TabLayout
                        android:id="@+id/slidingTabs"
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_gravity="top"
                        app:layout_constraintTop_toTopOf="parent"
                        app:tabIndicator="@drawable/lines"
                        app:tabIndicatorHeight="6dp"
                        app:tabIndicatorFullWidth="false"
                        app:tabMode="fixed"
                        app:tabSelectedTextColor="#000"
                        app:tabTextAppearance="@style/CustomTextAppearanceTab"
                        app:tabTextColor="@color/bluey_grey" />

I've tried with both SVG and PNG
Thanks

A: The default style applies a tint to the tabIndicator.
You can add in your layout (or in your style) the tabIndicatorColor.
    <com.google.android.material.tabs.TabLayout
        app:tabIndicatorColor="@color/..."
        ..>

You can use a color or you can use "@null" (it depends by your original drawable).
About the tab width you can use the app:tabMinWidth attribute.
    <com.google.android.material.tabs.TabLayout
        app:tabIndicatorFullWidth="true"
        app:tabMinWidth="125dp"
        ..>


text:
Q: Add a legend in the middle of a circular Gauge chart with Extjs I've drawn a circular gauge using extjs chart series. I would like to indicate the value of the gauge into the middle of it but I don't succeed. Does anyone could help me?
Here is the code I tried:
{
    xtype: 'polar',
    width: 60,
    height: 60,
    background: '#00c6c9',
    style: {left:0, right:0},
    series: {
            type: 'gauge',
            minimum: 0,
            maximum: 30,
            value: 10,
            colors: ['#25a2b6', 'lightgrey'],
            donut: 75,
            background: '#00c6c9',
            totalAngle: Math.PI * 2,
            style: {left:0, right:0},
            needleLength: 100
            /*,
            renderer: function(sprite, record, attributes, index, store) {
                var sprite2 = Ext.create('Ext.draw.Sprite', {
                type: 'text',
                text: Math.floor(attributes.value),
                font: '16px Arial',
                x: 30,
                y: 30
                });
                sprite2.show(true);
                return attributes;
            },
            label: {
                field: 'value',
                display: 'middle'
            }*/
    }
}

I just want to show the value '10' of the series. In comments you can see I tried to add a renderer function and a label property. In this label, I guess I cannot write "field:'value'" but since I don't need to define a field I don't konw what to use.
Many thanks

A: Here is the solution, you can change your sprite on render function of chart, and then redraw it, changing x,y,value and other things
Ext.create({
    xtype: 'polar',
    renderTo: document.body,
    width: 160,
    height: 160,
    background: '#00c6c9',
    style: {
        left: 0,
        right: 0
    },
    listeners:{
        render: function(chart){
            var sprite=Ext.clone(chart.getSprites()[0]);
            //modify sprite here
            sprite.text=''+chart.getSeries()[0].config.value;
            chart.setSprites(sprite);
            chart.redraw();
        }
    },
    sprites: [{
        type: 'text',
        x: 58,
        y: 95,
        text: 'test',
        fontSize: 40,
        fillStyle: 'white'
    }],
    series: {
        type: 'gauge',
        minimum: 0,
        maximum: 30,
        value: 10,
        colors: ['#25a2b6', 'lightgrey'],
        donut: 75,
        background: '#00c6c9',
        totalAngle: Math.PI * 2,
        style: {
            left: 0,
            right: 0
        },
        needleLength: 100
    }

    });


text:
Q: Including all terms in wordpress tax_query I'm a little bit confused, why I can't include all the terms in tax_query automatically?
My code:
'tax_query' => array(
    array(
        'taxonomy' => 'city',
        'field' => 'slug',
        'terms' => array( nyc, boston, london ),
         )
)

What If I've dozens of cities? Isn't it uncool to add them all manually?

A: In addition to the marked 'best answer', there is another way which might be even faster because we don't have to pull the terms and extract the names first.
This is achieved with a trick by using a non-existing operator (none of 'IN', 'NOT IN', 'AND', 'EXISTS' and 'NOT EXISTS'). For example, the string 'XXX' does the job and causes WP to not enter the cases during the query generation and therefore also the 0=1 concatenation is skipped.
(The cases are located in the function get_sql_for_clause() of the file class-wp-tax-query.php, where the allowed operators are checked via conditions and there is no 'else'.)
.
$args = array ('tax_query' =>
     array(
         array(
              'taxonomy' => 'city',
              //'field' => 'term_id', // <-- not needed, default
              //'terms' => $term_ids, // <-- not needed
              'operator' => 'XXX'     // Use a non-existing operator
         )
     )
);

A: Unless you have posts that don't have a city aren't you essentially querying all your posts? Anyway, Eric Holmes is correct that you should be using WP_Query in lieu of query_posts().
That said, you can get a list of all the terms in a taxonomy and then use those values in your tax query.
// get all terms in the taxonomy
$terms = get_terms( 'city' );
// convert array of term objects to array of term IDs
$term_ids = wp_list_pluck( $terms, 'term_id' );

// proceed with tax query
$args = array ('tax_query' => array(
    array(
        'taxonomy' => 'city',
        'field' => 'term_id',
        'terms' => $term_ids,
         )
)
);

$city_posts = new WP_Query( $args );

A: Firstly, don't use query_posts. Create a new WP_Query object instead.
Secondly, why would you need to add all the categories, if you are literally adding ALL categories? Would this not be the same as getting all posts? You can also specify which to NOT include. ie. "Everything but Chicago".


text:
Q: Using an \index format which changes based on section of the document I am copying a long book with musical pieces throughout, set with gregorio tex.  Each musical piece has a \label and is entered in one of several indexes created using imakeidx.
The document has multiple formats of page numbers: roman, arabic, and then several other notations, e.g. [3], 7*, and <<22>>, based on different divisions of the overall document.  Each section starts with a value of 1, but formatted differently.
I'd like \label/\pageref and \index to function seamlessly to give the right page with the right format based on the location of the chant.
I have previously posted about this problem here:  More than two page formats for \label / \ref and \index with imakeidx
I was given the tip by David Carlisle that I can use \index{item|foo} to apply a format to the index page using a function \foo that I define.  This is definitely on the way to solving the problem.
The problem is that there is basically one \index statement in the program - buried in a function \dostuff called by the gregorio tex package when a musical piece is loaded.
So I have an existing function
\newcommand{dostuff}{......
...
\index{item|foo}
...
}

I'd like to change the format of the index by redefining \foo at the start of each section in the document where the page number format changes, such as
% Switch to star pages now....
\renewcommand{\foo}[1]{#1*}

Instead, when I do this, the index only uses the most recent definition of foo at the time the \printindex executes, so every page number gets displayed in the same format, in this case, e.g. [7].
Is there a way to fix the definition of \foo or the \index command to get the page reference to get written to the index file at the time the index statement is given, so to use the 'current' definition of \foo and thus make sure the right format is applied?
I could redefine all of the macro \dostuff at the start of each document division, but it is a long macro and that would be a pain. If it is possible, just changing \foo would be a lot simpler, since that's all that changes.

A: This question was a follow-on question, as noted in the post.  The answer was posted in the original question thread, linked in the top post here, but I repeat it for completeness.
The above solution in the comments thanks to David Carlisle solves the problem.  In my function, I define
\bigfunction{
...
\index{item|foo}
...
}

where foo is defined, e.g.
\newcommand{foo}[1]{#1*}

to get starred page numbers, and similarly for other formats.
I have to then redefine the function \bigfunction at the beginning of each section to get different versions of foo for each section.


text:
Q: Spark - Convert Tuples to Tab Seperated String I want to create a function that takes an RDD of tuples and converts each tuple to a tab separated string.  I want the function to be able to handle Tuples of any size.
If I already have this RDD created, I can get the desired output using:
rdd.map(line => (0 to (line.productArity-1)).map(line.productElement(_)).toList.mkString("\t"))

How can I convert this piece of code to work as a function that takes an RDD of tuples, or is there a good library that already does this?

A: Something like this should work:
def toTab[T <: Product](rdd:RDD[T]) = rdd.map(_.productIterator.mkString("\t"))


text:
Q: Atualizar APN's por VAB Bom dia,
sou jr na empresa e recebi a tarefa de tentar identificar onde faço a alteração do BD no código AOSP para que quando o aparelho receber a atualização por VAB, as APN's sejam alteradas pelas novas. O local do arquivo xml para as novas APN's eu encontrei, fica em vendor/sprd/telephony-res/apn mas preciso que as APNS que estão salvas no BD sejam alteradas pelas novas, pois só alterando o xml elas não alteraram. A princípio me disseram que o BD tem que ser mudado para um novo mas honestamente não sei nem por onde começar, qual repositório faz isso.