text:
Q: Generate custom CSV export from JSON data In one of my ModelAdmin tabs, I have a column containing JSON-encoded data which I want to convert into a CSV table and export. Most of the questions I've seen were exporting rows of data directly from tables but how about extracting the data from one of the columns first before converting it to a CSV table for export.
Any ideas will be greatly appreciated.

A: As you're using PHP and want to output as CSV, the first thing you should do is convert that JSON to Array. Then you can use some PHP functions to prompt the result as CSV. Let's code:
$arr = json_decode($jsonInput, true);
if(empty($arr)) {
     die("INVALID JSON");
}
$filename = "your-filename.csv";
$now = gmdate("D, d M Y H:i:s");
header("Expires: $now GMT");
header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
header("Last-Modified: {$now} GMT");
header("Content-Type: application/force-download");
header("Content-Type: application/octet-stream");
header("Content-Type: application/csv");
header("Content-Disposition: attachment;filename=$filename");
header("Content-Transfer-Encoding: binary");
$df = fopen('php://output', 'w');
fputs($df, $bom = ( chr(0xEF) . chr(0xBB) . chr(0xBF) ));
fputcsv($df, array_keys(reset($arr)), ';');
foreach($arr as $row) {
    fputcsv($df, $row, ';');
}
fclose($df);

A: @KikoGarcia, thanks for the input. However, it would be simpler to do it like this. Also, when I tried your code, it copies the whole page to the exported CSV file. There must be an exit(); included after fclose();.
After converting the JSON data to array, I had to loop through and create another array since there are nested data in it which I need for export. Once I got the final array, I call this function i.e.  $this->arrayToCSVExport($finalArr);
public function arrayToCSVExport($array, $filename = "backup.csv") {
header('Content-Type: text/csv; charset=utf-8');
header('Content-Disposition: attachment; filename="'.$filename.'";');
$bookdata = fopen('php://output', 'w');

// output the column headings
fputcsv($bookdata, array(
      'Customer Type',
      'Company Name',
      'Contact First Name',
      'Contact Last Name',
      'Contact Phone',
      'Contact Mobile',
      'Contact Email',
      'Contact Address',
      'Course Name',
      'Event ID',
      'Student First Name',
      'Student Last Name',
      'Student Phone',
      'Student Mobile',
      'Student Email',
      'Student Address',
      'Purchase Order'
));
foreach ($array as $user) {
   fputcsv($bookdata, $user);
}
fclose($bookdata);
exit();

}


text:
Q: DISM throws error with HRESULT=80310000 Got an error out of DISM when attempting to capture Surface Pro 3's existing image. I boot to WinPE via USB flash drive fine. I attached a second USB drive (Drive E:) AFTER WinPE boot, and check that I can navigate to it. I can, so I return back to the WinPE drive and then execute the command:
Dism /Capture-Image /ImageFile:E:\My_Win81.wim /CaptureDir:C:\ /Name:"July2015"

Dism errors out. Examination of the Dism log only reveals this one line:
wimmanager processed the command line but failed hresult=80310000

I've searched several sources and come up empty handed - Microsoft doesn't have any documentation that I've found on this DISM error, so I'm here asking if anyone's run into this before and what, if anything was your solution / workaround.
Note: Thinking it might have something to do with the second drive, I tried saving to the initial WinPE USB drive; same exact result.

A: Geeze. Nevermind - my brain is running on only one cup of coffee this morning. I need to shutdown BitLocker first before capturing an image.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Keyboard shortcut for Spotlight doesn't work in full screen Google Chrome on Mac OS X 10.7 (Lion) I've noticed that the Spotlight Search keyboard shortcut (cmd space) doesn't work if I'm running Google Chrome (12.0.742.122) as full screen application in Lion.
Is this a Chrome-related bug or is this inherent of some type of applications? Is there a way to fix it?

A: Chrome doesn't currently support Lion's full screen features. They are working on a version that does.
Until that is finished, you'll have to use Chrome's built-in full screen capabilities (not based on Lion's).
You can change the keyboard shortcut to enter that the same way you'd change any other (System Preferences-> Keyboard-> Keyboard Shortctus-> [+] button

A: Problem seems to be resolved in newer Chrome versions.

A: No such problem with Safari (just tried it). the way to fix it: just switch to safari :P it's the same webkit rendering engine as chrome (meaning it's the same speed) and now it's a whole lot nicer with some of the new lion features


text:
Q: PHP foreach loop I'm trying to write a script but keep getting stuck.
I have a variable $message. I want to parse it. So that everything contained between * and * could be a different color. For example:
This is message * 1

Wouldn't be effected. But
This is a *message* see how it works *again here*.

Would have message and again here in a different color.

A: With regexpes:
$in = 'This is a *message* see how it works *again here*.';
$out = preg_replace('/\*([^*]+)\*/', '$1', $in);
print $out;

little faster than non-greedy matches.

A: Use explode to split the string on the asterisks. After that, you can output each element in the array, with the right markup inbetween to change the color.
Something like this:
$parts = explode('*', $message);

$italic = false;
for ($part in $parts)
{
  if ($italic)
    echo '' . $part . '';
  else
    echo $part;

  $italic = !$italic;
}

A: I would suggest the use of preg_replace():
$message = preg_replace("#\*(.*?)\*#", "\\1", $message);

A: $output = preg_replace('/\*([^*]+)\*/', '$1', $message);

or
$output = preg_replace('/\*(.+?)\*/', '$1', $message);

A: $message = 'This is a *message* see how it works *again here*.';
$colorMessage =  preg_replace('/\*([^\*]+|[\w]+)\*/', "$0", $message);


text:
Q: Why is Voldemort so dumb? This was always odd to me, if Voldemort wanted his Horcruxes safe, why didn't he just turn his Horcrux into a grain of rice and leave it in the middle of the safari? And I know that Voldemort is a trophy collector or whatever, but this was his soul we're talking about! Surely he could use something unsuspecting?
I mean come on Voldemort, your mother's old house and the Room of Requirement, did he really think they were good places to hide his frickn' soul? I mean you may question the diary but no one really suspects it and it's used as more of a weapon than a safe guard.
Also in the Chamber of Secrets 16 year old Tom Riddle said this:

'You're dead Harry Potter,' said Riddle's voice above him. 'Dead. Even Dumbledore's bird knows it. Do you see what he's doing, Potter? He's crying'.

And then when Fawkes heals him Voldy's just like, oh yeah... phoenix tears.
How can he be so powerful and yet so dumb?

A: His own pride is his downfall.
Dumbledore addresses this:

"And they could be anything?" said Harry. "They could be oh, in tin cans or, I dunno, empty potion bottles..."
"You are thinking of Portkeys, Harry, which must be ordinary objects, easy to overlook. But would Lord Voldemort use tin cans or old potion bottles to guard his own precious soul? You are forgetting what I have showed you. Lord Voldemort liked to collect trophies, and he preferred objects with a powerful magical history His pride, his belief in his own superiority, his determination to carve for himself a startling place in magical history; these things, suggest to me that Voldemort would have chosen his Horcruxes with some care, favouring objects worthy of the honour."
"The diary wasn't that special."
"The diary, as you have said yourself, was proof that he was the heir of Slytherin. I am sure that Voldemort considered it of stupendous importance."
Harry Potter and the Half-Blood Prince, chapter 23: "insert chapter title here"

Voldemort's pride is what makes him decide to use grandiose objects for his Horcruxes. He's so overconfident that he didn't take Phoenix tears into account. It's why he battled Harry himself in the graveyard.
Voldemort's pride clouds his judgment and has always been his downfall.


text:
Q: sample same 1 million records in two applications with same logic I have two different applications which are running on two different machines.

*

*Application A is receiving data from Source A.

*Application B is receiving data from Source B.

Technically Source A and Source B are supposed to provide same data. Source A and B are not controlled by us. It is managed by some other team.
Now I want to sample records coming from both Source A and B in those two applications. If I am sampling 1 million records from Source A then I want to sample same 1 million records from Source B as well. I am using userId coming from both the source to sample the records. So given a userId I need to add some logic by which I can sample 1 million records. And then I will use same logic in both my applications to get same 1 million sampled records from both the source A and B.
We are getting bunch of userId's from both the sources and there is no specific pattern for that.
What is the algorithm and logic I should use for this so that I can sample 1 million records. I want to use the same logic in both the applications.. Is there any way to do this? I was thinking of using modulus here? I have the exact same below code in both of my applications:
  public void writeToDatabase(final Holder holder) {
    String userId = holder.getUserId();
    // how to make sure that we are storing only 1 million user data in database
    // and it should be same user data from both the system.
    // need some logic on userId

    // write to database
  }

After storing same data from both the sources (A and B), I need to do some data quality comparisons between those two sources. Basically, I will compare same 1 million userId data from Source A with Source B.
Note:
One million is just a number, 10,000 samples is also a fine or 5000 samples is also a fine.

