text:
Q: Flask-RESTful API: multiple and complex endpoints In my Flask-RESTful API, imagine I have two objects, users and cities. It is a 1-to-many relationship. Now when I create my API and add resources to it, all I can seem to do is map very easy and general URLs to them. Here is the code (with useless stuff not included):
class UserAPI(Resource):  # The API class that handles a single user
  def __init__(self):
    # Initialize

  def get(self, id):
    # GET requests

  def put(self, id):
    # PUT requests

  def delete(self, id):
    # DELETE requests

class UserListAPI(Resource):  # The API class that handles the whole group of Users
  def __init__(self):

  def get(self):

  def post(self):

api.add_resource(UserAPI, '/api/user/<int:id>', endpoint='user')
api.add_resource(UserListAPI, '/api/users/', endpoint='users')

class CityAPI(Resource):
  def __init__(self):

  def get(self, id):

  def put(self, id):

  def delete(self, id):

class CityListAPI(Resource):
  def __init__(self):

  def get(self):

  def post(self):

api.add_resource(CityListAPI, '/api/cities/', endpoint='cities')
api.add_resource(CityAPI, '/api/city/<int:id>', endpoint='city')

As you can see, I can do everything I want to implement a very basic functionality. I can GET, POST, PUT, and DELETE both objects. However, my goal is two-fold:
(1) To be able to request with other parameters like city name instead of just
city id. It would look something like:
api.add_resource(CityAPI, '/api/city/<string:name>', endpoint='city')
except it wouldn't throw me this error:

AssertionError: View function mapping is overwriting an existing
endpoint function

(2) To be able to combine the two Resources in a Request. Say I wanted to get all the
users associated with some city. In REST URLs, it should look something like:
/api/cities/<int:id>/users
How do I do that with Flask? What endpoint do I map it to?
Basically, I'm looking for ways to take my API from basic to useful.

A: Your are making two mistakes.
First, Flask-RESTful leads you to think that a resource is implemented with a single URL. In reality, you can have many different URLs that return resources of the same type. In Flask-RESTful you will need to create a different Resource subclass for each URL, but conceptually those URLs belong to the same resource. Note that you have, in fact, created two instances per resource already to handle the list and the individual requests.
The second mistake that you are making is that you expect the client to know all the URLs in your API. This is not a good way to build APIs, ideally the client only knows a few top-level URLs and then discovers the rest from data in the responses from the top-level ones.
In your API you may want to expose the /api/users and /api/cities as top-level APIs. The URLs to individual cities and users will be included in the responses. For example, if I invoke http://example.com/api/users to get the list of users I may get this response:
{
    "users": [
        {
            "url": "http://example.com/api/user/1",
            "name": "John Smith",
            "city": "http://example.com/api/city/35"
        },
        {
            "url": "http://example.com/api/user/2",
            "name": "Susan Jones",
            "city": "http://example.com/api/city/2"
        }
    ]
}

Note that the JSON representation of a  user includes the URL for that user, and also the URL for the city. The client does not need to know how to build these, because they are given to it.
Getting cities by their name
The URL for a city is /api/city/<id>, and the URL to get the complete list of cities is /api/cities, as you have it defined.
If you also need to search for cities by their name you can extend the "cities" endpoint to do that. For example, you could have URLs in the form /api/cities/<name> return the list of cities that match the search term given as <name>.
With Flask-RESTful you will need to define a new Resource subclass for that, for example:
    class CitiesByNameAPI(Resource):
        def __init__(self):
            # ...
        def get(self, name):
            # ...

    api.add_resource(CitiesByNameAPI, '/api/cities/<name>', endpoint = 'cities_by_name')

Getting all the users that belong to a city
When the client asks for a city it should get a response that includes a URL to get the users in that city. For example, let's say that from the /api/users response above I want to find out about the city of the first user. So now I send a request to http://example/api/city/35, and I get back the following JSON response:
{
    "url": "http://example.com/api/city/35",
    "name": "San Francisco",
    "users": "http://example/com/api/city/35/users"
}

Now I have the city, and that gave me a URL that I can use to get all the users in that city.
Note that it does not matter that your URLs are ugly or hard to construct, because the client never needs to build most of these from scratch, it just gets them from the server. This also enables you to change the format of the URLs in the future.
To implement the URL that gets users by city you add yet another Resource subclass:
    class UsersByCityAPI(Resource):
        def __init__(self):
            # ...
        def get(self, id):
            # ...

    api.add_resource(UsersByCityAPI, '/api/cities/<int:id>/users', endpoint = 'users_by_city')

I hope this helps!

A: you can do the id/name thing without duplicating the resource:
api.add_resource(CitiesByNameAPI, '/api/cities/<name_or_id>', endpoint = 'cities_by_name')

class CitiesByNameAPI(Resource):
    def get(self, name_or_id):
        if name_or_id.isdigit():
            city = CityModel.find_by_id(name_or_id)
        else:
            city = CityModel.find_by_name(name_or_id)

        if city:
            return city.to_json(), 200
        return {'error': 'not found'}, 404

not sure if there are any negative effects from this.


text:
Q: Dúvidas sobre composição de classes ou herança Estou com algumas dúvidas nessa composição entre o ClienteJuridico e ClienteFisico com a NotaFiscal. Eu dei uma pesquisada e vi que da pra instanciar os objetos dessas classes dentro de outra, no caso seria a composição, mas como eu poderia herdar os atributos dessas classes na classe NotaFiscal?

A: Acho um pouco estranho ClienteJuridico, e ClienteFisico, herdar de Pessoa. Não totalmente absurdo, mas parece conceitualmente errado, talvez seja só questão de nome. Será que um dia essas pessoas não poderão ser fornecedores ou terem outros papéis? Ficará esquisito. Mas esse não é o problema.
Você tem que decidir, quer herdar ou quer compor? Elas são essencialmente antagônicas. Uma NotaFiscal é um ClienteJuridico? Como? Não consigo imaginar como isto é possível, então herança parece descartada. A composição parece adequada. Mas tem problemas. Não consigo imaginar porque um cliente deva ter referência a um objeto de nota fiscal. Também acho estranho a NF permitir ter tanto CPF quanto CNPJ.
A herança de NotaFiscal em Vendas parece mais absurda ainda (nem sei bem o que esta classe faz). Minha sugestão é rever seu conceito do que é herança. Tem material sobre o assunto aqui no site.
E percebo outros problemas no modelo, mas são detalhes que não são foco da pergunta.
Note que o uso do termo atributo está correto porque isto é UML, mas quando for se referenciar na linguagem isso chama-se campo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Update on key violation in Stored Procedure using BULK INSERT & Trigger I have a stored procedure that performs a bulk insert of a large number of DNS log entries. I wish to summarise this raw data in a new table for analysis. The new table takes a given log entry for FQDN and Record Type and holds one record only with a hitcount.
Source table might include 100 rows of:
FQDN, Type
www.microsoft.com,A

Destination table would have:
FQDN, Type, HitCount
www.microsoft.com, A, 100

The SP establishes a unique ID made up of [FQDN] +'|'+ [Type], which is then used as the primary key in the destination table.
My plan was to have the SP fire a trigger that did an UPDATE...IF @@ROWCOUNT=0...INSERT. However, that of course failed because the trigger receives all the [inserted] rows as a single set so always throws a key violation error.
I'm having trouble getting my head around a solution and need some fresh eyes and better skills to take a look. The bulk insert SP works just fine and the raw data is exactly as desired. However trying to come up with a suitable method to create the summary data is beyond my present skills/mindset.
I have several 10s of Tb of data to process, so I don't see the summary as a something we could do dynamically with a SELECT COUNT - which is why I started down the trigger route.
The relevant code in the SP is driven by a cursor consisting of a list of compressed log files needing to be decompressed and bulk-inserted, and is as follows:
-- Bulk insert to a view because bulk insert cannot populate the UID field
SET @strDynamicSQL = 'BULK INSERT [DNS_Raw_Logs].[dbo].[vwtblRawQueryLogData] FROM ''' + @strTarFolder + '\' + @strLogFileName + ''' WITH (FIRSTROW = 1, FIELDTERMINATOR = '' '', ROWTERMINATOR = ''0x0a'', ERRORFILE = ''' + @strTarFolder + '\' + @strErrorFile + ''', TABLOCK)'
--PRINT @strDynamicSQL
EXEC (@strDynamicSQL)

-- Update [UID] field after the bulk insert
UPDATE [DNS_Raw_Logs].[dbo].[tblRawQueryLogData]
    SET [UID] = [FQDN] + '|' + [Type]
    FROM [tblRawQueryLogData]
    WHERE [UID] IS NULL

I know that the UPDATE...IF @@ROWCOUNT=0...INSERT solution is wrong because it assumes that the input data is a single row. I'd appreciate help on a way to do this.
Thank you

A: First, at that scale make sure you understand columnstore tables.  They are very highly compressed and fast to scan.
Then write a query that reads from the raw table and returns the summarized
create or alter view DnsSummary
as
select FQDN, Type, count(*) HitCount
from tblRawQueryLogData
group by FQDN, Type
Then if querying that view directly is too expensive, write a stored procedure that loads a table after each bulk insert.  Or make the view into an indexed view.

