text:
Q: Looping through an MPI ring in C I'm having trouble figuring out how to do multiple iterations in my MPI code. Just from testing multiple for loops in different spots tells me I am doing something wrong. Part of our instructions are to pass the token around the ring multiple times specified in the command line arguments, but i cant seem to get it to work correctly by even hard coding the iterations. I left the top for loop in(Which doesn't work) but commented out the others.
This is probably a more complicated task than I am anticipating.
Any help is appreciated
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    double starttime, endtime;
    MPI_Init(&argc, &argv);
    starttime = MPI_Wtime();
    int world_rank;
    int world_size;

    for (int i = 0; i < 3; i++)

        MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
        MPI_Comm_size(MPI_COMM_WORLD, &world_size);

//pass the token

        int token =1000;

//for (int i = 0; i < 3; i++)
//{
    if (world_rank == 0)
    {
        token = 0;
        MPI_Send(&token, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);

        MPI_Recv(&token, 1, MPI_INT, world_size - 1, 0, MPI_COMM_WORLD,
        MPI_STATUS_IGNORE);

        printf("FINAL TOKEN %d\n", token);
    }
    else if(world_rank < world_size - 1 )
    {
        MPI_Recv(&token, 1, MPI_INT, world_rank-1, 0, MPI_COMM_WORLD,
        MPI_STATUS_IGNORE);

        printf("%d has token %d sending to %d\n", world_rank, token,
        world_rank+1);
        token = token + 2;

        MPI_Send(&token, 1, MPI_INT, world_rank+1, 0, MPI_COMM_WORLD);
        }
    else
        {
        MPI_Recv(&token, 1, MPI_INT, world_rank-1, 0, MPI_COMM_WORLD,
        MPI_STATUS_IGNORE);
        printf("%d has token %d sending to %d\n", world_rank, token,
        world_rank+1);
        token = token + 2;
        MPI_Send(&token, 1, MPI_INT, 0, 0, MPI_COMM_WORLD);
        }
    endtime = MPI_Wtime();
    printf("That took %f seconds\n",endtime-starttime);
    }
    MPI_Finalize();

    return 0;
}

Here's the compile and run output:
$ mpicc -std=c99 test.c
$ mpirun -np 3 ./a.out
1 has token 0 sending to 2
That took 0.000187 seconds
2 has token 2 sending to 3
That took 0.000145 seconds
FINAL TOKEN 4
That took 0.000180 seconds
FINAL TOKEN 4
That took 0.000212 seconds
2 has token 2 sending to 3
That took 0.000202 seconds
2 has token 2 sending to 3
That took 0.000233 seconds
1 has token 0 sending to 2
That took 0.000291 seconds
1 has token 0 sending to 2
That took 0.000322 seconds
FINAL TOKEN 4
That took 0.000244 seconds

A: As noted in this comment, the for loop is missing braces {} and the token would be reset each iteration of the loop.
Also, you can remove one of your cases and include world_rank==world_size with the modulo operator %.
#include <mpi.h>
#include <stdio.h>
#include <stdlib.h>

int main(int argc, char* argv[])
{
    double starttime, endtime;
    MPI_Init(&argc, &argv);
    starttime = MPI_Wtime();
    int world_rank;
    int world_size;

    MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
    MPI_Comm_size(MPI_COMM_WORLD, &world_size);

    //pass the token

    int token =1000;

    for (int i = 0; i < 3; i++)
    {
        if (world_rank == 0)
        {
            // token = 0; removed
            MPI_Send(&token, 1, MPI_INT, 1, 0, MPI_COMM_WORLD);

            MPI_Recv(&token, 1, MPI_INT, world_size - 1, 0, MPI_COMM_WORLD,
            MPI_STATUS_IGNORE);

            printf("FINAL TOKEN %d\n", token);
        }
        else
        {
            MPI_Recv(&token, 1, MPI_INT, world_rank-1, 0, MPI_COMM_WORLD,
            MPI_STATUS_IGNORE);

            printf("%d has token %d sending to %d\n", world_rank, token,
            (world_rank+1)%world_size); // modified
            token = token + 2;

            MPI_Send(&token, 1, MPI_INT, (world_rank+1)%world_size, 0, MPI_COMM_WORLD); // modified
        }

        endtime = MPI_Wtime();
        printf("That took %f seconds\n",endtime-starttime);
    }
    MPI_Finalize();

    return 0;
}


text:
Q: Possible to get comprehensive view on all defined names in PostgreSQL? The SQL standard prescribes a rather large vocabulary; on top of this, RDBMSs implement their own constructs. Then they add hundreds of function names, internal and user-facing. On top of that, users go and define schema(ta)s, tables, indexes, custom functions, types, whatnot. Now, when I want to, say, create a function, a table or a column I have to name it. Some names (like all I think) are no-go, some names (for some kinds of objects?) are OK even though they clash (b/c they are not ambiguous). Good names clearly should be not confusing. But how can I get an exhaustive list of all the names that a given PostgreSQL DB instance 'knows' at any given point in time?
FWIW I scanned to Postgres docs for lists, but they don't seem to have any; instead, there's a list of SQL commands that does not list e.g. order and by (b/c that's subsumed under select); I'd have to peruse all the pages of Chapter 9. Functions and Operators to compile a list of all the function names. Not to speak of extensions, which by default put their stuff into the public schema.
Is there a truly comprehensive way to list all these 'defined words' complete with their roles, origins, comments etc. in a single huge list? I know there's psql's \d+ and so on, and I already have a small collection of utility views to provide subsets of what I'm looking for, but nothing resembling a Grand Inclusive List of Everything.

A:
RDBMSs implement their own constructs. Then they add hundreds of function names, internal and user-facing.

All of them for PostgreSQL are defined in the schema pg_catalog. You can access them with the S argument in psql. For example \dfS for show all system functions.

On top of that, users go and define schema(ta)s, tables, indexes, custom functions, types, whatnot.

You can never know what users create. You'll have to check that out for each install by querying the catalog.

Is there a truly comprehensive way to list all these 'defined words' complete with their roles, origins, comments etc. in a single huge list?

I'm not 100% sure it's what you want, but perhaps you're looking for the Reserved Keyword list?
Update

"You'll have to check that out for each install by querying the catalog."—exactly, can you tell me such a query? – John Frazer Jun 17 at 8:03

Sure, so what you want to do is run psql -E, then run \?. This gives you the far more than what you've asked for (viz. list tables, views, and sequences , aggregates , access methods , tablespaces , conversions , casts , default privileges , domains , foreign tables , foreign servers , user mappings , foreign-data wrappers , functions , text search configurations , text search dictionaries , text search parsers , text search templates , roles , indexes , large objects, same as \lo_list , procedural languages , materialized views , schemas , operators , collations , table, view, and sequence access privileges , sequences , tables , data types , roles , views , foreign tables , extensions , event triggers , databases). Next pick one of them, like \df which lists functions,
You'll get a query like
SELECT n.nspname as "Schema",
  p.proname as "Name",
  pg_catalog.pg_get_function_result(p.oid) as "Result data type",
  pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
 CASE
  WHEN p.proisagg THEN 'agg'
  WHEN p.proiswindow THEN 'window'
  WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
  ELSE 'normal'
 END as "Type"
FROM pg_catalog.pg_proc p
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
ORDER BY 1, 2, 4;

This is internally the query that psql uses to get this information. You can cut it up though if you only want the name and don't care about whether or not the function is an aggregate, window, or trigger; and, you can cut it further if you don't care about the result and arguments types.
SELECT n.nspname as "Schema",
  p.proname as "Name"
FROM pg_catalog.pg_proc p
     LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
WHERE pg_catalog.pg_function_is_visible(p.oid)
      AND n.nspname <> 'pg_catalog'
      AND n.nspname <> 'information_schema'
ORDER BY 1, 2;

Etc., or of course you can query the slower information_schema interface which is part of the SQL spec and standardized.
SELECT routine_catalog, routine_schema, routine_name
FROM information_schema.routines
WHERE routine_schema NOT IN ('pg_catalog', 'information_schema');

A: Adding to the other answers: there is a listing of SQL keywords, including the ones that are used by PostgreSQL:
https://www.postgresql.org/docs/current/static/sql-keywords-appendix.html
Search for the ones that are 'reserved' or non-reserved.

A:

SELECT n.nspname as "Schema",
          p.proname as "Name",
          pg_catalog.pg_get_function_result(p.oid) as "Result data type",
          pg_catalog.pg_get_function_arguments(p.oid) as "Argument data types",
         CASE
          WHEN p.proisagg THEN 'agg'
          WHEN p.proiswindow THEN 'window'
          WHEN p.prorettype = 'pg_catalog.trigger'::pg_catalog.regtype THEN 'trigger'
          ELSE 'normal'
         END as "Type"
        FROM pg_catalog.pg_proc p
             LEFT JOIN pg_catalog.pg_namespace n ON n.oid = p.pronamespace
        WHERE pg_catalog.pg_function_is_visible(p.oid)
        --and n.nspname='public' -- you can enable this if you want to get comprehensive view on all defined names
        ORDER BY 1, 2, 4;

redpajama_set_name: RedPajamaStackExchange


text:
Q: openstack instance is not accessible on LAN i have setup single machine openstack using devstack. my instances running on machine.
openstack machine ip 192.168.2.32

instance machine ip 10.0.0.2 and 172.24.4.1

i can ping 172.24.4.1 from openstack machine. but i can't ping this machine from personal computer.and can't access instance. How can I solve it?
Ip Forward
 /proc/sys/net/ipv4/ip_forward 1

/etc/nova/nova.conf
flat_interface = em1
flat_network_bridge = br100
vlan_interface = em1
public_interface = br100
network_manager = nova.network.manager.FlatDHCPManager
firewall_driver = nova.virt.libvirt.firewall.IptablesFirewallDriver
compute_driver = libvirt.LibvirtDriver
default_ephemeral_format = ext4...

ifconfig
br100     Link encap:Ethernet  HWaddr 00:26:55:4b:46:0a
          inet addr:10.0.0.1  Bcast:10.0.0.255  Mask:255.255.255.0
          inet6 addr: fe80::707a:83ff:fe0f:4db0/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:62087 errors:0 dropped:0 overruns:0 frame:0
          TX packets:38260 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:71936261 (71.9 MB)  TX bytes:5377931 (5.3 MB)

em1       Link encap:Ethernet  HWaddr 00:26:55:4b:46:0a
          inet6 addr: fe80::226:55ff:fe4b:460a/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:63127 errors:0 dropped:0 overruns:0 frame:0
          TX packets:39439 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:73159657 (73.1 MB)  TX bytes:6162268 (6.1 MB)

lo        Link encap:Local Loopback
          inet addr:127.0.0.1  Mask:255.0.0.0
          inet6 addr: ::1/128 Scope:Host
          UP LOOPBACK RUNNING  MTU:65536  Metric:1
          RX packets:163787 errors:0 dropped:0 overruns:0 frame:0
          TX packets:163787 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:495519545 (495.5 MB)  TX bytes:495519545 (495.5 MB)

virbr0    Link encap:Ethernet  HWaddr de:30:60:02:bc:dc
          inet addr:192.168.122.1  Bcast:192.168.122.255  Mask:255.255.255.0
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:0
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)

vnet0     Link encap:Ethernet  HWaddr fe:16:3e:11:ee:00
          inet6 addr: fe80::fc16:3eff:fe11:ee00/64 Scope:Link
          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1
          RX packets:15 errors:0 dropped:0 overruns:0 frame:0
          TX packets:474 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:500
          RX bytes:1581 (1.5 KB)  TX bytes:74117 (74.1 KB)