A: Run a decent hash algorithm, and take all of the ids whose hash is below some threshold.  You want it fast, and secure doesn't matter.
For example if you take all user IDs whose MD5 hash starts with '00', you'll get approximately a half-percent of all records, and you'll get the same half-percent on both sides.  You need know nothing about the way they have selected hashes, and there should be no observable pattern.  You can adjust what range of hashes you accept in any way that you want.
(You will get much closer to 0.5% by taking the ones whose hashes are alphabetically less than '018AE'.  Or you can arrange any fraction that you want.)
Without knowing how many user IDs they have, I cannot tell you how many you will probably get.
(If the sources use different user IDs for the same person, well, then you've got your work cut out for you...)

A: Check out Reservoir Sampling: https://en.wikipedia.org/wiki/Reservoir_sampling
You could use reservoir sampling to select the first n records from Source A to ensure an equal chance of each record being chosen. The Algorithm R might be the relevant method for you. After you retrieve the samples from Source A, you can then use the User IDs for those samples to retrieve the same samples from Source B.
Keep in mind that this method will provide the most statistically random sample, but it does not use the same logic to sample from Source A  and Source B. In addition, if you do not store your data, you may not be able to find the correct User IDs from Source B if the dataset is too large.


text:
Q: AES-256 encryption: Generate 256bits(32bytes) key from my fixed string I would like to use AES256 to encrypt a text, I'd like to use my email test@gmail.com as the key to encrypt it.
This is what I tried:
String key = "test@gmail.com";
SecretKeySpec keySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

byte iv[] = SOME_RANDOM_32_BYTES;
IvParameterSpec ivSpec = new IvParameterSpec(iv);

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

byte[] encryptedResult = cipher.doFinal(text.getBytes("UTF-8"));

When I run above code, I got InvalidKeyException:
java.security.InvalidKeyException: Key length not 128/192/256 bits.

I checked on internet, the reason is my key is not 128/192/256 bits. My question is, how can I generate a 256bits(32bytes) key from my email string test@gmail.com ?

A: You can hash your key string (test@gmail.com) to a 256bit value using SHA256.
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(yourEmail.getBytes());
byte[] encryptionKey = md.digest();

A: There can be multiple reasons for this. One of them is below.
Usually this error comes when you don't have the update policy in your JRE.
Java by default provide AES with 128, for 256 we have to put new policies provided by Java.

A: You should not bake your own crypto! (Unless you are very knowledgeable on the matter, that is.)
You should use an existing (and audited) encryption library.
Also, you should not use a guessable string such as your e-mail address as a password. Please, look for advice on how to choose a good password.
Now that I have said this, here are more details.
The proper way to implement password based encryption is to use a KDF (Key Derivation Function) to generate an encryption key from your password. Here are a few KDFs that you can use for this task: Argon2, Scrypt, Bcrypt and PBKDF2.
Key derivation functions include mechanisms to defend against know attacks such as rainbow tables and dictionary attacks, notably a "salt" and a work factor. Modern KDFs such as Argon2 also attempt to prevent attackers from gaining an advantage by using hardware more suitable to the task.
Generally speaking, here how this is used:

*

*Select a work factor (the largest you can afford)

*Generate the salt using a CSPRNG

*Generate the encryption key and a MAC secret using your chosen KDF with the password, salt and work factor.

*Generate an IV (initialization vector) using a CSPRNG

*Encrypt the data to be protected using the generated encryption key.

*Compute the MAC of the encrypted message using the generated secret.

*Serialize the salt, the work factor, the computed MAC and the encrypted data.  (Optionally, identifiers indicating what are the chosen KDF, encryption scheme and MAC should also be included if these are not fixed.)

Your encrypted message is the serialized data produced in step 7. Get any of the steps wrong (and that is easy) and your encryption code will probably break in horrible ways.
Perhaps now you get a sense of why you should use an existing library?
Note: the current best practice is to use AEAD (Authenticated Encryption with Associated Data) instead of encrypt-then-MAC as described above. Look this up if you are interested: I am not going to discuss this here.


text:
Q: Net functions behave slightly different for IPv4 from IPv6. Why? I'm using BigQuery to truncate IPv4 & IP46 IP addresses. By that I mean I want to drop the part that might be used to identify a real person.
Here's some demo code:
select *,
        NET.IP_TO_STRING(NET.IP_TRUNC(NET.IP_FROM_STRING(v.IPv4Address), 24)),
        NET.IP_TO_STRING(NET.IP_TRUNC(NET.IP_FROM_STRING(v.IPv6Address), 64))
from (
  select struct(
     "254.34.78.20" as `IPV4Address`,
     "2a02:c7e:3f0d:e00:48e:abff:d697:9cc2" as `IPv6Address`
  ) as v
)

It returns:

v
f0_
f1_

{ "IPV4Address": "254.34.78.20", "IPv6Address": "2a02:c7e:3f0d:e00:48e:abff:d697:9cc2" }
254.34.78.0
2a02:c7e:3f0d:e00::

I'd simply like to know why these functions return a 0 for the truncated portion of the IPv4 address but nothing for the truncated portion of the IPv6 address.
I know this isn't really a BigQuery question per se as its more about networks and I suspect BigQuery is just doing what any other such library would do... but interested to know why this is nonetheless. Maybe I'll tag it with IPv6 too

A:
I'd simply like to know why these functions return a 0 for the
truncated portion of the IPv4 address but nothing for the truncated
portion of the IPv6 address.

It is returning 0 for the truncated part of the IPv6 address.
IPv6 addresses can have several forms, but the canonical form requires you to shorten the longest run of 0 fields with a double colon (::). That is at the end of your address 2a02:c7e:3f0d:e00::, and that means it is 2a02:c7e:3f0d:e00:0:0:0:0 properly shortened.


text:
Q: Using Cache-API not possible in Safari/Chrome on IOS, is that correct? Question
Can I or can I not use caching API with service workers on IOS in either Safari or Chrome as of IOS 13.1?
Background
I have a web app, that is to be used offline.
I use:

*

*Serviceworker

*Cache API

*IndexedDB

Works in Chrome on Windows/Android
Works as expected.
Does not work when offline on IOS
However, on IOS (13.1+), if you try to refresh (click refresh in browser) an html file when offline, the cache does not seem to work (you get the standard page not found error). This goes for Chrome as well as Safari.
Confusing information about caching API on IOS Safari
According to CanIUse, the caching API is not supported in Safari latest, which would explain the behaviour. I was not able to find information about Chrome for IOS support for cache, but I would guess it is not supported, if not in Safari.
I have found several sources that say caching API is supported in IOS Safari, so I am pretty confused.
Question again
Can I or can I not use caching API with service workers on IOS in either Safari or Chrome as of IOS 13.1?
I have deliberately not included any code examples, as the question is general and depends on whether the feature is supported in IOS Safari/Chrome or not. If it is possible to use the caching api, but I somehow implemented it wrong in code, that is for another specific post.

A: According to https://developer.mozilla.org/en-US/docs/Web/API/Cache#Browser_compatibility  cacheapi should be supported in desktop safari not in mobile. I found this post https://webkit.org/blog/8090/workers-at-your-service/ check the bottom they are waiting for your feedback :)
And for chrome according to https://chromestatus.com/feature/6461631328419840 it suppose to work. you can find who is responsible of the cache api in chrome and file a bug from that page.
over all I should say cache api looks like not used very much. because there is not much detailed posts on the topic.


text:
Q: In AWS how do I add an API key to my API? Hello:  I've been following two tutorials in the AWS documentation:
creating the sample pet store API (https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-create-api-from-example.html)
...and creating an API key (https://docs.aws.amazon.com/apigateway/latest/developerguide/api-gateway-setup-api-key-with-console.html#api-gateway-usage-plan-create-apikey).
When I test the pet store get method with the provided URL, it returns:

Welcome to your Pet Store API You have successfully deployed your
first API. You are seeing this HTML page because the GET method to the
root resource of your API returns this content as a Mock integration.
The Pet Store API contains the /pets and /pets/{petId} resources. By
making a GET request to /pets you can retrieve a list of Pets in your
API. If you are looking for a specific pet, for example the pet with
ID 1, you can make a GET request to /pets/1.
You can use a REST client such as Postman to test the POST methods in
your API to create a new pet. Use the sample body below to send the
POST request:
{
"type" : "cat",
"price" : 123.11 }

Now I go to the API Gateway -> API -> Resources ->  -> Method Request -> API Key Required and change it to "True" and redeploy.
When I go to the provided URL to test, now the page returns:

{"message":"Forbidden"}

Which makes sense... I told it API required = true, right?
So my question is, how do I pass the API key?  So that I don't get the "forbidden" result?  I didn't see that in the tutorial links I pasted above and haven't been able to find elsewhere.

A: *

*You Create a Usage Plans

*Attach this usage plan to your API and Stage

*Create an API Key

*Now invoke your API with header named x-api-key and value of it is the API Key created in step-3

Sample:
curl -i -H "x-api-key: Cd2YiWs8Fv8Lg6njI0wXf1iiNOE94XjM3EQe8567" -X GET https://7r9cvghbf4.execute-api.ap-northeast-2.amazonaws.com/dd/pets

A: Assuming you've followed all steps for creating the API key you can use this API key by specifying it in the x-api-key header within your request.

You distribute API keys to your customers and require them to pass the API key as the X-API-Key header of each incoming request.

More information for using API keys in API Gateway is available on: Choose an API key source - Amazon API Gateway


text:
Q: Integrity Constrains Violation issue : Cakephp 3.x I just want to import csv file data to the database table. All fields were inserted successfully except my custom field that is date field(added_date).
It is display the error that.
Error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'added_date' cannot be null

And below is my code for insertion csv data.
while (($emapData = fgetcsv($file, 10000, ",")) !== FALSE)
{
    $rs[$cnt]['client_id'] = $emapData[0];
    $rs[$cnt]['name'] = $emapData[1];
    $rs[$cnt]['address1'] = $emapData[3];
    $rs[$cnt]['address2'] = $emapData[4];
    $rs[$cnt]['county'] = $emapData[8];
    $rs[$cnt]['city'] = $emapData[6];
    $rs[$cnt]['country'] = $emapData[8];
    $rs[$cnt]['postcode'] = $emapData[7];
    $rs[$cnt]['email_label'] = $emapData[14];
    $rs[$cnt]['time_spent_on_site'] = $emapData[20];
    $rs[$cnt]['added_date'] = date('Y-m-d H:i:s'); <== gives error that integrity constrains violation.

    $cnt++;
}

fclose($file);

if (count($rs) > 0)
{
    $customers = TableRegistry::get('Customers');
    $entities = $customers->newEntities($rs);

    $customers->connection()->transactional(function () use ($customers, $entities) {
        foreach ($entities as $entity)
        {
            $customers->save($entity);
        }
    });
}

And database table structure is as follows:

Thanks you so much.

A: Its concept introduce in Cakephp 3.x that we need to use
$rs[$cnt]['added_date'] = new \DateTime('now');
in place of
$rs[$cnt]['added_date'] = date('Y-m-d H:i:s'); //Deprecated in Cakephp 3.x
Thank you so much for your approach.


text:
Q: React JS: console.debug is not a function I'm running a ReactJs web app, my web running well in webpack-dev-server,
but chrome/firefox console always got "Uncaught TypeError: console.debug is not a function" after I bundle my codes, I have no idea how to solve this.

A: try adding node: { console: true } and debug: true in webpack config file.


text:
Q: String used in recv() does not printf as it should I am trying to write a server-client program for practice but I'm having trouble with the the string I use in the recv() function.
void *recieve_handler(void *socket_desc){
int client_sock = *(int*)socket_desc;
int data_len;
char client_message[BUFFER_SIZE];

data_len = 1;

while (data_len > 0){
    data_len = recv(client_sock, client_message, BUFFER_SIZE, 0);
    client_message[data_len-1] = '\0';
    printf("%s\n", client_message);
    printf("ME:");
}
close(client_sock);

}

I would like after I receive the string from the client to print it and then print a label in the next line.
The problem is whatever I try,I keep getting this outcome:
"1st message from client"
[buffer]

and then when the client sends another message it prints along with me ME: label in front of it.
ME: "2nd message from client"

I need to have the label printed with the 1st message.

A: try to flush the stdout fflush(stdout); after printing ME:
e.g.
printf("%s\n", client_message);
printf("ME:");
fflush(stdout);


text:
Q: Create an AzureBlobDatastore() with SDK-V2 I am trying to create an AzureBlobDatastore() via the azure-sdk-v2. Previously, I successfully managed to perform the same operation via azure-sdk-v1 (from tutorial link in the next paragraph).
I am following this tutorial : https://learn.microsoft.com/en-us/azure/machine-learning/migrate-to-v2-resource-datastore#create-a-datastore-from-an-azure-blob-container-via-account_key in order to set up/create my AzureBlobDatastore().
This is the code that I am using (like in the tutorial, only updating the parameters in MLClient.from_config() (if I don't use the credential parameter I get an error stating that the parameter is empty):
ml_client = MLClient.from_config(credential=DefaultAzureCredential(),
                                 path="./workspace_config_sdk2.json")
store = AzureBlobDatastore(
    name="azureml_sdk2_blob",
    description="Datastore created with sdkv2",
    account_name=storage_account_name,
    container_name=container_name,
    protocol="wasbs",
    credentials={
        "account_key": "..my_account_key.."
    },
)

ml_client.create_or_update(store)

I get the following error:

AttributeError: 'dict' object has no attribute
'_to_datastore_rest_object'

Note that the workspace_config_sdk2.json config has the following scheme:
{
    "subscription_id": "...",
    "resource_group": "...",
    "workspace_name": "..."
}

How can I solve this error?
EDIT: On investigating the issue, it seems that it falls back to some code in "azure\ai\ml\entities\_datastore\azure_storage.py"
    175 def _to_rest_object(self) -> DatastoreData:
    176     blob_ds = RestAzureBlobDatastore(
    177         account_name=self.account_name,
    178         container_name=self.container_name,
--> 179         credentials=self.credentials._to_datastore_rest_object(),
    180         endpoint=self.endpoint,
    181         protocol=self.protocol,
    182         tags=self.tags,
    183         description=self.description,
    184     )
    185     return DatastoreData(properties=blob_ds)

AttributeError: 'dict' object has no attribute '_to_datastore_rest_object'


text:
Q: why are results of message queue on macOS and Ubuntu different Recently I'm learning process communication on Linux. And I wrote a C program to do the following things:

*

*Process A sets up a message queue(like a mailbox)

*Process B sends three messages "111", "222", "333" in order to the queue.

*Process C reads messages in an order of "333", "111", "222" from the queue.

*Process D deletes the queue.

I firstly wrote this program on Ubuntu 16.04 and it worked fine just as I thought:
Results on Ubuntu 16.04
However, when I compiled the same code and tried to run on macOS(Sierra 10.12.3), results are different from those on Ubuntu:
Results on macOS
No matter how I make changes to the code(e.g. sleep for a few seconds in Process A), the queue is always deleted before the third message sends.
Here is my code:
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/msg.h>
#include <sys/types.h>
#include <errno.h>

#define MAX_TEXT 1024

struct mymsg123
{
        long int priority;
        char text[MAX_TEXT];
};

int main()
{
    int msgid = -1; //message id
    struct mymsg123 data; //message to send

    //set up message queue(mailbox) in Process A
    msgid = msgget((key_t)1234, 0666 | IPC_CREAT);
    if(msgid == -1)
    {
            fprintf(stderr, "msgget failed in Process A with error: %d\n", errno);
            exit(EXIT_FAILURE);
    }
    printf("Mailbox created in Process A\n");

    pid_t pid = fork(); //to create Process B
    if (pid < 0) {fprintf(stderr, "Fork failed in Process A"); exit(EXIT_FAILURE); }
    //child Process B
    else if (pid == 0)
    {
        const char msg1[] = "111";
        //set the first message
        data.priority = 2;
        strcpy(data.text, msg1);
        //send the first message
        if (msgsnd(msgid, (void*)&data, MAX_TEXT, 0) == -1)
        {
            fprintf(stderr, "msgsnd failed in Process B when sending msg1\n");
            exit(EXIT_FAILURE);
        }
        printf("Sent msg %s, priority %ld to mailbox\n", data.text, data.priority);

        const char msg2[] = "222";
        //set the second message
        data.priority = 3;
        strcpy(data.text, msg2);
        //send the second message
        if (msgsnd(msgid, (void*)&data, MAX_TEXT, 0) == -1)
        {
            fprintf(stderr, "msgsnd failed in Porcess B when sending msg2\n");
            exit(EXIT_FAILURE);
        }
        printf("Sent msg %s, priority %ld to mailbox\n", data.text, data.priority);

        const char msg3[] = "333";
        //set the third message
        data.priority = 1;
        strcpy(data.text, msg3);
        //send the third message
        if (msgsnd(msgid, (void*)&data, MAX_TEXT, 0) == -1)
        {
            fprintf(stderr, "msgsnd failed in Process B when sending msg3\n");
            exit(EXIT_FAILURE);
        }
        printf("Sent msg %s, priority %ld to mailbox\n", data.text, data.priority);
    }
    //parent Process A
    else
    {
        pid_t pid = fork(); //to create Process C
        if (pid < 0) {fprintf(stderr, "Fork failed in Process A"); exit(EXIT_FAILURE); }
        //child process C
        else if (pid == 0)
        {
            //receiving priority 1 message
            long int priority = 1;
            if(msgrcv(msgid, (void*)&data, BUFSIZ, priority, 0) == -1)
            {
                fprintf(stderr, "msgrcv failed with error in Process C when receiving priority 1 msg: %d\n", errno);
                exit(EXIT_FAILURE);
            }
            printf("Received priority 1 message in Process C from mailbox: %s\n", data.text);
            //receiving priority 2 message
            priority = 2;
            if(msgrcv(msgid, (void*)&data, BUFSIZ, priority, 0) == -1)
            {
                fprintf(stderr, "msgrcv failed with error in Prcess C when receiving priority 2 msg: %d\n", errno);
                exit(EXIT_FAILURE);
            }
            printf("Received priority 2 message in Process C from mailbox: %s\n", data.text);
            //receiving priority 3 message
            priority = 3;
            if(msgrcv(msgid, (void*)&data, BUFSIZ, priority, 0) == -1)
            {
                fprintf(stderr, "msgrcv failed with error in Process C when receiving priority 3 msg: %d\n", errno);
                exit(EXIT_FAILURE);
            }
            printf("Received priority 3 message in Process C from mailbox: %s\n", data.text);
        }
        //parent Process A
        else
        {
            pid_t pid = fork(); //to create Process D
            if (pid < 0) {fprintf(stderr, "Fork failed in Process A"); exit(EXIT_FAILURE); }
            //child process D
            else if (pid == 0)
            {
                //sleep(10);
                if (msgctl(msgid, IPC_RMID, 0) == -1)
                {
                    fprintf(stderr, "msgctl(IPC_RMID) failed in Process D\n");
                            exit(EXIT_FAILURE);
                }
                printf("Mailbox deleted in Process D\n");
            }
            //parent Process A
            else
                ;
        }
    }
    //sleep(10);

    exit(EXIT_SUCCESS);
}

Advanced thanks!

A: It would be helpful if you printed the error message itself, rather than just the error codes.
Anyway, I think this is happening because the message queue size appears to be 2048 bytes on macOS, but is usually something like 16384 on Linux. Coupled with your MAX_TEXT size of 1024, the third message cannot be sent as the queue is full. It may block until the first msgrcv call dequeues the first message, freeing up space, but macOS doesn't give man pages for this, so I'm going off the Linux pages.
Regardless, you have a race condition, because process D will delete the message queue immediately, without waiting for it to become empty. Thus, if process B blocks because the queue is full, and process D deletes it, B will return with an error. But this is all dependent on the scheduling of the processes, thus the race condition.
You can change the queue size in macOS, but you need to have superuser privileges for it to take effect. You could verify this without running as root by decreasing your MAX_TEXT define to something like 128 and verifying that it works on both.


text:
Q: Advanced Security Permissions for Shared Drive I have a large, shared drive of folders that are automatically created when a client is added to software that we use. I want to allow users to access the folders on the top level of the drive but not write, edit, delete or move any of these (read only). I also want them to be able to access the folders underneath the top folders in the drive with full read/write privileges.
For example:
 Drive X: (shared drive)
 |
 +-- 1. Top Folder 1 (read only)
 |      |
 |      +-- lower folder/files (read/write)
 |      |
 |      +-- lower folder/files (read/write)
 |
 |
 +-- 2. Top Folder 2 (read only)
 |      |
 |      +-- lower folder/files (read/write)
 |      |
 |      +-- lover folder/files (read/write)

How do I achieve this?

A: You can accomplish your goal with what I call Top Level Folder Permissions.
Summary

*

*On the drive's root, grant Read permissions to your users which flow down to all subfolders and files throughout the drive.

*On each "Top Level" folder in the root drive, apply special permissions that grant users Modify permissions to the folders' contents (all files and subfolders) but not to the Top Level folders themselves.

Steps to Implement

*

*On the Root drive, grant Everyone (or another group of your choice) standard Read permissions

*Optionally, on the Root drive, consider ensuring SYSTEM and Administrators are granted Full Control, then remove all other permissions (e.g. those granted to CREATOR OWNER or Users)

*On each Top-Level folder:

*

*Grant the Everyone group Modify permissions, then edit that permission assignment in the Advanced Security Settings to apply to Subfolders and files only

*Still in Advanced Security Settings make another entry granting the Everyone group the following specific permissions and apply these to This folder only:

*

*Create files / write data

*Create folders / append data

*Repeat step #3 for each Top Level folder

How it Works
The effect of #1 is to grant your security group the ability to Read everything on the drive.
The effect of #3 is to grant your security group the ability to Modify all child objects of your Top Level folders without granting them permission to modify the Top Level folders themselves.  This isn't sufficient to permit them to Create anything in the Top Level folders, hence the extra explicit 'create' permissions.
Apply to Many Top Level Folders
The permissions of step #3 above must be applied to each "Top Level" folder. This can be time consuming if you have many folders. These permissions can be applied to all subfolders in the drive's root using the FOR and ICACLS run in an Elevated Command Prompt:
For /D %f In (C:\*.*) Do ICACLS "%f" /grant "Everyone":(OI)(CI)(IO)(M)
For /D %f In (C:\*.*) Do ICACLS "%f" /grant "Everyone":(WD,AD)

As shown, these two commands will modify all subfolders in C:\ to grant the permissions outlined in step #3 to the Everyone group.  Modify these two elements to suit your needs. Test first before running on a production system!


text:
Q: CSS counter increment does not work as expected I don't really understand why the counter doesn't increment the h3 elements.
https://jsfiddle.net/Lqcqzta6/

XXXX

YYYY

ZZZZ

ZZZZ

ZZZZ

YYYY

ZZZZ

ZZZZ

ZZZZ

I found an example that explains something similar, but that problem was about elements that didn't have the same direct parent. These have.
Multiple CSS counters not working as expected

A: Its because you have applied counter-reset: h3counter in the wrong place i.e. h2:before. You will need to apply counter-reset: h3counter to the
 tag not its :before

h1 {
  counter-reset: h2counter;
}

h2 {
  counter-reset: h3counter;
}

h2:before {
  content: counter(h2counter) ".\0000a0\0000a0";
  counter-increment: h2counter;
}

h3:before {
  content: counter(h2counter) "." counter(h3counter) ".\0000a0\0000a0";
  counter-increment: h3counter;
}

  XXXX

  YYYY

  ZZZZZZ

  ZZZZZZ

  ZZZZZZ

  YYYY

  ZZZZZZ

  ZZZZZZ

  ZZZZZZ

A: You can't reset in the pseudo element before for you h2 instruction.

h1 {
  counter-reset: h2counter;
}

h2 {
  counter-reset: h3counter;
}

h2:before {
  content: counter(h2counter) ".\0000a0\0000a0";
  counter-increment: h2counter;
}

h3:before {
  content: counter(h2counter) "." counter(h3counter) ".\0000a0\0000a0";
  counter-increment: h3counter;
}

h1 - 1

h2 - 1

h3 - 1

h3 - 2

h3 - 3

h2 - 2

h3 - 1

h3 - 2

h3 - 3


text:
Q: Prove some identites. Prove the following identity. I do not know where to start. Any help would be most welcome. Thank you very much.
$$
\int_0^1 \left[-\frac{1}{x} + \frac{1}{x\sqrt{1+x}}\right]dx=\sum_{l=1}^\infty \binom{-1/2} {l} \frac{1}{l}
$$
$$
\int_0^1 \left[-\frac{1}{x^3}+ \frac{1}{x^3 \sqrt{1+x}}+\frac{1}{2 x^2 \sqrt{1+x}}-\frac{1}{8 x  \sqrt{1+x}} \right]dx=\sum_{l=3}^\infty\binom{-1/2}{l} \frac{1}{l-2}
    +\ \ \  \ \ \ \ \ \ \ \ \ \ \ \ \ +\frac{1}{2} \sum_{l=2}^\infty \binom{-1/2}{l} \frac{1}{l-1}
    - \frac{1}{8}\sum_{l=1}^\infty \binom{-1/2}{l} \frac{1}{l}
$$

A: The right hand side of your first identity is nothing else than the integral of $\dfrac1x$ times the binomial series expansion for $(1+x)^{^{-\frac12}}=\dfrac1{\sqrt{1+x}}$ calculated at $x=1$. A similar approach applies to the right hand side of your other identity as well.

$$\int_0^1\left[-\frac{1}{x}+\frac{1}{x\sqrt{1+x}}\right]dx=\int_0^1\frac{1}{x}\left[\frac{1}{\sqrt{1+x}}-1\right]dx=\int_0^1\frac{1}{x}\left[\sum_{l=0}^\infty{-\frac12\choose l}x^l-1\right]dx=$$
$$=\int_0^1\frac{1}{x}\left[1+\sum_{l=1}^\infty{-\frac12\choose l}x^l-1\right]dx=\sum_{l=1}^\infty{-\frac12\choose l}\int_0^1x^{l-1}dx=\sum_{l=1}^\infty{-\frac12\choose l}\frac{x^l}l|_0^1=$$
$$=\sum_{l=1}^\infty{-\frac12\choose l}\frac1l$$


text:
Q: XAML StackPanel divided is it possible in XAML to separate in a StackPanel control (or any container in general) rows and columns with lines? So that it looks for example like a chessboard? And also when the user resizes the window, the panel would also resize.

A: The only one of the built in Panels that draws lines is a Grid with ShowGridLines="True" set on it but the lines drawn are just kind of ugly dashed lines that can't be changed and are really only good for debugging purposes.
To draw your own lines you can just add an identical border into each cell, or each row or column if you want them to stretch across the whole layout. The easiest way to do a chessboard layout is with a UniformGrid:
<UniformGrid Rows="2" Columns="2">
    <Border BorderBrush="Gray" BorderThickness="1" />
    <Border BorderBrush="Gray" BorderThickness="1" />
    <Border BorderBrush="Gray" BorderThickness="1" />
    <Border BorderBrush="Gray" BorderThickness="1" />
</UniformGrid>

For a full board you can save typing and use an ItemsControl bound to some 64 item collection with a template for the lines:
<ItemsControl ItemsSource="{Binding ListOf64Items}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Border BorderBrush="Gray" BorderThickness="1"/>
        </DataTemplate>
    </ItemsControl.ItemTemplate>
    <ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <UniformGrid Rows="8" Columns="8"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
</ItemsControl>

There are also lots of possible variations depending on what exactly you want out of the grid.


text:
Q: Auto addition of text within cells of column A if one enters a number in the same cell of the column I am complete novice in Google script, but have a little bit of knowledge of spreadsheet formula and function.
I need that if my user enter any number in a cell in column A (say, 123 in A1), it automatically gives out in the same cell (as a drop-down list) two options - LAPL/2K17/123 and LA/2K17/123 - to choose from.
I don't think it is possible to achieve through spreadsheet funcions, is it even possible through Google Script as the same cell in which the data is being entered has to have the changed text?

A: here is an option- not exactly what you are looking for, however it may function for you.

function onEdit(e){
var ss = SpreadsheetApp.getActiveSheet();
var resp = ss.getDataRange().getValues();
for(var n=0;n<resp.length;n++)
{
  for(var p=0;p<resp[n].length;p++)
  {
    if(resp[n][p].toString().match(/^123/)) {

  var ui = SpreadsheetApp.getUi(); // Same variations.

  var result = ui.alert(
     'Please confirm',
     'LAPL/2K17/123?',
      ui.ButtonSet.YES_NO);

  // Process the user's response.
  if (result == ui.Button.YES) {
    // User clicked "Yes".
    ui.alert('Setting Value to LAPL/2K17/123');
    ss.getRange(n+1,p+1).setValue('LAPL/2K17/123')
  } else {
    // User clicked "No" or X in the title bar.
    ss.getRange(n+1,p+1).setValue('LA/2K17/123')
    ui.alert('Setting Value to LA/2K17/123');
  }

    };
  }
}};


text:
Q: Serialize form data into JSON object I'm trying to serialize a form data into a JSON Object, but I get stuck when I need to create the carts object.
What I want to achieve after getting all the data in the form is an Object like the snippet below. How can I do this?
So you can see and test the full code here http://jsbin.com/OyAzAZA/3/
{
  "client_id": 1,
  "carts": [
    {
      "cart_id": 1,
      "items": [
        {
          "code": "01",
          "descrption": "text 1"
        },
        {
          "code": "02",
          "descrption": "text 2"
        }
      ]
    },
    {
      "cart_id": 2,
      "items": [
        {
          "code": "03",
          "descrption": "text 3"
        },
        {
          "code": "04",
          "descrption": "text 4"
        }
      ]
    }
  ]
}

A: This is the code that gets you the specified JSON:
$(function() {
    $('form').on('click', 'button', function() {
        var clientId = $('form').find('input[name="client_id"]').val(),
        $tables = $('form').find('table'),
        data = {};

        data.client_id = clientId;
        data.carts = [];

        $.each($tables, function(i, v) {
            var cart = {};
            cart.cart_id = $(v).attr('id');
            cart.items = [];
                $rows = $(v).find('tr');

            $.each($rows, function(i, v) {
              var item = {};
                item.code = $(v).find('input[name="code"]').val();
                    item.description = $(v).find('input[name="description"]').val();
              cart.items.push(item);
            });
          data.carts.push(cart);
        });
    console.log(data);
});
});


text:
Q: Mongo: how to group documents of a collection based on a key which is a property of a inner document I have a collection of documents, each representing a vote for a movie. Each document contains an inner document which describes the movie. Something like this
{movie: {_id: '123', name: 'fargo'}, vote: 'good'},
{movie: {_id: 'abc', name: 'fargo'}, vote: 'good'},
{movie: {_id: 'abc', name: 'fargo'}, vote: 'bad'},
{movie: {_id: 'xyz', name: 'fargo'}, vote: 'good'},

For whatever reason, over time, the same movie 'fargo' has been marked with different _id, but it is the same movie. In other words, the real key for a movie is the name, not _id as it usual to imagine.
Now what I would like to do is to group, via aggregation pipeline, all movies with the same name, ignoring the fact that they may have different _ids, and count the number of good and bad votes they have received.
So, in the case of the example, I would like to receive as result of the aggregation something like
{name: 'fargo', votes: [
  {vote: 'good', count: 3},
  {vote: 'bad', count: 1}
]}

So far I have tried
{$group: {_id: {movieName: "$movie.name", vote: "$vote"}, count: {$sum: 1}, }}
but with no luck.
Any suggestion to understand where I make a mistake would be appreciated.

A: This is what you are looking for:
[
    {$project: {
      _id: "$movie.name",
      "good": {$cond: {if: {$eq: ["$vote","good"]}, then: 1, else: 0}},
      "bad": {$cond: {if: {$eq: ["$vote","bad"]}, then: 1, else: 0}}
    }},
    {$group: {
      _id: "$_id",
      good: {$sum: "$good"},
      bad: {$sum: "$bad"}
    }}
]

Output (for your sample documents):
{
  "_id" : "fargo",
  "good" : 3.0,
  "bad" : 1.0
}

Explanation of the pipeline stages:

*

*Project: use the name of the move as _id and represent good and bad votes numerically

*Group: count each vote individually for every film


text:
Q: Is it possible to step into a member function defined in a .dll file? I downloaded an SDK from NVIDIA and I'm using Visual Studio 2015 to run the demo project files provided in the SDK.
The demo project files in the SDK worked as expected until I made some small changes in the code (If you'd like details about the changes, please see last paragraph).
After making these changes, a line in the code seems to run forever. Using the debugger I found that there's a member function in that line of code that is not returning anything and therefore the program flow is just stuck at that line. I tried stepping into this function but it's defined in a .dll file that came with the SDK.
Visual Studio tells me that the symbol file is not loaded and the PDB file cannot be found on the Microsoft Server. The debugger lets me see the disassembly code but I don't know if I can identify the problem using that.
So now I'm stuck at a line of code because the member function defined in a .dll file won't return anything and just keeps on running (I've left it running for over an hour and still it didn't return anything).
I want to identify the reason why this is happening, but I'm unable to see the source code of the member function so I have no idea what's happening inside the member function or how to debug it. Is there any way I can identify the cause of this problem? Is it possible to somehow see the source code of the member function in a way that I can understand what is going on?
More details on changes I made:
I've separated this from main body of the question because I don't see it as being very relevant but it may be useful for the answerer. The SDK stitches videos together into a single video (creating 360 view videos). The demo project works fine as long as I use the demo video files. The video files are fed into the project using command line arguments. When I feed my own video files to the demo project, that's when I face this problem, otherwise the member function returns successfully and the project successfully creates a stitched video. The only thing I changed is the input to the project (i.e. the video files), I haven't changed the source code at all.

A: If the provider of the DLL doesn't deliver the source code, you obviously can't see it. That would be the common way to handle it - unless they are open source, their source code is the company's intellectual property, so of course they are not showing it to you.
If it is open source, you typically can download the debug-DLLs (which contain the source code). Microsoft also delivers many runtime DLLs in version with source code (but of course not Windows itself). Check in the SDK if there is a debug version of that DLL, and link with it instead of the one you are currently using.
So, in a nutshell, you can't see it unless they give it to you.

A: As stated by VTT and Aganju, I cannot step into the member function defined in the DLL unless the source code is provided to me with the DLL. This answers what I asked. For my specific case, I was working with NVIDIA VRWorks 360 Video SDK, the problem was caused by not having the right codec for the video files that get stitched. Although this is mentioned nowhere in the SDK documentation, the video codec that should be used is H264 - MPEG-4 AVC (part 10) (AVC1).


text:
Q: Maintain hundred of customized branches over master branch Currently we are having one main master branch for our PHP application in shared repository. We have more than 500 clients who are subscribing our software. For different purposes, most of them are having some customization in their project. The customization can from only text field name, up to totally new feature and module, or new table/column in database.
The challenges that we are facing is we maintain hundreds of customized branches and distribute to clients. From  time to time, we provide new feature and update our master branch, then we would like to push master branch changes to customized branch, in order to update customized branch to latest version.
  Unfortunately this will result in a lot of conflict for customized code vs master code. We need many manpower to go through every single branch and solve all the conflict. This is very inefficiency way and human mistake keep happen when we are solving the conflict.
I am looking for efficiency way to maintain all customized codes in own client's release branch, but they can keep update with master branch when we are releasing new feature, with only minimal effort to merge the coding.

A: I don't think there is a quick and easy answer to this. The fact that there is so much customization allowed in your product basically means you have 500 seperate products.
In my opinion the first step would be to seperate the core product from all the customization. Then create a seperate repository where you keep all your client branches and treat the core product as a dependancy. You could do this by way of a git-submodule or with some sort of dependancy package solution.
This way each client depends on a particular version of your core product, and you can control when a certain client get's upgraded to a newer release.
Of course this means you core product will have to support some form of feature toggles and/or module overrides that allow the customization to take place.


text:
Q: Marionette Application with Multiple Entry Points Currently the application that I am building is a single page marionette application with a single entry point. When the user is at "/" I pass a very simple jade document:
 body

    header

    section
        div#main

script(src='/javascripts/lib/require.js', data-main='/javascripts/application.js')

The only javascript that I am loading to this is my require.js page, and once that's loaded I start things with Backbone.Marionette.Application() and thats the only app object I create for the whole app and that takes care of everything.
define([
  'zepto', 'marionette', 'router', 'events'],
function ($, Marionette, router, Event) {
    // set up the app instance
    var MyApp = new Backbone.Marionette.Application();

    MyApp.addRegions({
      main: "#main"
    });

    MyApp.addInitializer(function(){

    });

    MyApp.on("initialize:after", function(){
        var newRouter = new router(MyApp);
        Backbone.history.start();
    });

    MyApp.start();
    return MyApp;

});

If I have multiple entry points (in other words, multiple html pages created in the server side) for example one for "Classroom", one for "User Profile" one for "Discussion" , does that mean I need separate require.js documents to load for each page and separate Backbone.Marionette.Application() objects?

A: You don't have to otherwise it's too troublesome :) That's the job of Route.
At first, don't start app right away in the app definition. Remove this line
MyApp.start();

Then, put such command at the footer of your html page, and better after dom ready
$(function(){
  MyApp.start();
});

The third is the most important. You need to define your routes in App or sub app(better). Here is the code "borrowed" from BBCloneMail
BBCloneMail.module("ContactApp", {
  startWithParent: false,
  define: function (ContactApp, App, Backbone, Marionette, $, _) {

    var Router = Marionette.AppRouter.extend({
      before: function() {
        App.startSubApp("ContactApp", {});
      },

      appRoutes: {
        "contacts": "showContacts"
      }
    });

In above case, when visitor enters your app from example.com/contacts, the method showContacts will be trigger and that's the start of your arranging page specific logic.
For more about appRouter:
https://github.com/marionettejs/backbone.marionette/blob/master/docs/marionette.approuter.md


text:
Q: Get message and title From Push Notification GCM to activity I have try to get a message and title from gcm push notification to the activity but it's not work. Here my code below:
sendNotification in GcmIntentService.java Class:
private void sendNotification(String msg) {
        mNotificationManager = (NotificationManager)
                this.getSystemService(Context.NOTIFICATION_SERVICE);

        Intent intent = new Intent(this, NotificationActivity.class);
        intent.putExtra("message", msg);

        intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP| Intent.FLAG_ACTIVITY_SINGLE_TOP);

        Log.e("message", msg);

        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent , 0);

        NotificationCompat.Builder mBuilder =
                new NotificationCompat.Builder(this)
                        .setContentTitle(getResources().getString(R.string.app_name))
                        .setSmallIcon(R.mipmap.ic_launcher)
                        .setStyle(new NotificationCompat.BigTextStyle()
                                .bigText(msg))
                        .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
    }

NotificationActivity.java Class
Toast.makeText(this, "message"+ getIntent().getStringExtra("message"), Toast.LENGTH_LONG).show();

Thank You!

A: try this:
//onCreate() or onNewIntent() method
bundle = getIntent().getExtras();
if (bundle != null && bundle.getString("message") != null) {
    Toast.makeText(this, "message"+ getIntent().getExtra().getString("message"), Toast.LENGTH_LONG).show();

}

add above condition


text:
Q: Titan cassandra does not use defined indexes for custom gremlin steps We have defined 5 indexes using titan cassandra in the follow block of code
 def mgmt = g.managementSystem;
 try {
     if (!mgmt.containsGraphIndex("byId")) {
         def key = mgmt.makePropertyKey('__id').dataType(String.class).make()
         mgmt.buildIndex("byId",Vertex.class).addKey(key).buildCompositeIndex()
     }
     if (!mgmt.containsGraphIndex("byType")) {
          def key = mgmt.makePropertyKey('__type').dataType(String.class).make()
         mgmt.buildIndex("byType",Vertex.class).addKey(key).buildCompositeIndex()
     }
     if (!mgmt.containsGraphIndex("lastName")) {
         def key = mgmt.makePropertyKey('lastName').dataType(String.class).make()
         mgmt.buildIndex('lastName',Vertex.class).addKey(key).buildMixedIndex(INDEX_NAME)
     }
     if (!mgmt.containsGraphIndex("firstName")) {
         def key = mgmt.makePropertyKey('firstName').dataType(String.class).make()
         mgmt.buildIndex('firstName',Vertex.class).addKey(key).buildMixedIndex(INDEX_NAME)
     }
     if (!mgmt.containsGraphIndex("vin")) {
         def key = mgmt.makePropertyKey('vin').dataType(String.class).make()
         mgmt.buildIndex('vin',Vertex.class).addKey(key).buildMixedIndex(INDEX_NAME)
     }
     mgmt.commit()
 } catch (Exception e) {
     System.err.println("An error occurred initializing indices")
     e.printStackTrace()
 }

we then execute the following query
g.V.has('__id','49fb8bae5f994cf5825b849a5dd9b49a')

This produces a warning informing us that :
"Query requires iterating over all vertices [{}]. For better performance, use indexes"
I'm confused because according to the documentation these indexes are set up correctly, but for some reason titan is not using them.
The indexes are created before any data is in the graph, so reindexing is not neccessary. Any help is greatly appreciated.
Update-
I've managed to break this down into a very simple test. In our code we have developed a custom gremlin step to use for the stated query
Gremlin.defineStep('hasId', [Vertex,Pipe], { String id ->
    _().has('__id', id)
})

then from our code we call
g.V.hasId(id)

It appears that when we use the custom gremlin step the query does not use the index, but when using the vanilla gremlin call the index is used.
It looks like a similar oddity was noted in this post
https://groups.google.com/forum/#!topic/aureliusgraphs/6DqMG13_4EQ

A: I would prefer to check for existence of the property key which would mean you adjust your checks to:
if (!mgmt.containsRelationType("__id")) {

I tried out your code in the Titan Gremlin Console and I'm not seeing an issue:
gremlin> g  = TitanFactory.open("conf/titan-cassandra.properties")
==>titangraph[cassandrathrift:[127.0.0.1]]
gremlin> mgmt = g.managementSystem
==>com.thinkaurelius.titan.graphdb.database.management.ManagementSystem@2227a6c1
gremlin> key = mgmt.makePropertyKey('__id').dataType(String.class).make()
==>__id
gremlin> mgmt.buildIndex("byId",Vertex.class).addKey(key).buildCompositeIndex()
==>com.thinkaurelius.titan.graphdb.database.management.TitanGraphIndexWrapper@6d4c273c
gremlin> mgmt.commit()
==>null
gremlin> mgmt = g.managementSystem
==>com.thinkaurelius.titan.graphdb.database.management.ManagementSystem@79d743e6
gremlin> mgmt.containsGraphIndex("byId")
==>true
gremlin> mgmt.rollback()
==>null
gremlin> v = g.addVertex()
==>v[256]
gremlin> v.setProperty("__id","123")
==>null
gremlin> g.commit()
==>null
gremlin> g.V
12:56:45 WARN  com.thinkaurelius.titan.graphdb.transaction.StandardTitanTx  - Query requires iterating over all vertices [()]. For better performance, use indexes
==>v[256]
gremlin> g.V("__id","123")
==>v[256]
gremlin> g.V.has("__id","123")
==>v[256]

Note I'm not getting any ugly message about "...use indexes".  Perhaps you can try my example here and see if that behaves as expected before going back to your code.
UPDATE: In answer to the updated question above with respect to the custom step.  As the post you found noted, Titan's query optimizer doesn't seem to be able to sort this one out.  I think it's easy to see why in this example:
gremlin> g = TinkerGraphFactory.createTinkerGraph()
==>tinkergraph[vertices:6 edges:6]
gremlin> Gremlin.defineStep('hasName', [Vertex,Pipe], { n -> _().has('name',n) })
==>null
gremlin> g.V.hasName('marko')
==>v[1]
gremlin> g.V.hasName('marko').toString()
==>[GremlinStartPipe, GraphQueryPipe(vertex), [GremlinStartPipe, PropertyFilterPipe(name,EQUAL,marko)]]

The "compiled" Gremlin looks like that last line above.  Note that custom step compiles to an "inner" pipe with a new GremlinStartPipe.  Compare that to the same without the custom step:
gremlin> g.V.has('name','marko').toString()
==>[GremlinStartPipe, GraphQueryPipe(has,vertex), IdentityPipe]

Titan can optimize the "GraphQueryPipe" with embedded has, but it seems that isn't the case with the custom step's signature.  I think the workaround (at least for this particular scenario is write a function that returns the pipe.
gremlin> def hasName(g,n){g.V.has('name',n)}
==>true
gremlin> hasName(g,'marko')
==>v[1]
gremlin> hasName(g,'marko').toString()
==>[GremlinStartPipe, GraphQueryPipe(has,vertex), IdentityPipe]

Passing 'g' around kinda stinks.  Perhaps write your DSL so that 'g' gets wrapped in an class that then lets you do:
with(g).hasName('marko')

A final thought would be to use Groovy meta-programming facilities:
gremlin> Graph.metaClass.hasName = { n -> delegate.V.has('name',n) }
==>groovysh_evaluate$_run_closure1@600b9d27
gremlin> g.hasName("marko").toString()
==>[GremlinStartPipe, GraphQueryPipe(has,vertex), IdentityPipe]
gremlin> g.hasName("marko")
==>v[1]


text:
Q: for loop with bash from variable Lets say I have a variable which has values :
#!/bin/sh
    MYVARIABLE="first,second,third"

    for vars in MYVARIABLE
    do
    echo $vars
    done

this above doesn't work what I want but it looks fine, this should print first second third without , I wan't it to be printed without , any sugestions?

A: Use IFS (the input field separator), eg.
#!/bin/sh
MYVARIABLE="first,second,third"
IFS=","

for vars in $MYVARIABLE
do
  echo $vars
done

A: MYVARIABLE="first,second,third"
IFS=","
set -- $MYVARIABLE
for i in ${@}; do echo $i; done

# you can also use an array in cases where you want to use the values later on
array=($@)
for i in ${!array[@]}; do echo ${array[i]}; done

A: try
MYVARIABLE="first,second,third"

for vars in $(echo $MYVARIABLE | tr "," "\n")
do
  echo $vars
done

Or if you use IFS, don't forget to set IFS back to the original one when done
MYVARIABLE="first,second,third"

OIFS=$IFS
IFS=","
for vars in $MYVARIABLE
do
    echo $vars
done
IFS=$OIFS

A: Not sure what you want to do with the content of MYVARIABLE, or how do you fill it, but a very good option to deal with CSV data is to use awk.
If you have just this variable to be printed:
echo $MYVARIABLE | awk 'BEGIN { RS="," }{ print $0 }'
If you have a CSV file and need to perform calculation/transformation on the data then you should let the awk to fetch the file, using someting like:
awk 'BEGIN { FS="," ; OFS="\n" } { print $1,$2,$3 }' filename.csv
(this is just an ideia, not really related to your question)


text:
Q: Git filter-branch to remove trunk folder I migrated my svn repository to git, however for some reason there are still trunk folders, which should not be the case. I want to remove these folders without damaging the history line.
This is the git repository I have at the moment:
- My repository
  -- Project1
     --- trunk
         ---- src
         ---- somefile.txt
         ---- someotherfile.cpp
         ---- andanotherfile.cpp

and this is what I want to have:
- My repository
  -- Project1
     --- src
     --- somefile.txt
     --- someotherfile.cpp
     --- andanotherfile.cpp

I got to know that the command filter-branch is used to for this, however I could not find an example which suits my case, apart from this and this, but then even there I felt a bit confused and not sure if I should try or not. Anyone ran into something similar and can confirm that those are the solutions?
Thanks in advance.
Update: So I got to know that the following command is used most of the time to do the deed:
git filter-branch --index-filter \
    'git ls-files -s | sed "s-/trunk/-/-" |
        GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
            git update-index --index-info &&
     mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"' HEAD

indeed, I checked the sed line and it does tell me that it would remove the trunk and move whatever is inside, to the upper directory. However, the execution gives and error of:
../myrepository/.git-rewrite/t/../index.new': No such file or directory

I don't know why am I getting this error. I looked it up and it seems I need an addition to this command, a number before the HEAD, like 83df928c..HEAD. However, I don't know what this is for (I mean, revision number, most likely, but why?) or what is mine. Would appreciate help. Almost got it!

A: clone another repo to have a test
git filter-branch --tree-filter 'cd Project1;cp trunk/* ./; rm -rf trunk'

A: So, here it goes.
The command which does the magic is:
git filter-branch -f --index-filter \
    'git ls-files -s | sed "s-/trunk/-/-" |
            GIT_INDEX_FILE=$GIT_INDEX_FILE.new \
            git update-index --index-info &&
     mv "$GIT_INDEX_FILE.new" "$GIT_INDEX_FILE"' af117ec86a30ba6676571cd1f73083c5cfbec0bd..HEAD

note the commit tag before ..HEAD, that should be either second or third earliest commit tag that you should enter. If you enter the first, you get an error.
To find out the commit tag of the earliest commit, simply use:
git log

and scroll down as much as you can, there you will see the earliest commits. Take the second or third. It's done.


text:
Q: How to set Button position after all Recyclerview items Hello:)I have some activity with RecyclerView and Button. I want the button to be positioned after all the items of the Recyclerview. I'm trying to do this, but the button either crawls out of the screen or locks in one place.  How I can do it?
My XML with RecyclerView and Button:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    tools:context=".TestText"
android:orientation="vertical"
    android:id="@+id/lineartest"
    >

<androidx.constraintlayout.widget.ConstraintLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recyclerviewtest"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"

        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:listitem="@layout/test"></androidx.recyclerview.widget.RecyclerView>

    <Button
        android:id="@+id/verify_button"

        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="fill_vertical"

        android:text="Проверить"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.0"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/recyclerviewtest"
        app:layout_constraintVertical_bias="1.0" />
</androidx.constraintlayout.widget.ConstraintLayout>

</RelativeLayout>


text:
Q: Purpose of Unions in C and C++ I have used unions earlier comfortably; today I was alarmed when I read this post and came to know that this code
union ARGB
{
    uint32_t colour;

    struct componentsTag
    {
        uint8_t b;
        uint8_t g;
        uint8_t r;
        uint8_t a;
    } components;

} pixel;

pixel.colour = 0xff040201;  // ARGB::colour is the active member from now on

// somewhere down the line, without any edit to pixel

if(pixel.components.a)      // accessing the non-active member ARGB::components

is actually undefined behaviour I.e. reading from a member of the union other than the one recently written to leads to undefined behaviour. If this isn't the intended usage of unions, what is? Can some one please explain it elaborately?
Update:
I wanted to clarify a few things in hindsight.

*

*The answer to the question isn't the same for C and C++; my ignorant younger self tagged it as both C and C++.

*After scouring through C++11's standard I couldn't conclusively say that it calls out accessing/inspecting a non-active union member is undefined/unspecified/implementation-defined. All I could find was §9.5/1:

If a standard-layout union contains several standard-layout structs that share a common initial sequence, and if an object of this standard-layout union type contains one of the standard-layout structs, it is permitted to inspect the common initial sequence of any of standard-layout struct members. §9.2/19: Two standard-layout structs share a common initial sequence if corresponding members have layout-compatible types and either neither member is a bit-field or both are bit-fields with the same width for a sequence of one or more initial members.

*While in C, (C99 TC3 - DR 283 onwards) it's legal to do so (thanks to Pascal Cuoq for bringing this up). However, attempting to do it can still lead to undefined behavior, if the value read happens to be invalid (so called "trap representation") for the type it is read through. Otherwise, the value read is implementation defined.

*C89/90 called this out under unspecified behavior (Annex J) and K&R's book says it's implementation defined. Quote from K&R:

This is the purpose of a union - a single variable that can legitimately hold any of one of several types. [...] so long as the usage is consistent: the type retrieved must be the type most recently stored. It is the programmer's responsibility to keep track of which type is currently stored in a union; the results are implementation-dependent if something is stored as one type and extracted as another.

*Extract from Stroustrup's TC++PL (emphasis mine)

Use of unions can be essential for compatness of data [...] sometimes misused for "type conversion".

Above all, this question (whose title remains unchanged since my ask) was posed with an intention of understanding the purpose of unions AND not on what the standard allows E.g. Using inheritance for code reuse is, of course, allowed by the C++ standard, but it wasn't the purpose or the original intention of introducing inheritance as a C++ language feature. This is the reason Andrey's answer continues to remain as the accepted one.

A: In C it was a nice way to implement something like an variant.
enum possibleTypes{
  eInt,
  eDouble,
  eChar
}

struct Value{

    union Value {
      int iVal_;
      double dval;
      char cVal;
    } value_;
    possibleTypes discriminator_;
}

switch(val.discriminator_)
{
  case eInt: val.value_.iVal_; break;

In times of litlle memory this structure is using less memory than a struct that has all the member.
By the way C provides
    typedef struct {
      unsigned int mantissa_low:32;      //mantissa
      unsigned int mantissa_high:20;
      unsigned int exponent:11;         //exponent
      unsigned int sign:1;
    } realVal;

to access bit values.

A: The purpose of unions is rather obvious, but for some reason people miss it quite often.
The purpose of union  is to save memory by using the same memory region for storing different objects at different times. That's it.
It is like a room in a hotel. Different people live in it for non-overlapping periods of time. These people never meet, and generally don't know anything about each other. By properly managing the time-sharing of the rooms (i.e. by making sure different people don't get assigned to one room at the same time), a relatively small hotel can provide accommodations to a relatively large number of people, which is what hotels are for.
That's exactly what union does. If you know that several objects in your program hold values with non-overlapping value-lifetimes, then you can "merge" these objects into a union and thus save memory. Just like a hotel room has at most one "active" tenant at each moment of time, a union has at most one "active" member at each moment of program time. Only the "active" member can be read. By writing into other member you switch the "active" status to that other member.
For some reason, this original purpose of the union got "overridden" with something completely different: writing one member of a union and then inspecting it through another member. This kind of memory reinterpretation (aka "type punning") is not a valid use of unions. It generally leads to undefined behavior is described as producing implementation-defined behavior in C89/90.
EDIT: Using unions for the purposes of type punning (i.e. writing one member and then reading another) was given a more detailed definition in one of the Technical Corrigenda to the C99 standard (see DR#257 and DR#283). However, keep in mind that formally this does not protect you from running into undefined behavior by attempting to read a trap representation.

A: Although this is strictly undefined behaviour, in practice it will work with pretty much any compiler. It is such a widely used paradigm that any self-respecting compiler will need to do "the right thing" in cases such as this. It's certainly to be preferred over type-punning, which may well generate broken code with some compilers.

A: In C++, Boost Variant implement a safe version of the union, designed to prevent undefined behavior as much as possible.
Its performances are identical to the enum + union construct (stack allocated too etc) but it uses a template list of types instead of the enum :)

A: The behaviour may be undefined, but that just means there isn't a "standard". All decent compilers offer #pragmas to control packing and alignment, but may have different defaults. The defaults will also change depending on the optimisation settings used.
Also, unions are not just for saving space. They can help modern compilers with type punning. If you reinterpret_cast<> everything the compiler can't make assumptions about what you are doing. It may have to throw away what it knows about your type and start again (forcing a write back to memory, which is very inefficient these days compared to CPU clock speed).

A: You could use unions to create structs like the following, which contains a field that tells us which component of the union is actually used:
struct VAROBJECT
{
    enum o_t { Int, Double, String } objectType;

    union
    {
        int intValue;
        double dblValue;
        char *strValue;
    } value;
} object;

A: Technically it's undefined, but in reality most (all?) compilers treat it exactly the same as using a reinterpret_cast from one type to the other, the result of which is implementation defined. I wouldn't lose sleep over your current code.

A: Others have mentioned the architecture differences (little - big endian).
I read the problem that since the memory for the variables is shared, then by writing to one, the others change and, depending on their type, the value could be meaningless.
eg.
    union{
      float f;
      int   i;
    } x;
Writing to x.i would be meaningless if you then read from x.f - unless that is what you intended in order to look at the sign, exponent or mantissa components of the float.
I think there is also an issue of alignment: If some variables must be word aligned then you might not get the expected result.
eg.
    union{
      char  c[4];
      int   i;
    } x;
If, hypothetically, on some machine a char had to be word aligned then c[0] and c[1] would share storage with i but not c[2] and c[3].

A: For one more example of the actual use of unions, the CORBA framework serializes objects using the tagged union approach. All user-defined classes are members of one (huge) union, and an integer identifier tells the demarshaller how to interpret the union.

A: In the C language as it was documented in 1974, all structure members shared a common namespace, and the meaning of "ptr->member" was defined as adding the
member's displacement to "ptr" and accessing the resulting address using the
member's type.  This design made it possible to use the same ptr with member
names taken from different structure definitions but with the same offset;
programmers used that ability for a variety of purposes.
When structure members were assigned their own namespaces, it became impossible
to declare two structure members with the same displacement.  Adding unions to
the language made it possible to achieve the same semantics that had been
available in earlier versions of the language (though the inability to have
names exported to an enclosing context may have still necessitated using a
find/replace to replace foo->member into foo->type1.member).  What was
important was not so much that the people who added unions have any particular
target usage in mind, but rather that they provide a means by which programmers
who had relied upon the earlier semantics, for whatever purpose, should still
be able to achieve the same semantics even if they had to use a different
syntax to do it.

A: The behavior is undefined from the language point of view. Consider that different platforms can have different constraints in memory alignment and endianness. The code in a big endian versus a little endian machine will update the values in the struct differently. Fixing the behavior in the language would require all implementations to use the same endianness (and memory alignment constraints...) limiting use.
If you are using C++ (you are using two tags) and you really care about portability, then you can just use the struct and provide a setter that takes the uint32_t and sets the fields appropriately through bitmask operations. The same can be done in C with a function.
Edit: I was expecting AProgrammer to write down an answer to vote and close this one. As some comments have pointed out, endianness is dealt in other parts of the standard by letting each implementation decide what to do, and alignment and padding can also be handled differently. Now, the strict aliasing rules that AProgrammer implicitly refers to are a important point here. The compiler is allowed to make assumptions on the modification (or lack of modification) of variables. In the case of the union, the compiler could reorder instructions and move the read of each color component over the write to the colour variable.

A: The most common use of union I regularly come across is aliasing.
Consider the following:
union Vector3f
{
  struct{ float x,y,z ; } ;
  float elts[3];
}

What does this do?  It allows clean, neat access of a Vector3f vec;'s members by either name:
vec.x=vec.y=vec.z=1.f ;

or by integer access into the array
for( int i = 0 ; i < 3 ; i++ )
  vec.elts[i]=1.f;

In some cases, accessing by name is the clearest thing you can do.  In other cases, especially when the axis is chosen programmatically, the easier thing to do is to access the axis by numerical index - 0 for x, 1 for y, and 2 for z.

A: As others mentioned, unions combined with enumerations and wrapped into structs can be used to implement tagged unions. One practical use is to implement Rust's Result<T, E>, which is originally implemented using a pure enum (Rust can hold additional data in enumeration variants). Here is a C++ example:
template <typename T, typename E> struct Result {
    public:
    enum class Success : uint8_t { Ok, Err };
    Result(T val) {
        m_success = Success::Ok;
        m_value.ok = val;
    }
    Result(E val) {
        m_success = Success::Err;
        m_value.err = val;
    }
    inline bool operator==(const Result& other) {
        return other.m_success == this->m_success;
    }
    inline bool operator!=(const Result& other) {
        return other.m_success != this->m_success;
    }
    inline T expect(const char* errorMsg) {
        if (m_success == Success::Err) throw errorMsg;
        else return m_value.ok;
    }
    inline bool is_ok() {
        return m_success == Success::Ok;
    }
    inline bool is_err() {
        return m_success == Success::Err;
    }
    inline const T* ok() {
        if (is_ok()) return m_value.ok;
        else return nullptr;
    }
    inline const T* err() {
        if (is_err()) return m_value.err;
        else return nullptr;
    }

    // Other methods from https://doc.rust-lang.org/std/result/enum.Result.html

    private:
    Success m_success;
    union _val_t { T ok; E err; } m_value;
}

A: As you say, this is strictly undefined behaviour, though it will "work" on many platforms. The real reason for using unions is to create variant records.
union A {
   int i;
   double d;
};

A a[10];    // records in "a" can be either ints or doubles
a[0].i = 42;
a[1].d = 1.23;

Of course, you also need some sort of discriminator to say what the variant actually contains. And note that in C++ unions are not much use because they can only contain POD types - effectively those without constructors and destructors.

A: You can use a a union for two main reasons:

*

*A handy way to access the same data in different ways, like in your example

*A way to save space when there are different data members of which only one can ever be 'active'

1 Is really more of a C-style hack to short-cut writing code on the basis you know how the target system's memory architecture works. As already said you can normally get away with it if you don't actually target lots of different platforms. I believe some compilers might let you use packing directives also (I know they do on structs)?
A good example of 2. can be found in the VARIANT type used extensively in COM.

A: @bobobobo code is correct as @Joshua pointed out (sadly I'm not allowed to add comments, so doing it here, IMO bad decision to disallow it in first place):
https://en.cppreference.com/w/cpp/language/data_members#Standard_layout tells that it is fine to do so, at least since C++14

In a standard-layout union with an active member of non-union class type T1, it is permitted to read a non-static data member m of another union member of non-union class type T2 provided m is part of the common initial sequence of T1 and T2 (except that reading a volatile member through non-volatile glvalue is undefined).

since in the current case T1 and T2 donate the same type anyway.


text:
Q: Frontend framework to consume RESTful backend I've build a RESTful backend in Spring + Hibernate framework. Now, i'm starting with frontend in Spring MVC. So, my jsp pages make an AJAX call to the frontend URL which inturn calls the backend URL to get the data.
Is this a proper way of implementation? Or should i re-think on the design? How about replacing frontend Spring MVC with Angular.js or any other framework?

A:
So, my jsp pages make an AJAX call to the frontend URL which inturn calls the backend URL to get the data.

No. The JSPs are your frontend. JSPs are one way to generate and deliver HTML to the client. When it is successfully delivered to the client, the HTML is rendered and the JS is executed.
Within the JS-code you are able to make calls to the backend to get your data.

Is this a proper way of implementation?

Yes.

How about replacing frontend Spring MVC with Angular.js or any other framework?

You are free to do that as you like.
Since recommending one or the other framework would be based on my subjective opinion, I won't say anything but: Angular is en vogue. So: yes, it is one possible solution.
And since Angular itself is only a JS-framework you could combine it without further ado with JSPs.


text:
Q: How to detect when app moves to task switcher and continues running I have an app where I clean up some UI when the app moves to the background. The notification of the app moving to the background occurs if, for example, on the iPad, the user swipes up to invoke the task switcher. However, the app continues to operate while the task switcher is open. How can I distinguish this from the app moving to background and not visible in the task switcher? Interestingly, if I launch the app from Xcode, the app does not continue in the task switcher. However, if it's not connected to Xcode, it continues.
For debugging purposes, I've linked the app delegate to the main view controller so I can send messages for display when the app delegate receives calls. I did this because the behavior doesn't happen when connected to Xcode, so a print will not work. I haven't found a method or notification yet that indicates this state.

A: Here is the flow of the app, noting specific function calls or notification calls.
App is launched.
viewDidAppear in viewController is called
UIScene.didActivateNotification notification is received.
applicationDidBecomeActive: is called in AppDelegate.
Task switcher is invoked by panning up slightly from bottom if iPad.
UIScene.willDeactivateNotification notification is received.
applicationWillResignActive: is called in AppDelegate.
Release task switcher, thus keeping app on screen, but icons now appear over app at bottom (stop panning after a brief pan)
UIScene.didActivateNotification notification is received.
applicationDidBecomeActive: is called in AppDelegate.
Task switcher again - this time continue panning until multiple apps appear in task switcher
UIScene.willDeactivateNotification notification is received.
applicationWillResignActive: is called in AppDelegate.
Open Safari (this time we're switching to a different app instead of returning to our app
Pan up to open task switcher (at this point the app is no longer running)
UIScene.didEnterBackgroundNotification was called at some point when the app was not visible.
Open App
applicationDidBecomeActive: is called in AppDelegate.


text:
Q: Accessing $state outside angularjs I have an angularjs application. The app is supposed to be a hybrid mobile app for android and iOS. I have a JavaScript file in the project which is not a part of any module. In that JavaScript file I need to call the respective template URL, either through $state or any method which loads the controller also.
For $scope I found many ways of accessing it outside that angularjs project but could not find the same for $state.

A: we can use java-script
window.location.href //to change location

for example:
 suppose right now I am in https://www.google.co.in/
now i want to navigate to https://news.google.co.in/
we can simply write
window.location.href ="https://news.google.co.in/"

it will navigate to that page
Now in your project you might have defined your routing like this
function routeConfig($stateProvider, $urlRouterProvider, $httpProvider) {
$stateProvider
  .state('landing.home', {
    url: '/home',
    templateUrl: "app/components/homeFolder/home.html",
    controller: 'homeController',
    controllerAs: 'homec'
  })
  .state('landing.hometwo', {
    url: '/home1',
    templateUrl: "app/components/OnHand/Templates/OnHandhome.html",
    controller: 'OnHandController',
    controllerAs: 'Onhand'
  })

  })

Now  if you are in angularjs controller you will simply use
 $state.go('landing.home');// to navigate to your required location

But if you are not in angularjs Module you can change window.location to navigate to required page
for example to achieve ---$state.go('landing.home'); you can write
window.location.href ="https:complete url"

or otherwise
window.location.hash ="#/home1" //the url which is defined for that state


text:
Q: An error while trying to pull data from mysql using spring jdbc
Snapshot of the project structure
Just 2 days into java & spring.
Trying to pull data from mySQL DB using spring in a maven project.
Following a tutorial.
But when the code is run, getting the following error(Only a portion of the error is attached).
All the codes are attached below.
error:
Jul 25, 2015 11:00:15 PM
org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing
org.springframework.context.support.ClassPathXmlApplicationContext@da2dbb:      startup date [Sat Jul 25 23:00:15 IST 2015]; root of context hierarchy
Jul 25, 2015 11:00:15 PM
org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [com/caveofprogramming/spring/test/beans/Beans.xml]
Jul 25, 2015 11:00:16 PM
org.springframework.core.io.support.PropertiesLoaderSupport loadProperties
INFO: Loading properties file from class path resource [com/caveofprogramming/spring/props/jdbc.properties]
Jul 25, 2015 11:00:16 PM  org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in    org.springframework.beans.factory.support.DefaultListableBeanFactory@f438e: defining beans [offersDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource]; root of factory hierarchy
Jul 25, 2015 11:00:16 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@f438e: defining beans [offersDao,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.beans.factory.config.PropertyPlaceholderConfigurer#0,dataSource]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'offersDao': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void com.caveofprogramming.spring.test.OffersDAO.setDataSource(javax.sql.DataSource); nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1074)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:291)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:580)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)
at

App.java
package com.caveofprogramming.spring.test;

import java.util.List;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class App {

public static void main(String[] args) {

    ApplicationContext context = new ClassPathXmlApplicationContext("com/caveofprogramming/spring/test/beans/Beans.xml");

    OffersDAO offersDao = (OffersDAO)context.getBean("offersDao");
    List<Offer> offers = offersDao.getOffers();

    for(Offer offer:offers){
        System.out.println(offer);
    }
    ((ClassPathXmlApplicationContext)context).close();
}

}

Offer.java
package com.caveofprogramming.spring.test;

public class Offer {
private String author;
private String title;

public String getAuthor() {
    return author;
}

public void setAuthor(String author) {
    this.author = author;
}

public String getTitle() {
    return title;
}

public void setTitle(String title) {
    this.title = title;
}

@Override
public String toString() {
    return "Offer [author=" + author + ", title=" + title + "]";
}

}

OffersDAO.java
package com.caveofprogramming.spring.test;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component;

@Component("offersDao")
public class OffersDAO {

    private JdbcTemplate jdbc;
    @Autowired
    public void setDataSource(DataSource jdbc) {
        System.out.println("TESTINGGGGGGGGG in setDataSource");
        this.jdbc = new JdbcTemplate(jdbc);
    }

    public List<Offer> getOffers(){

         return jdbc.query("select * from library.book", new RowMapper<Offer>(){

            public Offer mapRow(ResultSet rs, int rowNum) throws SQLException {

                Offer offer = new Offer();
                offer.setTitle(rs.getString("title"));
                offer.setAuthor(rs.getString("author"));
                return offer;
            }});

    }
}

jdbc.properties
jdbc.username = root
jdbc.password = 123456
jdbc.driver   = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql://localhost:3306/library

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

    <context:component-scan base-package="com.caveofprogramming.spring.test">    </context:component-scan>
    <context:property-placeholder
    location="com/caveofprogramming/spring/props/jdbc.properties" />

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
    destroy-method="close">

        <property name="driverClassName" value="${jdbc.driver}"></property>
        <property name="url" value="${jdbc.url}"></property>
        <property name="password" value="${jdbc.password}"></property>
        <property name="username" value="${jdbc.username}"></property>
    </bean>

</beans>

Do ask, if more clarity is needed.
Thanks in advance

A: Your exception is java.lang.NoClassDefFoundError: org/apache/commons/pool/impl/GenericObjectPool which basically means the required java class is not on the class path.
The problem is due to commons-pool not being in your class path.

*

*Ideally this should be availed when your add the apache tomcat server as a  server in your project and doing will get the commons-pool from the server

*If this is not the case then kindly add it in the lib folder by downloading it

*If it's a maven project then it has it in the pom.xml

commons-pool
commons-pool
1.5.6


text:
Q: Formula Field Count of ActivityHistories I have a custom object with Activities enabled, as such it has the child relationship ActivityHistories - I wanted to show a count() of the related Activities associated w/ each object of a certain type:
COUNT(WHERE ActivityHistory.Type = 'Call')
Is this possible in a Formula Field? I don't see any merge fields for it, and I can't create a Roll-Up Summary (inactive the field editor UI, so I assume it's not available that way?)
Or do I have to write a custom trigger and update it when the Task is inserted?

A: You will have to write an Apex Trigger. The trigger should fire and work on multiple events, like
insert - if a closed activity (even or task is inserted)(+count)update - if open activity is closed (+count) if closed activity is opened(-count)delete - if closed activity is deleted (-count)undelete - if a deleted closed activity is restored.
Let me guide you to a link that can help you to write this trigger. This link calculated count for OpenActivities, all you have to do is apply your logics and count for ActivityHistory.
http://rjpalombo.com/2013/11/counting-open-activities-salesforce/


text:
Q: iPhone - Ordering Core data relationship I currently have an app which lists a number of events (horse riding, party, etc), i want to be able to add these events to a list of 'favourites' which will be stored in core data, but i also want these events to be sorted in the order they were added to favourites. I realise i could just add an index property to the event and sort using a descriptor when i retrieve the events but i would like to be able to add events to multiple lists of favourites, so i don't think that would work.
I've also looked into ordered relationships, which is exactly what i am looking for but requires iOS5, as a last resort i could probably cope with that although i would prefer to be able to find  another way to do this if possible. Any ideas?
Thanks.
EDIT: The user can also add and remove lists of favourites so adding a date property and sorting by that would not be possible.

A: Go with ordered relationships with iOS 5. iOS devices are updated fairly quickly and I imagine that you would not be forsaking a large percentage of potential customers. Not to mention the time you will save from having to roll your own implementation.

A: The correct solution is to have a 3rd entity that represents a membership of an event to a favourite list. Let's call it EventInFavourites.
EventInFavourites has two many-to-one relations:
Favourites <-------->> EventInFavourites
This one says that a Favourites can have several Event in it
Event <---------->> EventInFavourites
This one says that an Event can be part of several Favourites lists.
Finally, the position of that event in that favourite list is represented with an attribute of
 EventInFavourites, let's say position.
So when you want to add an event to a favorite lists, you create an EventInFavourites instance and you link it to that event and to that favorite list. A bit like this:
EventInFavourites *newFavouriteMembership = [EventInFavourites insertInManagedObjectContext:self.moc];
newFavouriteMembership.event = anEvent;
newFavouriteMembership.favourites = aFavouritesList;
newFavouriteMembership.position = 3; // or whatever
[self.moc save:NULL];

I left out a few details, but that should give you the big picture.
And of course, you can wait for iOS 5.

A: Store the time & date when the item was added to the favorites. Later, when querying the db, order by this timestamp.
With different lists of favorites you might want to store multiple timestamps, one for each list.