A: Thanks for the answer David, obvious when someone else looks at it!
I ran the view-based solution with 14M records (about 4 hours worth) and it took 40secs to return, so I think i'll modify the SP to drop and re-create summary table each time it runs the bulk insert.
The source table also includes a timestamp for each entry. I would like to grab the earliest and latest times associated with each UID and add that to the summary.
My current summary query (courtesy of David) looks like this:
SELECT [UID], [FQDN], [Type], COUNT([UID]) AS [HitCount]
    FROM [DNS_Raw_Logs].[dbo].tblRawQueryLogData
    GROUP BY [UID], [FQDN], [Type]
    ORDER BY COUNT([UID]) DESC

And returns:
UID, FQDN, Type, HitCount
www.microsoft.com|A, www.microsoft.com, A, 100

If I wanted to grab first earliest and latest times then I think I'm looking at nesting 3 queries to grab the earliest time (SELECT TOP N...ORDER BY... ASC), the latest time (SELECT TOP N...ORDER BY... DESC) and the hitcount. Is there a more efficient way of doing this, before I try and wrap my head around this route?


text:
Q: Get columnnames as string sepparated by comma / list i am doing some inserts with some of my tables and all fields but a few need to be inserted or updated. Like here.
Is there a quick way to get the columns of a table returned as a string so i can copy them into my sql query?
For example i have a table:
create table myTable1
(
column1                   integer  not null,
column2                   integer  not null ,
column3                   integer  not null,
column4                   integer  not null,
column5                   integer  not null,
...a lot more fields...
)

And later i want to insert something from another table  myTable2 that has the same fields (dont question my ways and why i have two identical tables).
INSERT INTO myTable SELECT column1, column2, column3, column4, ...
FROM table_source

But the tables have so many fields it is cumbersome to write them donw manualy and it would be faster to have a string where i can just delete the column names i dont need. Is there a nice query that ouputs "column1, column2, column3, column4, ..." so i dont have to write that myself and can copy tha into my query?

A: Found the answer quickly.
SELECT table_catalog, string_agg(column_name, ', ')
  FROM information_schema.columns
 WHERE table_schema = 'mySchema'
   AND table_name   = 'myTable' GROUP  BY 1;

This query does the trick for me.


text:
Q: Reading file with pandas read csv is not working All the column data is going inside the "index" column
the header starts from row number 7
'''
 index      mfg    legalId    resellerName   resellerCountry
(SONICWALL',' ','HEXAPAGE','FRANCE')
(SONICWALL',' ','SEXTANT BTS LLC','UNITED STATES')
(SONICWALL',' ','New Vision Networks, Inc.','UNITED STATES')
'''

All the values are inside index column, i want those values to come under specified column respectively
Specified columns are

mfg, legalId, resellerName, resellerCountry

Below is the code which i have written, please help me how to do this
df2=pd.read_csv(data, header=6, keep_default_na=False, sep=',', delimiter=',', quoting=csv.QUOTE_MINIMAL)

A: if your .csv file already has columns as first row then remove header=6 argument and let it infer which is default.

 If you keep "index" column in csv file then with header='infer' dataframe will look like below table which is not aligned with respect to data. As data is shifted to left because data does not have index values mentioned
+----+-----------+-------+--------------------------+----------------+-------------------+
|    | index     | mfg   | legalId                  | resellerName   | resellerCountry   |
+====+===========+=======+==========================+================+===================+
|  0 | SONICWALL |       | HEXAPAGE                 | FRANCE         |                   |
+----+-----------+-------+--------------------------+----------------+-------------------+
|  1 | SONICWALL |       | SEXTANT BTS LLC          | UNITED STATES  |                   |
+----+-----------+-------+--------------------------+----------------+-------------------+
|  2 | SONICWALL |       | New Vision Networks Inc. | UNITED STATES  |                   |
+----+-----------+-------+--------------------------+----------------+-------------------+

 you can remove "index" column from .csv file and reset_index on dataframe by:
df2.reset_index(level=0, inplace=True)

 and data will be:
+----+---------+-----------+-----------+--------------------------+-------------------+
|    |   index | mfg       | legalId   | resellerName             | resellerCountry   |
+====+=========+===========+===========+==========================+===================+
|  0 |       0 | SONICWALL |           | HEXAPAGE                 | FRANCE            |
+----+---------+-----------+-----------+--------------------------+-------------------+
|  1 |       1 | SONICWALL |           | SEXTANT BTS LLC          | UNITED STATES     |
+----+---------+-----------+-----------+--------------------------+-------------------+
|  2 |       2 | SONICWALL |           | New Vision Networks Inc. | UNITED STATES     |
+----+---------+-----------+-----------+--------------------------+-------------------+


text:
Q: Post Photos as Fan Page not as User (Post as User Working 100%) I´m trying to post Photos on my Fan Page using Facebook API but the Posts appears as my User and not as Fan Page it self.
I know i should use the Page Access Token instead of the App User Access Token but when i put the Page Access Token i get:
Fatal error: Uncaught OAuthException: A user access token is required to request this resource.
What should i do to post the Image as Fan Page itself not as the app Owner ?
Here´s the Working Code:
require_once('src/facebook.php');

$pageid = "xxxxxxxxxxxxx";
$accessToken = "xxxxxxxxxxxxxxxx";

$facebook = new Facebook(array(
    "appId"  => "xxxxxxxxxxxxxx",
    "secret" => "xxxxxxxxxxxxxxxxxxxx",
    "cookie" => true,
));

$args = array(
    'access_token' => $accessToken,
    "url"      => "http://example.com/image.jpg",
    "message"  => "Picture Caption",
    );

$facebook->api("/$pageid/photos?access_token='.$accessToken","post",$args);

A: I just figure it out what was wrong. I was using wrong Page Access Token, the right way to get the right Page Access Token is through the following link:
https://graph.facebook.com/me/accounts?access_token=USER_ACCESS_TOKEN
You can even try the new Access Token on Debug Tools:
https://developers.facebook.com/tools/debug/
If you do that you´ll see a field named "Profile ID", this field has to be the same as your Fan Page ID, and probably will.
Now all my post appear as my Fan Page.
Hope someone else find this usefull.


text:
Q: NodeJs XSLT Transformation I need to transform an XML document using XSLT in nodejs. I can't seem to find a library for nodejs that is currently maintained and encompasses the full standard of XSLT.
Does anyone have any suggestions on a package or something in native nodejs to perform transformation?

A: 2020 Update
Saxon-JS 2 now supports XSLT 3.0 in Node.js and in the browser!

Former answer
Your only (pure JavaScript, XSLT standards compliant) hope is Saxon-JS, but it may not be entirely ready to run on Node.js yet:

*

*XSLT 2.0 or 3.0 for Node.js?

*Saxon-JS should depend only upon JavaScript, not web browsers

*Is SaxonJS 1.1.0 compliant with NodeJS 8.9.4 ?

*SaxonJS on Node.js
Michael Kay reads Q/A here and may perhaps provide an update beyond what's listed in the above links.

A:
encompasses the full standard of XSLT

could be treated as "compliant with browser implementation" in order to reuse XSLT as in browser as on server side. Native client side implementation could be significant denominator as speed and CPU load is level of magnitude is different in comparison with JS-based implementation.
https://www.npmjs.com/package/xslt-processor is promising cross-tier compatible implementation of XSLT 1.0.


text:
Q: How to add multiple widgets to one application? I have developed a widget that has certain functionality, but some people have asked me to create a similar widget but with a slight different functionality. Both widgets will look the same but behave slightly different. I tried adding a different receiver for the second widget to my manifest file. I also created a separate widget provider xml file and I have a separate class that implements the AppWidgetProvider with the different functionality. Yet, when I add the second widget to home page, it seems to be using the functionality of the first widget, and not the new functionality.
Here is some of the code:
I have to separate classes that extend the AppWidgetProvider (one for each widget). The class names are iContacts and iContactsQuickDial.
The difference between this two classes is the OnReceive method which implements the different logic. The other methods are exactly the same.
Manifest receivers:
    <receiver android:name=".iContacts" android:label="@string/app_name">
       <intent-filter>
              <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
              <action android:name="android.appwidget.action.CONFIGURATION_CHANGED" />
              <action android:name="com.mesa.icontacts.ConfigureContacsActivity.ACTION_UPDATE_WIDGET" />
                <action android:name="com.mesa.icontacts.iContacts.ACTION_WIDGET_SHOW_CONTACT_1" />
                <action android:name="com.mesa.icontacts.iContacts.ACTION_WIDGET_SHOW_CONTACT_2" />
                <action android:name="com.mesa.icontacts.iContacts.ACTION_WIDGET_SHOW_CONTACT_3" />
                <action android:name="com.mesa.icontacts.iContacts.ACTION_WIDGET_SHOW_CONTACT_4" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                 android:resource="@xml/icontacts_widget_provider" />
        </receiver>

        <receiver android:name=".iContactsQuickDial"
                  android:label="@string/app_name_quick_dial">
            <intent-filter>
                <action android:name="android.appwidget.action.APPWIDGET_UPDATE" />
                <action android:name="android.appwidget.action.CONFIGURATION_CHANGED" />
                <action android:name="com.mesa.icontacts.ConfigureContacsActivity.ACTION_UPDATE_WIDGET" />
                <action android:name="com.mesa.icontacts.iContacts.ACTION_WIDGET_SHOW_CONTACT_1" />
                <action android:name="com.mesa.icontacts.iContacts.ACTION_WIDGET_SHOW_CONTACT_2" />
                <action android:name="com.mesa.icontacts.iContacts.ACTION_WIDGET_SHOW_CONTACT_3" />
                <action android:name="com.mesa.icontacts.iContacts.ACTION_WIDGET_SHOW_CONTACT_4" />
            </intent-filter>
            <meta-data android:name="android.appwidget.provider"
                 android:resource="@xml/icontacts_quick_dial_widget_provider" />
        </receiver>

