text:
Q: Facebook iOS SDK - get friends list Using the Facebook iOS SDK, how can I get an NSArray of all my friends and send them an invitation to my app? I am specifically looking for the graph path to get all of the friends.

A: Maybe this could help
[FBRequestConnection startForMyFriendsWithCompletionHandler:
 ^(FBRequestConnection *connection, id<FBGraphUser> friends, NSError *error)
  {
     if(!error){
       NSLog(@"results = %@", friends);
     }
  }
];

A: With Facebook SDK 3.0 you can do this:
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
                                  NSDictionary* result,
                                  NSError *error) {
    NSArray* friends = [result objectForKey:@"data"];
    NSLog(@"Found: %lu friends", (unsigned long)friends.count);
    for (NSDictionary<FBGraphUser>* friend in friends) {
        NSLog(@"I have a friend named %@ with id %@", friend.name, friend.objectID);
    }
}];

A: Use the function below to asynchronously fetch user's friends stored in an NSArray:
- (void)fetchFriends:(void(^)(NSArray *friends))callback
{
    [FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection, id response, NSError *error) {
        NSMutableArray *friends = [NSMutableArray new];
        if (!error) {
            [friends addObjectsFromArray:(NSArray*)[response data]];
        }
        callback(friends);
    }];
}

In your code, you can use it as such:
[self fetchFriends:^(NSArray *friends) {
    NSLog(@"%@", friends);
}];

A: // declare an array in header file which will hold the list of all friends -
NSMutableArray * m_allFriends;
// alloc and initialize the array only once
m_allFriends = [[NSMutableArray alloc] init];
With FB SDK 3.0 and API Version above 2.0 you need to call below function (graph api with me/friends)to get list of FB Friends which uses the same app.
// get friends which use the app
-(void) getMineFriends
{
    [FBRequestConnection startWithGraphPath:@"me/friends"
                                 parameters:nil
                                 HTTPMethod:@"GET"
                          completionHandler:^(
                                              FBRequestConnection *connection,
                                              id result,
                                              NSError *error
                                              ) {
                              NSLog(@"me/friends result=%@",result);

                              NSLog(@"me/friends error = %@", error.description);

                              NSArray *friendList = [result objectForKey:@"data"];

                              [m_allFriends addObjectsFromArray: friendList];
                          }];
}

Note : 1) The default limit for the number of friends returned by above query is 25.
2)If the next link comes in result, that means there are some more friends which you will be fetching in next query and so on.
3)Alternatively you can change the limit (reduce the limit, exceed the limit from 25) and pass that in param.
////////////////////////////////////////////////////////////////////////
For non app friends -
// m_invitableFriends - global array which will hold the list of invitable friends
Also to get non app friends you need to use (/me/invitable_friends) as below -
- (void) getAllInvitableFriends
{
    NSMutableArray *tempFriendsList =  [[NSMutableArray alloc] init];
    NSDictionary *limitParam = [NSDictionary dictionaryWithObjectsAndKeys:@"100", @"limit", nil];
    [self getAllInvitableFriendsFromFB:limitParam addInList:tempFriendsList];
}

- (void) getAllInvitableFriendsFromFB:(NSDictionary*)parameters
                            addInList:(NSMutableArray *)tempFriendsList
{
    [FBRequestConnection startWithGraphPath:@"/me/invitable_friends"
                                 parameters:parameters
                                 HTTPMethod:@"GET"
                          completionHandler:^(
                                              FBRequestConnection *connection,
                                              id result,
                                              NSError *error
                                              ) {
                              NSLog(@"error=%@",error);

                              NSLog(@"result=%@",result);

                              NSArray *friendArray = [result objectForKey:@"data"];

                              [tempFriendsList addObjectsFromArray:friendArray];

                              NSDictionary *paging = [result objectForKey:@"paging"];
                              NSString *next = nil;
                              next = [paging objectForKey:@"next"];
                              if(next != nil)
                              {
                                  NSDictionary *cursor = [paging objectForKey:@"cursors"];
                                  NSString *after = [cursor objectForKey:@"after"];
                                  //NSString *before = [cursor objectForKey:@"before"];
                                  NSDictionary *limitParam = [NSDictionary dictionaryWithObjectsAndKeys:
                                                              @"100", @"limit", after, @"after"
                                                              , nil
                                                              ];
                                  [self getAllInvitableFriendsFromFB:limitParam addInList:tempFriendsList];
                              }
                              else
                              {
                                  [self replaceGlobalListWithRecentData:tempFriendsList];
                              }
                          }];
}

- (void) replaceGlobalListWithRecentData:(NSMutableArray *)tempFriendsList
{
    // replace global from received list
    [m_invitableFriends removeAllObjects];
    [m_invitableFriends addObjectsFromArray:tempFriendsList];
    //NSLog(@"friendsList = %d", [m_invitableFriends count]);
    [tempFriendsList release];
}

A: Here is a more complete solution:
In your header file:
@interface myDelegate : NSObject <UIApplicationDelegate, FBSessionDelegate, FBRequestDelegate> {
    Facebook *facebook;
    UIWindow *window;
    UINavigationController *navigationController;

    NSArray *items; // to get facebook friends
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) Facebook *facebook;
@property (nonatomic, retain) NSArray *items;
@end

Then in your implementation:
@implementation myDelegate

@synthesize window;
@synthesize navigationController;
@synthesize facebook;
@synthesize items;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

...

    facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID_FROM_FACEBOOK" andDelegate:self];

    [facebook requestWithGraphPath:@"me/friends" andDelegate:self];

    return YES;
}

Then you need at least the following delegate protocol method:
- (void)request:(FBRequest *)request didLoad:(id)result {
    //ok so it's a dictionary with one element (key="data"), which is an array of dictionaries, each with "name" and "id" keys
    items = [[(NSDictionary *)result objectForKey:@"data"]retain];
    for (int i=0; i<[items count]; i++) {
        NSDictionary *friend = [items objectAtIndex:i];
        long long fbid = [[friend objectForKey:@"id"]longLongValue];
        NSString *name = [friend objectForKey:@"name"];
        NSLog(@"id: %lld - Name: %@", fbid, name);
    }
}

A: To get list of friends you can use
https://graph.facebook.com/me/friends
[facebook requestWithGraphPath:@"me/friends"
                     andParams:nil
                   andDelegate:self];

To know more about all the possible API please read
https://developers.facebook.com/docs/reference/api/

A: With facebook SDK 3.2 or above we have a facility of FBWebDialogs class that opens a view which already contains the friend(s) list. Pick the friends and send invitations to all of them. No need to use any additional API calls.
Here i have briefly described the resolution step-by-step.

A: (void)getFriendsListWithCompleteBlock:(void (^)(NSArray *, NSString *))completed{

if (!FBSession.activeSession.isOpen)
{
    NSLog(@"permissions::%@",FBSession.activeSession.permissions);

    // if the session is closed, then we open it here, and establish a handler for state changes
    [FBSession openActiveSessionWithReadPermissions:@[@"basic_info", @"user_friends"]
                                       allowLoginUI:YES
                                  completionHandler:^(FBSession *session,
                                                      FBSessionState state,
                                                      NSError *error) {
                                      if (error)
                                      {
                                          UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                message:error.localizedDescription
                                                                                delegate:nil
                                                                                cancelButtonTitle:@"OK"
                                                                                otherButtonTitles:nil];
                                          [alertView show];
                                      }
                                      else if (session.isOpen)
                                      {
                                          [self showWithStatus:@""];
                                          FBRequest *friendRequest = [FBRequest requestForGraphPath:@"me/friends?fields=name,picture,gender"];

                                              [friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                                  NSArray *data = [result objectForKey:@"data"];
                                                  NSMutableArray *friendsList = [[NSMutableArray alloc] init];
                                                  for (FBGraphObject<FBGraphUser> *friend in data)
                                                  {
                                                      //NSLog(@"friend:%@", friend);
                                                      NSDictionary *picture = [friend objectForKey:@"picture"];
                                                      NSDictionary *pictureData = [picture objectForKey:@"data"];
                                                      //NSLog(@"picture:%@", picture);
                                                      FBData *fb = [[FBData alloc]
                                                                    initWithData:(NSString*)[friend objectForKey:@"name"]
                                                                    userID:(NSInteger)[[friend objectForKey:@"id"] integerValue]
                                                                    gender:(NSString*)[friend objectForKey:@"gender"]
                                                                    photoURL:(NSString*)[pictureData objectForKey:@"url"]
                                                                    photo:(UIImage*)nil
                                                                    isPhotoDownloaded:(BOOL)NO];
                                                      [friendsList addObject:fb];
                                                  }

                                                  [self dismissStatus];
                                                  if (completed) {
                                                      completed(friendsList,@"I got it");
                                                  }
                                              }];

                                      }
                                  }];
    }
}

A: Here is a Swift Version.
var friendsRequest : FBRequest = FBRequest.requestForMyFriends()
friendsRequest.startWithCompletionHandler{(connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
    let resultdict = result as NSDictionary
    let friends : NSArray = resultdict.objectForKey("data") as NSArray

    println("Found: \(friends.count) friends")
    for friend in friends {
        let id = friend.objectForKey("id") as String
        println("I have a friend named \(friend.name) with id " + id)
    }
}

A: For Inviting non app friend -
you will get invite tokens with the list of friends returned by me/invitable_friends graph api. You can use these invite tokens with FBWebDialogs to send invite to friends as below
- (void) openFacebookFeedDialogForFriend:(NSString *)userInviteTokens {

    NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
                                   userInviteTokens, @"to",
                                   nil, @"object_id",
                                   @"send", @"action_type",
                                   actionLinksStr, @"actions",
                                   nil];

    [FBWebDialogs
     presentRequestsDialogModallyWithSession:nil
     message:@"Hi friend, I am playing game. Come and play this awesome game with me."
     title:nil
     parameters:params
     handler:^(
               FBWebDialogResult result,
               NSURL *url,
               NSError *error)
     {
         if (error) {
             // Error launching the dialog or sending the request.
             NSLog(@"Error sending request : %@", error.description);
         }
         else
         {
             if (result == FBWebDialogResultDialogNotCompleted)
             {
                 // User clicked the "x" icon
                 NSLog(@"User canceled request.");
                 NSLog(@"Friend post dialog not complete, error: %@", error.description);
             }
             else
             {
                 NSDictionary *resultParams = [g_mainApp->m_appDelegate parseURLParams:[url query]];

                 if (![resultParams valueForKey:@"request"])
                 {
                     // User clicked the Cancel button
                     NSLog(@"User canceled request.");
                 }
                 else
                 {
                     NSString *requestID = [resultParams valueForKey:@"request"];

                     // here you will get the fb id of the friend you invited,
                     // you can use this id to reward the sender when receiver accepts the request

                     NSLog(@"Feed post ID: %@", requestID);
                     NSLog(@"Friend post dialog complete: %@", url);
                 }
             }
         }
     }];
}