please help. thanks

A: Ping is blocked by default. You should allow ping in security group.
1)1st find out which is security group
Click on instance name -> Security Groups
(It will be default if u didn't configure any)
2) Go to Compute -> Access & security
 Select security group -> Manage rules
3) Click Add Rule
Rule - All ICMP
Direction - Ingress
Then Click Add
You will be able to ping to floating IP assigned to instance.


text:
Q: Is it possible to compare Guid values using Entity Framework Core? I would like to implement cursor based pagination using uniqueidentifier column in SQL Server. Is there any way to make this query to run server-side with Entity Framework Core?
var cursor = Guid.NewGuid();
// This query will not delegate filtering to database
var items = await dbContext.Items.Where(x => x.Id.CompareTo(cursor) > 0).ToListAsync();


text:
Q: Why is my JSON URL not outputting JSON data? I have checked the URL and it works but when I try to output the readableJSON, it is empty?!
Here is my output:
Not empty now
2016-02-20 10:19:29.162 ThisLondon[55922:4080604] the URL: [

]
2016-02-20 10:19:29.162 ThisLondon[55922:4080604] 0

Here is my code:
selectedTube = "Circle"
let url = NSURL(string: "https://api.tfl.gov.uk/Line/\(selectedTube)/Arrivals?app_id=6573044a&app_key=7a97df35339dc68625384077a5e07304")
let jsonData = NSData(contentsOfURL: url!)
let readableJSON = JSON(data: jsonData!, options: NSJSONReadingOptions.MutableContainers, error: nil)

NSLog("the URL: \(readableJSON)")

A: Try using this:
    let selectedTube = "circle"
        let headers = ["cache-control": "no-cache",]

let request = NSMutableURLRequest(URL: NSURL(string: "https://api.tfl.gov.uk/Line/\(selectedTube)/Arrivals?app_id=6573044a&app_key=7a97df35339dc68625384077a5e07304")!,
                                                cachePolicy: .UseProtocolCachePolicy,
                                            timeoutInterval: 10.0)
        request.HTTPMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
          if (error != nil) {
            print(error)
          } else {
            let httpResponse = response as? NSHTTPURLResponse
            print(httpResponse)
          }
        })

        dataTask.resume()

A: I'm not quite sure what your problem is. The following code works just fine in a playground. I would suspect the problem lies within your custom JSON function:
import Foundation

let selectedTube = "Circle"
let url = NSURL(string: "https://api.tfl.gov.uk/Line/\(selectedTube)/Arrivals?app_id=6573044a&app_key=7a97df35339dc68625384077a5e07304")
if let jsonData = NSData(contentsOfURL: url!) {
    let readableJSON = try NSJSONSerialization.JSONObjectWithData(jsonData, options: NSJSONReadingOptions.MutableContainers)
    NSLog("the URL: \(readableJSON)")
} else {
        print("Cannot read data.")
}


text:
Q: SetOnFocusChangeListener with NullpointerException I have fragment A:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     view = inflater.inflate(R.layout.fragment_main, container, false);
     CustomKeyboard customKeyboard = new CustomKeyBoard(getActivity());

     etAge = (EditText) getActivity().findViewById(R.id.etAge);
     customKeyboard.actionEt(etAge);
     return view;
}

And I have class B:
    public class CustomKeyboard {

private Context context;

    public CustomKeyboard (Context context) {
        this.context = context;
    }

    private void hideKeyboard(View view) {
        InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Activity.INPUT_METHOD_SERVICE);
        inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
    }
                public void actionEt(Edittext edittext){
                    editText.setOnFocusChangeListener((view, hasFocus) -> {
                       if(!hasFocus) {
                             hideKeyboard(view);
                        } else {
                          //........
                        }
                    });
                }
    }

The Exception:
                                                  Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.EditText.setOnFocusChangeListener(android.view.View$OnFocusChangeListener)' on a null object reference
What is the reason of the problem? Hope for some help.
EDIT:
NOW THE APP RUNS. But the Edittexts dont hide.

A: It should be
etAge = (EditText) view.findViewById(R.id.etAge);
Its hard to judge without an XML to look at; to be safe we will add and extra condition.
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
     view = inflater.inflate(R.layout.fragment_main, container, false);

     etAge = (EditText) view.findViewById(R.id.etAge);
     if(etAge != null){
        CustomKeyboard customKeyboard = new CustomKeyBoard(getActivity());
        customKeyboard.actionEt(etAge);
     }
     return view;
}

A: Your code:
etAge = (EditText) getActivity().findViewById(R.id.etAge);

Is wrong because it inflates from an activity instead of the view it is located in. The cause is comparable to getting a Nullpointer when finding a view in a different layout
Correct code:
etAge = (EditText) view.findViewById(R.id.etAge);

As this finds the EditText in the view instead of the activity(which has no defined view inflated)


text:
Q: Is there a word for lighting striking twice? Looking for word to describe something extremely rare, specifically lightning striking twice. Is there any word for this?

A: If you're looking for an idiomatic way to say this, you've hit the nail on the head!
The phrase:

Lightning doesn't strike twice.

Often is used to say that it's unlikely that the same thing will happen again. Def.
Other suitable phrases are:

*

*Chance Event

*Accident

*Coincidence

*Fluke

*Surprise

*Freak Occurrence (as @Smock mentioned)

Please note, these aren't entirely interchangeable, so it is worth looking them up to make sure you are using the best one for the situation you're trying to describe.

A: All the words in @Bee's answer are great, and focus on the meaning of being statistically unlikely. If you are looking for a word to carry the shock or surprise of such an incident then perhaps also consider:

*

*Incredible

*Inconceivable

*Extraordinary

*Unheard-of

*Unimaginable

*Unthinkable


text:
Q: Add an unknown-sized list of security groups to an EC2 instance We have a CloudFormation template that creates an EC2 instance and a security group (among many other resources), but we need to be able to add some additional pre-existing security groups to that same EC2 instance.
The issue we have is that the number of pre-existing security groups won't always be the same, and we want to have a single template that will handle all cases.
Currently, we have an input parameter that looks like this:
"WebTierSgAdditional": {
  "Type": "String",
  "Default": "",
  "Description": ""
}

We pass into this parameter a comma-delimited string of pre-existing security groups, such as 'sg-abc123,sg-abc456'.
The SecurityGroup tag of the EC2 instance look like this:
"SecurityGroups": [
  {
    "Ref": "WebSg"
  },
  {
    "Ref": "WebTierSgAdditional"
  }
]

With this code, when the instance gets created, we get this error in the AWS console:

Must use either use group-id or group-name for all the security groups, not both at the same time

The 'WebSg' ref above is one of the security groups being created elsewhere in the template. This same error appears if we pass in a list of group names rather than a list of group Id's through the input parameter.
When we change the "Type" field of the input parameter to be 'CommaDelimitedList', we get an error saying:

Value of property SecurityGroups must be of type List of String

It obviously can't join a list with a string to make it a new list.
When the parameter only contains a single sg id, everything gets created successfully, however, we need to have the capability to add more than just one sg id.
We have tried many different combinations of using Fn::Join within the SecurityGroups tag, but nothing seems to work.  What we really need is some sort of 'Explode' function to extract the individual id's from the parameter string.
Does anyone know of a nice way to get this to work?

A: There is another solution which I got from the support and I found nicer.
Basically it is just getting each security group by its index from the list and then adds the internal one at the end.
"SecurityGroupList": {
    "Description": "List of existing security groups",
    "Type": "CommaDelimitedList"
},
...
"InternalSecurityGroup": {
    "Type": "AWS::EC2::SecurityGroup"
},
...
"SecurityGroupIds": [
    {
        "Fn::Select": [
            "0",
            {
                "Ref": "SecurityGroupList"
            }
        ]
    },
    {
        "Fn::Select": [
            "1",
            {
                "Ref": "SecurityGroupList"
            }
        ]
    },
    {
        "Fn::Select": [
            "2",
            {
                "Ref": "SecurityGroupList"
            }
        ]
    },
    {
        "Ref": "InternalSecurityGroup"
    }
],

Hope this helps anyone else.

A: AWS introduced Fn::Split in January 2017 and this is now possible. It's not pretty, but you're essentially converting two lists into strings with Fn::Join, and then converting the strings back to a list with Fn::Split.
Parameters:

    WebTierSgAdditional:
        Type: CommaDelimitedList
        Default: ''

Conditions:

    HasWebTierSgAdditional: !Not [ !Equals [ '', !Select [ 0, !Ref WebTierSgAdditional ] ] ]

Resources:

    WebSg:
        Type: AWS::EC2::SecurityGroup
        Properties:
            # ...

    Ec2Instance:
        Type: AWS::EC2::Instance
        Properties:
            # ...
            SecurityGroupIds: !Split
                  - ','
                  - !Join
                      - ','
                      -   - !Ref WebSg
                          - !If [ HasWebTierSgAdditional, !Join [ ',', !Ref WebTierSgAdditional ], !Ref 'AWS::NoValue' ]

WebTierSgAdditional starts as a list, but gets converted into a string with each item separated by a comma via !Join [ ',', !Ref WebTierSgAdditional ]. That is included in another list that includes !Ref WebSg that also gets converted to a string with each item separated by a comma. !Split will take a string and split items into a list as separated by a comma.

A: As you've found out, the problem is that you need to send a list of strings as the security groups, and although CloudFormation gives you a method to join a list of strings into a single delimited string it doesn't provide an easy method for splitting a delimited string into a list of strings.
Unfortunately the only way I know how to do this is with a nested stack. You can make use of the parameter type "CommaDelimitedList" to split a comma delimited string into a list of strings.
The basic method is this:

*

*Create your security group in your cloudformation template.

*Merge that security group ID with your list of security groups using Fn::Join.

*Pass that list to a nested stack (a resource of type AWS::CloudFormation::Stack).

*Take that parameter as type "CommaDelimitedList" in the separate template.

*Pass the parameter ref into your EC2 instance declaration.

I've tested this out with the following 2 templates and it's working:
Main template:
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Parameters" : {
        "SecurityGroups" : {
            "Description" : "A comma separated list of security groups to merge with the web security group",
            "Type" : "String"
        }
    },
    "Resources" : {
        "WebSg" : ... your web security group here,
        "Ec2Instance" : {
            "Type" : "AWS::CloudFormation::Stack",
            "Properties" : {
                "TemplateURL" : "s3 link to the other stack template",
                "Parameters" : {
                    "SecurityGroups" : { "Fn::Join" : [ ",", [ { "Ref" : "WebSg" }, { "Ref" : "SecurityGroups" } ] ] },
                }
            }
        }
    }
}

The nested template (linked to by the "TemplateURL" above):
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Parameters" : {
        "SecurityGroups" : {
            "Description" : "The Security Groups to launch the instance with",
            "Type" : "CommaDelimitedList"
        },
    }
    "Resources" : {
        "Ec2Instance" : {
            "Type" : "AWS::EC2::Instance",
            "Properties" : {
                ... etc
                "SecurityGroupIds" : { "Ref" : "SecurityGroups" }
            }
        }
    }
}

I'd love to know if there's a better way to do this. As you mention it really needs an explode function.

A: You can actually write the necessary conversion function in lambda without creating a substack, to get the necessary List-String.
For example: http://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/walkthrough-custom-resources-lambda-lookup-amiids.html
In fact, this function doesn't really need to do anything other than receive list and return it back. I had a similar scenario where I had a List-AWS::EC2::Subnet::Id- and needed to pass that to a resource that required a List-String.
Process:
Define a LambdaExecutionRole.
Define a ListToStringListFunction of type AWS::Lambda::Function, add code that returns in the cfnresponse data {'Result':event['ResourceProperties']['List']}.
Define a custom resource MyList type Custom::MyList, give the ServiceToken of GetAtt the ListToStringListFunction Arn. Also pass List as a property that Refs the original list.
Reference MyList with Fn::GetAtt(MyList,Result)