Both widgets use the same configuration activity since this logic doesn't change.
Both providers:
icontacts_widget_provider:
<?xml version="1.0" encoding="UTF-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
   android:minWidth="300dip"
   android:minHeight="75dip"
   android:initialLayout="@layout/main"
/>

icontacts_quick_dial_widget_provider
<?xml version="1.0" encoding="UTF-8"?>
<appwidget-provider xmlns:android="http://schemas.android.com/apk/res/android"
   android:minWidth="300dip"
   android:minHeight="75dip"
   android:initialLayout="@layout/main"
/>

Note that the layout is the same for both since both widgets must look the same
Any ideas would be appreciated?
Thank you


text:
Q: ASP.NET TextBox control with label text in the background I'm creating a login page. I want to create ASP.NET TextBox controls that have "Username" and "Password" as their Text, but as soon as they receive focus, these words should disappear and whatever the user types should appear, just like normal textbox. If the user leaves it blank and tabs to the next textbox, then these words appear again. This will eliminate the need for having separate labels in front of the text boxes. I would appreciate if someone can share their expertise for doing this.

A: Use the TextBox Watermark Extender that's in Microsoft's AJAX Toolkit.

A: Google "ASP.NET Watermark textbox". Theres a ton of implemnentations


text:
Q: Замаппить объекты в Java JPA Имеется следующая структура БД PostgreSQL:
    CREATE TABLE a_type (
      id INT4 PRIMARY KEY
    );

    CREATE TABLE a (
      id        INT8 PRIMARY KEY,
      a_type_id INT4 NOT NULL REFERENCES a_type (id)
    );

    CREATE TABLE b_type (
      id INT4 PRIMARY KEY
    );

    CREATE TABLE b (
      id        INT8 PRIMARY KEY,
      b_type_id INT4 NOT NULL REFERENCES b_type (id)
    );

    CREATE TABLE c (
      id INT8 PRIMARY KEY NOT NULL REFERENCES a_type (id) REFERENCES b_type (id)
    );

Хотелось бы замаппить на доменные объекты в Java:
    @Entity
    interface A {
        @Id
        Long id;

        @ManyToOne
        @JoinColumn
        AType aType;
    }

    @Entity
    class AType {
        @Id
        Integer id;
    }

    @Entity
    interface B {
        @Id
        Long id;

        @ManyToOne
        @JoinColumn
        BType bType;
    }

    @Entity
    class BType {
        @Id
        Integer id;
    }

    @Entity
    class C implements A, B {
        @Id
        Long id;

        @ManyToOne
        @JoinColumn
        AType aType;

        @ManyToOne
        @JoinColumn
        BType bType;
    }

Чтобы в Spring CRUD Repository можно было создать и использовать следующие репозитории:
    interface ARepository extends CrudRepository<A, Long> {
    }

    interface BRepository extends CrudRepository<B, Long> {
    }

    interface CRepository extends CrudRepository<C, Long> {
    }

То есть если существует в БД строка в таблице c, то с таким же ID существуют объекты в таблицах a и b.
Прошу подсказать в какую сторону смотреть, чтобы разобраться с тем какие аннотации JPA использовать для реализации задуманного.


text:
Q: Linear Program Modelling Coinset pay amount $k$ You are given a coinset ov values c1,...,cn and a target value of k you need to pay. For each i element {1,...,n} let ni be the number of coins of value ci in your wallet. You want to pay (or overpay) the target value k such that the number of coins in your wallet (after the change has been paid) is minimized.
You can assume that the change is returned in a minimum number of coins.
Contrusct an ILP that sloves the problem. Explain the meaning of all the variables.
I have no glue.... Here is my "try":
Variable: x - for the number of coins in my wallet (coinset c1,...,n)
          c - the value of the Sum of the Coins
Objective Function:
      min the Sum of the coins in my wallet: also min x

Constraints:
      s.t.      c <= k

I think this is not complete and not right......

A: First of all, the question uses the variable $n$ to represent both the number of coin types and the number of each coin you have. This is confusing to say the least, so let's say you have $m_i$ coins of value $c_i$ to begin with, where $i$ ranges from $1, \dots, n$. Secondly, I'm assuming one can neglect the change returned; the question is unclear in this regard.
Instead of having one variable $x$ representing the total amount, let's have variables $x_1, \dots, x_n$ where $x_i$ is the number of coins of value $c_i$ that you spend. Therefore, your objective function is the following:
$$\min m_1 + \dots + m_n - x_1 - \dots - x_n$$
Now, consider the constraints. We need the value of the coins we spend to equal or exceed $k$:
$$c_1x_1+\dots+c_nx_n\geq k$$
We cannot spend more coins than we have:
$$x_1\leq m_1$$
$$\vdots$$
$$x_n\leq m_n$$
We must spend a nonnegative number of coins:
$$x_1\geq0$$
$$\vdots$$
$$x_n\geq0$$
Finally, all variables are integers:
$$x_1, \dots, x_n\text{ integer}$$


text:
Q: EF6 Async Methods Confusion Recently we upgraded to EF6 hopping to take advantage of its async call in our webapi controller but after some online reading i can to know
- EF6 async call is not thread safe

While thread safety would make async more useful it is an orthogonal feature. It is
unclear that we could ever implement support for it in the most general case, given that
EF interacts with a graph composed of user code to maintain state and there aren't
easy ways to ensure that this code is also thread safe.

https://entityframework.codeplex.com/wikipage?title=Task-based%20Asynchronous%20Pattern%20support%20in%20EF.
but same thing is conveyed in this question
EF Data Context - Async/Await & Multithreading
but when i looked at samples from MS http://msdn.microsoft.com/en-us/data/jj819165.aspx
i am confused , because if i look at answers provided in stackoverflow question it seems currently we dont have any solution/pattern to implement it thread safe with single db context?
So my question is again how to achieve
var dbContext = new DbContext();
var something = await dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 1);
var morething = await dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 2);

is a correct way with thread safe feature?

A: From the same EF docs you quoted:

For the moment, EF will detect if the developer attempts to execute
  two async operations at one time and throw.

So, this code should work even if there's a thread switch after await, because it's still executed sequentially:
var dbContext = new DbContext();
var something = await dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 1);
var morething = await dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 2);

At least, this is how it is expected to work. If sequential execution still produces a threading-related exception, this should be reported as an EF bug.
On the other hand, the following code will most likely fail, because we introduce parallelism:
var dbContext = new DbContext();
var somethingTask = dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 1);
var morethingTask = dbContext.someEntities.FirstOrDefaultAsync(e => e.Id == 2);

await Task.WhenAll(somethingTask, morethingTask);

var something = somethingTask.Result;
var morething = morethingTask.Result;

You need to make sure you don't use the same DbContext with more than one pending EF operation.
Updated, the 1st code fragment actually works fine with EF v6.1.0, as expected.

A: The thing about Entity Framework contexts (and other ORMs for that matter) is that they are not thread safe. What this means it that you shouldn't share the same context object between more than one thread or you could face some of the following problems:

*

*Entities not committed in the database would be shared between more
than one execution plan;

*Exceptions thrown by the context, invalidating every thread that is
using that context, and how would you take care of that;

*Memory leaks that could happen by not knowing when to dispose the
context (is anyone still using the context?);

These are just a few subset of problems you would face by sharing the context. In fact, you should see the context as a unit of work for your current execution plan, that will store the entities and changes only relevant to you. After you complete everything, it should be disposed. Take a look at the following snippet:
using(var ctx = new MyDbContext()){
    var car = await ctx.Cars.FindAsync(id);
    car.Owner = new Person{ Name = "John Doe" };
    await ctx.SaveAsync();
}

Why do you need async method executions then? Because the thread currently executing, instead of waiting idle for the result of your database query, will be able to execute other jobs, like taking care of pending web requests, continue the execution of tasks that eventually terminated, etc. Note that every thread has an overhead and your thread pool can't use threads that are idle waiting for an operation to terminate.
What you should try to do, and since you are implementing a Web Application, is using a context by web request, because that's your execution plan. Maybe this can lead you further (Repository and UoW pattern with service layer). Normally I use IoC frameworks with factory patterns and interceptors, but if you want to keep it simple, you may create a wrapper for the HttpContext.Items and disposing your context at the end of the request.


text:
Q: D3 update bar chart - Can't bind new data Hello I'm new to d3 and I couldn't update the data in my bar chart.
I'm creating the bars using following code.
g.selectAll(".bar")
.data(data)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.letter) + 1; })
.attr("y", function(d) { return y(d.frequency); })
.attr("width", x.bandwidth() - 1)
.attr("height", function(d) { return height - y(d.frequency); })

I was able to modify the data using hard coded values:
var bar = svg.selectAll(".bar");

bar.transition().duration(750).data(data).enter()
   .attr("y", function(d) { return 0; })
   .attr("height", function(d) { return Math.random()*100; });

How can i properly bind the new data?

A: See the snippet below for an example of updating the bar chart with new data programmatically and showing a transition animation in the process.

var data = [{x:10, y:10, w:50, h:25},
            {x:10, y:40, w:150, h:25},
            {x:10, y:70, w:70, h:25}];

var g = d3.select("g");