A: -(void)getFBFriends{

    NSDictionary *queryParam =
    [NSDictionary dictionaryWithObjectsAndKeys:@"SELECT uid, sex,name,hometown_location,birthday, pic_square,pic_big FROM user WHERE uid = me()"
     @"OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())", @"q", nil];
    // Make the API request that uses FQL
    [FBRequestConnection startWithGraphPath:@"/fql"
                                 parameters:queryParam
                                 HTTPMethod:@"GET"
                          completionHandler:^(FBRequestConnection *connection,
                                              id result,
                                              NSError *error) {
                              if (error) {
                                  NSLog(@"Error: %@", [error localizedDescription]);
                              } else {
                                  NSDictionary *data=result;
                                  //NSLog(@"the returned data of user is %@",data);
                                  NSArray *dataArray=[data objectForKey:@"data"];
                                //dataArray contains first user as self user and your friend list

                              }
                          }];
}


text:
Q: django dev server unread POST data will error I have the solution, this is more of a Why question.  The problem is when running a django dev server, when i make an ajax POST request with data, if the view never looks at the POST dict, i get a urllib2 exception.  "a connection was forcibly closed by a remote host" or something.
If theres no post data, it returns fine, if the data is read, not even stored, a simple
request.POST
will return ok as well.  Why is this?
Thanks

A: I'm guessing you're not sending the csrfmiddleware_token on your post request. It's a prevention mechanism for CSRF attacks and needs to be set on all POST messages. See the documentation for details.

A: You need to disable CSRF protection for that view function as it is enabled by default (the CSRF Middleware).
You can opt to disable CSRF protection via two ways:

*

*Remove the CSRF middleware and use the @csrf_protect decorator on
view functions that you wish to use the CSRF protection. Use this if you generally don't
need CSRF (eg. no forms for most of the pages). See https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#the-decorator-method

*Use the @csrf_exempt decorator on the view you wish to exempt the CSRF protection from.
This is useful when you only have a few view functions that does not require CSRF
protection. See https://docs.djangoproject.com/en/1.3/ref/contrib/csrf/#exceptions

redpajama_set_name: RedPajamaStackExchange


text:
Q: reload tableView in last method run I have method that get notification as I download one image. I can download a lot of objects and I want to update tableView then I have last notification of downloaded image. How the best way to accomplish it?
- (void)requestDownloadAvatarWithImageString:(NSString *)imageString completion:(void (^)(AFHTTPRequestOperation *operation, UIImage *image, NSError *error))completion __attribute__((nonnull(2)))
{
NSParameterAssert(completion);

NSString *urlString = imageString;
NSURL *url = [NSURL URLWithString:urlString];
NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];

AFHTTPRequestOperation *requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:urlRequest];
requestOperation.responseSerializer = [AFImageResponseSerializer serializer];

[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    completion(operation, responseObject, nil);

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    DDLogError(@"FAIL download image: %@",error);
}];

[requestOperation start];
}

A: dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