A: A much simpler 2 line solution would be following:
Provided you have a common AppSecurityGroups as below in mappings or can be as a parameter:
"AppSecurityGroups" : "sg-xxx,sg-yyyy,sg-zzz"

and second security group(service specific) ServiceSecurityGroup with value sg-aaa as a parameter in your CFT.
Write a condition on service security group to check if it's None or not.
"Conditions": {
  "IsEmptySSG": {
     "Fn::Equals": [
       {"Ref": "ServiceSecurityGroup"},
       "None"
     ]
  }
}

Then merge the security groups based on the condition that ServiceSecurityGroup is not empty.
"SecurityGroups" : {
  "Fn::If" : [
    "IsEmptySSG",
    {"Fn::Split" : [ "," , {"Ref" : "AppSecurityGroups"} ]},
    {"Fn::Split" : [ "," ,
        { "Fn::Join" : [ ",", [{"Ref" : "AppSecurityGroups"}, { "Ref" : "ServiceSecurityGroup" }]]}
      ]
    }
  ]
}

This would dynamically append 2 CSV lists of security groups into one to be used by your AWS resources.
I have tested and used it for a similar problem, worked really well.

A: Following the approach of @alanthing I came up with this solution in JSON format. Just make sure the parameter is not empty, as in my case I'm not checking for that. And also note that the template is incomplete, just showing the relevant parts.
Posting it here in case it's useful for anybody.
  "Parameters": {
    "SecurityGroups": {
      "Type": "List<AWS::EC2::SecurityGroup::Id>",
      "Description": "List of security groups"
    }
  },
  "Resources": {
    "EC2Instance": {
      "Type": "AWS::EC2::Instance",
      "Properties": {
        "SecurityGroupIds": {
          "Fn::Split": [
            ",",
            {
              "Fn::Sub": [
                "${SGIdsByParam},${SGByLogicalId}",
                {
                  "SGIdsByParam": {
                    "Fn::Join": [",", {
                      "Ref": "SecurityGroups"
                    }]
                  },
                  "SGByLogicalId": {
                    "Fn::GetAtt": ["InstanceSecurityGroup", "GroupId"]
                  }
                }
              ]
            }
          ]
        }
      }


text:
Q: How can I generate markdown docs with dartdoc 6.1.2 I used to generate markdown docs for my project with dartdoc 5.1.2
However,I find that there is no command or option to generate markdown docs when I update my dartdoc to version 6.1.2
I have tried these commands:
dart doc --format md
dart doc --format=md
dart doc . -- formar md

but get this error:
Could not find an option named "format".


text:
Q: gmail api strait forward way to get sender email I'm having problems getting the sender's email address,
$single_message = $gmail->users_messages->get('me', $msg_id);

"from" usually yields the senders name
To get the email address I have this code
if($partes->getName() == 'Authentication-Results')
{
    $outh_res = $partes->getValue();
    if(strpos($outh_res, 'smtp.mailfrom=') !== false)
    {
        $bits = explode('smtp.mailfrom=',$outh_res);
        $mail = $bits[1];
        if(strpos($mail, ';') !== false)
        {
            $bits = explode(';',$mail);
            $mail = str_replace('"', '',$bits[0]);
        }
    }
}

That always gives me an email, but when the sender is behind mail chimp (or their own servers (postfix)) for example: bounces+2063633-785c-info=myemail.com@sg1.senderemail.com
In the best case I receive @sendermail.com (from gmail itself I know its info@sendermail.com) so it's useless
In some cases
if($partes->getName() == 'Reply-To')
{
    $other_mail = str_replace('"', '',$partes->getValue());
}

Gives me a helpful email others just the senders name
as suggested in github php gmail api issue # 521 and other places
$only_header = $gmail->users_messages->get('me',$msg_id, ['format' => 'metadata', 'metadataHeaders' => ['To','X-Original-To','X-Original-From','From','Reply-To','Subject']]);

It gives exactly the same info.
Is there any way that the api gives me exactly the sender email address even if it's behind mail chimp or other 3rd party sender?
There's a similar answer Get sender email from gmail-api, I already loop the headers and tried zingzinco's answer.
Edit: Thanks to Joey Tawadrous;
Php code:
if($partes->getName() == 'From')
{
    $raw_from = $partes->getValue();
    if(strpos($raw_from, '<') !== false)
    {
        $bit = explode('<',$raw_from);
        $bit2 = explode('>',$bit[1]);
        $final_email = $bit2[0];
        $sender_name = str_replace('"', '',$bit[0]);
    }
    else
    {
        $sender_name = limpiarm(str_replace('"', '',$raw_from));
    }
}

A: var email = '';

var messageFrom = _.where(message.payload.headers, {name: 'From'})[0].value;

    if(messageFrom.includes('<')) {
        var fromObj = messageFrom.split('<');
        email = fromObj[1];

        fromObj = email.split('>');
        email = fromObj[0];
    }

return email;


text:
Q: What is the value of z-coordinate in opengl I have just started learning modern opengl using lwjgl 3. I am confused with the coordinate system of opengl.
I know that when you specify the width and height of the window the coordinates are mapped to that width and height.For example if screen width is 600 the coordinate[1,0] will be mapped to[600,0].
What I wanna know is what is the distance value of z Coordinate?

A: The z coordinate corresponds to depth. It's value is usually the fraction representing the distance of the fragment between the near plane and the far plane, as demonstrated here: The camera and its near and far planes. Clipped means that a fragment is not visible.
The z/depth value is used mainly for depth testing, a process which makes objects that are behind other objects (specifically they must be occluded by them) culled. It is best described here (from learnopengl.com):

OpenGL stores all its depth information in a z-buffer, also known as a depth buffer. GLFW automatically creates such a buffer for you (just like it has a color-buffer that stores the colors of the output image). The depth is stored within each fragment (as the fragment's z value) and whenever the fragment wants to output its color, OpenGL compares its depth values with the z-buffer and if the current fragment is behind the other fragment it is discarded, otherwise overwritten. This process is called depth testing and is done automatically by OpenGL.

I highly recomend checking out learnopengl.com even if you are using LWJGL because the majority of what you can find there also applies to it.


text:
Q: Should I bind to SharedService property in WPF Prism I used a SharedService (Prism) to get data between two module. In the SharedService, I put a string property named AdapterName.
Assume that in module A has ViewAViewModel and module B has ViewBViewModel
public class ViewAViewModel : BindableBase {
    private string _adapterNameA;
    public string AdapterNameA
    {
        get { return _adapterNameA; }
        set { SetValue (ref _adapterNameA, value); }
    }

    private ISharedService _sharedService;
    public ISharedService SharedService {
        get { return _sharedService; }
        set { SetValue (ref _sharedService, value); }
    }

    public ViewAViewModel (ISharedService sharedService) {
        _sharedService = sharedService;
    }
}

public class ViewBViewModel : BindableBase {
    private string _adapterNameB;
    public string AdapterNameB {
        get { return _adapterNameB; }
        set { SetValue (ref _adapterNameB, value); }
    }

    private ISharedService _sharedService;
    public ISharedService SharedService {
        get { return _sharedService; }
        set { SetValue (ref _sharedService, value); }
    }

    public ViewBViewModel (ISharedService sharedService) {
        _sharedService = sharedService;
    }
}

public interface ISharedService {
    string AdapterName { get; set; }
}

public class SharedService : BindableBase, ISharedService {
    private string _adapterName;
    public string AdapterName {
        get { return _adapterName; }
        set { SetValue (ref _adapterName, value); }
    }
}

I have a textbox both ViewA and ViewB, and I want the value in the textbox in ViewA always the same as in ViewB. So should I change SharedService.AdapterName value in AdapterNameA get, set (similar with AdapterNameB)?
public string AdapterNameA
{
    get {
        _adapterNameA = SharedService.AdapterName;
        return _adapterNameA;
        }
    set {
        SetValue (ref _adapterNameA, value);
        SharedService.AdapterName = value;
    }
}

or binding directly to SharedService property
Text = "{Binding Path=SharedService.AdapterName, UpdateSourceTrigger=PropertyChanged}"

or another way? (I am trying making WPF MVVM with Prism)

A: If the shared service implements the INotifyPropertyChanged event and raise change notifications you could bind to its property directly provided that you really want to expose the service through a property of the view model(s). You might not want to do this dependening on what the service does.
If you don't want to expose the service, you're left with creating wrapper properties in the view models. This provides better encapsulation at the expense of some extra lines of code for the wrapper properties (if you have several).
But there is no real right or wrong here. You will have to decide which solution that makes most sense for you in this particular scenario.
In general, a service is supposed to abstract away and take care of fetching some results from somewhere and pass these back to the view model. It doesn't typically implement the INotifyPropertyChanged event and expose properties that the views bind directly to. It's the responsbility of the view model to define and expose this properties. The view model may still use the service to populate the properties.


text:
Q: Search through posts and comments I have a small social feature which is part of a bigger application.
All I'm looking for is a simple search algorithm, where I can give it a string, and it will tell me yes or no. This seems like something I would have found already, but all search discusses I've seen are too in depth for this.
I know contains is too simple. I know with an input string of four words, you try them in different combinations.
Something like:
Bool shouldIIncludeThis(string postText) {}

Would be ideal
Use case:
Have a social feature with a structure similar to a blog: posts and comments.
Posts have a field called body, and so do comments.
If someone types in "outage restoration efficiency in November", I really have no clue as to how I would properly return a list of posts based on the content of the posts and its attached comments.
So I would like to loop through a collection of posts with that text in mind, never more than 300, so I'm not looking for maximum performance. Just a simple way to send in a string through the method signature, and to have that method tell me if the post or comment in question is a good match for the string provided.
I can take care of the rest.


text:
Q: Onclick in xml by include In my project,I user onclick directly in the xml to assign a onclick methond to a button,it worked in my activityA, but when i have an activityB which setcontentview with a xml using  the xml which contains the "onclick" and add the same onclick function in my activityB,it does not work in the activityB.
What should I do to make it work?
Maybe find the button using findviewbyid and asign a new onclick to it work,but is there a more direct way to do this?

A: the onClick of activityA will not work for the button clicked in activityB..you'll have to again write the code of onClick in activityB..


text:
Q: comparing datetime variables How do I compare datetime variable passed to the store procedure with datetime variable in the table.
e.g. In my where clause @paramDate value is 2/10/2012
 set sql = 'WHERE product.RegisteredDate >= ' + @paramDate

when I exec(@sql)
it fails, Error:
 Conversion failed when converting datetime from character string.

Thx

A: SET @sql = '... WHERE product.RegisteredDate >= '''
    + CONVERT(CHAR(8), @paramDate, 112) + ''';';

If @ParamDate is NULL you can probably do this:
SET @sql = 'SELECT ...';

SET @sql = @sql + COALESCE(' WHERE product.RegisteredDate >= '''
    + CONVERT(CHAR(8), @paramDate, 112) + ''';', '');

Or even:
SET @sql = 'SELECT ...';

IF @paramDate IS NOT NULL
BEGIN
    SET @sql = @sql + '... WHERE product.RegisteredDate >= '''
        + CONVERT(CHAR(8), @paramDate, 112) + ''';';
END

A: Try this:
CONVERT(varchar, @paramDate, 101)

See here for more information:
http://msdn.microsoft.com/en-us/library/ms187928.aspx

A: Since you're trying to execute a dynamic query, you could use sp_executesql instead of exec so that you can use parameters in your generated query. Here are the details for sp_executesql.
For example:
set @sql = 'WHERE product.RegisteredDate >= @dynamicParm'

EXECUTE sp_executesql @sql, N'@dynamicParm DATETIME', @dynamicParm = @paramDate


text:
Q: Handle AADSTS70008/ AADSTS50173 error codes returned from [MSAL] [.Net] I wanted to ask about the best and documented way to catch those error codes AADSTS70008/ AADSTS50173
 returned from MSAL in case of expired tokens/authorization codes.
Is it okay to catch them in the message of the exception or how?
cause I was debugging and I didn't find those error returned in the error code field of MsalServiceException


text:
Q: Does the distribution $\log(1 + x^{-2}) / 2\pi$ have a name? I ran across this density the other day.  Has someone given this a name?
$f(x) = \log(1 + x^{-2}) / 2\pi$
The density is infinite at the origin and it also has fat tails.  I saw it used as a prior distribution in a context where many observations were expected to be small, though large values were expected as well.

A: Perhaps not.
I could not find it in this fairly extensive list of distributions:
Leemis and McQuestion 2008 Univariate Distribution Relationships. American Statistician 62(1) 45:53

A: Indeed, even the first moment does not exist.  The CDF of this distribution is given by
$$F(x) = 1/2 + \left(\arctan(x) - x \log(\sin(\arctan(x)))\right)/\pi$$
for $x \ge 0$ and, by symmetry, $F(x) = 1 - F(|x|)$ for $x \lt 0$.  Neither this nor any of the obvious transforms look familiar to me.  (The fact that we can obtain a closed form for the CDF in terms of elementary functions already severely limits the possibilities, but the somewhat obscure and complicated nature of this closed form quickly rules out standard distributions or power/log/exponential/trig transformations of them.  The arctangent is, of course, the CDF of a Cauchy (Student $t_1$) distribution, exhibiting this CDF as a (substantially) perturbed version of the Cauchy distribution, shown as red dashes.)


text:
Q: how to use "buh-bye" in daily life? How can we use "buh-bye" in daily life? Can we use it just on the phone? any restrictions?
I have seen on the web that it can be used always in informal situations.

A: If you were in a formal conversation, say, with a professor or teacher, you wouldn't want to use "buh-bye" when leaving the conversation. The proper thing to say would be goodbye, or bye. Buh-bye is something that should be used informally with friends or relatives.
Someone else had said "bye-bye" is a better alternative to buh-bye; however, I believe that, in practice, they both come off the same way. Buh-bye is what comes out when you're saying bye-bye quickly, and enunciating bye-bye may even make you seem more informal than saying buh-bye. I would imagine saying bye-bye to a little child or baby, not to an adult.
In short, stick to goodbye or bye in more formal conversations and buh-bye in more informal ones.


text:
Q: How to read collection only if UID matches collection name in Firebase Firestore? I created a Collection of user IDs for each user and I want to set the database rules to read the collection item only if the user ID matches the collection item name.
I tried something like:
 service cloud.firestore {
    match /databases/{database}/documents {
      match /{document=**} {
        allow read: if request.auth != null;
      }
      match /{userId} {
        allow read: if belongsTo(userId);
      }
      function belongsTo(userId) {
        return request.auth.uid == userId
      }
    }
    }

A: Firestore reads documents. There is no concept of reading a collection. So your rules must provide access to documents.
To grant access to all documents in the collection named after the user's UID:
  match /{userId}/{document} {
    allow read: if belongsTo(userId);
  }


text:
Q: combining date and time and changing it to GMT I have read many answers for combining date and time and nothing worked so far. I am working in Oracle SQL developer version 3.1.06 and I am trying to combine date and time stamps together. Date is in format dd-mmm-yy. And time is in the following 3 formats-
1. 0348A-- meaning 3:48 am
2. 03:48:00
3. 228 -- meaning minutes from midnight, calculated as (3*60)+48.
And for all these timestamps, I want a query that gets me to this format --
mm/dd/yyyy hh:mm:ss .
I can change the dates and times to string and attach them, but then when I work in powerpivot I am not able to change them to the required format. So, I want to do it in the query itself.
I have already tried something like this-
1. CAST(deptdt as DATETIME)+CAST(time as DATETIME)
2. CAST(depdt AS TIMESTAMP(0)) + (depdt - TIME '00:00:00' HOUR TO SECOND) AS DATETIME
Please help!!


text:
Q: Have Visual Studio Code show a preview of the file to be opened from Ctrl+P Is there a way to have Visual Studio Code show a preview of the file to be opened from Ctrl+P when I navigate over the suggestions list with the arrow keys?
I expect to see the file I navigate over in Ctrl+P in the editor below. Sublime Text has this.


text:
Q: Saving jung graph with Custom Node and Edge How can one save a JUNG graph with a custom node and edge? Problem is, till now we have been able to save a JUNG graph of fields with primitive types like integer, string, etc. But the JUNG graph custom node and edge we are working with involves using datatypes like ArrayList and some more complicated datastructures inside the the edge and/or node.
I have searched a lot on the web but came across how to save a simple custom node/edge using only int or string or double.
Moreover, my aim is not to save an image file like jpeg, etc. The point is to save it in a format which can easily be loaded again into the JUNG format when required to perform certain operations.
How can one save such a graph?
Thanks.

A: Here are two links that address saving a Jung Graph in the fashion you have described. The main point being you need to save using GraphML in order to save the data of the nodes.
This link is saving using the GraphML writer.
http://halfclosed.wordpress.com/2010/12/04/graphml-with-jung-saving/
This link is about loading from a GraphML file.
http://halfclosed.wordpress.com/2010/12/04/graphml-with-jung-loading-from-graphml/
GraphML is a file format for saving graphs, as it stores the data. It is worth noting that it doesn't necessarily save the layout. Unfortunately saving your data in the GraphML format is not completely trivial, but it can be done.


text:
Q: Qt5 App crashes on close (QWidget::show) So I have been stuck at this problem for a while now. For some reason, my application always crashes on close and this is the error message I get:

The inferior stopped because it triggered an exception.
Stopped in thread 0 by: Exception at 0x50c15a08, code: 0xc0000005: read access violation at: 0x0, flags=0x0 (first chance)

The stack shows the following:

QWidget::show Line: 7030

And this is what my main.cpp currently looks like:
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();
    return a.exec();
}

I have no clue why the crash is occurring.
A little background: This is a multi-threaded application (using both QThread and QtConcurrent). When the threads are NOT started, the application closes just fine. Hence I added the following check to ensure that the thread is being terminated properly but this is not helping:
    void MainWindow::closeEvent(QCloseEvent *event)
    {
            if (thread->isRunning()) {
                thread->terminate();
                while(!thread->isFinished()){
                }
                event->accept();
            }
    }

EDIT: How the new thread was created
QThread *myThread = new QThread(this);
        Worker *worker  = new Worker(this, user, p);
        worker->moveToThread(myThread);

        connect(myThread, SIGNAL(started()), worker, SLOT(doWork()));
        connect(worker, SIGNAL(workDone()), this, SLOT(deleteThread()));
        myThread->start();

...and this is how I am handling the deletion of the thread after the download completes:
void MainWindow::deleteThread(){
    worker->deleteLater();
    myThread->quit();
    while(!myThread->isFinished()){
    }
    myThread->deleteLater();
}

A: You should either listen for terminated signal from the thread or wait for the thread to terminate. Telling the thread to terminate doesn't block, so if you then immediately accept the close event you will get your exception.
This is described in more detail in the documentation for the terminate slot

A: Proper QThread stop code is:
myThread->quit();
myThread->wait();

Also you have used moveToThread(this);
You need to moveToThread back to parent thread first.
For example your code is:
moveToThread(this);
start();

You need to save currentThread() before moveToThread() like this:
QThread *savedThread=currentThread();

moveToThread(this);
start();

And before quit or terminate you need to restore it:
moveToThread(savedThread);

quit();
wait();

You can put it on destructor of course.


text:
Q: Spline interpolation 3D array - python I need to do an interpolation between a 3D array and 1D array with spline method and I need to have the same result as in Mathematica (I am converting a code.
from scipy.interpolate import griddata
from scipy.interpolate import LinearNDInterpolator
from scipy.interpolate import NearestNDInterpolator
points = np.array([
        [ 27.827,  18.53 , -30.417], [ 24.002,  17.759, -24.782],
        [ 22.145,  13.687, -33.282], [ 17.627,  18.224, -25.197],
        [ 29.018,  18.841, -38.761], [ 24.834,  20.538, -33.012],
        [ 26.232,  22.327, -27.735], [ 23.017,  23.037, -29.23 ],
        [ 28.761,  21.565, -31.586], [ 26.263,  23.686, -32.766]])

# and put the moisture corresponding data values in a separate array:
values = np.array([0.205,  0.197,  0.204,  0.197,  0.212,
                   0.208,  0.204,  0.205, 0.211,  0.215])
# Finally, put the desired point/points you want to interpolate over
request = np.array([[25, 20, -30], [2, 1, -3]])
linInter= LinearNDInterpolator(points, values)
linInter1 = NearestNDInterpolator(points,values)
output= linInter1(np.array([[27,20,-32],[2,2,-3]]))

The result of my output in python is:
array([0.205, 0.197])
The result of my output in mathematica is:
[0.202864,0.0298707]

I think that the main problem is due to the extrapolation.
In this case what should be the function that could give me the nearest value as in Mathematica?

Thanks

I need to have the same result or almost the same as Mathematica


text:
Q: Prime ideals of a quotient ring. I  want to prove that
If R  is any ring  and  I be an ideal, then an ideal P containing I is a prime ideal of R   iff   P/I is prime ideal of R /I.
Could you check my proof ?
Proof:  Let P be a prime ideal  .   To prove first P/I is prime ideal of  R/I. Let $ (a+I), (b+I) \in R/I$  such that
$(a+I)( b+I) \in P/I$. Then  $ab+I \in P/I$. It implies  $ab \in P$.
As P is prime,  $a \in P$ or $b \in P \implies a +I \in P/I$ or $b+I\in P/I$
Hence $P/I$ is prime.
Conversely,  let $P/I$ be a prime ideal of $R/I$. let us prove that $P$ is prime ideal of  $R$ .     Let $a,b \in R$ such that  $ab \in P$ then
  $ab+I \in P/I \implies ( a+I)(b+I) \in P/I$.
As  $P/I$ is prime, $a+I \in P/I$  or $b+I \in P/I \implies  a \in P$ or $b \in P$ .

A: Here is the standard way of proving this: By some of these isomorphism theorems, we have $(R/I)/(P/I) \cong R/P$. This immediately gives you all you need.


text:
Q: R: Loop to capture weather data from multiple station I wanted to perform loop to capture weather data from multiple stations using code below:
library(rwunderground)

sample_df <- data.frame(airportid = c("K6A2",
                                      "KAPA",
                                      "KASD",
                                      "KATL",
                                      "KBKF",
                                      "KBKF",
                                      "KCCO",
                                      "KDEN",
                                      "KFFC",
                                      "KFRG"),
                        stringsAsFactors = FALSE)

history_range(set_location(airport_code =sample_df$airportid), date_start = "20170815", date_end = "20170822",
              limit = 10, no_api = FALSE, use_metric = FALSE, key = get_api_key(),
              raw = FALSE, message = TRUE)

It won't work.

A: Currently, you are passing the entire vector (multiple character values) into the history_range call. Simply lapply to iteratively pass the vector values and even return a list of history_range() return objects. Below uses a defined function to pass the parameter. Extend the function as needed to perform other operations.
capture_weather_data <- function(airport_id) {
    data <- history_range(set_location(airport_code=airport_id),
                  date_start = "20170815", date_end = "20170822",
                  limit = 10, no_api = FALSE, use_metric = FALSE, key = get_api_key(),
                  raw = FALSE, message = TRUE)

    write.csv(data, paste0("/path/to/output/", airport_id, ".csv"))
    return(data)
}

data_list <- lapply(sample_df$airportid, capture_weather_data)

Also, name each item in list to the corresponding airport_id character value:
data_list <- setNames(data_list, sample_df$airportid)

data_list$K6A2   # 1st ITEM
data_list$KAPA   # 2nd ITEM
data_list$KASD   # 3rd ITEM
...

In fact, with sapply (the wrapper to lapply) you can generate list and name each item in same call but the input vector must be a character type (not factor):
data_list <- sapply(as.character(sample_df$airportid), capture_weather_data,
                    simplify=FALSE, USE.NAMES=TRUE)
names(data_list)

A: I think this history_range function that you brought up, from the rwunderground package as I understand, requires a weather underground API key. I went to the site and even signed up for it, but the email validation process in order to get a key (https://www.wunderground.com/weather/api) doesn't seem to be working correctly at the moment.
Instead I went to the CRAN mirror (https://github.com/cran/rwunderground/blob/master/R/history.R) and from what I understand, the function accepts only one string as set_location argument. The example provided in the documentation is
history(set_location(airport_code = "SEA"), "20130101")

So what you should be doing as a "loop", instead, is
sample_df <- as.vector(sample_df)
for(i in 1:length(sample_df)){
  history_range(
    set_location(airport_code = sample_df[[i]]),
    date_start = "20170815", date_end = "20170822",
    limit = 10, no_api = FALSE, use_metric = FALSE,
    key = get_api_key(),
    raw = FALSE, message = TRUE)
}

If this doesn't work, let me know. (Ack, somebody also gave another answer to this question while I was typing this up.)


text:
Q: Single word for "people with premonition" What do you call people who have great power of premonition?

A: Psychic is the suitable word to describe people who have great power of premonition. Psychic (noun) is "a person who has a special mental ability, for example being able to know what will happen in the future or what people are thinking" (Source: Cambridge Dictionaries).
It originated  in early 19th century from Greek "psukhikos" ( Ref: http://dictionary.reference.com/browse/psychic).

A: A sensitive. (from M-W)

*

*a person having occult or psychical abilities.

*a person with psychic powers; medium.


text:
Q: Content Type not queryable in Content Search Web part Essentially what I'm trying to achieve is to have a page with two Content Search Web Parts that each pull back items of a specific content type. To do this I have created a few custom content types on my site, however I only seem to be able to query/refine by one of content types and not by the other.
I can't think of anything I may have done differently when setting up the content types (they both have the same parent, same group and almost identical columns).
Can anyone weigh in on where I may be going wrong?
Edit: Using SharePoint Online
Thanks


text:
Q: Why are files my sandboxed app creates/renames getting the com.apple.quarantine attribute? I am writing temporary files from a sandboxed app that need to be executable, but they are marked as quarantine despite changing the usual settings.
I've explicitly set LSFileQuarantineEnabled to NO in my app's Info.plist just in case (this is already supposed to be the default) with no change.
Based on a comment at How can I stop my app from setting the "quarantine" bit?, I've also tried adding com.apple.security.files.user-selected.executable = YES to my app's entitlements files but that has no effect either. (The destination files are not "user selected" — maybe that's why not?)
Is there any other configuration that would prevent the system from marking written files as quarantined? Note that my app does not need to pass Apple censorship; I am opting in to the sandbox voluntarily.


text:
Q: How can I simplify my matlab code? Can't find a way that works fine Need help for simplifying my matlab code.
lambda = 1;
k = 2*pi/lambda;
w = 2*pi*v/lambda;
z=linspace(0,10,10000);
t=linspace(0,10,10);  %time
theta=(pi)*rand(1,length(t));   %random phase
for a=1:length(t)
    u1=1./(1+exp(-2.*(10e4).*(t(a)-z./v)));   %step function
    u2=1./(1+exp(-2.*(10e4).*(t(a)-z./v-1)));
    u3=1./(1+exp(-2.*(10e4).*(t(a)-z./v-2)));
    u4=1./(1+exp(-2.*(10e4).*(t(a)-z./v-3)));
    u5=1./(1+exp(-2.*(10e4).*(t(a)-z./v-4)));
    u6=1./(1+exp(-2.*(10e4).*(t(a)-z./v-5)));
    u7=1./(1+exp(-2.*(10e4).*(t(a)-z./v-6)));
    u8=1./(1+exp(-2.*(10e4).*(t(a)-z./v-7)));
    u9=1./(1+exp(-2.*(10e4).*(t(a)-z./v-8)));
    u10=1./(1+exp(-2.*(10e4).*(t(a)-z./v-9)));
    del_u1=u1-u2;
    del_u2=u2-u3;
    del_u3=u3-u4;
    del_u4=u4-u5;
    del_u5=u5-u6;
    del_u6=u6-u7;
    del_u7=u7-u8;
    del_u8=u8-u9;
    del_u9=u9-u10;
    y1=del_u1.*cos(k.*z-w.*t(a)+theta(1));
    y2=del_u2.*cos(k.*z-w.*t(a)+theta(2));
    y3=del_u3.*cos(k.*z-w.*t(a)+theta(3));
    y4=del_u4.*cos(k.*z-w.*t(a)+theta(4));
    y5=del_u5.*cos(k.*z-w.*t(a)+theta(5));
    y6=del_u6.*cos(k.*z-w.*t(a)+theta(6));
    y7=del_u7.*cos(k.*z-w.*t(a)+theta(7));
    y8=del_u8.*cos(k.*z-w.*t(a)+theta(8));
    y9=del_u9.*cos(k.*z-w.*t(a)+theta(9));
    y10=u10.*cos(k.*z-w.*t(a)+theta(10));
    yy=y1+y2+y3+y4+y5+y6+y7+y8+y9+y10;
    figure(1)
    plot(z,yy); grid on; axis image;
    drawnow;
end

The equation is not complicated but I got hard time trying to simplify it. I'm suppose to repeat the equation 1000 times, means
length(theta)=1000, u1~u1000, del_u1~del_u999, y1~y1000, yy=y1+y2+...y1000.
How can I simplify my code?

A: This is Matlab, aka Matrix Laboratory. Write it in matrix form !
instead of u1 , u2, ... write the vector\array u ,  the del_u will become u(1:end-1,:)-u(2:end,:) etc.
same for if y is a vector\array  [y1 y2 y3...]... then yy=sum(y).
This is very very basic matlab programing, you can read all about it in the documentation.
EDIT:
Here is an identical version of your code in the question (written and tested in Matlab 2019b), showing how to obtain the arrays and implement vectorization instead the inflation of variables u1,u2, and for loop etc.
u        = 1./(1+exp(-2.*(10e4).*  (t'-permute(0:9,[3 1 2])-z./v) ));
del_u    = cat(3,u(:,:,1:end-1)-u(:,:,2:end), u(:,:,end));
cos_term = cos(k.*z-w.*t'+permute(theta,[3 1 2]));
yy       = sum(del_u.*cos_term,3) ;

A: This code works well, without a need to change it when the size of the data is changed. This code also runs faster:
v = 1;
lambda = 1;
k = 2*pi/lambda;
w = 2*pi.*v./lambda;
z=linspace(0,10,10000);
t=linspace(0,10,10);  %time
theta=(pi)*rand(1,length(t));   %random phase
for a=1:length(t)
   u = 1./(1+exp(-2.*(10e4).*(bsxfun(@minus, t(a) - z./v, [0:9]'))));
   del_u = [u(1:end-1, :)-u(2:end, :); u(end, :)];
   y = del_u.*cos(bsxfun(@plus, k.*z - w.*t(a), theta'));
   yy = sum(y);
   figure(1)
   plot(z,yy); grid on; axis image;
   drawnow;
end


text:
Q: Pop-up error while using command login to appcenter code push I´m having an error while trying to login to into code-push to get my keys, tried using both code-push and appcenter cli login command and didn't work.
pop-up print


text:
Q: Composite fields in Birt I'm a total beginner with Birt (actually it's my first day with it) and my task is to create a Birt report that looks exactly like one done in Flash/Flex ... This report is looking really well.
The problem is: Im my Flex solution I have one field of a DataGrid that consists of a Label followed by a numeric output, if the numeric value is 0 or greater.
Based upon two values of a recordsets row I get an Internationalized Value by applying Mapping features of Birt (This allready works great). The resulting String should then be appended with "({value})" if value is greater or equal 0.
When using the designer, I can only place a second field in it's own table cell or table row, but I seem to be unable to output both fields in one table cell.
It would be great if someone could guide me through this.
Chris

A: You may build entire string in Dynamic Text JavaScript expession.
Using i18n in Javascript is briefly described in BIRT FAQ. The one interesting question could be How can I localize strings in JavaScript - this expression gives localized text:
reportContext.getMessage("companyNameKey", reportContext.getLocale())

Row data is stored in the row array. All available fields you can find in an Expression Builder. As you found and double-clicked desired field, it appears expression like this:
row["FOO_NUMBER"].value

Putting all together:
reportContext.getMessage("Foo number:", reportContext.getLocale()) +
  (row["FOO_NUMBER"].value > 0) ? ( "("+row["FOO_NUMBER"].value+")" ) : ("")

A: Thanks to jinowolskis post ... just wanted to add the full solution just if anyone runs into the same problem :-)
importPackage( Packages.java.text );
var myKey = "" + row["vulnerabilityClass"] + "." + row["result"];
if(row["cvssScore"] >= 0) {
    var nf = NumberFormat.getNumberInstance(reportContext.getLocale());
    nf.setMinimumFractionDigits(1);
    nf.setMaximumFractionDigits(1);
    reportContext.getMessage(myKey, reportContext.getLocale()) + " (" + nf.format(row["cvssScore"]) + ")";
} else {
    reportContext.getMessage(myKey, reportContext.getLocale());
}


text:
Q: change color of words within an array if i have an javascript array of words
var keywords = ["select","from","where","mars"];

and HTML element holding a text

Hello from planet mars

How to use javascript to color in orange any word found in this element mytext of words list in the array keywords !

A: Here is one way to do it:

var keywords = ["select", "from", "where", "mars"];

let originalText = document.querySelector("#mytext").innerText

for (const word of keywords) {
  originalText = originalText.replace(new RegExp(word, "g"), `<span class="orange">${word}</span>`)
}

document.querySelector("#mytext").innerHTML = originalText
.orange {
  color: orange;
}

Hello from planet mars

we are iterating over the keywords and replacing the innerHTML with a new content where we would wrap mentions of the keyword with a markup that would give it a color.

A:

var keywords = ["select","from","where","mars"];
let div = document.getElementById('mytext')
let text_content = div.textContent.split(' ')

let html = text_content.map(e => {

    return keywords.includes(e) ? `<span class='orange'>${e}</span>` : e })

div.innerHTML = html.join(' ')

.orange{
  color:orange;
  }

Hello from planet mars

A:

Hello from planet mars

You can use this code and replace the orange color with the color you want

var keywords = ["select","from","where","mars"];
                mytext=document.getElementById("mytext");
                len=keywords.length;
                for(i=0;i<len;i++){
                    mytext.innerHTML=mytext.innerHTML.replaceAll(keywords[i],""+ keywords[i] +"");
                }

Hello from planet mars

A: you can try
var keywords = ["select","from","where","mars"];
const el = document.querySelector('#mytext');
keywords.map(kw => el.innerText = el.innerText.replace(new RegExp(kw, 'g'), '' + kw + ''))
el.innerHTML = el.innerText

A: Yet another regex option, but creating a single regex out of the array resulting in a single query/innerHTML assignment.

const keywords = ["select","from","where","mars"];

const mytext = document.getElementById('mytext');

mytext.innerHTML = mytext.textContent.replace(
  new RegExp(`\\b${keywords.join('\\b|\\b')}\\b`, 'g'),
  (match) => `<span class='orange'>${match}</span>`
);
.orange {
  color: orange;
}

Hello from planet mars, select from fromage mars.

The resulting regex
/\bselect\b|\bfrom\b|\bwhere\b|\bmars\b/g


text:
Q: OpenJPA in OSGi not finding MySQL JDBC Connector Bundle I am currently working on an OSGi project on Felix (v4.0.3). I need to use JPA so I have installed the Apache Aries JPA bundles. I also installed OpenJPA   and I need it to connect to a MySQL Database, using the MySQL Connector Bundle. Unfortunately it does not work, OpenJPA says it cannot find the MySQL JDBC class and I cannot figure out what's broken, maybe I am doing something wrong. I'll explain below what I installed precisely along with the persistence.xml file and the actual exception I get.
Here's the list of the Apache Aries bundles I installed :

*

*org.apache.aries.jpa.api-0.3.jar

*org.apache.aries.jpa.container.context-0.3.jar

*org.apache.aries.jpa.container-0.3.jar

*org.apache.aries.util-0.4.jar

I then installed the dependencies of those Apache Aries JPA bundles. I downloaded them from Springsource :

*

*com.springsource.javax.transaction-1.1.0.jar

*com.springsource.org.apache.log4j-1.2.16.jar

*com.springsource.slf4j.api-1.6.1.jar

*com.springsource.slf4j.log4j-1.6.1.jar

*javax.persistence_2.0.4.v201112161009.jar (this one is from EclipseLink in case it matters)

I also installed OpenJPA and all its dependencies. I found bundles 2 to 5 (commons-*) in the lib folder of the apache-openjpa-2.2.0 downloaded folder. I downloaded Serp here because the jar found in the lib folder wasn't an OSGi bundle. Finally I found the last two bundles (#7 and #8) in Springsource :

*

*openjpa-2.2.0.jar

*commons-collections-3.2.1.jar

*commons-dbcp-1.4.jar

*commons-lang-2.4.jar

*commons-pool-1.5.4.jar

*org.apache.servicemix.bundles.serp-1.13.1_4.jar

*com.springsource.javax.servlet-2.5.0.jar

*com.springsource.org.objectweb.asm-3.2.0.jar

Once I finally had OpenJPA installed, I still needed the MySQL JDBC Driver bundle, which I also got from the Springsource repository along with its commons-logging dependency :

*

*com.springsource.com.mysql.jdbc-5.1.6.jar

*com.springsource.org.apache.commons.logging-1.1.1.jar

Now at this point the list of bundles installed is getting quite large. I said I installed OpenJPA but it's only because I could not figure out how to use any other provider with Aries. I initially wanted to use EclipseLink but apparently Apache Aries does not detect it as a provider and according to this blog you have to make yet another bundle containing your own activator for Aries to notice EclipseLink. I tried it but it didn't work so I fell back on using OpenJPA instead.
So now I have two questions :

*

*How can I make OpenJPA notice my MySQL Bundle ?

OR alternatively :

*

*How can I make Apache Aries notice EclipseLink ?

Here's the persistence.xml file I use :
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="userManager.model" transaction-type="RESOURCE_LOCAL">
    <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
    <class>org.project.dao.entity.UserEntity</class>
    <properties>
        <property name="openjpa.ConnectionDriverName" value="com.mysql.jdbc.Driver" />
        <property name="openjpa.ConnectionURL" value="jdbc:mysql://localhost:3306/usermanager?autoReconnect=true" />
        <property name="openjpa.ConnectionUserName" value="root" />
        <property name="openjpa.ConnectionPassword" value="root" />
    </properties>
</persistence-unit>
</persistence>

The error occurs when the following Constructor of my DAO class is executed :
    @PersistenceContext(unitName="userManager.model")
private EntityManager em;
private EntityManagerFactory emf;

public UserDAOBean() {
    em = emf.createEntityManager();
}

Here's the error I get with OpenJPA not finding MySQL. Of course it is worth mentioning that both the URL and the username/password do work :
<openjpa-2.2.0-r422266:1244990 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: There were errors initializing your configuration: <openjpa-2.2.0-r422266:1244990 fatal user error> org.apache.openjpa.util.UserException: A connection could not be obtained for driver class "com.mysql.jdbc.Driver" and URL "jdbc:mysql://localhost:3306/usermanager?autoReconnect=true".  You may have specified an invalid URL.
at org.apache.openjpa.jdbc.schema.DataSourceFactory.newConnectException(DataSourceFactory.java:255)
at org.apache.openjpa.jdbc.schema.DataSourceFactory.newDataSource(DataSourceFactory.java:123)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.createConnectionFactory(JDBCConfigurationImpl.java:844)
at org.apache.openjpa.jdbc.conf.JDBCConfigurationImpl.getConnectionFactory(JDBCConfigurationImpl.java:732)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.openjpa.lib.conf.ConfigurationImpl.instantiateAll(ConfigurationImpl.java:295)
at org.apache.openjpa.conf.OpenJPAConfigurationImpl.instantiateAll(OpenJPAConfigurationImpl.java:1671)
at org.apache.openjpa.kernel.AbstractBrokerFactory.makeReadOnly(AbstractBrokerFactory.java:646)
at org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBrokerFactory.java:203)
at org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBrokerFactory.java:156)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:227)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:154)
at org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityManager(EntityManagerFactoryImpl.java:60)
at org.apache.aries.jpa.container.impl.CountingEntityManagerFactory.createEntityManager(CountingEntityManagerFactory.java:64)
at javax.persistence.EntityManagerFactory$$Proxy.createEntityManager(Unknown Source)

I've cut the exception (it keeps going on and on) until this point :
Caused by: java.lang.ClassNotFoundException: com.mysql.jdbc.Driver not found by org.apache.openjpa [12]
at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1460)
at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:72)
at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1843)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:169)
at org.apache.openjpa.jdbc.schema.DataSourceFactory.newDataSource(DataSourceFactory.java:85)
... 108 more

PS: I couldn't post the links to Aries, OpenJPA or EclipseLink because of the spam restriction, sorry :/

A: Thanks to Holly Cummins and after another bunch of hours of research, I've been able to find a solution to my problem. I'll detail it below, this is going to be a very long answer.
If you want to use EclipseLink with Apache Aries (which I find orders of magnitude simpler to install than OpenJPA for OSGi because it's contained in only 5 bundles), you will have to checkout the EclipseLink - Aries adapter directly from apache because it has not been released yet.
Go to an appropriate folder and execute the following command to get it :
svn checkout https://svn.apache.org/repos/asf/aries/trunk/jpa/jpa-container-eclipselink-adapter/

You should get a folder named jpa-container-eclipselink-adapter. Now, assuming that you are using Linux and have Maven installed, run the following commands :
cd jpa-container-eclipselink-adapter
mvn clean install

Once Maven has successfully compiled the source of the adapter, you will find it in your Maven repository using the path
<maven-repo>/org/apache/aries/jpa/org.apache.aries.jpa.eclipselink.adapter/0.3.1-SNAPSHOT/org.apache.aries.jpa.eclipselink.adapter-0.3.1-SNAPSHOT.jar

You'll have to deploy this bundle with the others (copying it in the bundle folder for Felix).
So that was for the EclipseLink part, now in order to make your persistence actually work you'll have to use Blueprint with Aries. Here is the list of all the bundles you'll need to get from the [http://aries.apache.org/downloads/currentrelease.html](Apache Aries download page)

*

*org.apache.aries.blueprint

*org.apache.aries.proxy

*org.apache.aries.jndi.api

*org.apache.aries.jndi

*org.apache.aries.blueprint

*org.apache.aries.jpa.api

*org.apache.aries.jpa.container.context

*org.apache.aries.jpa.container

*org.apache.aries.transaction.blueprint

*org.apache.aries.transaction.manager (This one is listed twice on their site, it's just a duplicate)

*org.apache.aries.util

Once you're done downloading Aries, you still need dependencies (get them from SpringSource). These are the bundles for SLF4J, Log4J, SLF4J Log4J Binding and javax.transaction 1.1 API.

*

*http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.slf4j.api&version=1.6.1

*http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.slf4j.log4j&version=1.6.1

*http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.javax.transaction&version=1.1.0

*http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.apache.log4j&version=1.2.16
You'll also need the bundles from EclipseLink (you need the OSGi bundle version)
http://www.eclipse.org/eclipselink/downloads/
Open the zip and get the following files :

*

*org.eclipse.persistence.antlr

*org.eclipse.persistence.asm

*org.eclipse.persistence.core

*org.eclipse.persistence.jpa

*javax.persistence

Finally, assuming that you want to use a MySQL database, you'll need the bundles for the MySQL JDBC Driver (downloaded from Springsource)

*

*http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.com.mysql.jdbc&version=5.1.6

*http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.org.apache.commons.logging&version=1.1.1
Once you have all those bundles installed, you need to use a non-jta-datasource that you will get through JNDI. Here's a persistence.xml file that you can change for your needs :

<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd"
    version="2.0" xmlns="http://java.sun.com/xml/ns/persistence">
    <persistence-unit name="userManager" transaction-type="RESOURCE_LOCAL">
        <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
        <non-jta-data-source>osgi:service/javax.sql.DataSource/(osgi.jndi.service.name=jdbc/userManagerDS)</non-jta-data-source>
        <class>com.example.dao.entity.UserEntity</class>
        <exclude-unlisted-classes>true</exclude-unlisted-classes>
        <properties>
            <!-- EclipseLink should create the database schema automatically -->
            <!-- <property name="eclipselink.ddl-generation" value="create-tables" />
            <property name="eclipselink.ddl-generation.output-mode" value="database" /> -->
        </properties>
    </persistence-unit>
</persistence>

See the javax.sql.Datasource in the non-jta-data-source tag ? That's what we'll define using Blueprint xml.
In order to do so, you'll first need to add the OSGI-INF/blueprint/ folders in your persistence bundle (the one containing your DAOs and Entities). This is the default folder where blueprint xml files are located, any xml file located here will be scanned. Once that's done, create the blueprint.xml file (the name can be changed) and paste (and modify) the following code :

        <bean id="dataSource" class="com.mysql.jdbc.jdbc2.optional.MysqlDataSource">
        <property name="url" value="jdbc:mysql://localhost:3306/usermanager?autoReconnect=true" />
        <property name="user" value="root" />
        <property name="password" value="root" />
    </bean>

    <service id="MySQLDataSource" interface="javax.sql.DataSource" ref="dataSource">
        <service-properties>
            <entry key="osgi.jndi.service.name" value="jdbc/userManagerDS" />
        </service-properties>
    </service>

    <service id="userDAOService" interface="com.example.dao.remote.UserDAORemote">
        <bean class="com.example.dao.beans.UserDAOBean">
            <jpa:unit index="0" unitname="userManager" />
        </bean>
    </service>
</blueprint>

Here, we are doing two things. First, we tell Aries to create the userManagerDS datasource and configure it with the JDBC Driver, URL, user and password. This is the same datasource that we used in the persistence.xml file.
Then, we inject the EntityManagerFactory in our DAO. Our DAO is the com.example.dao.beans.UserDAOBean class, we need to add its name to the bean tag. This class will have to implement an interface and we'll need to add this interface to the service tag. Now the final jpa:unit tag tells Aries to inject the EntityManagerFactory related to the persistence unit called userManager (the same name we used in the persistence.xml) by using the first constructor of UserDAOBean. This is done by using the index="0" attribute. This also means you have to have some code like the following in your DAO :

private EntityManager em;
private EntityManagerFactory emf;

public UserDAOBean(EntityManagerFactory emf) {
    this.emf = emf;
    this.em = emf.createEntityManager();
}

It's also possible to inject the EMF using a setter. Here are further resources to help you use Blueprint :

*

*http://aries.apache.org/modules/jpaproject.html

*http://aries.apache.org/modules/blueprint.html

*http://mail-archives.apache.org/mod_mbox/aries-user/201104.mbox/%3C15F2C30E-2A71-4320-9992-DBCF181B58E4@gmail.com%3E
Optional : Be careful, if you are using Felix, adding the javax.transaction bundle will cause a "uses constraint violation" because the system bundle (bundle 0) also exports this API. You'll have to keep it from exporting it by changing the following line in the config.properties :
#org.osgi.framework.system.packages=

You'll have to put in here the list of all the packages that the previous bundle exported. Unfortunately, there's no way to "remove" a package, you have to redefine the entire list of packages to be exported. Here's mine, I hope it helps (yes it is very, very long) :
org.osgi.framework.system.packages=org.osgi.framework;version=1.6.0, org.osgi.framework.launch;version=1.0.0, org.osgi.framework.wiring;version=1.0.0, org.osgi.framework.startlevel;version=1.0.0, org.osgi.framework.hooks.bundle;version=1.0.0, org.osgi.framework.hooks.resolver;version=1.0.0, org.osgi.framework.hooks.service;version=1.1.0, org.osgi.framework.hooks.weaving;version=1.0.0, org.osgi.service.packageadmin;version=1.2.0, org.osgi.service.startlevel;version=1.1.0, org.osgi.service.url;version=1.0.0, org.osgi.util.tracker;version=1.5.0, javax.accessibility;version=0.0.0.1_006_JavaSE, javax.activation;version=0.0.0.1_006_JavaSE, javax.activity;version=0.0.0.1_006_JavaSE, javax.annotation.processing;version=0.0.0.1_006_JavaSE, javax.annotation;version=0.0.0.1_006_JavaSE, javax.crypto.interfaces;version=0.0.0.1_006_JavaSE, javax.crypto.spec;version=0.0.0.1_006_JavaSE, javax.crypto;version=0.0.0.1_006_JavaSE, javax.imageio.event;version=0.0.0.1_006_JavaSE, javax.imageio.metadata;version=0.0.0.1_006_JavaSE, javax.imageio.plugins.bmp;version=0.0.0.1_006_JavaSE, javax.imageio.plugins.jpeg;version=0.0.0.1_006_JavaSE, javax.imageio.spi;version=0.0.0.1_006_JavaSE, javax.imageio.stream;version=0.0.0.1_006_JavaSE, javax.imageio;version=0.0.0.1_006_JavaSE, javax.jws.soap;version=0.0.0.1_006_JavaSE, javax.jws;version=0.0.0.1_006_JavaSE, javax.lang.model.element;version=0.0.0.1_006_JavaSE, javax.lang.model.type;version=0.0.0.1_006_JavaSE, javax.lang.model.util;version=0.0.0.1_006_JavaSE, javax.lang.model;version=0.0.0.1_006_JavaSE, javax.management.loading;version=0.0.0.1_006_JavaSE, javax.management.modelmbean;version=0.0.0.1_006_JavaSE, javax.management.monitor;version=0.0.0.1_006_JavaSE, javax.management.openmbean;version=0.0.0.1_006_JavaSE, javax.management.relation;version=0.0.0.1_006_JavaSE, javax.management.remote.rmi;version=0.0.0.1_006_JavaSE, javax.management.remote;version=0.0.0.1_006_JavaSE, javax.management.timer;version=0.0.0.1_006_JavaSE, javax.management;version=0.0.0.1_006_JavaSE, javax.naming.directory;version=0.0.0.1_006_JavaSE, javax.naming.event;version=0.0.0.1_006_JavaSE, javax.naming.ldap;version=0.0.0.1_006_JavaSE, javax.naming.spi;version=0.0.0.1_006_JavaSE, javax.naming;version=0.0.0.1_006_JavaSE, javax.net.ssl;version=0.0.0.1_006_JavaSE, javax.net;version=0.0.0.1_006_JavaSE, javax.print.attribute.standard;version=0.0.0.1_006_JavaSE, javax.print.attribute;version=0.0.0.1_006_JavaSE, javax.print.event;version=0.0.0.1_006_JavaSE, javax.print;version=0.0.0.1_006_JavaSE, javax.rmi.CORBA;version=0.0.0.1_006_JavaSE, javax.rmi.ssl;version=0.0.0.1_006_JavaSE, javax.rmi;version=0.0.0.1_006_JavaSE, javax.script;version=0.0.0.1_006_JavaSE, javax.security.auth.callback;version=0.0.0.1_006_JavaSE, javax.security.auth.kerberos;version=0.0.0.1_006_JavaSE, javax.security.auth.login;version=0.0.0.1_006_JavaSE, javax.security.auth.spi;version=0.0.0.1_006_JavaSE, javax.security.auth.x500;version=0.0.0.1_006_JavaSE, javax.security.auth;version=0.0.0.1_006_JavaSE, javax.security.cert;version=0.0.0.1_006_JavaSE, javax.security.sasl;version=0.0.0.1_006_JavaSE, javax.sound.midi.spi;version=0.0.0.1_006_JavaSE, javax.sound.midi;version=0.0.0.1_006_JavaSE, javax.sound.sampled.spi;version=0.0.0.1_006_JavaSE, javax.sound.sampled;version=0.0.0.1_006_JavaSE, javax.sql.rowset.serial;version=0.0.0.1_006_JavaSE, javax.sql.rowset.spi;version=0.0.0.1_006_JavaSE, javax.sql.rowset;version=0.0.0.1_006_JavaSE, javax.sql;version=0.0.0.1_006_JavaSE, javax.swing.border;version=0.0.0.1_006_JavaSE, javax.swing.colorchooser;version=0.0.0.1_006_JavaSE, javax.swing.event;version=0.0.0.1_006_JavaSE, javax.swing.filechooser;version=0.0.0.1_006_JavaSE, javax.swing.plaf.basic;version=0.0.0.1_006_JavaSE, javax.swing.plaf.metal;version=0.0.0.1_006_JavaSE, javax.swing.plaf.multi;version=0.0.0.1_006_JavaSE, javax.swing.plaf.synth;version=0.0.0.1_006_JavaSE, javax.swing.plaf;version=0.0.0.1_006_JavaSE, javax.swing.table;version=0.0.0.1_006_JavaSE, javax.swing.text.html.parser;version=0.0.0.1_006_JavaSE, javax.swing.text.html;version=0.0.0.1_006_JavaSE, javax.swing.text.rtf;version=0.0.0.1_006_JavaSE, javax.swing.text;version=0.0.0.1_006_JavaSE, javax.swing.tree;version=0.0.0.1_006_JavaSE, javax.swing.undo;version=0.0.0.1_006_JavaSE, javax.swing;version=0.0.0.1_006_JavaSE, javax.tools;version=0.0.0.1_006_JavaSE, javax.transaction.xa;version=0.0.0.1_006_JavaSE, javax.transaction;version=0.0.0.1_006_JavaSE, javax.xml.bind.annotation.adapters;version=0.0.0.1_006_JavaSE, javax.xml.bind.annotation;version=0.0.0.1_006_JavaSE, javax.xml.bind.attachment;version=0.0.0.1_006_JavaSE, javax.xml.bind.helpers;version=0.0.0.1_006_JavaSE, javax.xml.bind.util;version=0.0.0.1_006_JavaSE, javax.xml.bind;version=0.0.0.1_006_JavaSE, javax.xml.crypto.dom;version=0.0.0.1_006_JavaSE, javax.xml.crypto.dsig.dom;version=0.0.0.1_006_JavaSE, javax.xml.crypto.dsig.keyinfo;version=0.0.0.1_006_JavaSE, javax.xml.crypto.dsig.spec;version=0.0.0.1_006_JavaSE, javax.xml.crypto.dsig;version=0.0.0.1_006_JavaSE, javax.xml.crypto;version=0.0.0.1_006_JavaSE, javax.xml.datatype;version=0.0.0.1_006_JavaSE, javax.xml.namespace;version=0.0.0.1_006_JavaSE, javax.xml.parsers;version=0.0.0.1_006_JavaSE, javax.xml.soap;version=0.0.0.1_006_JavaSE, javax.xml.stream.events;version=0.0.0.1_006_JavaSE, javax.xml.stream.util;version=0.0.0.1_006_JavaSE, javax.xml.stream;version=0.0.0.1_006_JavaSE, javax.xml.transform.dom;version=0.0.0.1_006_JavaSE, javax.xml.transform.sax;version=0.0.0.1_006_JavaSE, javax.xml.transform.stax;version=0.0.0.1_006_JavaSE, javax.xml.transform.stream;version=0.0.0.1_006_JavaSE, javax.xml.transform;version=0.0.0.1_006_JavaSE, javax.xml.validation;version=0.0.0.1_006_JavaSE, javax.xml.ws.handler.soap;version=0.0.0.1_006_JavaSE, javax.xml.ws.handler;version=0.0.0.1_006_JavaSE, javax.xml.ws.http;version=0.0.0.1_006_JavaSE, javax.xml.ws.soap;version=0.0.0.1_006_JavaSE, javax.xml.ws.spi;version=0.0.0.1_006_JavaSE, javax.xml.ws.wsaddressing;version=0.0.0.1_006_JavaSE, javax.xml.ws;version=0.0.0.1_006_JavaSE, javax.xml.xpath;version=0.0.0.1_006_JavaSE, javax.xml;version=0.0.0.1_006_JavaSE, org.ietf.jgss;version=0.0.0.1_006_JavaSE, org.omg.CORBA.DynAnyPackage;version=0.0.0.1_006_JavaSE, org.omg.CORBA.ORBPackage;version=0.0.0.1_006_JavaSE, org.omg.CORBA.TypeCodePackage;version=0.0.0.1_006_JavaSE, org.omg.CORBA.portable;version=0.0.0.1_006_JavaSE, org.omg.CORBA;version=0.0.0.1_006_JavaSE, org.omg.CORBA_2_3.portable;version=0.0.0.1_006_JavaSE, org.omg.CORBA_2_3;version=0.0.0.1_006_JavaSE, org.omg.CosNaming.NamingContextExtPackage;version=0.0.0.1_006_JavaSE, org.omg.CosNaming.NamingContextPackage;version=0.0.0.1_006_JavaSE, org.omg.CosNaming;version=0.0.0.1_006_JavaSE, org.omg.Dynamic;version=0.0.0.1_006_JavaSE, org.omg.DynamicAny.DynAnyFactoryPackage;version=0.0.0.1_006_JavaSE, org.omg.DynamicAny.DynAnyPackage;version=0.0.0.1_006_JavaSE, org.omg.DynamicAny;version=0.0.0.1_006_JavaSE, org.omg.IOP.CodecFactoryPackage;version=0.0.0.1_006_JavaSE, org.omg.IOP.CodecPackage;version=0.0.0.1_006_JavaSE, org.omg.IOP;version=0.0.0.1_006_JavaSE, org.omg.Messaging;version=0.0.0.1_006_JavaSE, org.omg.PortableInterceptor.ORBInitInfoPackage;version=0.0.0.1_006_JavaSE, org.omg.PortableInterceptor;version=0.0.0.1_006_JavaSE, org.omg.PortableServer.CurrentPackage;version=0.0.0.1_006_JavaSE, org.omg.PortableServer.POAManagerPackage;version=0.0.0.1_006_JavaSE, org.omg.PortableServer.POAPackage;version=0.0.0.1_006_JavaSE, org.omg.PortableServer.ServantLocatorPackage;version=0.0.0.1_006_JavaSE, org.omg.PortableServer.portable;version=0.0.0.1_006_JavaSE, org.omg.PortableServer;version=0.0.0.1_006_JavaSE, org.omg.SendingContext;version=0.0.0.1_006_JavaSE, org.omg.stub.java.rmi;version=0.0.0.1_006_JavaSE, org.w3c.dom.bootstrap;version=0.0.0.1_006_JavaSE, org.w3c.dom.events;version=0.0.0.1_006_JavaSE, org.w3c.dom.ls;version=0.0.0.1_006_JavaSE, org.w3c.dom;version=0.0.0.1_006_JavaSE, org.xml.sax.ext;version=0.0.0.1_006_JavaSE, org.xml.sax.helpers;version=0.0.0.1_006_JavaSE, org.xml.sax;version=0.0.0.1_006_JavaSE

A: You may have better luck using a JNDI datasource rather than a direct jdbc connection. The Aries blog sample has a blog.datasource bundle which registers a datasource using Blueprint. The list of required bundles is longer than what you currently have, but you can just copy them all from the blog-assembly/target directory or pom.xml.
Alternatively, Aries have an org.apache.aries.jpa.eclipselink.adapter which does the same thing as the article you linked to. Aries use it for testing against EclipseLink, so it definitely should work. You could also look at the Aries tests to see how it's used and see if there's an EclipseLink test you can copy.

A: Things may be easier when using the gemini blueprint dbAccess plugin (http://www.eclipse.org/gemini/dbaccess/) , which I think will work for Aries as well. For MySQL be sure to include the connector plugin (e.g. http://ebr.springsource.com/repository/app/bundle/version/detail?name=com.springsource.com.mysql.jdbc&version=5.1.6). This should be sufficient to get the database up and running, provided the blueprint.xml (to use the example above) is configured properly, as above.


text:
Q: How to access instance variables in C++ like Objective-C getter and setter The following is an example:
In circle.h
class circle
{
    double _radius;
public:
    double getRadius() {return _radius;}
    void setRadius(double r) {_radius=r;}
}

In main
int main()
{
    circle a;
    cout<<a.getRadius();    // I want to use "a.radius"
    a.setRadius(3.2);       // I want to use "a.radius=3.2"
}

So the first question is why we should use get and set function to access instance variables rather than directly access them? The second question is how to do operator overloading to let the function call of get and set looks concise(like what objective-c did)?

A: Of course, the simplest way to make the syntax that you're hoping for available is to just make _radius a public member called radius:
class circle
{
public:
    double radius;
}

Now you can use it like so:
circle c;
c.radius = 10.0;

However, you shouldn't make such decisions based only on how you'd like to write code (or how you might write it in C#). I recommend that you think about the following points for every member:

*

*Does it make sense to set the member directly? Perhaps the member is just a private part of the object's state and is affected by other member functions. Consider the following example, where the interface you really want to expose is just a function that increases the size of the circle:
class circle
{
public:
    circle(double radius, double delta = 1.0)
      : radius(radius), delta(delta) { }

    double increaseSize() {
      radius += delta;
      return radius;
    }
private:
    double radius;
    double delta;
}

*Do you need to enforce an invariant? Consider, perhaps, that you have decided that there can be no such thing as a circle with a negative radius. You might want to enforce this by having a member function that checks the given new radius to make sure it is greater than 0.

*Do you want to provide some different representation of the member through the interface? Maybe you want the circle to keep its radius as a member, but the only thing any clients will want to know is its area. You could make radius private and then provide a getArea function like so:
class circle
{
public:
    circle(double radius)
      : radius(radius) { }

    double getArea() {
      return PI * radius * radius;
    }
private:
    double radius;
}

*It's possible that none of the above points apply at the moment, but may do at some point in the future. If you have this foresight, it might be best to provide getter and setter functions now. This ensures that the interface that clients use won't change later on.
As an alternative naming scheme for your getters and setters, it's quite common to simply have two overloaded functions - one for setting and one for getting - like so:
class circle
{
public:
    void radius(double); // Set the radius
    double radius();     // Get the radius
private:
    double radius;
}

A: In answer to the first question: so your object is encapsulated and you can deal with changed internal representation or the need to modify/update when radius changes.
To the second: you can't. C++ does not support object getters and setters like that.
(It is actually just about possible, but it really isn't worth it)

A: *

*There's various reasons to do this with setters and getters;

*

*They provide better encapsulation; the actual values of a class' internal variables should be the responsibility of the class to set/get, not that of a user of an instance of a class. But there's different schools of thought on this subject.

*They leave open the possibility of doing more than just setting/getting a value upon calling a setter/getter. For example,
class circle
{
    double _radius;
    double _perimeter;

public:

    double getRadius() {return _radius;}

    void setRadius(double r) {
            _radius = r;
            _perimeter = 2*M_PI*r;
    }
};

*Well, the way you indicate can be accomplshed simply by making radius a public variable :) However, consider this alternative approach:
class circle
{
private:
    double _radius;

public:
    const double &radius;

    circle(double R)
        : radius(R)
        : radius(_radius)
    {}

    void setRadius(double r) {
        _radius = r;
    }
};

which would then be used like this:
cout << a.radius;    // works
a.radius = 3.2;      // produces error
a.setRadius(3.2);    // works

This approach has the benefit of concise, possibly more intuitive getters (i.e., use the actual variable name), more concise code (no need for countless virtually empty getters), and possibly even increased performance (a call to a getter function is slower than directly accessing a variable, although this depends on compiler optimization settings).
There's benefits and drawbacks to all methods mentioned here. In the end, it's really all up to the preferences of your team/employer.

A: You use a getter and setter to achieve better encapsulation and to make it possible to change the underlying implementation in easier way.
About the second question: you can not do that. You will have to write a getter and setter method.

A: Well there is the initializer way:
OCD::OCD ( ) : _number( 0 )
{
}

and the in body constructor way:
OCD::OCD ( size_t initial_value )
{
  _number = initial_value;
}

to access them inside the class instance just use the variable name:
  _number = value;

but if you have an global, local or argument variable with the same name, you can be specific like this:
  this->_number = value;

then from outside of the instance you can call it thus:
  // (that is if _number was public)
  std::cout << "ocd2._number    => " << ocd2._number << std::endl;
  std::cout << "ocd3p->_number  => " << ocd3p->_number << std::endl;

same goes for methods:
  std::cout << "ocd2.get( )     => " << ocd2.get() << std::endl;
  std::cout << "ocd3p->get( )   => " << ocd3p->get() << std::endl;

see my gist on the subject: https://gist.github.com/LaughingSun/7d2330ccff0777bec106


text:
Q: How can I drop all connections to a given host under FreeBSD? I know about tcpdrop which is in base distribution. But this tool requires port numbers to be specified. Is there any tool to drop connections by IP?

A: BTW, newer versions of tcpdrop(1) have -a and -l flags that makes it easily "grepable":
[savetherbtz@host ~]$ tcpdrop -l -a | grep 127.0.0.1
tcpdrop 127.0.0.1 10006 127.0.0.1 14796
tcpdrop 127.0.0.1 10006 127.0.0.1 13794
tcpdrop 127.0.0.1 10006 127.0.0.1 12996
tcpdrop 127.0.0.1 10006 127.0.0.1 12208
tcpdrop 127.0.0.1 10018 127.0.0.1 27132
tcpdrop 127.0.0.1 27132 127.0.0.1 10018
tcpdrop 127.0.0.1 10018 127.0.0.1 24355
tcpdrop 127.0.0.1 24355 127.0.0.1 10018

Once satisfied with the output you can then pipe this back to sh to execute the terminations:
[savetherbtz@host ~]$ tcpdrop -l -a | grep 127.0.0.1 | sh

A: Well, you could use some unix tools to give you the proper tcpdrop syntax and just run it through xargs in your own script I think. Here's an ugly example, there are probably prettier ways:
netstat -an | grep $IPADDR | awk '{print $4"."$5}' | awk -F '\.' '{print $1"."$2"."$3"."$4" "$5" "$6"."$7"."$8"."$9" "$10}' | xargs tcpdrop

This uses awk to peel out the two IP/port pairs and then glue them together with a dot so you can use another awk to just spit out the desired dotted quad space port syntax.
There's probably a slicker all-in-one regex that's more clear. $IPADDR is the ip you want to drop.


text:
Q: Frobenius twist commutes with fiber product Let $k$ be a field, and let $X$ be a scheme over $k$.  Let $f:k\to k$ be the embedding of fields defined by $f(\lambda)=\lambda^p$.  Define the first Frobenius twist of $X$ to be the scheme $X\times_f k$, where we consider $\operatorname{spec}k$ as a scheme over itself via $f$.  The first Frobenius twist can be viewed as a functor from the category of schemes over $k$ to itself.
I'd like to show that the bifunctors $(-\times_k-)^{(1)}$ and $(-)^{(1)}\times_k(-)^{(1)}$ are naturally isomorphic.  To do so, for any schemes $X$ and $Y$, I need to define an isomorphism
$$\varphi_{X,Y}:(X\times_kY)\times_fk\to(X\times_fk)\times_k(Y\times_fk)$$
I don't know how to think about schemes very well, so I've resorted to using the universal property of the fiber product many different times to arrive at some fairly large and complicated commutative diagrams in order to define $\varphi_{X,Y}$.  Even though this method gives me the existence of such a morphism, it is not clear to me how to show this is an isomorphism (perhaps larger commutative diagrams, which would be horrible).
I would like to know if there is a better way to think about the above canonical identification, or in other words, how would someone well-versed in algebraic geometry solve my exercise (if at all!).
In the affine case, I can think of the isomorphism of commutative $k$-algebras
$$(k[X]\otimes_fk)\otimes_k(k[Y]\otimes_fk)\cong(k[X]\otimes_kk[Y])\otimes_fk$$
but I'd like to be able to think in the language of general schemes (I'm always more comfortable in the affine case, because all of the information is contained in a nice, concrete $k$-algebra).

A: Essentially, what you state in the affine case globalizes.
What follows works for $S$ any scheme over $\mathbb F_p$. In our case we can take $S=\textrm{Spec }k$. Let $f^\ast:S'\to S$ be the morphism corresponding to the Frobenius endomorphism (Here, $S'$ is $S$, with the new structure given by $f$). Then, for an $S$-scheme $X$, when we form the fiber product $X^{(1)}=X\times_SS'$, the structural morphism of this scheme is the second projection onto $S'$, so $S'$ is the scheme over which $X^{(1)}$ and $Y^{(1)}$ are defined. This said, we have, as $S'$-schemes,
\begin{align}
(X\times_SY)^{(1)}&\overset{\textrm{def}}{=}(X\times_SY)\times_SS'\cong X\times_S(Y\times_SS')=X\times_S Y^{(1)}\cong X\times_{S}(S'\times_{S'}Y^{(1)})\notag\\
&\cong (X\times_SS')\times_{S'}Y^{(1)}=X^{(1)}\times_{S'} Y^{(1)}.
\end{align}
This is also an isomorphism over $S$.