// Bind initial data to empty selection, then use enter()
// to access the virtual selection from the data-join
// and subsequently append a rect for each virtual selection
g.selectAll(".bar")
  .data(data)
  .enter().append("rect")
    .attr("class", "bar")
    .attr("x", function(d) { return d.x; })
    .attr("y", function(d) { return d.y; })
    .attr("width", function(d) {return d.w; })
    .attr("height", function(d) { return d.h; });

var new_data = [{x:10, y:10, w:150, h:25},
                {x:10, y:40, w:50, h:25},
                {x:10, y:70, w:100, h:25}];

// Bind the new data to the rect objects. Since new_data
// is of the same size as number of rects, enter() and exit()
// selections from data-join will be empty and the rects
// with updated bound data are now available in the default
// update selection.
g.selectAll(".bar")
  .data(new_data) // grab the update selection by default
      .transition().duration(3000)
      .attr("width", function(d) { return d.w; }); // Update the attribute
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

<svg width="400" height="400">
  <g>
  </g>
</svg>


text:
Q: Obtain actual --cores [N], --jobs [N], -j [N] value given from command line within the snakefile How is it possible to access all configuration values and corresponding parameters passed by command line to snakemake, within the snakefile?
For example by running:
snakemake -p --use-conda -j 16 --snakefile ../../Snakefile --configfile pipeline-test.config.yaml

In particular I wish obtain the number of available cores within the snakefile to be able to perform some computation with that value.

A: You can use sys.argv within your snakefile to parse the command line parameters.