dispatch_semaphore_t semaphore = dispatch_semaphore_create(NUMBER_OF_RETURNED_OBJECTS);
dispatch_async(queue, ^{
    for (i = 0; i<NUMBER_OF_RETURNED_OBJECTS; i++)
    {
        dispatch_async(queue, ^{

            fetchObject(i); // it's specific to your application

            dispatch_semaphore_signal(semaphore);
        }
    }
    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
}

[your_table_view reloadData];

or simply get all image paths in an array then download them with SDWebImage
- (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{

UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:MyIdentifier];

NSString *url = [NSString stringWithString, imageArray[indexPath.row]];

[cell.cell_image setImageWithURL:[NSURL URLWithString: url] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

}


text:
Q: numpy iterate over two 2d arrays Say I have two matrices:
X, Y = np.meshgrid(np.arange(0, 2, 0.1), np.arange(3, 5, 0.1))

And a function, something like:
def func(x) :
    return x[0]**2 + x[1]**2

How can I fill a matrix Z (of size np.shape(X)), where each entry is formed by calling func on the two corresponding values of X and Y, i.e.:
Z[i, j] = func([X[i, j], Y[i, j]])

Is there a way without using a double nested for-loop?

A: For given numpy arrays X and Y, you could just do -
Zout = X**2 + Y**2

If you are actually constructing X and Y like that, there is a direct way to get Z with broadcasting and thus avoid np.meshgrid, like so -
Zout = np.arange(0, 2, 0.1)**2 + np.arange(3, 5, 0.1)[:,None]**2

A: This is also works as a vectorized form of function evaluation:
import numpy as np
X, Y = np.meshgrid(np.arange(0, 2, 0.1), np.arange(3, 5, 0.1))
def func(x) :
    return x[0]**2 + x[1]**2

Z = func([X,Y])


text:
Q: Best approach for Laravel Cashier "top up" purchase flow I'm building a web application where users can purchase "SMS credits". Each credit can be used to send an SMS. So users will need to purchase credits which are then stored as a CreditTransaction entry with a delta column in my database, this way, each transaction can have a negative or positive delta value and the sum of all of these is the user's credit balance.
My initial approach here, is to have a Laravel job called ProcessCreditTransaction which is triggered on the checkout, I believe this is fine for customers that enter my try block, but for customers that enter the catch, and where additional payment action is required, how can I only trigger my Job if successful?
Right now, for example, if the $e->payment->requiresPaymentMethod() block is triggered, then so is my job to add credits to their account, but if they didn't complete the purchase, then they've now got a positive amount of credits in their account?
How's best to handle this, here's my current checkout purchase flow:
The TODO comments are the parts I need some advice on.
// attempt to charge
try {
    $productPrice = Cashier::stripe()->prices->retrieve($productOption->stripe_id);

    // get user
    $user = Auth::user();

    // get customer
    if (Cashier::findBillable($user->stripe_id)) {
        $user->invoicePrice($productOption->stripe_id);
    } else {
        $user->createOrGetStripeCustomer();
        $user->updateDefaultPaymentMethod($request->input('token'));
        $user->invoicePrice($productOption->stripe_id);
    }

    // update region of API key
    if (!$apiKey->region_code) {
        $apiKey->region_code = $request->input('region');
        $apiKey->save();
    }

    // apply balance
    ProcessCreditTransaction::dispatch(
        Carbon::now(), $user->id, $apiKey->uuid, $productOption->quantity
    )->onQueue('on-demand-runs-now');

    return response()->json([
        'complete' => true,
        'message' => "You've successfully topped-up credits for this API key. You'll soon be able to download the invoice for this item. You can now start sending messages using this API key to the SMS region you specified.",
        'redirectTo' => "$frontendUrl/account/billing/checkout/result/?success=true&id=".$productOption->id,
    ], 200);

} catch (IncompletePayment $e) {

    // if we require some action, perform it here
    if ($e->payment->requiresAction()) {

        // update region of API key
        if (!$apiKey->region_code) {
            $apiKey->region_code = $request->input('region');
            $apiKey->save();
        }

        // apply balance
        // TODO: we may need to move this part to an event
        ProcessCreditTransaction::dispatch(
            Carbon::now(), $user->id, $apiKey->uuid, $productOption->quantity
        )->onQueue('on-demand-runs-now');

        return response()->json([
            'message' => 'We require some payment action from you to complete this purchase, this usually means you need to open your banking app to approve this subscription.',
            'requiresAction' => true,
            'redirectTo' => route('cashier.payment', [
                $e->payment->id,
                'redirect' => "$frontendUrl/account/billing/checkout/result/?id=".$productOption->id,
            ]),
        ], 400);
    } elseif ($e->payment->requiresPaymentMethod()) {

        // update region of API key
        if (!$apiKey->region_code) {
            $apiKey->region_code = $request->input('region');
            $apiKey->save();
        }

        // apply balance
        // TODO: we may need to move this part to an event
        ProcessCreditTransaction::dispatch(
            Carbon::now(), $user->id, $apiKey->uuid, $productOption->quantity
        )->onQueue('on-demand-runs-now');

        return response()->json([
            'message' => "The payment method currently set up is invalid or has sufficient funds, we're going to redirect you to complete this transaction, please wait.",
            'requiresAction' => true,
            'redirectTo' => route('cashier.payment', [
                $e->payment->id,
                'redirect' => "$frontendUrl/account/billing/checkout/result/?id=".$productOption->id,
            ]),
        ], 400);
    } elseif ($e->payment->requiresConfirmation()) {

        // update region of API key
        if (!$apiKey->region_code) {
            $apiKey->region_code = $request->input('region');
            $apiKey->save();
        }

        // apply balance
        // TODO: we may need to move this part to an event
        ProcessCreditTransaction::dispatch(
            Carbon::now(), $user->id, $apiKey->uuid, $productOption->quantity
        )->onQueue('on-demand-runs-now');

        return response()->json([
            'message' => 'We jsut need you to confirm this payment.',
            'requiresAction' => true,
            'redirectTo' => route('cashier.payment', [
                $e->payment->id,
                'redirect' => "$frontendUrl/account/billing/checkout/result/?id=".$productOption->id,
            ]),
        ], 400);
    }

    // generic error
    return response()->json([
        'message' => "We wasn't able to complete this purchase. You haven't been charged. Please try again soon.",
        'requiresAction' => true,
        'redirectTo' => "$frontendUrl/account/billing/checkout/result/?success=false",
    ], 400);
}


text:
Q: scheme - Evaluate true or false list I have a true/false list (like this (#f #f #f #f #f #t)) and I want to loop through it, making an if statement and making appends.
But my map/if iterator does not work as I expected
I`m trying this:
(map (if (false? lst) "do this" "do that" ) lst)

In pseudo code I would have something like this
for each value in lst
  if value
    "do that"
  else
    "do this"

A: Remember that map receives as parameters a list and a function that operates on each element. Try this:
(map (lambda (e)
       (if (false? e)
           "do this"
           "do that"))
     lst)

For example, if we define lst as '(#f #f #f #f #f #t) the result is:
'("do this" "do this" "do this" "do this" "do this" "do that")


text:
Q: How to process json from Google Maps API From https://developers.google.com/maps/documentation/distancematrix/
If I enter:
http://maps.googleapis.com/maps/api/distancematrix/json?origins=Hickory+NC&destinations=Niagra+Falls+NY&sensor=false&units=imperial

Then I get:
{
   "destination_addresses" : [ "Niagara Falls, NY, USA" ],
   "origin_addresses" : [ "Hickory, NC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "667 mi",
                  "value" : 1072719
               },
               "duration" : {
                  "text" : "11 hours 21 mins",
                  "value" : 40835
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

But if I issue this command:
<cfhttp method="get" result="myContent" url="http://maps.googleapis.com/maps/api/distancematrix/json">
    <cfhttpparam type="url" name="origins" value="Hickory+NC">
    <cfhttpparam type="url" name="destinations" value="Niagra+Falls+NY">
    <cfhttpparam type="url" name="sensor" value="false">
    <cfhttpparam type="url" name="units" value="imperial">
</cfhttp>
<cfdump var="#myContent#">

Then I get back a structure with a StatusCode=200OK, but Text=NO.

A: Add  getAsBinary="never" to your cfhttp
<cfhttp method="get" result="myContent" url="http://maps.googleapis.com/maps/api/distancematrix/json" getAsBinary="never">
    <cfhttpparam type="url" name="origins" value="Hickory+NC">
    <cfhttpparam type="url" name="destinations" value="Niagra+Falls+NY">
    <cfhttpparam type="url" name="sensor" value="false">
    <cfhttpparam type="url" name="units" value="imperial">
</cfhttp>
<cfdump var="#myContent#">

Returns me this in the myContent.FileContent
 {
    "destination_addresses": ["Niagara Falls, NY, USA"],
    "origin_addresses": ["Hickory, NC, USA"],
    "rows": [{
        "elements": [{
            "distance": {
                "text": "667 mi",
                "value": 1072719
            },
            "duration": {
                "text": "11 hours 21 mins",
                "value": 40835
            },
            "status": "OK"
        }]
    }],
    "status": "OK"
}


text:
Q: Calculate the distance travelled by each inspector using lat, long of tracking data using groupby pandas I have a dataframe as shown below. Which is inspector tracking data (latitude and longitude) almost in each minute.
Inspector_ID   Timestamp               Latitude      Longitude
1              2018-07-24 7:31:00      100.491491    13.725239
1              2018-07-24 7:31:01      101.491491    15.725239
1              2018-07-24 7:32:04      104.491491    14.725239
1              2018-07-24 7:33:06      102.491491    10.725239
2              2018-07-24 8:35:08      105.491491    8.725239
2              2018-07-24 8:36:10      101.491491    15.725239
2              2018-07-24 8:37:09      101.491491    12.725239
2              2018-07-24 8:39:00      106.491491    16.725239

From the above data I would like find out the distance travelled by an inspector from each consecutive tracking data (latitude and longitude of the inspector).
Expected output (example)
Inspector_ID      Timestamp               Latitude      Longitude    Distance
    1              2018-07-24 7:31:00      100.491491    13.725239    nan
    1              2018-07-24 7:31:01      101.491491    15.725239    2.3
    1              2018-07-24 7:32:04      104.491491    14.725239    1.2
    1              2018-07-24 7:33:06      102.491491    10.725239    3.6
    2              2018-07-24 8:35:08      105.491491    8.725239     nan
    2              2018-07-24 8:36:10      101.491491    15.725239    5.6
    2              2018-07-24 8:37:09      101.491491    12.725239    2.1
    2              2018-07-24 8:39:00      106.491491    16.725239    3

Here I would like to calculate the distance groupby Inspector_ID.
Note: The number populated in Distance column are not the correct distance.
I am not aware, how to calculate distance using latitude and longitude. I am very new in pandas as well.

A: Use GroupBy.diff:
df['distance']=df.groupby('Inspector_ID')[['Latitude','Longitude']].diff().pow(2).sum(axis=1,min_count=1).pow(1/2)
print(df)

   Inspector_ID           Timestamp    Latitude  Longitude  distance
0             1 2018-07-24 07:31:00  100.491491  13.725239       NaN
1             1 2018-07-24 07:31:01  101.491491  15.725239  2.236068
2             1 2018-07-24 07:32:04  104.491491  14.725239  3.162278
3             1 2018-07-24 07:33:06  102.491491  10.725239  4.472136
4             2 2018-07-24 08:35:08  105.491491   8.725239       NaN
5             2 2018-07-24 08:36:10  101.491491  15.725239  8.062258
6             2 2018-07-24 08:37:09  101.491491  12.725239  3.000000
7             2 2018-07-24 08:39:00  106.491491  16.725239  6.403124

if you want 0 instead of NaN remove min_count = 1

*

*What is done here is to calculate the module of each vector constructed from consecutive points of each inspector


text:
Q: How to Use Multiple 'IN' on a DataTable I have asked how to use the 'IN'  here.
So far, this SQL Server query:
select *
  from table
  where column1 in
    (
        select column2
        from table
    )

can be translated as:
table.Select(
    string.Format("column1 in ({0})",
    string.Join(",", table Rows.OfType<DataRow>()
        .Select(r=>r["column2"].ToString())
        .Distinct())));

My question is how to translate this SQL query:
select column3
  from table
  where column1 in
    (
        select column2
        from table
    )

So that I can use what's inside on column3 on another 'IN'.
(e.g.)
select columnA
  from table2
  where columnB in
    (
        select column3
        from table1
        where column1 in
            (
                select column2
                from table1
            )
    )

A: Linq is a tool.  It has its strengths and its limitations.
What I would do is use a custom query to accomplish this.  Let SQL Server do the brunt work here, not Linq.  It'll dramatically improve the performace, as well.
var sqlTxt = "select columnA "  +
    "from table2 "  +
    "where columnB in "  +
    "( select column3 "  +
    " from table1 "  +
    " where column1 in " +
        "(select column2 " +
            "from table1) " +
    ")"

results = ExecuteQuery(sqlTxt);


text:
Q: jquery display a list of items in
* Hi I want to display a list of item inside
sample html code

           Game

code
var games = new Array();
    games[0] = "World of Warcraft";
    games[1] = "Lord of the Rings Online";
    games[2] = "Aion";
    games[3] = "Eve Online";
    games[4] = "Final Fantasy XI";
    games[5] = "City of Heros";
    games[6] = "Champions Online";
    games[7] = "Dark Age of Camelot";
    games[8] = "Warhammer Online";
    games[9] = "Age of Conan";
    function pageLoaded(){
        var list = "";

            for(i=0; i<games.length; i++){
        list ="
"+games[i]+"
";
        $("#gamelist").append(list);
        //document.getElementById("gamelist").innerHTML=list;
        list = "";
        }

}

Seems there is wrong with my js code. It doesn't output anything

A: On jsfiddle

Game

var games = ["World of Warcraft", "Lord of the Rings Online", "Aion", "Eve Online", "Final Fantasy XI", "City of Heros", "Champions Online", "Dark Age of Camelot", "Warhammer Online", "Age of Conan"];

var gamelist = document.getElementById("gamelist");

games.forEach(function (game) {
    var li = document.createElement("li");

    li.textContent = game;
    gamelist.appendChild(li);
});

This is pure Javascript but I see you changed your tag to jQuery, but I will leave it here.
Additionally if you didn't want to create the array initialised, like I did above, you could have done it like this, as new Array() is considered bad practise.
var games = new Array();

games.push("World of Warcraft");
games.push("Lord of the Rings Online");
games.push("Aion");
games.push("Eve Online");
games.push("Final Fantasy XI");
games.push("City of Heros");
games.push("Champions Online");
games.push("Dark Age of Camelot");
games.push("Warhammer Online");
games.push("Age of Conan");

A: There are so many things you are doing wrong in it.
Firstly, it is not pure javascript, its jquery.
you need to reference jQuery api to be able to use jQuery.
however, you can achieve what you want through pure javascript also.
Now let's look at your mistakes

*

*you have created a function pageLoaded, but have not called it anywhere. You need to call a function in order to make its logic work. Am assuming you want to call your pageLoaded method when the page is ready. you can either call it on body load or simply inside jQuery's .ready i.e  $(document).ready(function(){ pageLoaded()});.
This method simply ensures, your logic executes when the dom is ready

*you have written non-keyword, meaningless words inside your method "items in the array". remove it in order to make your function work. Am assuming you wanted to put a comment over there, put a comment like this inside script tag:
 //items in the array

*you are not concatenating new values to your list variable, you are overwritting its content with each iteration, so instead of list ="
"+games[i]+"
"; this, do this
 list +="
"+games[i]+"
";

*finally, you are appending the list to #gamelist inside the for loop. do it outside the loop. once your list is complete. and remove the line list=" "
so place this line  $("#gamelist").append(list); outside the for loop.
try your function like this:
var games = new Array();
    games[0] = "World of Warcraft";
    games[1] = "Lord of the Rings Online";
    games[2] = "Aion";
    games[3] = "Eve Online";
    games[4] = "Final Fantasy XI";
    games[5] = "City of Heros";
    games[6] = "Champions Online";
    games[7] = "Dark Age of Camelot";
    games[8] = "Warhammer Online";
    games[9] = "Age of Conan";
$(document).ready(function(){
        var list = "";
        for(i=0; i<games.length; i++){
        list +="
"+games[i]+"
";
        }
    $("#gamelist").append(list);

});

see this fiddle

A: You need to refresh the listview after dynamically appending elements in it; otherwise it won't update.
 $("#gamelist").append(list).listview("refresh");


text:
Q: A (very naive) question about Homotopy Type Theory In homotopy type theory, homotopy types can be viewed as logical types and it is possible to prove some theorems about them without using any underlying space (no simplicial set, no topological space). It is a kind of synthetic algebraic topology. Is it just a coincidence that the word "type" may have these two meanings ? What I mean is: what had in mind the one who invented this terminology of "homotopy types" ? And do we even know where that terminology of "homotopy types" comes from. I guess that the answer will be that it is a coincidence but since it is written nowhere in the book, I ask the question in order to be sure.

A: There seem to be at least two distinct traditions in mathematics for the use of 'type'.
The 'Homotopy types' of algebraic topology seem to have been defined in analogy to 'order types'.  Two ordered sets have the same order type when they are isomorphic.  Cantor defined the ordinal numbers to be the order types of well-ordered sets.  I have not checked whether he used the German equivalent of the word 'type'.
The 'intensional types' of HoTT originate with Bertrand Russell's approach to resolving his paradox by requiring each mathematical object to be of some type, with constraints on which objects are allowed to belong to any given type. Any formal quantifier could only be a quantifier over some type. This was in contrast to Frege who allowed all of his objects to belong to a single realm which could be quantified over.
No doubt both traditions have a source in everyday usage; e.g. from the free dictionary
Type: A number of people or things having in common traits or characteristics that distinguish them as a group or class.

A: Maybe I should repost my comment above as a genuine answer:
It's a coincidence, but a very fortunate one (for a change).

*

*When people started saying "homotopy type" $X$ they meant "the type of $X$" as in "what kind of space is X?".

*When people said "type" $X$ in logic (type theory), they meant the type of its terms, as in "what kind of thing is an $x \in X$?".
In a naive sense, these two usages of "type" are not actually the same. Remarkably, as one digs deeper and understands that intensional type theory is essentially homtopy type theory, it turns out by lucky coincidence that at the bottom of it indeed this is the same notion of "type" in both cases.
I think its one of those trivialities that deserve to be regarded as "deep".


text:
Q: Running concurrent processes using pipe in C I'm working on an assignment in C aimed at using a pipe to pass variables between two processes. Both processes must be forked from the parent, and they must run concurrently to pass one character at a time (sort of demonstrated below).
The issue I'm having is that the fork()ed processes are not running concurrently. The sender seems to go first, and after running for ~26 seconds the receiver begins. Here is the code I have written:
#include <stdio.h>

int ret;
int pipearray[2];
char buffer[26];

void mysender();
void myreceiver();

int main()
{
  int pid = 0;
  int i = 0;
  ret = pipe(pipearray);

  while (i < 2) {
    pid = fork();
    if ( pid == 0 && i == 0 ) /* child process execution (receiver) */
      {
    myreceiver();
    printf("Your receiver is done\n");
    exit(0);
      }

     else if ( pid == 0 && i == 1 ) /* now executes sender */
     {
    mysender();
    printf("Your sender is done\n");
    exit(0);
     }
    ++i;
  }

  close(pipearray[0]);
  close(pipearray[1]);
  sleep(30);
  printf("Parent function has finished.\n");

  return 0;
}

void mysender()
{
  char c;
  int index = 90;
  close(pipearray[0]);

  while (index > 64) /* loop for all values of A-Z in ASCII */
    {
      c = (char) index;
      open(pipearray[1]);
      write(pipearray[1], c, sizeof(c)); /* Sends letter to pipe */
      --index;
      sleep(1);
    }

  close(pipearray[1]);
}

void myreceiver()
{
  int index = 0;
  close(pipearray[1]);

  while(buffer != 'A') /*loop runs until 'A' is handled */
  {
    sleep(1);
    open(pipearray[0]);
    read(pipearray[0], buffer, 1);
    printf("%s", &buffer);
    index++;
    if ( index == 26 ) { break; }
  }

  close(pipearray[0]);
}

Expected Result:
ZYXWVUTSRQPONMLKJIHGFEDCBA
Your sender is done
Your receiver is done
The parent function has finished.

My result:
Your sender is done
The parent function has finished.
Your receiver is done

I'm very new to C programming but I've been banging away at this for a while. Any tips to why these might not be running simultaneously would be very appreciated.

A: There is many errors in your code. Don't try to open the pipe after fork, it is already open and has no name. Write should use the address of c. Read must read into the right place. A flush must be done after write to stdout. Your conditional must be slightly modified to be guaranteed correct. The parent process must wait its children. Here is the modified code :
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
int ret;
int pipearray[2];
char buffer[26];

void mysender();
void myreceiver();

int main()
{
  int pid = 0;
  int i = 0;
  ret = pipe(pipearray);

  while (i < 2) {
    pid = fork();
    if ( pid == 0 && i == 0 ) /* child process execution (receiver) */
      {
        myreceiver();
        printf("Your receiver is done\n");
        exit(0);
      }

    else if ( pid == 0 && i == 1 ) /* now executes sender */
      {
        mysender();
        printf("Your sender is done\n");
        exit(0);
      }
    ++i;
  }

  close(pipearray[0]);
  close(pipearray[1]);
  // Don't sleep, but wait until the end of the two children
  wait(NULL);
  wait(NULL);
  //  sleep(30);
  printf("Parent function has finished.\n");

  return 0;
}

void mysender()
{
  char c;
  int index = 90;
  close(pipearray[0]);

  while (index > 64) /* loop for all values of A-Z in ASCII */
    {
      c = (char) index;
      // try to open a anonymous pipe is a non-sense
      //      open(pipearray[1]);
      // Send a buffer by its address
      write(pipearray[1], &c, sizeof(c)); /* Sends letter to pipe */
      --index;
      sleep(1);
    }

  close(pipearray[1]);
}

void myreceiver()
{
  int index = 0;
  close(pipearray[1]);

  // Ensure condition is entered first
  buffer[index] = 0;
  // This is not the best condition ever, but ok.
  while(buffer[index] != 'A') /*loop runs until 'A' is handled */
  {
    sleep(1);
    // Don't open an anonymous pipe
    //    open(pipearray[0]);
    // Read at the right position
    read(pipearray[0], buffer+index, 1);
    // print and flush, could also be printf("%s"...); flush(stdout);
    printf("%s\n", buffer);
    index++;
    if ( index == 26 ) { break; }
  }

  close(pipearray[0]);
}

Now, consider to remove the sleeps in the reader, as it will be synchronized with the writes such that no read is possible if no write has been done. Alos consider to read more that one byte, because there is no concept of message, so that you can read as much byte you consider necessary to read, and as usual it is better to try reading a bunch of bytes when you can.


text:
Q: Print variable together with string? I have variable like this one:
myVar db 'A','B',0

I need to embed 'A' and 'B' in the middle of a string that is printed on screen. Something like this:
CALL PTHIS
db 'first val is ', %1, ' second val is ', %2, 0

I think I saw something like this somewhere. How can this be done?

A: For the sake of an answer I wrote a very simple printf parser. It works like its big brother of C, but understands only the format specifier '%c' and '%s'. This can be expanded as well.
It's also a good example to explore the C calling convention.
Following program assembles in EMU8086, TASM, JWASM and MASM>=6.0:
.MODEL tiny                     ; For MASM 6 and TASM
.CODE                           ; For MASM 6 and TASM
.186                            ; For MASM 6 (push immediates)
ORG 100h                        ; Origin for COM program

start:
                                ; printf (&format, &myVar, myVar[0], myVar[1])
    push WORD PTR myVar + 1     ; Forth argument (single character directly pushed)
    push WORD PTR myVar + 0     ; Third argument (single character directly pushed)
    push OFFSET myVar           ; Second argument (address of null terminated string)
    push OFFSET fmt             ; First argument (address of null terminated format string)
    call printf
    add sp, 2 * 4               ; Adjust stack: 4 arguments a 2 bytes

    lea dx, report
    mov ah, 09h
    int 21h

    RET                         ; return to operating system.

printf PROC
        push bp                 ; Prologue
        mov bp, sp
        sub sp, 2 * 3           ; Reserve local stack for three WORDs
        mov [bp-2], bx          ; Preserve BX (CCall calling convention)
        mov [bp-4], si          ; Preserve SI (CCall calling convention)
        mov [bp-6], di          ; Preserve DI (CCall calling convention)

        mov di, 4               ; Counter to the arguments
        mov si, [bp+di]         ; Get the first argument
    output:
        mov ax, [si]            ; Get two characters
        cmp al, '%'             ; First charcter == '%'
        jnz J1                  ; No, skip over the placeholder blocks

        cmp ah, 'c'             ; Second character == 'c'
        jnz no_c                ; No, skip over the '%c' placeholder block
        inc si                  ; Adjust the index to format string
        add di, 2               ; Point to the next argument on stack
        mov al, BYTE PTR [bp+di]    ; Get the argument (it is a directly pushed character)
        jmp J1                      ; and print it
    no_c:

        cmp ah, 's'             ; Second character = 's'
        jnz no_s                ; No skip over the %s placeholder block
        add si, 2               ; Adjust the index to format string
        add di, 2               ; Point to the next argument on stack
        mov bx, [bp+di]         ; Get argument (it is an offset to an ASCIIZ string)
    next:
        mov al, [bx]            ; Get character
        test al, al             ; character == 0
        jz output               ; Yes - this string is ready, turn back to format string
        mov ah, 0Eh             ; Teletype
        int 10h                 ; BIOS
        inc bx                  ; Point to next charcter
        jmp next                ; Repeat the output
    no_s:

    J1:
        test al, al             ; Character == 0?
        jz ready                ; Yes, format string is ready, print is done

    doit:
        mov ah, 0Eh             ; Teletype
        int 10h                 ; BIOS
        inc si                  ; Point to next character
        jmp output              ; Repeat the bunch

    ready:
        mov bx, [bp-2]          ; Restore BX (CCall calling convention)
        mov si, [bp-4]          ; Restore SI (CCall calling convention)
        mov di, [bp-6]          ; Restore DI (CCall calling convention)
        mov sp, bp              ; Epilogue
        pop bp
        ret
printf ENDP

fmt     db "From the word %s is the first char %c and the second char %c",0
myVar   db 'H','e','l','l','o',0
report  db 13,10,13,10,"I'm back to the root",13, 10,'$'

END start                       ; Directive to stop the compiler.


text:
Q: Updating 14.04.1 MYSQL from 5.5 to 5.7 I have been trying to update MYSQL on my ubuntu 14.04.1 server following the directions here: MySQL 5.5 Update to MySQL 5.7 but have been running into some difficulties.  I can run:

sudo dpkg -i mysql-apt-config_0.8.0-1_all.deb
sudo apt-get update

but then when I get to:

sudo apt-get install mysql-server

I get failure notifications as follows:

Reading package lists... Done
Building dependency tree
Reading state information... Done
You might want to run 'apt-get -f install' to correct these:
The following packages have unmet dependencies:
linux-image-extra-3.13.0-48-generic : Depends: linux-image-3.13.0-48-generic but it is not going to be installed
linux-image-generic : Depends: linux-image-3.13.0-48-generic but it is not going to be installed
mysql-server : Depends: mysql-community-server (= 5.7.17-1ubuntu14.04) but it is not going to be installed
E: Unmet dependencies. Try 'apt-get -f install' with no packages (or specify a solution).

MYSQL fails to update at this point.  What am I doing wrong? Thanks.


text:
Q: Why do Android alarms fire at the same time? Below is a pretty simple method that takes a Date and an id for an alarm to be fired which starts a countdown. For some reason I don't understand, if I call it once with one date and id 0 and call it again with another date and id 1 (i.e., two different countdowns), Android will fire both alarms at the same time (specifically the first date passed with id 0) so both countdowns start at the same time.
Can anyone tell me why and how to fix it? Thanks!
public void setCountdownAlarm(Date fireTime, int id)
{
    // startCountdown will be called at fireTime
    BroadcastReceiver startCountdown = new BroadcastReceiver() {
        @Override public void onReceive( Context context, Intent theIntent )
        {
            countdownTimer = new Timer();
            countdownTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    onSecondTick(showtime);
                }
            }, 0, 100); // call every 10th of a second
        }
    };

    this.registerReceiver( startCountdown, new IntentFilter("com.counter.app.CountActivity.COUNT") );
    Intent intent = new Intent("com.counter.app.CountActivity.COUNT");
    PendingIntent pintent = PendingIntent.getBroadcast( this, id, intent, 0 );
    AlarmManager manager = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));

    if (Build.VERSION.SDK_INT >= 19)
        manager.setExact(AlarmManager.RTC_WAKEUP, fireTime.getTime(), pintent);
    else
        manager.set(AlarmManager.RTC_WAKEUP, fireTime.getTime(), pintent);
}

Editing to say that when I waited for the second alarm to fire, Android actually calls startCountdown twice -- once again for each alarm. Help!

A: I figured out what I did wrong. As explained in answers to similar questions, the second parameter of PendingIntent.getBroadcast (requestCode) must be unique if you want to get a unique pending intent. I took care of that by passing "id".
The second problem was that I registered the BroadcastReceiver each time I called setCountdownAlarm. The BroadcastReceiver should only be registered once, typically in the onCreate method of the activity.


text:
Q: Primefaces Datatable SelectOneMenu Render Problem I have a primefaces (8.02) datatable with editable rows (rowEditor/celleditor). A couple of the data-elements in each row are a drop-downs (selectOneMenu) with value & label.
My problem is when I click on the roweditor pencil and the row goes into edit-mode my drop-down columns only show the centered arrow (cursor) of the drop-down (selectOneMenu) element. No text at all. In the showcase for editable datatable the cursor is neatly tucked to the right and I can see both text and cursor.
Once I click on the cursor it presents me with the list of selectable elements. Then I choose one and the drop-down collapses as it should but again all I see is the (centered) cursor) not any of the selected text, not even partially. When I press roweditor-save I can see a value change has occurred in accordance to what I picked in the drop-down.
I'm not sure where to start. The exact same selectonemenu construct works fine outside the datatable. I'm thinking its probably more a style/render problem? What I aslo noticed is when I tab through the row and I land on the drop-down I cannot use cursor keys to go through the options. Only mouse works. Maybe just another symptom of the same problem.
Any ideas would be appreciated, thanks for you time
Carsten


text:
Q: How would I rotate an object based on four vector3 points? Im currently working on procedural animation trying to understand the fundamentals and how to implement it better. I am stuck trying to work out how to rotate the body of this Quadruped based on its legs. I understand I would have to get the distance between the legs but I dont understand how I can translate that into Quaternion/Rotation values and apply it to the body it the centre!
Any advice or help would be appreciated! Thankyou!

A: First, I would use your calculations to determine the desired position of the front hips and the left rear hip. Then, I would use some vector math and Quaternion.LookRotation to solve for the rotation:
Quaternion GetBodyRotation(Vector3 frontLeftLegWorldPosition,
        Vector3 frontRightLegWorldPosition,
        Vector3 rearLeftLegWorldPosition)
{
    Vector3 localForward = frontLeftLegWorldPosition - rearLeftLegWorldPosition;
    Vector3 localRight = frontRightLegWorldPosition - frontLeftLegWorldPosition;
    Vector3 localUp = Vector3.Cross(localForward, localRight);

    return Quaternion.LookRotation(localForward, localUp);
}

Then, I would apply that rotation to the body with bodyTransform.rotation = resultOfAboveMethod;.
Then, assuming the left rear hip and front right hip are rotationally symmetrically positioned, you can set the position of the body such that it is in between the front right hip and left rear hip with bodyTransform.position = 0.5f * (frontRightLegWorldPosition +  rearLeftLegWorldPosition);


text:
Q: React sortable hoc drop my items to the end of the list When I using react sortable hoc library and dragging an item, it changes the transform3d of each li item (who is under the dragging item) to -22px what cause the item I dropped to be sent to the end of the list.
How can I change it to make transform only the relevant items?
An example

source code
I try to look for it on the internet and didn't find solution


text:
Q: Sum of Fibonacci Coefficient Power Series I am working on algorithm to count $g(x,n)$, where
\begin{align*}
g(x, n)&=\sum_{i=1}^nf(i).x^i\\
f(i)&=f(i-1)+f(i-2)\\
f(1)&=1,f(2)=1
\end{align*}
I need to compute $g(x,n)$ in logarithmic time. I've tried to change it into matrix exponentiation form, but turns out it didn't work for me. Is there any other way i can solve this problem?

A: Hint: Noting
$$ f(i)=\frac1{\sqrt 5}\left(\frac{1+\sqrt 5}{2}\right)^i-\frac1{\sqrt 5}\left(\frac{1-\sqrt 5}{2}\right)^i$$
so one has
\begin{eqnarray}
g(x,n)&=&\frac1{\sqrt 5}\sum_{i=1}^n\left(\frac{1+\sqrt 5}{2}\right)^ix^i-\frac1{\sqrt 5}\sum_{i=1}^n\left(\frac{1-\sqrt 5}{2}\right)^ix^i.
\end{eqnarray}
You can do the rest.

A: You can derive a closed formula from starting with $g(x,n)+xg(x,n)$ and then by using the Fibonacci property and some index shifts you get $g(x,n)$ again as well as some simple additional expressions. Solving the equation for $g(x,n)$ should give you
$$g(x,n) = \frac{x(f(1)-f(2))-f(1)+x^nf(n+1)+x^{n+1}f(n)}{1+x-\frac{1}{x}}$$
at last. The most expensive part is the computation of $f(n)$ and $f(n+1)$ but this can be done in logarithmic time with matrix exponentiation.

A: The $g(x, n)$ is the first $n$ terms  of generating function of the Fibonacci sequence that is in the following form:
$$
g(x, n)=Series(\frac{x}{1-x-x^2},n)=x+{x}^{2}+2\,{x}^{3}+\cdots + f_n\,x^n
$$
that means, you need to divide $x$ over $1-x-x^2$ polynomial for $n$ times and after that the quotient is your solution. I hope, you find it useful.


text:
Q: Yii CDbCommand binding non quoted params Can I bind non quoted params into query using Yii CDbCommand?
I try something like this
$sql = "INSERT :sourceTable SELECT * FROM :destTable GROUP BY :column1, :column2";
$params = array(
':sourceTable' => 'source_table_name'
...
);
Yii::app()->db->createCommand($sql)->execute($params);

but get an error, because Yii param binder adds single quotes on table names and my query brokes. Is there a way to bind Yii param without quotes?
Thanks

A: Don't pass the table name as a param, just put it like this (without prefix):
$sql = "INSERT INTO {{source_table_name}} SELECT * FROM {{dest_table_name}} GROUP BY :column1, :column2";
$params = array(
...
);
Yii::app()->db->createCommand($sql)->execute($params);

A: Not sure that is possible.
You could, however, put the variable directly into the query but use CDbSChema::quoteTableName on it first.
More information here: http://www.yiiframework.com/doc/api/1.1/CDbSchema#quoteTableName.


text:
Q: Saving image using fs.writeFile I'm trying to save an image using node's file-system that I got from https://picsum.photos/ but the file that is getting written is not what I'm expecting it to be.

const axios = require('axios');
const path = require('path');
const fs = require('file-system');

axios.get('https://picsum.photos/id/237/200/300')
  .then((data) => {
    fs.writeFile(path.resolve(__dirname, '../assets/test/test1.jpg'), data.data, (err) => {
      if (err) {
        console.log(err);
        throw err;
      }
      console.log('file save successfully');
    });
  })
  .catch((err) => {
    console.log(err);
  });

A: The data is probably being returned with the wrong encoding, as none is specified - most likely as text instead of as a binary stream, as the responseType is 'json' by default. There is an example of writing an image to disk with an axios request on the docs, in which responseType is set to stream and the given stream is piped to a writeStream. This is probably the kind of approach you'll need.
Below is the code example given on the docs:

// GET request for remote image
axios({
  method: 'get',
  url: 'https://picsum.photos/id/237/200/300',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });

If you want to use writeFile still, you can set responseType: 'arraybuffer' instead, and pass the given buffer to fs.writeFile.


text:
Q: How to read a RichText field? I have an agent which is supposed to show a Notes DB as XML. I successfully retrieved all the fields but the RichText one. This is a code snippet:
Set session = New NotesSession
Set doc = session.DocumentContext
Set db = Session.CurrentDatabase
Set view = db.getview("myView")
Set doc = view.GetFirstDocument()

While Not(doc Is Nothing)
    Print "<job>"
    Print "<id>" & doc.id(0) & "</id>" ' Works fine since ID is a normal field
    Print "<text>" & doc.text(0) & "</text>" ' Does not work at all
    Print "</job>"
    Set doc = view.GetNextDocument(doc)
Wend

If I use doc.text instead of doc.text(0) it only writes the first two words of the whole text. I suppose I have to cicle through the entire text but since I am new to Lotus Script I have no idea how to do it. Thank you guys.
EDIT: It turned out that Simon's answer is correct. The problem regards encoding as far as I can tell, if I remove the following Print:
Print |Content-Type:text/xml| & Chr$(13)

Everything works fine. I guess I need to define encoding in the header...
EDIT: I now use this Print instead:
Print "<text><![CDATA[" & rtitem.getUnformattedText() & "]]></text>"

However when I call the agent from the Browser it still broke at that print as it is ignoring the CDATA.

A: Don't use the dot notation. To get the Richtext field you will need to use the getFirstItem() method call and link it to a NotesRichTextItem object. After that you should be able to convert it to text using the getUnformattedText() method.
Dim rtitem As NotesRichTextItem
...
rtitem = doc.getFirstItem("text")

Print "<text>" & rtitem.getUnformattedText() & "</text>"

Of course you may need to parse that text to prevent non standard characters in the XML, or wrap it in a CDATA block.


text:
Q: Cannot properly display a manually created graph with Gephi Toolkit 0.9.1 I am trying to use the Gephi Toolkit 0.9.1 to manually create and display a graph, but I can't seem to get the correct output. I've seen plenty of code which imports a file and creates a graph from that, but that method uses containers, which don't seem to make sense if you have nothing to import. Below is my code (most of which is just pieces of the demo code smashed together). Below that is a link to the display I am getting, which is just a solid colored rectangle. It seems to just be an edge (albeit, weirdly formatted), because when I changed the edge color, the display changed accordingly. I have tried it with 2 nodes and 1 edge, as well as 3 nodes and 2 edges. Both have the exact same output, as far as I can tell. I am incredibly new to using the Gephi Toolkit, so I'm sure the mistake is reasonably simple and I appreciate any help you can give. Thank you!
Jason
public class BasicGraphBuild {

public static void main(String[] args) {
    BasicGraphBuild bscGraphBuild = new BasicGraphBuild();
    bscGraphBuild.script();
}

public void script() {
    ProjectController pc =
            Lookup.getDefault().lookup(ProjectController.class);
    pc.newProject();
    Workspace workspace = pc.getCurrentWorkspace();

    GraphModel graphModel = Lookup.getDefault()
            .lookup(GraphController.class).getGraphModel();

    Node n0 = graphModel.factory().newNode("n0");
    n0.setLabel("Node 0");
    Node n1 = graphModel.factory().newNode("n1");
    n1.setLabel("Node 1");
    Node n2 = graphModel.factory().newNode("n2");
    n2.setLabel("Node 2");

    Edge e1 = graphModel.factory().newEdge(n0, n1, 0, 1.0, true);
    Edge e2 = graphModel.factory().newEdge(n0, n2, 0, 1.0, true);

    DirectedGraph directedGraph = graphModel.getDirectedGraph();
    directedGraph.addNode(n0);
    directedGraph.addNode(n1);
    directedGraph.addNode(n2);
    directedGraph.addEdge(e1);
    directedGraph.addEdge(e2);

    // Preview configuration
    PreviewController previewController =
            Lookup.getDefault().lookup(PreviewController.class);
    PreviewModel previewModel = previewController.getModel();
    previewModel.getProperties().putValue(PreviewProperty.EDGE_CURVED,
            Boolean.FALSE);
    previewModel.getProperties().putValue(PreviewProperty.DIRECTED,
            Boolean.TRUE);
    previewModel.getProperties().putValue(PreviewProperty.EDGE_COLOR,
            new EdgeColor(Color.CYAN));
    // previewModel.getProperties().putValue(PreviewProperty.EDGE_OPACITY,
    // 50);
    // previewModel.getProperties().putValue(PreviewProperty.EDGE_RADIUS,
    // 10f);
    previewModel.getProperties().putValue(PreviewProperty.BACKGROUND_COLOR,
            Color.WHITE);

    // New Processing target, get the PApplet
    G2DTarget target = (G2DTarget) previewController
            .getRenderTarget(RenderTarget.G2D_TARGET);
    PreviewSketch previewSketch = new PreviewSketch(target);
    previewController.refreshPreview();
    previewSketch.resetZoom();

    // Add the applet to a JFrame and display
    JFrame frame = new JFrame("Test Preview");
    frame.setLayout(new BorderLayout());

    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.add(previewSketch, BorderLayout.CENTER);

    frame.setSize(1024, 768);
    frame.setVisible(true);

}

}

>>Output of the code<<

A: I found the solution to this, thanks to the Gephi forums. I needed to set the x and y coordinates of the nodes so that they weren't stacked on top of each other. This was done by using the node.setX and node.setY methods.


text:
Q: How do you merge tables with autonumber primary keys? I suppose everyone runs into this problem once in a while: you have two tables that have autonumber primary keys that need to be merged. There are many good reasons why autonumber primary keys are used in favour of say application-generated keys, but merging with other tables must be one of the biggest drawbacks.
Some problems that arise are overlapping ids and out of sync foreign keys. I would like to hear your approach for tackling this. I always run into problems, so I'm very curious if anybody has some sort of a general solution.
-- EDIT --
In response to the answers suggesting to use guids or other non-numeric keys, there are situations where in advance it just seems a better idea to use autonumber keys (and you regret this later), or you're taking over someone else's project, or you get some legacy database that you have to work with. So I'm really looking for a solution where you have no control over the database design anymore.

A: Solutions include:

*

*Use GUIDs as primary keys instead of a simpler identity field.  Very likely to avoid overlaps, but GUIDs are harder to use and don't play nicely with clustered indexes.

*Make the primary key into a multi-column key, the second column resolving overlapping values by identifying the source of the merged data.  Portable, works better with clustered indexes, but developers hate multi-column keys.

*Use natural keys instead of pseudokeys.

*Allocate new primary key values for one of the merged tables, and cascade these changes to any dependent rows.  This changes a merge operation into an ETL operation.  This is the only solution you can use for legacy data, if you can't change the database design.
I'm not sure there's a one-size-fits-all solution.  Choose one of these based on the situation.

A: Hm, I'm kind of enthousiastic about the idea that I just put in a comment at AlexKuznetsov's answer, so I'll make a whole answer about it.
Consider the tables to be named table1 and table2, with id1 and id2 as autonumber primary keys. They will be merged to table3 with id3 (a non-autonumber primary key).
Why not:

*

*Remove all foreign key constraints to table1 and table2

*For all foreign key fields referring to table1, execute an UPDATE table SET id1 = id1 * 2, and for FK fields referring to table2, execute an UPDATE table SET id2 = (id2) * 2 + 1

*Fill table3 by executing an INSERT INTO table3 SELECT id1 * 2 AS id3, ... FROM table1 UNION ALL SELECT id2 * 2 + 1 AS id3 FROM table2

*Create new foreign key constraints to table3

It can even work with 3 or more tables, just by using a higher multiplier.

A: One of the standard approaches (if not the standard approach), where you're designing for such an eventuality, is to use GUIDs for primary keys rather than integers - merging is then relatively painless as you are guaranteed not to encounter an overlap.
Barring a redesign, tho', I think you're stuck with having to insert into the table, accept that you'll get new primary keys, and ensure that you maintain the mapping from old-to-new ID - then insert referencing data with FK remapped etc. etc. If you data has a "business key" that will remain unique after the insert, this would save on having to keep track of the mapping.

A: I fyou are sure you have only two such tables, you can just have even IDs in one table (0,2,4,6,...) and odd IDs in another (1,3,5,7,...)

A: Assuming you also have a natural key in the tables to be merged then the process isn't difficult. The natural key is used to deduplicate and to correctly reassign any references. You can renumber the surrogate key values at any time - that being one of the principal advantages of using a surrogate in the first place.
So I don't see this as a problem with surrogate keys - provided you always enforce the natural key (actually I much prefer the term "business key"). If you haven't got business keys for these tables, well maybe now would be a good time to redesign so that ALL the necessary keys are properly implemented.


text:
Q: How to cast an Object to Arraylist I need cast an Object to Arraylist:
<% Arraylist<Products> mypr = sesion.getAttribute("products");  %>

                    Id
                    Category
                    Model
                    Stock
                    Price

                <%
                    for (Products xx : mypr) {
                        out.println(xx.toString() + "
");
                    }
                %>

A: Assuming it's an ArrayList, you could cast it (I'd recommend the List interface like)
List<Products> mypr = (List<Products>) sesion.getAttribute("products");


text:
Q: How use the hash in my custom login laravel5 I am developing my own login and I have the following code
public function login(Request $request ) {
         $email = \Request::input('email');
        $password = \Request::input('password');
        if (Auth::attempt(['email' => $email, 'password' => $password]))
        {
            //echo "success";
            return redirect('home');
        }
        else {
            return "fail";
        }
    }

And the CreateUserRequest
<?php namespace App\Http\Requests;

use App\Http\Requests\Request;

class CreateUserRequest extends Request {

    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'nif' => 'required | max:9 ',
            'name' => 'required | max:255',
            'email' => 'required',
            'cognoms' => 'required | max:255',
            'birthday' => 'required',
            'password' => 'required | confirmed',
            'password_confirmation' => 'required',
            'municipios' => 'required | Integer|Min:1',
            'presentacion' => 'required',
            'file' => 'required'

        ];
    }

}

My register controller
public function registro(CreateUserRequest $request){

        $usuario = new User();
        $usuario->nif = \Request::input('nif');
        $usuario->name = \Request::input('name');
        $usuario->cognoms = \Request::input('cognoms');
        $usuario->birthday = \Request::input('birthday');
        $usuario->email = \Request::input('email');
        $usuario->password= \Request::input('password');
        /**Foto del usuario**/
        $file = \Request::file('file');
        $fileName = $file->getClientOriginalName();
        $file->move(public_path().'/uploads/', $fileName);
        $usuario->file = 'uploads/'.$fileName.'';
        $usuario->save();
        /**Asignamos el rol a la tabla intermedia***/
        $user = User::find($usuario->id);
        $user->roles()->attach(1);
        return redirect('/');
    }

The model
<?php namespace App;

use Illuminate\Auth\Authenticatable;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Auth\Passwords\CanResetPassword;
use Illuminate\Contracts\Auth\Authenticatable as AuthenticatableContract;
use Illuminate\Contracts\Auth\CanResetPassword as CanResetPasswordContract;

class User extends Model implements AuthenticatableContract, CanResetPasswordContract {

    use Authenticatable, CanResetPassword;

    /**
     * The database table used by the model.
     *
     * @var string
     */
    protected $table = 'users';

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['nif','name','cognoms','email', 'password','idempresa','id_poblacion','id_online',];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = ['password', 'remember_token'];

     public function empresa()
    {
        return $this->belongsTo('Empresa');
    }

     public function municipio()
    {
        return $this->belongsTo('App\Ciudad','id_poblacion');
    }

     public function roles()
    {
        return $this->belongsToMany('App\Rol')->withPivot('user_id','rol_id');
    }

    public function mensajes()
    {
        return $this->belongsToMany('App\User')->withPivot('id_emisor','id_receptor');
    }

    public function subastas(){
        return $this->hasMany('App\Subasta','id_creador','id');
    }

    public function pujas(){
        return $this->hasMany('App\Puja','id_subasta','id');
    }
}

When I put the password , the laravel create the user andthe field password in database is white.

A: Please try this:
public function registro(CreateUserRequest $request){

            $file = $request->file('file');
            $fileName = $file->getClientOriginalName();
            $file->move(public_path().'/uploads/', $fileName);

            $user = User::create([
                'nif' => $request->input('nif'),
                'name' => $request->input('name'),
                'cognoms' => $request->input('cognoms'),
                'birthday' => $request->input('birthday'),
                'email' => $request->input('email'),
                'password' => \Hash::make($request->input('password')),
                'file' => 'uploads/'.$fileName.'',
            ]);

            /**Asignamos el rol a la tabla intermedia***/
            $user = User::find($user->id);
            $user->roles()->attach(1);
            return redirect('/');

   }


text:
Q: Case Auto-Response rule - 'Send response to all recipients' doesn't support Email Service I have an Email Service, to handled incoming emails, which is replacing Email-To-Case, to handle duplicate cases (by matching the Subject of the incoming email with existing cases). This is working fine.
My issue is that the Case Auto-Response rule, is set to 'Send response to all recipients', and it is my understanding that this is only supported for Email-To-Case.

Trying to come up with a solution, I was able to find the following article (https://customers.internetcreations.com/KnowledgeDetail?name=Include-Additional-Email-Addresses-on-Auto-Response-feature-does-not-work-with-Email-to-Case-Premium), by 'Email to case premium' which is utilizing Case Teams as part of an independent workflow rule bonded with the appropriate email alert.
Is there any way to achieve this without Case Teams?
My Case object does have a custom 'Additional CC' (and 'Additional BCC') custom fields, which holds the email addresses of the recipients, but I am not seeing any option to add custom fields in the Email Alert:

A: You said

My Case object does have a custom 'Additional CC' (and 'Additional BCC') custom fields, which holds the email addresses of the recipients, but I am not seeing any option to add custom fields in the Email Alert

If those custom fields are of type Email, then they will appear in the Email Alert. Type Text won't work. Of course, if type Email the value of each field must be unitary - e.g. foo@bar.com, not delimited like foo1@bar.com,foo2@bar.com


text:
Q: Amount of NaHCO3 needed to neutralize HCl With the equation:
HCl + NaHCO3 --> NaCl + CO2 + H2O
Find the number of grams of NaHCO3, to three significant figures, required to neutralize 75 mililitres of 0.110 mol/l HCl.
I'm stuck on this problem. I think I either use the molarity formula or c=n/v?
If someone could show or give me a hint on how to start the problem I think I can figure the rest out.
Thank you in advance!

A: Since it's an easy question, let me venture an answer.
First find the amount in moles of $\rm{HCl}$ you have to neutralise.
In $75$ ml of the given acid solution, you will have $75 \times 10^{-3} \times 0.110 = 8.25 \times 10^{-3}$ mol of $\rm{HCl}$.
You will need exactly that many moles of $\rm{NaHCO_3}$ to neutralise that amount of acid since the stoichiometric ratio as per the balanced equation is $1:1$
The molecular "weight" (or mass) of the $\rm{NaHCO_3}$ molecule is $84$ (just add the atomic masses - $23 + 1 + 12 + 3 \times 16$. Which means $1$ mole of $\rm{NaHCO_3}$ weighs very close to $84$ gram.
$8.25 \times 10^{-3}$ mol of $\rm{NaHCO_3}$ has a mass of $8.25 \times 10^{-3} \times 84 = 0.693$ gram.


text:
Q: Invalid conversion from throwing function of type '(_) throws -> ()' to non-throwing function type '(CallResult) -> Void' Have the following block of code:
do {
  try call.receiveMessage { callResult in
    if let msg = try callResult.resultData {
      let result = try decoder.decode(valueType, from: msg)
    }
    // other stuff
} catch let error {
  if let callback = self.onError {
    callback(error)
  }
}

this fails to compile due to an error at try call.receieveMessage:
Invalid conversion from throwing function of type '(_) throws -> ()' to non-throwing function type '(CallResult) -> Void'
The function I'm calling did indeed have a signature change:

from:  public func receiveMessage(completion: @escaping (Data?) throws -> Void) throws {
  to:  public func receiveMessage(completion: @escaping (CallResult) -> Void) throws {

What I'm having trouble getting my head around is the fact that other calls of this same method aren't having an issue, so I'm haven't quite nailed down what makes this particular block special.
Any advice would be appreciated.

A: Should have sat on it a bit longer.  The resolution is to wrap the lambda with a do/catch.


text:
Q: How to integrate the metaio + Open CV for android application? Hi i'm trying to create a application related to the Augmented Reality (AR) and was able to configure my application with Metaio SDK and OpenCV library successfully in two separate application.
but the thing is i want to use both the library of OpenCV and Metaio together into one application. so can any one help me with its integration.
In my single application I want to use OpenCV for markerless detection and MetaIO for 3D Model rendering.
Metaio:http://www.metaio.com/
OpenCV:http://opencv.org/
=====>
I'm using opencv to detect shapes in a camera image and want to display 3D objects rendered by metaio on those shapes. Similar to marker tracking.
Metaio and openCV, each have their own cameraview. I have disabled cameraview of openCV.
I want to convert an ImageStruct object received in onNewCameraFrame() method into an OpenCV Mat in Android. For this, I have registered MetaioSDKCallback to continuously receive camera frame.
But onSDKReady() and  onNewCameraFrame() method of this callback is not being called,though I have added 'metaioSDK.requestCameraImage()'.
This where i'm stuck with it.

A: I suggest you to integrate the sdk of Opencv4android, and to see the samples come with, they are very good examples to teach you how to use the camera easily
For your objective probably face detection example is good to check.
Here is the tuto that help you to install and configure opencv SDK
For AR I can't help you so much, but have look at this discussion, it could be helpful.


text:
Q: Private nested classes - C++11 compiler misbehavior? Or as designed? Consider the following code:
class Main
{
  private:
      class Inner
      {
        public:
          void DoSomething() {}
      };

  public:
    static Inner* CreateInner() { return new Inner(); }
 };

It is impossible to compile the following:
Main::Inner* pInner = Main::CreateInner();
pInner->DoSomething();

Because we'll get a compiler error 'C2248: cannot access private class decalred in class Main'
However, using the following syntax will compile and execute smoothly:
auto pInner = Main::CreateInner();
pInner->DoSomething();

Suddenly, (to my surprise, anyway...), the inner private class is 'visible' to the outside world...
Does anyone aware to this compiler behavior?
Is it considered 'valid' to use the auto keyword according to the C++11 standard in this case, or is it some kind of a bug?
It behaves as described on both:

*

*Visual Studio 2010 - platform toolset v100

*Visual Studio 2013 - platform toolset v120

Any thoughts?
Thanks!


text:
Q: var_dump() returning zero arry. unable to upload file PHP upload.php
The var_dump() function is returning zero array. What am i doing wrong here ?
<form method="post" action="upload.php">

    <input type="file" name ="file" id="file"><input type="submit" value="upload">

</form>
<?php

if(isset($_POST['file']))
{

   var_dump($_FILES);

}
?>

A: You need to add the form enctype
<form method="post" action="upload.php" enctype="multipart/form-data">

A: You need to add enctype="multipart/form-data" to your form to upload files
<form method="post" action="upload.php" enctype="multipart/form-data">

Check this for more


text:
Q: how to select all with the same exact id and replace ONLY the id for a new random one? Let's say I have:
<input type="text" id="first" attribute1="test" attribute2="hello" attribute3="happy">
<input type="text" id="first" attribute1="test" attribute2="hello" attribute3="happy">
<input type="text" id="first" attribute1="test" attribute2="hello" attribute3="happy">

it may be 2, 3 or more.
I want to select all input's that has id exactly "first" and then dinamically generantes new ids something like "first_3192391" "first_9592213" but it must be unique for each one, and then replace the "first" for this new one generated.
find("#first").each() {
   new_id = time.now();
   current_id = this.id
   this.replace(current_id, new_id)
}

something like the above algorithim should return:
<input type="text" id="first_32931" attribute1="test" attribute2="hello" attribute3="happy">
<input type="text" id="first_24122" attribute1="test" attribute2="hello" attribute3="happy">
<input type="text" id="first_31292" attribute1="test" attribute2="hello" attribute3="happy">

I was trying to use the replaceWith() method but with no luck.

A: You need to give each html attribute a class, then select by the class, loop through them and then assign ids
 $(".first").each(function(){
    $(this).attr("id", Math.floor(Math.random()*1000));
    });

HTML:
 <input type="text" class="first" attribute1="test" attribute2="hello" attribute3="happy">
    <input type="text" class="first" attribute1="test" attribute2="hello" attribute3="happy">
    <input type="text" class="first" attribute1="test" attribute2="hello" attribute3="happy">

A: You should setup your application so that it generates valid HTML. However, if this is not possible, you could do:
$('input[id="first"]').prop('id', function(i, id) {
   return  id + '_' + i;
});

This iterates over all input fields which have the id first and appends the index they have in the set to the id.


text:
Q: GeoPandas to PostGIS database New to using GeoPandas instead of Pandas. I am trying to export a GeoPandas dataframe to a PostgreSQL database (with PostGIS extension).
The import is from the same database as I try to export to using:
gpd.GeoDataFrame.from_postgis(sql, con, geom_col='geom')

The CRS seems to be imported as well as srid=25832. When I print gdf.crs it yields as expected:
{'init': 'epsg:25832'}

A sample of the geodataframe looks like this, where the last column geom (the geometry) seems to be the problem child:
row_num     model  ...  mean_res                            geom
0          1  644862.0  ...  37.40605  POINT (573187.125 6131561.456)
1          2  644862.0  ...  36.36506  POINT (573189.374 6131560.369)
2          3  644862.0  ...  35.42172  POINT (573191.623 6131559.282)
3          4  644862.0  ...  34.90574  POINT (573193.873 6131558.194)
4          5  644862.0  ...  34.36104  POINT (573196.122 6131557.107)
..       ...       ...  ...       ...                             ...
116      117  644862.0  ...  41.61498  POINT (573448.099 6131435.305)
117      118  644862.0  ...  41.26093  POINT (573450.350 6131434.217)
118      119  644862.0  ...  41.39089  POINT (573452.600 6131433.129)
119      120  644862.0  ...  41.49015  POINT (573454.851 6131432.041)
120      121  644862.0  ...  41.56080  POINT (573457.101 6131430.954)

My problem is when I try to export the dataframe using:
df.to_sql(tablename, con=engine, schema=schemaname, if_exists='replace', index=False)

The engine is from the SQLAlchemy lib using psycopg2, which is working for a "normal" Pandas dataframe (i.e. without geometry)
I get the error:
"Table could not be edited: databasename.schemaname.tablename
'GeometryDtype' object has no attribute 'base'"

A: GeoPandas will support postGIS from the next release. At this moment, you can try using this branch https://github.com/geopandas/geopandas/pull/1248 which brings that support or just get the code from it.
Since geopandas 0.8.0 you will be able to do df.to_postgis(tablename, con=engine, schema=schemaname, if_exists='replace', index=False).


text:
Q: array_pop() expects array, boolean given for $event_type_term ->slug I have the following function I wrote …
add_filter('post_type_link', 'events_permalink_structure', 10, 4);

function events_permalink_structure($post_link, $post, $leavename, $sample) {
    if ( false !== strpos( $post_link, '%event_type%' ) ) {
        $event_type_term = get_the_terms( $post->ID, 'event_type' );
        $post_link = str_replace( '%event_type%', array_pop( $event_type_term )->slug, $post_link );
    }
    return $post_link;
}

When creating a new post I get the following Warnings in the backend …

Warning: array_pop() expects parameter 1 to be array, boolean given in
  /Users/my/htdocs/wr/wp-content/themes/wr/functions.php on line 168
Notice: Trying to get property of non-object in
  /Users/my/htdocs/wr/wp-content/themes/wr/functions.php on line 168

Any ideas what I'm doing wrong here?
Thank you in advance!

A: get_the_terms() is probably returning false.
Do a print_r($event_type_term) to see what you have in it.
From: http://codex.wordpress.org/Function_Reference/get_the_terms

Array of term objects on success. False if no terms are found in the
  given taxonomy and a wp_error object if an invalid taxonomy is
  entered.


text:
Q: Using Redis variables as local session variables So my new portal project is running on PHP 7.2, using Laravel as the framework, and I'm wanting to use Redis as the Session Handler. I have it all set up and I thought everything was working correctly. I got the logins all setup and started some work on the main page when I asked someone to try logging in.
The setup is that when you login it saves a token to the database upon succession with a timer. Then I use Redis::set('token', *token*) and Redis::set('token_exp', *date and time of exp*) I know you can set tokens and stuff to automatically expire which I'll switch to after working on the project a bit more. But when the authentication method went to check and see if they were logged in, it saw the token for my log in.
I didn't realize that those weren't saving based on the session but rather publically. How do I make it so stuff set through Redis is only per session and not server-wide?
I could potentially use a key stored in $_SESSION to access the REDIS variables but I feel like that really defeats the purpose of using REDIS if I'm going to use $_SESSION anyway.

A: Redis is a facade for the direct connection to the redis server. Any data stored using a Redis::set is simply set on the redis instance.
To set something on the session, you can use it's facade:
\Session::put('token', 'xyz');

Documentation: https://laravel.com/docs/5.8/session#storing-data


text:
Q: TinyMCE doesn't work on all similar pages I have the TinyMCE sample with API key installed on a test page at https://myezwb.com/tinymce.htm - there is no other code on the page and the TinyMCE works great.
Now I have installed that same  at the top of 3 production pages at https://myezwb.com, just like I did on the test page.
It works on one page that has a single textarea but on similar pages with one or multiple textareas it won't work, with or without an API key.
I don't find any differences between the code or structure on the three pages and/or the test page.
What am I missing?
Thanks in advance.

A: The error:
tinymce.min.js:2 Failed to initialize the editor as the document is not in standards mode.
TinyMCE requires standards mode

explains the issue.  TinyMCE 5 requires the page in which it is loaded to be in Standards mode and not Quirks mode.
For more on this topic you can find lots of details online such as:

*

*https://developer.mozilla.org/en-US/docs/Web/HTML/Quirks_Mode_and_Standards_Mode

*https://www.quirksmode.org/css/quirksmode.html

*What is quirks mode?


text:
Q: SQL View - Combine multiple rows into 1 row I am trying to make a new view using in MSSql 2008 from three tables:
Table 1 has customer id and transaction id
Table 1
CustomerID      TransactionID
1                        1
1                        2

Table 2 has Purchases Transaction and Products ID
TransactionID    ProductID
1                     x
2                     y

Table 3 has Products Names
ProductID   Name
1            x
2            y

I view I would like to make should show
CustomerID  Product Name
1              x, y

When I use the following query:
SELECT     table1. CustomerID, table3.Name

FROM         table1 LEFT OUTER JOIN
                      Table2 ON table2. TransactionID    = table1.VisitId LEFT OUTER JOIN
                      Table3 ON table2. ProductID  = Table3. ProductID

                      GROUP BY table1. CustomerID, table3.Name

I get
CustomerID  Product Name
1           x
1           y

Thanks in Advance

A: One way to do this is to use a user defined function, something like:
SELECT table1.CustomerID, dbo.BuildStringOfCustomerProductNames(table1.CustomerID)
FROM table1

And create a user defined function like: dbo.BuildStringOfCustomerProductNames
that takes a customerid as input.
Inside there, you can run a query to loop through the table 2 and table 3 joined records to make a string, and return that.
Off hand I can't think of any other simple way to do it.


text:
Q: Docusign API review failed due to polling When I tried to do review before go to live in DocuSign, I was getting polling violation. My application uses embedded DocuSign with buyer will sign the embedded docusign and then seller will do the signing of same envelope Docusign.
So through application code I am taking the envelope id of the buyer signed envelope and passing to seller through app (all signing through application only).
So if seller sign the same envelope within 15 min(request to same envleop id), this polling violation happened.
But my application need this.
Maybe for passing review purpose If I do the request after 15 min and make it success also, after got to live if same thing happened, is there any problem?
How to solve polling violation in review before go to live?

A: First, read the Go-Live troubleshooting page if you haven't already.
What I think what you are doing is this:

*

*API call - create envelope

*API call  - get embedded signing for buyer

*API call - check envelope status

*API call - get embedded signing for seller

*API call - check envelope status
All of these within 15 min, which is what causing the violation.
Note that the issue is checking the status of the envelope twice within 15 min, not any API call. I would consider using the Connect webhook to determine the status of the envelope and eliminate the need to make multiple API calls to figure this out.

A: When the first signer completes the embedded signing ceremony, the signer's browser is redirected (by DocuSign) back to your application. And the event query parameter tells your app what happened during the signing ceremony (was it completed or something else).
At this point your app knows that the first signer finished. You can then make one call to DocuSign for the envelope status to confirm that the envelope was indeed signed by signer 1. (You should make the call since the redirect could have been spoofed by an attacker.)
Now you know that the envelope was signed by signer 1. You can now provide the signing ceremony to signer 2.
If you want your code to poll something to find out if signer 1 is done or not, you could poll a flag that your app sets for itself. You can't poll DocuSign more often than once per 15 minutes per envelope.
Also

Maybe for passing review purpose If I do the request after 15 min and make it success also, after got to live if same thing happened, is there any problem?

Don't do that! DocuSign also monitors applications in production and your app will be stopped at some point. The solution is to architect your app so you don't poll DocuSign. If you need to, you can poll your own app's database as often as you want. But I would recommend message passing instead.


text:
Q: Melhor forma de estruturar tabela de histórico com grande quantidade de dados Requisito funcional
Eu possuo dispositivos. Cada dispositivo, a grosso modo, possui seu identificador único, um endereço IP, e um tipo.
Eu tenho uma rotina de pings para todo dispositivo que possui um endereço ip.
Essa rotina nada mais é que um executável C#, que roda de 3 em 3 minutos e que tenta pingar o tal endereço IP do dispositivo.
O resultado do ping eu preciso guardar no banco de dados, bem como a data da verificação (independente do resultado do ping).
Parte Técnica:
Supondo que meu processo de ping e estruturação de banco esteja pronta a partir do dia 01/06/2016, eu preciso fazer duas coisas:

*

*Extração diária (que seja uma tabela alimentada)

*Extração em tempo real (ultimas 24 horas)

Ambas devem me retornar a mesma coisa:

*

*Dispositivos que estão indisponíveis há mais de 24 horas.

*Dispositivos que estão indisponíveis há mais de 7 dias.

Entende-se por indisponível o dispositivo que ao ser pingado, não respondeu o ping.
Entende-se por disponível o dispositivo que ao ser pingado, respondeu o ping com sucesso.
O que eu tenho hoje e funciona muito mal:
Uma tabela historico_disponibilidade, com a seguinte estrutura:
create table historico_disponibilidade (id_dispositivo number, respondeu number, data date);

Essa tabela possui grande quantidade de dados (hoje conta com 60 milhões, porém a tendência é crescer sempre exponencialmente)
As perguntas:

*

*Como atingir tais objetivos sem esbarrar em problemas de lentidão em queries?

*Como criar uma estrutura de tabela(s) que esteja preparada para receber milhões/bilhões de registros dentro do meu universo corporativo?

A: O problema não parece ser exponencial ou polinomial. Há alguns que são, aí não teria muito o que fazer. Se há uma implementação exponencial ou polinomial, tem que resolver isso, mas a pergunta não deixa claro como está sendo feito, me parece que nem é o caso.
O volume de linhas em uma tabela deve afetar muito pouco a performance de queries, desde que tenha os índices necessários e as próprias consultas não façam coisas muito esquisitas.
Mesmo que afete, a solução seria apagar os dados que não precisa mais. Se necessitar manter os dados apenas para efeitos históricos e não precisar mais manter consultas nos dados antigos (pelo menos não com frequência) a solução é ter uma tabela auxiliar que funcionaria como arquivo morto. Haveria uma transferência da tabela normal para essa de arquivo morto. Aparentemente só precisa manter os últimos 7 dias. Acho que nem preciso dizer que esta transferência pode ser automatizada. É possível usar ranges de dados para particionar as tabelas, mas não sei como isto funciona no Oracle.
Todos os bons bancos de dados do mercado, principalmente o Oracle, estão preparados para trabalhar com bilhões de linhas sem problemas. Se tiver um problema específico em uma query e não estiver achando uma solução (provavelmente com índice) aí vale postar em uma pergunta específica.
Note que a tabela é tão simples que não tem mais o que simplificar. A não ser que tenha coisas ocultas na pergunta.
Fico pensando se a rotina toda está errada. Me parece esquisito fazer o que está sendo feito, acho que é a solução certa para o problema errado, mas não vou entrar no mérito.