text:
Q: Devise: Sign up / Sign In works, but ruby wont recognize? [Update] This happens only on heroku, locally everything is working fine.
When i sign up a new user / or sign in with an existing one into my app, i get no error message or whatsoever.
Yet, the if user_signed_in? as an example is not working. I still get the sign up / sign in buttons, instead of the dashboard as an example. Same with active_admin, when i try to login, i get no errors, yet it just reloads the sign in page. This is really weird.
Again, only on heroku. When i try to login locally or try to sign up a new user, everything is working fine.
Heroku logs shows no errors (except for an missing image file)
$ heroku logs
2017-02-14T11:48:17.367871+00:00 app[web.1]:   Rendered project/index.html.erb within layouts/application (1.4ms)
2017-02-14T11:48:17.369701+00:00 app[web.1]:   Rendered shared/_header.html.erb (1.0ms)
2017-02-14T11:48:17.369874+00:00 app[web.1]:   Rendered shared/_message.html.erb (0.1ms)
2017-02-14T11:48:17.370124+00:00 app[web.1]:   Rendered shared/_footer.html.erb (0.1ms)
2017-02-14T11:48:17.370297+00:00 app[web.1]: Completed 200 OK in 5ms (Views: 3.2ms | ActiveRecord: 0.8ms)
2017-02-14T11:48:17.386624+00:00 heroku[router]: at=info method=GET path="/" host=herogamedev2.herokuapp.com request_id=8b8bf6db-d1bc-420e-bcc0-4efc9591adb0 fwd="94.218.91.178" dyno=web.1 connect=1ms service=13ms status=200 bytes=5750
2017-02-14T11:48:17.514234+00:00 heroku[router]: at=info method=GET path="/assets/application-1d6aff3e9562d68738287f8737bcd49d854bd20cc894434ed3975afebb8addd2.css" host=herogamedev2.herokuapp.com request_id=712f2bda-87a4-427c-ac27-b8297f81008a fwd="94.218.91.178" dyno=web.1 connect=0ms service=3ms status=304 bytes=133
2017-02-14T11:48:17.632465+00:00 heroku[router]: at=info method=GET path="/assets/application-835796ed4ed64d77b216af341c67c9e3ada5866ff071e82dc15b0af01d47e9de.js" host=herogamedev2.herokuapp.com request_id=1a496b53-6500-455e-aada-aa2e535a2802 fwd="94.218.91.178" dyno=web.1 connect=0ms service=4ms status=304 bytes=133
2017-02-14T11:48:17.920864+00:00 heroku[router]: at=info method=GET path="/assets/pexel.jpeg" host=herogamedev2.herokuapp.com request_id=c962257e-2cb6-4c59-86e6-2cc6b6bb81e6 fwd="94.218.91.178" dyno=web.1 connect=1ms service=9ms status=404 bytes=1829
2017-02-14T11:48:17.899656+00:00 app[web.1]: Started GET "/assets/pexel.jpeg" for 94.218.91.178 at 2017-02-14 11:48:17 +0000
2017-02-14T11:48:17.903852+00:00 app[web.1]: ActionController::RoutingError (No route matches [GET] "/assets/pexel.jpeg"):
2017-02-14T11:48:17.903853+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
2017-02-14T11:48:17.903853+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
2017-02-14T11:48:17.903850+00:00 app[web.1]:
2017-02-14T11:48:17.903855+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/rack/logger.rb:38:in `call_app'
2017-02-14T11:48:17.903855+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/rack/logger.rb:20:in `block in call'
2017-02-14T11:48:17.903856+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.1/lib/active_support/tagged_logging.rb:68:in `block in tagged'
2017-02-14T11:48:17.903857+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.1/lib/active_support/tagged_logging.rb:26:in `tagged'
2017-02-14T11:48:17.903858+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.1/lib/active_support/tagged_logging.rb:68:in `tagged'
2017-02-14T11:48:17.903858+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/rack/logger.rb:20:in `call'
2017-02-14T11:48:17.903859+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/request_id.rb:21:in `call'
2017-02-14T11:48:17.903860+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/methodoverride.rb:22:in `call'
2017-02-14T11:48:17.903860+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/runtime.rb:18:in `call'
2017-02-14T11:48:17.903861+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.1/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
2017-02-14T11:48:17.903862+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/static.rb:116:in `call'
2017-02-14T11:48:17.903863+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/engine.rb:518:in `call'
2017-02-14T11:48:17.903864+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/application.rb:165:in `call'
2017-02-14T11:48:17.903864+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/lock.rb:17:in `call'
2017-02-14T11:48:17.903865+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/content_length.rb:15:in `call'
2017-02-14T11:48:17.903866+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/handler/webrick.rb:88:in `service'
2017-02-14T11:48:17.903863+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/sendfile.rb:113:in `call'
2017-02-14T11:48:17.903867+00:00 app[web.1]:   vendor/ruby-2.2.6/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
2017-02-14T11:48:17.903868+00:00 app[web.1]:   vendor/ruby-2.2.6/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
2017-02-14T11:48:17.903868+00:00 app[web.1]:   vendor/ruby-2.2.6/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'
2017-02-14T11:48:17.903869+00:00 app[web.1]:
2017-02-14T11:48:17.903870+00:00 app[web.1]:
2017-02-14T11:51:46.157350+00:00 heroku[router]: at=info method=GET path="/" host=herogamedev2.herokuapp.com request_id=b513d122-8920-4580-b4e1-500f535d2ee4 fwd="94.218.91.178" dyno=web.1 connect=0ms service=18ms status=200 bytes=5750
2017-02-14T11:51:46.149910+00:00 app[web.1]: Processing by ProjectController#index as HTML
2017-02-14T11:51:46.143633+00:00 app[web.1]: Started GET "/" for 94.218.91.178 at 2017-02-14 11:51:46 +0000
2017-02-14T11:51:46.152204+00:00 app[web.1]:   Project Load (0.6ms)  SELECT "projects".* FROM "projects"
2017-02-14T11:51:46.152561+00:00 app[web.1]:   Rendered project/index.html.erb within layouts/application (1.3ms)
2017-02-14T11:51:46.155256+00:00 app[web.1]:   Rendered shared/_header.html.erb (1.7ms)
2017-02-14T11:51:46.155495+00:00 app[web.1]:   Rendered shared/_message.html.erb (0.0ms)
2017-02-14T11:51:46.155858+00:00 app[web.1]:   Rendered shared/_footer.html.erb (0.2ms)
2017-02-14T11:51:46.156116+00:00 app[web.1]: Completed 200 OK in 6ms (Views: 4.7ms | ActiveRecord: 0.6ms)
2017-02-14T11:51:46.289308+00:00 heroku[router]: at=info method=GET path="/assets/application-1d6aff3e9562d68738287f8737bcd49d854bd20cc894434ed3975afebb8addd2.css" host=herogamedev2.herokuapp.com request_id=f23301ca-ff2f-4998-9896-5d0f60007f78 fwd="94.218.91.178" dyno=web.1 connect=0ms service=11ms status=304 bytes=133
2017-02-14T11:51:46.734862+00:00 heroku[router]: at=info method=GET path="/assets/pexel.jpeg" host=herogamedev2.herokuapp.com request_id=53d21642-c654-4ed1-ad1f-f5d3e6accf6f fwd="94.218.91.178" dyno=web.1 connect=0ms service=8ms status=404 bytes=1829
2017-02-14T11:51:46.417122+00:00 heroku[router]: at=info method=GET path="/assets/application-835796ed4ed64d77b216af341c67c9e3ada5866ff071e82dc15b0af01d47e9de.js" host=herogamedev2.herokuapp.com request_id=625f2fe6-d3f6-4fbd-a062-1b30cb2d3354 fwd="94.218.91.178" dyno=web.1 connect=0ms service=11ms status=304 bytes=133
2017-02-14T11:51:46.729375+00:00 app[web.1]: Started GET "/assets/pexel.jpeg" for 94.218.91.178 at 2017-02-14 11:51:46 +0000
2017-02-14T11:51:46.733787+00:00 app[web.1]:
2017-02-14T11:51:46.733789+00:00 app[web.1]: ActionController::RoutingError (No route matches [GET] "/assets/pexel.jpeg"):
2017-02-14T11:51:46.733790+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
2017-02-14T11:51:46.733791+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
2017-02-14T11:51:46.733792+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/rack/logger.rb:38:in `call_app'
2017-02-14T11:51:46.733793+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/rack/logger.rb:20:in `block in call'
2017-02-14T11:51:46.733793+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.1/lib/active_support/tagged_logging.rb:68:in `block in tagged'
2017-02-14T11:51:46.733794+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.1/lib/active_support/tagged_logging.rb:26:in `tagged'
2017-02-14T11:51:46.733795+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.1/lib/active_support/tagged_logging.rb:68:in `tagged'
2017-02-14T11:51:46.733796+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/rack/logger.rb:20:in `call'
2017-02-14T11:51:46.733796+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/request_id.rb:21:in `call'
2017-02-14T11:51:46.733797+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/methodoverride.rb:22:in `call'
2017-02-14T11:51:46.733798+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/runtime.rb:18:in `call'
2017-02-14T11:51:46.733799+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/actionpack-4.2.5.1/lib/action_dispatch/middleware/static.rb:116:in `call'
2017-02-14T11:51:46.733798+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/activesupport-4.2.5.1/lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'
2017-02-14T11:51:46.733800+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/sendfile.rb:113:in `call'
2017-02-14T11:51:46.733804+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/engine.rb:518:in `call'
2017-02-14T11:51:46.733805+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/application.rb:165:in `call'
2017-02-14T11:51:46.733806+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/lock.rb:17:in `call'
2017-02-14T11:51:46.733806+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/content_length.rb:15:in `call'
2017-02-14T11:51:46.733807+00:00 app[web.1]:   vendor/bundle/ruby/2.2.0/gems/rack-1.6.5/lib/rack/handler/webrick.rb:88:in `service'
2017-02-14T11:51:46.733808+00:00 app[web.1]:   vendor/ruby-2.2.6/lib/ruby/2.2.0/webrick/httpserver.rb:138:in `service'
2017-02-14T11:51:46.733809+00:00 app[web.1]:   vendor/ruby-2.2.6/lib/ruby/2.2.0/webrick/httpserver.rb:94:in `run'
2017-02-14T11:51:46.733809+00:00 app[web.1]:   vendor/ruby-2.2.6/lib/ruby/2.2.0/webrick/server.rb:294:in `block in start_thread'
2017-02-14T11:51:46.733810+00:00 app[web.1]:
2017-02-14T11:51:46.733810+00:00 app[web.1]:
2017-02-14T11:51:51.126778+00:00 app[web.1]: Started GET "/admin/login" for 94.218.91.178 at 2017-02-14 11:51:51 +0000
2017-02-14T11:51:51.131909+00:00 app[web.1]: Processing by ActiveAdmin::Devise::SessionsController#new as HTML
2017-02-14T11:51:51.147797+00:00 app[web.1]:   Rendered vendor/bundle/ruby/2.2.0/bundler/gems/activeadmin-7ff122d58083/app/views/active_admin/devise/shared/_links.erb (2.7ms)
2017-02-14T11:51:51.147851+00:00 app[web.1]:   Rendered vendor/bundle/ruby/2.2.0/bundler/gems/activeadmin-7ff122d58083/app/views/active_admin/devise/sessions/new.html.erb within layouts/active_admin_logged_out (14.6ms)
2017-02-14T11:51:51.148691+00:00 app[web.1]: Completed 200 OK in 17ms (Views: 15.7ms | ActiveRecord: 0.0ms)
2017-02-14T11:51:51.149987+00:00 heroku[router]: at=info method=GET path="/admin/login" host=herogamedev2.herokuapp.com request_id=24f52ba4-5e33-41df-92db-02792e3f3753 fwd="94.218.91.178" dyno=web.1 connect=1ms service=26ms status=200 bytes=3327
2017-02-14T11:51:55.832008+00:00 heroku[router]: at=info method=POST path="/admin/login" host=herogamedev2.herokuapp.com request_id=ee29663a-6e03-4b09-8ca2-2ba566b6e043 fwd="94.218.91.178" dyno=web.1 connect=0ms service=96ms status=302 bytes=1021
2017-02-14T11:51:55.738592+00:00 app[web.1]: Started POST "/admin/login" for 94.218.91.178 at 2017-02-14 11:51:55 +0000
2017-02-14T11:51:55.743302+00:00 app[web.1]: Processing by ActiveAdmin::Devise::SessionsController#create as HTML
2017-02-14T11:51:55.743339+00:00 app[web.1]:   Parameters: {"utf8"=>"✓", "authenticity_token"=>"RUV3xPCZVfG9OyBE2X25RQmegZQhMqiknxrVWvZH1lhL7cKscTmbODk/kX/qIxtKq85eEgAGJPMYuZLRWY2J6g==", "admin_user"=>{"email"=>"admin@example.com", "password"=>"[FILTERED]", "remember_me"=>"0"}, "commit"=>"Login"}
2017-02-14T11:51:55.745537+00:00 app[web.1]:   AdminUser Load (0.7ms)  SELECT  "admin_users".* FROM "admin_users" WHERE "admin_users"."email" = $1  ORDER BY "admin_users"."id" ASC LIMIT 1  [["email", "admin@example.com"]]
2017-02-14T11:51:55.819195+00:00 app[web.1]:    (0.6ms)  BEGIN
2017-02-14T11:51:55.820991+00:00 app[web.1]:   SQL (0.6ms)  UPDATE "admin_users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "admin_users"."id" = $5  [["last_sign_in_at", "2017-02-14 11:47:42.774425"], ["current_sign_in_at", "2017-02-14 11:51:55.817737"], ["sign_in_count", 4], ["updated_at", "2017-02-14 11:51:55.819377"], ["id", 1]]
2017-02-14T11:51:55.822643+00:00 app[web.1]:    (1.2ms)  COMMIT
2017-02-14T11:51:55.830995+00:00 app[web.1]: Completed 302 Found in 88ms (ActiveRecord: 3.0ms)
2017-02-14T11:51:55.830874+00:00 app[web.1]: Redirected to https://herogamedev2.herokuapp.com/admin
2017-02-14T11:51:55.951344+00:00 app[web.1]: Started GET "/admin" for 94.218.91.178 at 2017-02-14 11:51:55 +0000
2017-02-14T11:51:55.955533+00:00 app[web.1]: Processing by Admin::DashboardController#index as HTML
2017-02-14T11:51:55.956112+00:00 app[web.1]: Completed 401 Unauthorized in 1ms (ActiveRecord: 0.0ms)
2017-02-14T11:51:56.106141+00:00 heroku[router]: at=info method=GET path="/admin/login" host=herogamedev2.herokuapp.com request_id=7f27d81e-e1ed-4949-a33c-51a43e806165 fwd="94.218.91.178" dyno=web.1 connect=0ms service=26ms status=200 bytes=3327
2017-02-14T11:51:55.960821+00:00 heroku[router]: at=info method=GET path="/admin" host=herogamedev2.herokuapp.com request_id=6d953372-85c8-464c-ac1d-200326a6f992 fwd="94.218.91.178" dyno=web.1 connect=0ms service=12ms status=302 bytes=1033
2017-02-14T11:51:56.082699+00:00 app[web.1]: Started GET "/admin/login" for 94.218.91.178 at 2017-02-14 11:51:56 +0000
2017-02-14T11:51:56.087109+00:00 app[web.1]: Processing by ActiveAdmin::Devise::SessionsController#new as HTML
2017-02-14T11:51:56.102803+00:00 app[web.1]:   Rendered vendor/bundle/ruby/2.2.0/bundler/gems/activeadmin-7ff122d58083/app/views/active_admin/devise/sessions/new.html.erb within layouts/active_admin_logged_out (14.3ms)
2017-02-14T11:51:56.102750+00:00 app[web.1]:   Rendered vendor/bundle/ruby/2.2.0/bundler/gems/activeadmin-7ff122d58083/app/views/active_admin/devise/shared/_links.erb (2.6ms)
2017-02-14T11:51:56.105098+00:00 app[web.1]: Completed 200 OK in 18ms (Views: 17.0ms | ActiveRecord: 0.0ms)

Any ideas?
[Update]
Running heroku run rails console
and then @User.allreturns nil.
$ heroku run rails console
Running rails console on herogamedev2... starting, run.3740 (Free)
Running rails console on herogamedev2... connecting, run.3740 (Free)
Running rails console on herogamedev2... up, run.3740 (Free)
Loading production environment (Rails 4.2.5.1)
irb(main):001:0> @User.all
@User.all
NoMethodError: undefined method `all' for nil:NilClass
        from (irb):1
        from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/console.rb:110:in `start'
        from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/console.rb:9:in `start'
        from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:68:in `console'
        from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/commands/commands_tasks.rb:39:in `run_command!'
        from /app/vendor/bundle/ruby/2.2.0/gems/railties-4.2.5.1/lib/rails/commands.rb:17:in `<top (required)>'
        from /app/bin/rails:4:in `require'
        from /app/bin/rails:4:in `<main>'
irb(main):002:0>

So it seems like devise is not creating anything, however, i don't get any errors whatsoever and again, only on heroku, locally i can register, sign in, logout, edit and everything else.
  # ==> Mailer Configuration
  # Configure the e-mail address which will be shown in Devise::Mailer,
  # note that it will be overwritten if you use your own mailer class
  # with default "from" parameter.
  config.mailer_sender = 'appno-reply@example.com'

  # Configure the class responsible to send e-mails.
  # config.mailer = 'Devise::Mailer'

  # Configure the parent class responsible to send e-mails.
  # config.parent_mailer = 'ActionMailer::Base'

  # ==> ORM configuration
  # Load and configure the ORM. Supports :active_record (default) and
  # :mongoid (bson_ext recommended) by default. Other ORMs may be
  # available as additional gems.
  require 'devise/orm/active_record'

  # ==> Configuration for any authentication mechanism
  # Configure which keys are used when authenticating a user. The default is
  # just :email. You can configure it to use [:username, :subdomain], so for
  # authenticating a user, both parameters are required. Remember that those
  # parameters are used only when authenticating and not when retrieving from
  # session. If you need permissions, you should implement that in a before filter.
  # You can also supply a hash where the value is a boolean determining whether
  # or not authentication should be aborted when the value is not present.
  # config.authentication_keys = [:email]

  # Configure parameters from the request object used for authentication. Each entry
  # given should be a request method and it will automatically be passed to the
  # find_for_authentication method and considered in your model lookup. For instance,
  # if you set :request_keys to [:subdomain], :subdomain will be used on authentication.
  # The same considerations mentioned for authentication_keys also apply to request_keys.
  # config.request_keys = []

  # Configure which authentication keys should be case-insensitive.
  # These keys will be downcased upon creating or modifying a user and when used
  # to authenticate or find a user. Default is :email.
  config.case_insensitive_keys = [:email]

  # Configure which authentication keys should have whitespace stripped.
  # These keys will have whitespace before and after removed upon creating or
  # modifying a user and when used to authenticate or find a user. Default is :email.
  config.strip_whitespace_keys = [:email]

  # Tell if authentication through request.params is enabled. True by default.
  # It can be set to an array that will enable params authentication only for the
  # given strategies, for example, `config.params_authenticatable = [:database]` will
  # enable it only for database (email + password) authentication.
  # config.params_authenticatable = true

  # Tell if authentication through HTTP Auth is enabled. False by default.
  # It can be set to an array that will enable http authentication only for the
  # given strategies, for example, `config.http_authenticatable = [:database]` will
  # enable it only for database authentication. The supported strategies are:
  # :database      = Support basic authentication with authentication key + password
  # config.http_authenticatable = false

  # If 401 status code should be returned for AJAX requests. True by default.
  # config.http_authenticatable_on_xhr = true

  # The realm used in Http Basic Authentication. 'Application' by default.
  # config.http_authentication_realm = 'Application'

  # It will change confirmation, password recovery and other workflows
  # to behave the same regardless if the e-mail provided was right or wrong.
  # Does not affect registerable.
  # config.paranoid = true

  # By default Devise will store the user in session. You can skip storage for
  # particular strategies by setting this option.
  # Notice that if you are skipping storage for all authentication paths, you

  config.skip_session_storage = [:http_auth]

  application
  # won't boot properly.
  # config.reload_routes = true

  # ==> Configuration for :database_authenticatable
  # For bcrypt, this is the cost for hashing the password and defaults to 11. If
  # using other algorithms, it sets how many times you want the password to be hashed.
  #
  # Limiting the stretches to just one in testing will increase the performance of
  # your test suite dramatically. However, it is STRONGLY RECOMMENDED to not use
  # a value less than 10 in other environments. Note that, for bcrypt (the default
  # algorithm), the cost increases exponentially with the number of stretches (e.g.
  # a value of 20 is already extremely slow: approx. 60 seconds for 1 calculation).
  config.stretches = Rails.env.test? ? 1 : 10

  # Set up a pepper to generate the hashed password.
  # config.pepper = 'e89683643d7f4fdeb42d0ca84e0599babe3a08160e877b5a7668a92bc223c9f58dd171712775a4659162a99acf854382ad9bdd0ee0061fd81ec6c0830ab2cf46'

  # A period that the user is allowed to confirm their account before their
  # token becomes invalid. For example, if set to 3.days, the user can confirm
  # their account within 3 days after the mail was sent, but on the fourth day
  # their account can't be confirmed with the token any more.
  # Default is nil, meaning there is no restriction on how long a user can take
  # before confirming their account.
  # config.confirm_within = 3.days

  # If true, requires any email changes to be confirmed (exactly the same way as
  # initial account confirmation) to be applied. Requires additional unconfirmed_email
  # db field (see migrations). Until confirmed, new email is stored in
  # unconfirmed_email column, and copied to email column on successful confirmation.
  config.reconfirmable = true

  # Defines which key will be used when confirming an account
  # config.confirmation_keys = [:email]

  # ==> Configuration for :rememberable
  # The time the user will be remembered without asking for credentials again.
  # config.remember_for = 2.weeks

  # Invalidates all the remember me tokens when the user signs out.
  config.expire_all_remember_me_on_sign_out = true

  # If true, extends the user's remember period when remembered via cookie.
  # config.extend_remember_period = false

  # Options to be passed to the created cookie. For instance, you can set
  # secure: true in order to force SSL only cookies.
  # config.rememberable_options = {}

  # ==> Configuration for :validatable
  # Range for password length.
  config.password_length = 6..128

  # Email regex used to validate email formats. It simply asserts that
  # one (and only one) @ exists in the given string. This is mainly
  # to give user feedback and not to assert the e-mail validity.
  config.email_regexp = /\A[^@\s]+@[^@\s]+\z/

  # ==> Configuration for :timeoutable
  # The time you want to timeout the user session without activity. After this
  # time the user will be asked for credentials again. Default is 30 minutes.
  # config.timeout_in = 30.minutes

  # Number of authentication tries before locking an account if lock_strategy
  # is failed attempts.
  # config.maximum_attempts = 20

  # Time interval to unlock the account if :time is enabled as unlock_strategy.
  # config.unlock_in = 1.hour

  # Warn on the last attempt before the account is locked.
  # config.last_attempt_warning = true

  # ==> Configuration for :recoverable
  #
  # Defines which key will be used when recovering the password for an account
  # config.reset_password_keys = [:email]

  # Time interval you can reset your password with a reset password key.
  # Don't put a too small interval or your users won't have the time to
  # change their passwords.
  config.reset_password_within = 6.hours

  # When set to false, does not sign a user in automatically after their password is
  # reset. Defaults to true, so a user is signed in automatically after a reset.
  # config.sign_in_after_reset_password = true

  # ==> Configuration for :encryptable
  # Allow you to use another hashing or encryption algorithm besides bcrypt (default).
  # You can use :sha1, :sha512 or algorithms from others authentication tools as
  # :clearance_sha1, :authlogic_sha512 (then you should set stretches above to 20
  # for default behavior) and :restful_authentication_sha1 (then you should set
  # stretches to 10, and copy REST_AUTH_SITE_KEY to pepper).
  #
  # Require the `devise-encryptable` gem when using anything other than bcrypt
  # config.encryptor = :sha512

  # ==> Scopes configuration
  # Turn scoped views on. Before rendering "sessions/new", it will first check for
  # "users/sessions/new". It's turned off by default because it's slower if you
  # are using only default views.
  # config.scoped_views = false

  # Configure the default scope given to Warden. By default it's the first
  # devise role declared in your routes (usually :user).
  # config.default_scope = :user

  # Set this configuration to false if you want /users/sign_out to sign out
  # only the current scope. By default, Devise signs out all scopes.
  # config.sign_out_all_scopes = true

  # ==> Navigation configuration
  # Lists the formats that should be treated as navigational. Formats like
  # :html, should redirect to the sign in page when the user does not have
  # access, but formats like :xml or :json, should return 401.
  #
  # If you have any extra navigational formats, like :iphone or :mobile, you
  # should add them to the navigational formats lists.
  #
  # The "*/*" below is required to match Internet Explorer requests.
  # config.navigational_formats = ['*/*', :html]

  # The default HTTP method used to sign out a resource. Default is :delete.
  config.sign_out_via = :delete

  # ==> OmniAuth
  # Add a new OmniAuth provider. Check the wiki for more information on setting
  # up on your models and hooks.
  # config.omniauth :github, 'APP_ID', 'APP_SECRET', scope: 'user,public_repo'

  # ==> Warden configuration
  # If you want to use other strategies, that are not supported by Devise, or
  # change the failure app, you can configure them inside the config.warden block.
  #
  # config.warden do |manager|
  #   manager.intercept_401 = false
  #   manager.default_strategies(scope: :user).unshift :some_external_strategy
  # end

  # ==> Mountable engine configurations
  # When using Devise inside an engine, let's call it `MyEngine`, and this engine
  # is mountable, there are some extra configurations to be taken into account.
  # The following options are available, assuming the engine is mounted as:
  #
  #     mount MyEngine, at: '/my_engine'
  #
  # The router that invoked `devise_for`, in the example above, would be:
  # config.router_name = :my_engine
  #
  # When using OmniAuth, Devise cannot automatically set OmniAuth path,
  # so you need to do it manually. For the users scope, it would be:
  # config.omniauth_path_prefix = '/my_engine/users/auth'

 end

A: It looks like you may not have precompiled your assets before you pushed to Heroku, try:
rake assets:precompile
git add .
etc etc

I think that should help. For more information, see here: see this

A: I think that this line from the logs
UPDATE "admin_users" SET "last_sign_in_at" = $1, "current_sign_in_at" = $2, "sign_in_count" = $3, "updated_at" = $4 WHERE "admin_users"."id" = $5  [["last_sign_in_at", "2017-02-14 11:47:42.774425"], ["current_sign_in_at", "2017-02-14 11:51:55.817737"], ["sign_in_count", 4], ["updated_at", "2017-02-14 11:51:55.819377"], ["id", 1]]

tells us that a record was updated in your admin_users table when you logged in as an admin.
Unfortunately, I can't tell how your models are laid out, but my best bet is that you need to query for AdminUser records.
> AdminUser.all

You should also make sure that the user_signed_in? method deals with AdminUsers. Posting your devise configuration (in the model) and any overrides would help. Have you overriden anything in Admin::DashboardController#index?
Devise reads from the session cookie. How have you configured your session store? Could it be that there's a different configuration for Heroku?


text:
Q: read a single color png into a numpy array I'm trying to load a single color PNG file into a numpy array. With most PNG files, the code below works fine. However, if the PNG file contains only a single color, the RGBA values of each pixel in the numpy array is [0, 0, 0, 255] which results in a black image.  In the case of the color "red", how can I access the correct RGBA values? e.g. [255, 0, 0, 255]
from PIL import image
import numpy as np

red_image = Image.open("red.png")
arr = np.asarray(red_image)

When calling red_image.getBands(), I expected to see a tuple of ("R",) as per the documentation. Instead, I'm seeing ("P",). I have not idea yet what a "P" channel is but I think it's related to my question.

A: The 'P' mean the PIL mode is in "palettised". More info here: What is the difference between images in 'P' and 'L' mode in PIL?.
converting from "P" to "RGBA" fixed my issue.
from PIL import image
import numpy as np

red_image = Image.open("red.png")
red_image = red_image.convert("RGBA") # added this line
arr = np.asarray(red_image)


text:
Q: Windows Server Wail2ban and Folder Sharing not working together - Error 4625 no IP I have a new install of Windows Server 2012 on a VM and I intend to use Wail2ban (https://github.com/glasnt/wail2ban) to try and block people attacking the server.
I have successfully added Wail2ban and I have this working now, but it certainly was not straight forward. There we are few settings I needed to change in gpedit.msc in order to get the IP of the attacking host to actually show up in the Event Viewer. Originally no source address was shown in the event.
By changing about three settings I now have this working, but I am now unable to access the shared files on the server.
One setting I had to change is gpedit.msc->Computer Configuration->Windows Settings->Security Settings->Local Policies->Security Options->Network Security: restrict NTLM: Incoming NTLM traffic
I have set this to "Deny All Accounts" and I do get the attacker ip in Event viewer but I cannot access shared files. With the other settings "Allow All"/"Deny all Domains" I do not get the IP in the Event viewer but I can access shared files.
Does anyone have any ideas how I can get both working or is this just a no go?

A: I now have this working with a few alterations.
I have changed the NTLM settings back to default, this is not necessary to do unless you have followed other articles and changed these settings.
A commenter pointed me in the direction of Event ID 4625 Without Source IP. It seems in the extended logs the IP is logged, just not in event 4625.
I followed the following article Accessing Extended Logs and added the registry key for Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational
I then changed one line in the wail2ban.ps1 file to allow these logs to be used
$EventTypes = "Application,Security,System,Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational"     #Event logs we allow to be processed

I also had to change the wail2ban_config to add the log file also and reference the event type id
# Wail2ban Configuration
[Events]
#[Security]
#4625=RDP Logins
#[Application]
#18456=MSSQL Logins
[Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational]
140=RDP Logins
[Whitelist]
# Add your whitelist here, in the format `IP = Comment`
# Supports plain IPs , e.g. `12.34.56.78  = My Machine`
# Also, ranges, e.g. `11.22.33.0/24 = My Company Range`

Adding the [Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational] section being the important thing here.
Once I had rebooted so the registry changes could take effect wail2ban started to work as expected.
I found wbemtest (put in run) to be useful here as you are able to query the logs and check to see if Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational is part of Win32_NTLogEvent
Whilst I do now have this working, I will be looking at the solution proposed by @moteus as this looks like an interesting solution, that would be easily moved and installed.

A: I do not think it possible use Wail2Ban without source change.
This is how I solve this problem with nxlog and my SpyLog service.
1. I redirect from Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational event 140. This event has IP address.
I found this event in this answer
<Input eventlog>
    Module       im_msvistalog
    SavePos      TRUE
    ReadFromLast TRUE
    Channel      "Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational"
    <QueryXML>
        <QueryList>
            <Query Id="0" Path="Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational">
                <Select Path="Microsoft-Windows-RemoteDesktopServices-RdpCoreTS/Operational">*[System[(EventID=140)]]</Select>
            </Query>
        </QueryList>
    </QueryXML>
</Input>

<Output spylog>
    Module      om_udp
    Host        127.0.0.1
    Port        614
    Exec        $raw_event = "EventID: " + $EventID + "; " + $Message;
</Output>

<Route 1>
    Path        eventlog => spylog
</Route>

*In SpyLog I add new filter like

FILTER{ "nxlog-rdp";
  enabled = true;
  source = "net:udp://127.0.0.1:614";
  exclude = WHITE_IP;
  hint = "EventID: 140";
  failregex = {
    "^EventID: 140; A connection from the client computer with an IP address of ([%d%.:]+)";
    -- UTF8
    "^EventID: 140; Не удалось подключить клиентский компьютер с IP%-адресом ([%d%.:]+)";
  };
};


text:
Q: systemd: How to modify the HandlePowerKey action with a custom command? My headless server has a power button.
When the user presses it, I want the server to respond with a brief beep, then shutdown the server.
The system should only beep when manually pressing the power button, not when the system shuts down on its own (e.g. when idle).
systemd handles the ACPI event from the power button, but how can I add a beep to HandlePowerKey there?

A: this question was solved here: https://unix.stackexchange.com/q/1974
you just need to add that command like

echo -e "\a"

to execution of power button event.
it uses "beep" package, so you should install it before

sudo apt-get install beep


text:
Q: unable to invoke chaincode from client : Error processing transaction. Error: PEM encoded certificate is required i am tring to invoke chaincode command from client by i get Error processing transaction. Error: PEM encoded certificate is required this is my client code i am using to connect to the fabric network and invoke the chaincode.
i can invoke and execute chaincode commands from the peer cli but why can't i do it from a client. i think it might have to do something with tls parameter or something. can anyone tell me what i'm missing.
thanks
`
    'use strict';
    const fs = require('fs');
    const yaml = require('js-yaml');
    const { FileSystemWallet, Gateway } = require('fabric-network');
    const CommercialPaper = require('../chaincode/lib/paper');

   // A wallet stores a collection of identities for use
    const wallet = new FileSystemWallet('../identity/user/isabella/wallet');

  async function main() {

         const gateway = new Gateway();

   try {
          const userName = 'User1@org1.bionic.com';

         // Load connection profile; will be used to locate a gateway
        let connectionProfile =
        yaml.safeLoad(fs.readFileSync('../gateway/networkConnection.yaml', 'utf8')
        );

// Set connection options; identity and wallet
let connectionOptions = {
  identity: userName,
  wallet: wallet,
  discovery: { enabled: false, asLocalhost: true }
};

await gateway.connect(connectionProfile, connectionOptions);

const network = await gateway.getNetwork('bionicchannel');
console.error('error occured');

// Get addressability to commercial paper contract

const contract = await network.getContract('papercontract');

const issueResponse = await contract.submitTransaction(
  'issue',
  'BionicSoftware',
  '00001',
  '2020-05-31',
  '2020-11-30',
  '5000000');}

A: If you have TLS enabled, you are probably missing certificates client side (Node SDK).
I suggest to keep TLS enabled but remove mutual authentication, in this way the client does not have to autentify each time.
You must change environment variables on docker compose setting CLIENTAUTHREQUIRED to false and generating again certificates in the wallet for the client.

A: the problem was in the connection configuration yaml file after specifying the ca address which was not available at the time everything worked.


text:
Q: Google + button not displaying poperly I am trying to add social buttons to my site and I just cant bring the google+1 button closer to the the other social buttons. It just goes to the extreme left of the div.
I have put up the code in Jsfiddle please take a look
Here is how it is looking over at my end
See how the google+ button is to the extreme left
JSFiddle here http://jsfiddle.net/LYYhj/3/
The code - HTML part

Follow @XgenHosting

The CSS part
.grid_1, .grid_2, .grid_3, .grid_4, .grid_5, .grid_6, .grid_7, .grid_8, .grid_9, .grid_10, .grid_11, .grid_12 {
    display:inline;
    float:left;
    position:relative;
    margin:0 10px
}
.wrapper{overflow:hidden;position:relative;}
.ul-1 {
    overflow:hidden;
    float:right;
    padding:48px 3px 0 0;
}
.ul-1 li {
    float:left;
    font-size:12px;
    line-height:15px;
    font-family: 'Droid Sans', sans-serif;
    text-transform:uppercase;
    text-shadow: 0 1px rgba(0,0,0, 0.6);
    background:url(../images/ul-1.png) left 3px no-repeat;
    margin-left:8px;
    padding-left:8px;
    color:#ddd;
}
.ul-1 li:first-child {
    background:none;
    padding:0;
    margin:0;
}
.ul-1 li a {
    color:#ddd;
}
.ul-1 li a:hover {
    color:#f04011;
    text-decoration:none;
}

Also when I implement the code into my page the google+1 button moves up by a little and no matter what I do I just cant manage to bring it to align with the other social button.
Link to the page http://www.xgen-hosting.com

A: Here are the two ways you can do this.
Method 1: If you inspect element the google+ button in your browser and see the code for
 elements, you can see that width of the google plus button is 120px, decreasing it will make your google plus button to align with other
 buttons.
Below is the pic of what I am trying to say and what I tried using this method.

and this is the result I got:

Now, the second method, if above doesn't work:
Make the list as position: absolute; This way you can position the buttons like whatever you want.
If you don't want to put the absolute positioned elements on the page (because there position will vary according to screen size), then you can simply put the absolute position list inside of a
 which is positioned relatively.


text:
Q: Failed having default tenant to connect to a Multi-tenant application I want to migrate an existing single-tenant application to multi-tenant application.
The first step is to create a default tenant and get it connect to the application, the code is as following:
the model :
    @Entity
            @Multitenant(MultitenantType.TABLE_PER_TENANT)
            @TenantTableDiscriminator(type = SCHEMA, contextProperty = MULTITENANT_PROPERTY_DEFAULT)
            @Table(name = "UTILISATEUR")
    public class User implements Serializable {

  @SequenceGenerator(name = "USER_SEQ", sequenceName = "user_seq", allocationSize = 1)
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "USER_SEQ")
    @Column(name = "id", nullable = false)
    private Integer id;
    private String username;
    private String password;
     @ManyToMany
    @JoinTable(name = "user_roles", joinColumns = {
        @JoinColumn(name = "User_userid")}, inverseJoinColumns = {
        @JoinColumn(name = "Role_roleid")})
    private List<Role> roles;
     ..... }

 @Entity
    @Multitenant(MultitenantType.TABLE_PER_TENANT)
    @TenantTableDiscriminator(type = SCHEMA, contextProperty = MULTITENANT_PROPERTY_DEFAULT)
    public class Role implements Serializable {

@Id
@SequenceGenerator(name = "ROLE_SEQ", sequenceName = "ROLE_SEQ", allocationSize = 1)
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "ROLE_SEQ")
@Column(name = "id", nullable = false)
private Integer id;
private String
private String rolename;
@ManyToMany(mappedBy = "roles")
private List<User> users;
public Integer getId() {
        return id;
    }
    ....}

the persistence.xml file:
<?xml version="1.0" encoding="UTF-8"?>
    <persistence version="2.0" xmlns="http://java.sun.com/xml/ns/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">
        <persistence-unit name="com.nz_war_1.0-SNAPSHOTPU" transaction-type="JTA">
             <provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
            <jta-data-source>jdbc/SimpleCRUD_JDBC</jta-data-source>
            <exclude-unlisted-classes>false</exclude-unlisted-classes>
            <properties>
                <property name="eclipselink.logging.level" value="fine" />
                <property name="eclipselink.tenant-id"                     value="default_tenant" />
            </properties>
        </persistence-unit>
    </persistence>

I created a Singleton class to have the Entity Manager Factory:
   public class EmfProvider {

        private static final String DB_PU = "com.nz_war_1.0-SNAPSHOTPU";
        public static final boolean DEBUG = true;
        private static final EmfProvider singleton = new EmfProvider();
        private EntityManagerFactory emf;

        private EmfProvider() {
        }

        public static EmfProvider getInstance() {
            return singleton;
        }

        public EntityManagerFactory getEntityManagerFactory() {
            if (emf == null) {
                emf = Persistence.createEntityManagerFactory(DB_PU);
            }
            if (DEBUG) {
                System.out.println("factory created on: " + new Date());
            }
            return emf;
        }

        public void closeEmf() {
            if (emf.isOpen() || emf != null) {
                emf.close();
            }
            emf = null;
            if (DEBUG) {
                System.out.println("EMF closed at: " + new Date());
            }

        }
    }

The facade:  Note that I don't user @persistenceContext, and create the entitymanager using the persistence unit manually because later we have to deterimine the persistenceuUnit to use programaticly:
 public abstract class DataAccessService<T> {
     private EntityManager em;
    public DataAccessService() {}
    private Class<T> type;
    public DataAccessService(Class<T> type) {
            this.type = type;
        }
    public void create(T t) {
            em = EmfProvider.getInstance().getEntityManagerFactory().createEntityManager();
        this.em.persist(t);
        this.em.flush();
    this.em.refresh(t);

  public List findWithNamedQuery(String namedQueryName) {
        em = EmfProvider.getInstance().getEntityManagerFactory().createEntityManager();
        return this.em.createNamedQuery(namedQueryName).getResultList();
    }
..........
}

@Stateless
public class UserService extends DataAccessService<User>{

    public UserService(){
        super(User.class);
    }
}

after running the project I get an exception which is: Predeployment of PersistenceUnit [com.nz_war_1.0-SNAPSHOTPU] failed.
and a long error in glassfish log:
    Avertissement: EJB5184:A system exception occurred during an invocation on EJB UserService, method: public java.util.List com.nz.simplecrud.service.DataAccessService.findWithNamedQuery(java.lang.String)
    Avertissement: javax.ejb.EJBException
        at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
        at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
        at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
        at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
        at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
        at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
        at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
        at com.sun.proxy.$Proxy284.findWithNamedQuery(Unknown Source)
        at com.nz.simplecrud.service.__EJB31_Generated__UserService__Intf____Bean__.findWithNamedQuery(Unknown Source)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:606)
        at org.jboss.weld.util.reflection.SecureReflections$13.work(SecureReflections.java:267)
        at org.jboss.weld.util.reflection.SecureReflectionAccess.run(SecureReflectionAccess.java:52)
        at org.jboss.weld.util.reflection.SecureReflectionAccess.runAsInvocation(SecureReflectionAccess.java:137)
        at org.jboss.weld.util.reflection.SecureReflections.invoke(SecureReflections.java:263)
        at org.jboss.weld.bean.proxy.EnterpriseBeanProxyMethodHandler.invoke(EnterpriseBeanProxyMethodHandler.java:110)
        at org.jboss.weld.bean.proxy.EnterpriseTargetBeanInstance.invoke(EnterpriseTargetBeanInstance.java:56)
        at org.jboss.weld.bean.proxy.ProxyMethodHandler.invoke(ProxyMethodHandler.java:105)
        at com.nz.simplecrud.service.UserService$Proxy$_$$_Weld$Proxy$.findWithNamedQuery(UserService$Proxy$_$$_Weld$Proxy$.java)
        at com.nz.simplecrud.controller.UserController.init(UserController.java:64)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        ......

Caused by: Exception [EclipseLink-30005] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)
Internal Exception: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [com.nz_war_1.0-SNAPSHOTPU] failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class com.nz.simplecrud.entities.UserRoleView] has no primary key specified. It should define either an @Id, @EmbeddedId or an @IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
    at org.eclipse.persistence.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:127)
    at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactoryImpl(PersistenceProvider.java:111)
    at org.eclipse.persistence.jpa.PersistenceProvider.createEntityManagerFactory(PersistenceProvider.java:183)
....
Caused by: javax.persistence.PersistenceException: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [com.nz_war_1.0-SNAPSHOTPU] failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class com.nz.simplecrud.entities.UserRoleView] has no primary key specified. It should define either an @Id, @EmbeddedId or an @IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.createPredeployFailedPersistenceException(EntityManagerSetupImpl.java:2023)
    at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:2014)
Caused by: Exception [EclipseLink-28018] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [com.nz_war_1.0-SNAPSHOTPU] failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class com.nz.simplecrud.entities.UserRoleView] has no primary key specified. It should define either an @Id, @EmbeddedId or an @IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
    at org.eclipse.persistence.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:231)
    ... 135 more
Caused by: Exception [EclipseLink-7161] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class com.nz.simplecrud.entities.UserRoleView] has no primary key specified. It should define either an @Id, @EmbeddedId or an @IdClass. If you have defined PK using any of these annotations then make sure that you do not have mixed access-type (both fields and properties annotated) in your entity class hierarchy.
    at org.eclipse.persistence.exceptions.ValidationException.noPrimaryKeyAnnotationsFound(ValidationException.java:1425)

Grave: Error Rendering View[/admin/UserList.xhtml]
javax.el.ELException: /admin/UserList.xhtml @12,69 value="#{userController.lazyModel}": org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke [method] @PostConstruct public com.nz.simplecrud.controller.UserController.init() on com.nz.simplecrud.controller.UserController@519c628d
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)....

Grave: Error Rendering View[/admin/UserList.xhtml]
javax.el.ELException: /admin/UserList.xhtml @12,69 value="#{userController.lazyModel}": org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke [method] @PostConstruct public com.nz.simplecrud.controller.UserController.init() on com.nz.simplecrud.controller.UserController@5bcd013b
    at com.sun.faces.facelets.el.TagValueExpression.getValue(TagValueExpression.java:114)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:194)
    at javax.faces.component.ComponentStateHelper.eval(ComponentStateHelper.java:182)
    at javax.faces.component.UIData.getValue(UIData.java:731)....
Caused by: org.jboss.weld.exceptions.WeldException: WELD-000049 Unable to invoke [method] @PostConstruct public com.nz.simplecrud.controller.UserController.init() on com.nz.simplecrud.controller.UserController@5bcd013b
    at org.jboss.weld.bean.AbstractClassBean.defaultPostConstruct(AbstractClassBean.java:400)
    at org.jboss.weld.bean.ManagedBean$ManagedBeanInjectionTarget.postConstruct(ManagedBean.java:174)
    at org.jboss.weld.bean.ManagedBean.create(ManagedBean.java:294)
    at org.jboss.weld.context.AbstractContext.get(AbstractContext.java:107)

Can any one help me please.
Thank you.