问:
NpgsqlConnection.Open opens remote connection even when there is no internet
this is my first question in here.

So I have this app that connects to a remote database using Npgsql library.
 I have a method that connects to the db, execute a query, and finally it closes the connection.
It work fine, but the problem is that if, while the program is running but not calling the method, I disconnect the WiFi to simulate the inability to connect to the server, and then run the method, the connection method still is able to open the connection. This causes the query to get stuck.
I can't seem to find a way to check if I can connect to server because, even if I disconnect the internet, the NpgsqlConnection.Open() method still opens it.

Sorry about my english

```<code> public static NpgsqlConnection ConnectRemote()
    {
        try
        {
            remoteConnection = new NpgsqlConnection("Server = " + remoteData.server + "; " +
                                              "Port = " + remoteData.port + "; " +
                                              "User Id = " + remoteData.user + "; " +
                                              "Password = " + remoteData.password + "; " +
                                              "Database = " + remoteData.dataBase + "; ");

            remoteConnection.Open();
        }
        catch (NpgsqlException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            remoteConnection.Close();
            remoteConnection = null;
        }
        return remoteConnection;

    }

public static bool CheckRemote()
    {
            if (remoteConnection != null)
            {
                if (remoteConnection.FullState.Equals(ConnectionState.Open))
                    return true;
                return false;
            }
            return false;
    }

public bool AddNewProduct(Product product)
    {
        try
        {
            DBManager.ConnectLocal();
            DBManager.ConnectRemote();
            object[] parameters;

            if (DBManager.CheckRemote())
            {
                if (!DBManager.isSyncronized)
                {
                    DBManager.Syncronize();
                }

                parameters = new object[8];
                parameters[0] = 1;
                parameters[1] = product.id;
                parameters[2] = product.description;
                parameters[3] = (decimal)product.salePrice;
                parameters[4] = (decimal)product.cost;
                parameters[5] = product.minStock;
                parameters[6] = product.providerName;
                parameters[7] = product.category;
                DBManager.RunFunction(DBManager.remoteConnection, DBProcedures.createProduct, parameters);
            }
            else
            {
                string sql = "select * from createproduct(1, " + product.id + ", '" + product.description + "', " + (decimal)product.salePrice + ", "
                    + (decimal)product.cost + ", " + product.minStock + ", '" + product.providerName + "', '" + product.category + "'); ";
                parameters = new object[1];
                parameters[0] = sql;
                DBManager.RunFunction(DBManager.localConnection, "addsync", parameters);

                DBManager.isSyncronized = false;

            }

            parameters = new object[6];
            parameters[0] = product.description;
            parameters[1] = (decimal)product.salePrice;
            parameters[2] = (decimal)product.cost;
            parameters[3] = product.minStock;
            parameters[4] = product.providerName;
            parameters[5] = product.category;

            DataTable result = DBManager.RunFunction(DBManager.localConnection, DBProcedures.createProduct, parameters);
            DBManager.DisconnectLocal();
            DBManager.DisconnectRemote();
            return true;
        }
        catch (Npgsql.NpgsqlException ex)
        {
            return false;
        }
    }
</code>```

答:
A few things -- one unrelated, and two related.  I am hopeful that some combination of these will help.

First, the unrelated comment.  The NpgSqlStringBuilder class is a nice tool to help demystify the connection strings.  I realize yours works, but as you have to make edits (as I will suggest in a minute), I find it much easier to use than navigating String.Format, just as Query Parameters are easier (on top of being more secure) than trying to string.Format your way through passing arguments to a query.  Also, declare the ApplicationName in your connection string to help diagnose what exactly is happening on the server, like you will read in the next comment.

If you are using connection pooling, When a connection is closed, I don't think it's really closed -- not even on the database.  If you open server admin, you will see what I mean -- it kind of dangles out there, waiting to be reused.  Try setting pooled=false in your connection string to ensure that when you close a connection you really close it.

If this doesn't work, try a trivial query.  The cost will be minimal in cases where you don't need it and will undoubtedly fix your use case when you do need it.

All three suggestions are reflected here:

```<code>public static NpgsqlConnection ConnectRemote()
{
    NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
    sb.ApplicationName = "Connection Tester";
    sb.Host = remoteData.server;
    sb.Port = remoteData.port;
    sb.Username = remoteData.user;
    sb.Password = remoteData.password;
    sb.Database = remoteData.database;
    sb.Pooling = false;

    remoteConnection = new NpgsqlConnection(sb.ToString());

    try
    {
        remoteConnection.Open();
        NpgSqlCommand test = new NpgSqlCommand("select 1", remoteConnection);
        test.ExecuteScalar();
    }
    catch (NpgsqlException ex)
    {
       throw;
    }
    catch (Exception ex)
    {
       remoteConnection.Close();
       remoteConnection = null;
    }
    return remoteConnection;
}
</code>```

Body:
this is my first question in here.

So I have this app that connects to a remote database using Npgsql library.
 I have a method that connects to the db, execute a query, and finally it closes the connection.
It work fine, but the problem is that if, while the program is running but not calling the method, I disconnect the WiFi to simulate the inability to connect to the server, and then run the method, the connection method still is able to open the connection. This causes the query to get stuck.
I can't seem to find a way to check if I can connect to server because, even if I disconnect the internet, the NpgsqlConnection.Open() method still opens it.

Sorry about my english

 public static NpgsqlConnection ConnectRemote()
    {
        try
        {
            remoteConnection = new NpgsqlConnection("Server = " + remoteData.server + "; " +
                                              "Port = " + remoteData.port + "; " +
                                              "User Id = " + remoteData.user + "; " +
                                              "Password = " + remoteData.password + "; " +
                                              "Database = " + remoteData.dataBase + "; ");

            remoteConnection.Open();
        }
        catch (NpgsqlException ex)
        {
            throw;
        }
        catch (Exception ex)
        {
            remoteConnection.Close();
            remoteConnection = null;
        }
        return remoteConnection;

    }

public static bool CheckRemote()
    {
            if (remoteConnection != null)
            {
                if (remoteConnection.FullState.Equals(ConnectionState.Open))
                    return true;
                return false;
            }
            return false;
    }

public bool AddNewProduct(Product product)
    {
        try
        {
            DBManager.ConnectLocal();
            DBManager.ConnectRemote();
            object[] parameters;

            if (DBManager.CheckRemote())
            {
                if (!DBManager.isSyncronized)
                {
                    DBManager.Syncronize();
                }

                parameters = new object[8];
                parameters[0] = 1;
                parameters[1] = product.id;
                parameters[2] = product.description;
                parameters[3] = (decimal)product.salePrice;
                parameters[4] = (decimal)product.cost;
                parameters[5] = product.minStock;
                parameters[6] = product.providerName;
                parameters[7] = product.category;
                DBManager.RunFunction(DBManager.remoteConnection, DBProcedures.createProduct, parameters);
            }
            else
            {
                string sql = "select * from createproduct(1, " + product.id + ", '" + product.description + "', " + (decimal)product.salePrice + ", "
                    + (decimal)product.cost + ", " + product.minStock + ", '" + product.providerName + "', '" + product.category + "'); ";
                parameters = new object[1];
                parameters[0] = sql;
                DBManager.RunFunction(DBManager.localConnection, "addsync", parameters);

                DBManager.isSyncronized = false;

            }

            parameters = new object[6];
            parameters[0] = product.description;
            parameters[1] = (decimal)product.salePrice;
            parameters[2] = (decimal)product.cost;
            parameters[3] = product.minStock;
            parameters[4] = product.providerName;
            parameters[5] = product.category;

            DataTable result = DBManager.RunFunction(DBManager.localConnection, DBProcedures.createProduct, parameters);
            DBManager.DisconnectLocal();
            DBManager.DisconnectRemote();
            return true;
        }
        catch (Npgsql.NpgsqlException ex)
        {
            return false;
        }
    }

Body:
A few things -- one unrelated, and two related.  I am hopeful that some combination of these will help.

First, the unrelated comment.  The NpgSqlStringBuilder class is a nice tool to help demystify the connection strings.  I realize yours works, but as you have to make edits (as I will suggest in a minute), I find it much easier to use than navigating String.Format, just as Query Parameters are easier (on top of being more secure) than trying to string.Format your way through passing arguments to a query.  Also, declare the ApplicationName in your connection string to help diagnose what exactly is happening on the server, like you will read in the next comment.

If you are using connection pooling, When a connection is closed, I don't think it's really closed -- not even on the database.  If you open server admin, you will see what I mean -- it kind of dangles out there, waiting to be reused.  Try setting pooled=false in your connection string to ensure that when you close a connection you really close it.

If this doesn't work, try a trivial query.  The cost will be minimal in cases where you don't need it and will undoubtedly fix your use case when you do need it.

All three suggestions are reflected here:

public static NpgsqlConnection ConnectRemote()
{
    NpgsqlConnectionStringBuilder sb = new NpgsqlConnectionStringBuilder();
    sb.ApplicationName = "Connection Tester";
    sb.Host = remoteData.server;
    sb.Port = remoteData.port;
    sb.Username = remoteData.user;
    sb.Password = remoteData.password;
    sb.Database = remoteData.database;
    sb.Pooling = false;

    remoteConnection = new NpgsqlConnection(sb.ToString());

    try
    {
        remoteConnection.Open();
        NpgSqlCommand test = new NpgSqlCommand("select 1", remoteConnection);
        test.ExecuteScalar();
    }
    catch (NpgsqlException ex)
    {
       throw;
    }
    catch (Exception ex)
    {
       remoteConnection.Close();
       remoteConnection = null;
    }
    return remoteConnection;
}


来源: stackexchange

问:
when user turn On location show marker on current location
i create one map in this i show one marker on current location its working fine
when location turn on already but when Activity is on and i turn On location it does not show any marker i want to show marker when location is on
any help?..</p>

```<code>public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
         getCurrentLocation();
       // latLngCurrentLocation is my current location which is update using getCurrentLocation() method.

    if(latLngCurrentLocation != null) {

    // add marker on current location
            markerCurrent = mMap.addMarker(new MarkerOptions()
                    .position(latLngCurrentLocation)
                    .draggable(true)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                    .title("Current Location"));

            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrentLocation));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(8));
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.setOnMarkerDragListener(this);

        }

    }
</code>```

答: Through GpsTracker class or googleClient api you can get latitude and longtitude and then get it as gpstracker.getlatitude and getlongtitude and set this values to global variables and access it whereever you want.</p>

ContentLicense: CC BY-SA 3.0

Body:
i create one map in this i show one marker on current location its working fine
when location turn on already but when Activity is on and i turn On location it does not show any marker i want to show marker when location is on
any help?..

public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
         getCurrentLocation();
       // latLngCurrentLocation is my current location which is update using getCurrentLocation() method.

    if(latLngCurrentLocation != null) {

    // add marker on current location
            markerCurrent = mMap.addMarker(new MarkerOptions()
                    .position(latLngCurrentLocation)
                    .draggable(true)
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN))
                    .title("Current Location"));

            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrentLocation));
            mMap.animateCamera(CameraUpdateFactory.zoomTo(8));
            mMap.getUiSettings().setZoomControlsEnabled(true);
            mMap.setOnMarkerDragListener(this);

        }

    }


问:
Open a form from modal form that opened from parent form
I create a form which makes lightbox effect.And after creating this lightbox form, i create another form.

```<code>//Execute from parent form
Form f = new Form();
f.ShowInTaskbar = false;
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = FormStartPosition.CenterParent;
f.Opacity = 0.6;
f.ShowDialog(); // Open Modal window
notificationSize nds = new notificationSize();
nds.Show(); // Open another form on Modal Dialog
</code>```

After creating lightbox form, it doesn't show another form nds. Just showind the lightbox modal dialog.

how can i show the form on the modal form ?

答:
Well i don't quite get what the purpose of this is but this will do the trick:</p>

```<code>        var f = new Form();
        f.IsMdiContainer = true;
        f.ShowInTaskbar = false;
        f.BackColor = Color.Black;
        f.Size = this.Size;
        f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        f.StartPosition = FormStartPosition.CenterParent;
        f.Opacity = 0.6;
        var nds = new notificationSize();
        nds.Show();
        nds.MdiParent = f;
        f.ShowDialog(); // Open Modal window
</code>```

Body:
I create a form which makes lightbox effect.And after creating this lightbox form, i create another form.

//Execute from parent form
Form f = new Form();
f.ShowInTaskbar = false;
f.BackColor = Color.Black;
f.Size = this.Size;
f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
f.StartPosition = FormStartPosition.CenterParent;
f.Opacity = 0.6;
f.ShowDialog(); // Open Modal window
notificationSize nds = new notificationSize();
nds.Show(); // Open another form on Modal Dialog

After creating lightbox form, it doesn't show another form nds. Just showind the lightbox modal dialog.

how can i show the form on the modal form ?

Body:
Well i don't quite get what the purpose of this is but this will do the trick:

        var f = new Form();
        f.IsMdiContainer = true;
        f.ShowInTaskbar = false;
        f.BackColor = Color.Black;
        f.Size = this.Size;
        f.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
        f.StartPosition = FormStartPosition.CenterParent;
        f.Opacity = 0.6;
        var nds = new notificationSize();
        nds.Show();
        nds.MdiParent = f;
        f.ShowDialog(); // Open Modal window


问:
" are replaced with ' with ansible
In ansible, I need to generate daemon.json file with log-opts:

```<code>{% if docker_log_dict is defined %}
  "log-opts": {{ docker_log_dict.log_opts | default('[]') }},
{% endif %}
</code>```

With

```<code>log_opts: |
      {
        "syslog-address": "tcp://{{ my_ip_run }}:514",
        "tag": {% raw %}"{{.Name}}/{{.FullID}}"{% endraw %}
      }
</code>```

But then, when I check the generated daemon.json file, I get :

```<code>...
"log_opts":
      {
        'syslog-address': 'tcp://10.10.10.10:514',
        'tag': {% raw %}'{{.Name}}/{{.FullID}}'{% endraw %}
      }
</code>```

Thing is when replacing, ansible is replacing with simple quote instead of double quotes.

When restarting Docker daemon, it will fail unless I use double quotes?

I don't understand why is that happening.

Anyone know how to fix it ???

答:
You must add a filter to_json in your Jinja template

```<code>{% if docker_log_dict is defined %}
  "log-opts": {{ docker_log_dict.log_opts | to_json | default('[]') }},
{% endif %}
</code>```

I've found the answer here: https://groups.google.com/forum/#!topic/ansible-project/WUjiN9Wf32U

Title: " are replaced with ' with ansible

Body:
In ansible, I need to generate daemon.json file with log-opts:

{% if docker_log_dict is defined %}
  "log-opts": {{ docker_log_dict.log_opts | default('[]') }},
{% endif %}

With

log_opts: |
      {
        "syslog-address": "tcp://{{ my_ip_run }}:514",
        "tag": {% raw %}"{{.Name}}/{{.FullID}}"{% endraw %}
      }

But then, when I check the generated daemon.json file, I get :

...
"log_opts":
      {
        'syslog-address': 'tcp://10.10.10.10:514',
        'tag': {% raw %}'{{.Name}}/{{.FullID}}'{% endraw %}
      }

Thing is when replacing, ansible is replacing with simple quote instead of double quotes.

When restarting Docker daemon, it will fail unless I use double quotes?

I don't understand why is that happening.

Anyone know how to fix it ???

Body:
You must add a filter to_json in your Jinja template

{% if docker_log_dict is defined %}
  "log-opts": {{ docker_log_dict.log_opts | to_json | default('[]') }},
{% endif %}

I've found the answer here: https://groups.google.com/forum/#!topic/ansible-project/WUjiN9Wf32U


问:
ARM Branch Prediction based on code
so I'm trying to study for this test and one of the things on the study guide gives us some ARM Code and tells us to fill in a branch prediction table based on how the code runs.

I can understand how I'm supposed to do it, but with branch prediction the actual outcome comes into play, too, and I can't figure out the outcome (per cycle) from the code.  The code is:

```<code>    MOV r0, #4
B1  MOV r2, #5; Branch 1
    SUB r2, r2, r0
B2  SUBS r2, r2, #1; Branch 2
    BNE B2
    SUBS r0, r0, #1
    BNE B1
</code>```

What's confusing me is the BNE statements.  Usually when I see one of those conditional statements there has been a CMP statement earlier in the code, and that way I can know whether to take the branch or not.  But I see no compare statement anywhere in this code, so I don't know how to determine if I should take a branch or not.

答: The SUBS performs a subtraction and a comparison with zero of the result in one instruction. The BNE conditional branches use the condition flags that were set by these SUBS instructions

Title: ARM Branch Prediction based on code

Body:
so I'm trying to study for this test and one of the things on the study guide gives us some ARM Code and tells us to fill in a branch prediction table based on how the code runs.

I can understand how I'm supposed to do it, but with branch prediction the actual outcome comes into play, too, and I can't figure out the outcome (per cycle) from the code.  The code is:

    MOV r0, #4
B1  MOV r2, #5; Branch 1
    SUB r2, r2, r0
B2  SUBS r2, r2, #1; Branch 2
    BNE B2
    SUBS r0, r0, #1
    BNE B1

What's confusing me is the BNE statements.  Usually when I see one of those conditional statements there has been a CMP statement earlier in the code, and that way I can know whether to take the branch or not.  But I see no compare statement anywhere in this code, so I don't know how to determine if I should take a branch or not.


问:
Adding Some Extra calculation during the time of Sum on mongodb $sum function
My Mongo-Db dataset is this:

```<code>{
    "_id" : ObjectId("5a267533754884223467604a"),
    "user_id" : "5a20ee1acdacc7086ce7742c",
    "tv_count" : 1,
    "ac_count" : 0,
    "fridge_count" : 0,
    "blower_count" : 0,
    "chair_count" : 0,
    "sofa_count" : 0,
    "D2H_count" : 2,
    "lastmodified" : ISODate("2017-12-05T10:30:30.559Z"),
    "__v" : 0
}
</code>```

So I know i want to do some modification during the time of Sum.
My Sum Code is this:

```<code>Accessories.aggregate([
                {$match: { "lastmodified":{$gt: newTime}}},
                {
                    $project: {
                        total: {
                            $add: [ "$tv_count", "$ac_count", "$fridge_count", "$blower_count", "$chair_count", "$sofa_count", "$D2H_count"]
                        }
                    }
                }
            ]);
</code>```

So it will return the result

```<code>[ { _id: 5a267533754884223467604a, total: 3 } ]
</code>```

Now I want to do some extra calculation. Example is

```<code>Earlier Result will be 1+0+0+0+0+0+2 = 3

My desire result will be like (1*2)+0+0+0+0+0+(2*4) = 10
</code>```

Any Help will be appreciated.

答:
I would add an $addFields stage in the aggregation pipeline between the $match and the @project stage.
In the $addFields stage you can define new "helper fields" - eg.

```<code>{ $addFields: {
    "tv_temp": { $multiply: [ "$tv_count", 2 ] },
    "D2H_temp": { $multiply: [ "$D2H_count", 4 ] },
  }
}
</code>```

Using these fields, you can now calculate the total:

```<code>{ $project: {
  total: {
    $add: [ "$tv_temp", "$ac_count", "$fridge_count", "$blower_count", "$chair_count", "$sofa_count", "$D2H_temp"]
  }
}}
</code>```

Body:
My Mongo-Db dataset is this:

{
    "_id" : ObjectId("5a267533754884223467604a"),
    "user_id" : "5a20ee1acdacc7086ce7742c",
    "tv_count" : 1,
    "ac_count" : 0,
    "fridge_count" : 0,
    "blower_count" : 0,
    "chair_count" : 0,
    "sofa_count" : 0,
    "D2H_count" : 2,
    "lastmodified" : ISODate("2017-12-05T10:30:30.559Z"),
    "__v" : 0
}

So I know i want to do some modification during the time of Sum.
My Sum Code is this:

Accessories.aggregate([
                {$match: { "lastmodified":{$gt: newTime}}},
                {
                    $project: {
                        total: {
                            $add: [ "$tv_count", "$ac_count", "$fridge_count", "$blower_count", "$chair_count", "$sofa_count", "$D2H_count"]
                        }
                    }
                }
            ]);

So it will return the result

[ { _id: 5a267533754884223467604a, total: 3 } ]

Now I want to do some extra calculation. Example is

Earlier Result will be 1+0+0+0+0+0+2 = 3

My desire result will be like (1*2)+0+0+0+0+0+(2*4) = 10

Any Help will be appreciated.

Body:
I would add an $addFields stage in the aggregation pipeline between the $match and the @project stage.
In the $addFields stage you can define new "helper fields" - eg.

{ $addFields: {
    "tv_temp": { $multiply: [ "$tv_count", 2 ] },
    "D2H_temp": { $multiply: [ "$D2H_count", 4 ] },
  }
}

Using these fields, you can now calculate the total:

{ $project: {
  total: {
    $add: [ "$tv_temp", "$ac_count", "$fridge_count", "$blower_count", "$chair_count", "$sofa_count", "$D2H_temp"]
  }
}}


问:
Injecting Repository in Controller - Class does not exist
I've created App/Repositories/HelloRepository, but get Class App\Http\Controllers\HelloRepository does not exist

What am I missing to be able to inject my new repository into my controller

Repository:

```<code>namespace App\Repositories;

class HelloRepository
{
    public function sayHello()
    {
        return "Hello!";
    }
}
</code>```

Controller:

```<code><?php

namespace App\Http\Controllers;

use App\Repositories;

    public function index(HelloRepository $repo)
    {
        dd($repo->sayHello());
    }
</code>```

答:
put this at the at the top, i.e after you set namespace

```<code>use App\Repositories\HelloRepository
</code>```

and remove

```<code>use App\Repositories;
</code>```

Body:
I've created App/Repositories/HelloRepository, but get Class App\Http\Controllers\HelloRepository does not exist

What am I missing to be able to inject my new repository into my controller

Repository:

namespace App\Repositories;

class HelloRepository
{
    public function sayHello()
    {
        return "Hello!";
    }
}

Controller:

<?php

namespace App\Http\Controllers;

use App\Repositories;

    public function index(HelloRepository $repo)
    {
        dd($repo->sayHello());
    }

Body:
put this at the at the top, i.e after you set namespace

use App\Repositories\HelloRepository

and remove

use App\Repositories;


问:
Gson parsing a Json to a Realm object with SerializedName fields

I'm parsing a json string to a Realm object, but the json has the key "id", So I'm using a serializedName to bypass it.

Here is my Json (jsonString in the following example)

```<code>{
    "id": "someuuidString",
    ...
    (some more irrelevant fields)
}
</code>```

Here is my object decleration

```<code>public class MyObject extends RealmObject {

    @PrimaryKey
    private long id;

    @SerializedName("id")
    private String MyObjectId;
    ...
    (some more irrelevant fields, constructors, getters and setters)
}
</code>```

And later in the code i try the following

```<code>Gson gson = new GsonBuilder().create();
MyObject obj = gson.fromJson(jsonString, MyObject.class);
</code>```

So instead of parsing correctly, it crashes with the following exception

```<code>java.lang.IllegalArgumentException: class com.example.objects.MyObject declares multiple JSON fields named id
</code>```

So, what did I miss?

答:
It is because @SerializedName treats MyObjectId as "id", so you have 2 fields called id.

Change your object to

```<code>public class MyObject extends RealmObject {

    @PrimaryKey
    private long databaseId;

    @SerializedName("id")
    private String MyObjectId;
    ...
    (some more irrelevant fields, constructors, getters and setters)
}
</code>```

Generally maybe better is to remove this databaseId and set @PrimaryKey on MyObjectId. It depends on your needs

Body:
I'm parsing a json string to a Realm object, but the json has the key "id", So I'm using a serializedName to bypass it.

Here is my Json (jsonString in the following example)

{
    "id": "someuuidString",
    ...
    (some more irrelevant fields)
}

Here is my object decleration

public class MyObject extends RealmObject {

    @PrimaryKey
    private long id;

    @SerializedName("id")
    private String MyObjectId;
    ...
    (some more irrelevant fields, constructors, getters and setters)
}

And later in the code i try the following

Gson gson = new GsonBuilder().create();
MyObject obj = gson.fromJson(jsonString, MyObject.class);

So instead of parsing correctly, it crashes with the following exception

java.lang.IllegalArgumentException: class com.example.objects.MyObject declares multiple JSON fields named id

So, what did I miss?

Body:
It is because @SerializedName treats MyObjectId as "id", so you have 2 fields called id.

Change your object to

public class MyObject extends RealmObject {

    @PrimaryKey
    private long databaseId;

    @SerializedName("id")
    private String MyObjectId;
    ...
    (some more irrelevant fields, constructors, getters and setters)
}

Generally maybe better is to remove this databaseId and set @PrimaryKey on MyObjectId. It depends on your needs


问:
Eclipse Spring Boot - AutoConfigure cycle detected between TransactionAutoConfiguration and Neo4jDataAutoConfiguration
I had a really weird error starting yesterday on the Spring Boot application I am working on (1.5.2.RELEASE). I started getting the below exceptions when running the project in Eclipse.

When running it from the command line, everything worked fine (but I still need to run it from Eclipse when developing and debugging). I tried deleting the .classpath file, re-importing the projects, cleaning them in Eclipse, but the error persisted

```<code>2017-12-05 13:46:45.620 ERROR 11048 --- [  restartedMain] o.s.b.f.s.DefaultListableBeanFactory     : Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@744ed1b7: startup date [Tue Dec 05 13:46:43 EET 2017]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]

<STACK-TRACE>

2017-12-05 13:46:45.635 ERROR 11048 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.almetis.webraadmin.WebRaAdminApplication];
nested exception is java.lang.IllegalStateException: AutoConfigure cycle detected between org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration and org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:545) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]

<STACK-TRACE>

Caused by: java.lang.IllegalStateException: AutoConfigure cycle detected between org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration and org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration
at org.springframework.util.Assert.state(Assert.java:70) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]
</code>```

答:
After upgrading my main project and libraries to use Spring Boot 1.5.8.RELEASE, I could run my app in Eclipse again.

It seems there's a problem in the 1.5.2.RELEASE integration with Neo4J (see github issue and issue).

After taking a better look, I saw the reason: my main app was using Spring Boot 1.5.2 and one of the libraries it was consuming was using Spring Boot 1.5.8.

After playing around with the Spring Boot versions of my libraries and main app, I see:

if all libraries and main app are using Spring Boot 1.5.2, all works well

if all libraries and main app are using Spring Boot 1.5.8, all works well

if a library is using Spring Boot 1.5.8 and the main app is using Spring Boot 1.5.2, then the exceptions in the question are thrown

The error is a little bit cryptic (to say at least), but the main take-away is to keep all libraries and apps on the same Spring Boot version.

Body:
I had a really weird error starting yesterday on the Spring Boot application I am working on (1.5.2.RELEASE). I started getting the below exceptions when running the project in Eclipse.

When running it from the command line, everything worked fine (but I still need to run it from Eclipse when developing and debugging). I tried deleting the .classpath file, re-importing the projects, cleaning them in Eclipse, but the error persisted

2017-12-05 13:46:45.620 ERROR 11048 --- [  restartedMain] o.s.b.f.s.DefaultListableBeanFactory     : Destroy method on bean with name 'org.springframework.boot.autoconfigure.internalCachingMetadataReaderFactory' threw an exception
java.lang.IllegalStateException: ApplicationEventMulticaster not initialized - call 'refresh' before multicasting events via the context: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@744ed1b7: startup date [Tue Dec 05 13:46:43 EET 2017]; root of context hierarchy
at org.springframework.context.support.AbstractApplicationContext.getApplicationEventMulticaster(AbstractApplicationContext.java:404) [spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]

<STACK-TRACE>

2017-12-05 13:46:45.635 ERROR 11048 --- [  restartedMain] o.s.boot.SpringApplication               : Application startup failed

org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [com.almetis.webraadmin.WebRaAdminApplication];
nested exception is java.lang.IllegalStateException: AutoConfigure cycle detected between org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration and org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration
at org.springframework.context.annotation.ConfigurationClassParser.processDeferredImportSelectors(ConfigurationClassParser.java:545) ~[spring-context-4.3.7.RELEASE.jar:4.3.7.RELEASE]

<STACK-TRACE>

Caused by: java.lang.IllegalStateException: AutoConfigure cycle detected between org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration and org.springframework.boot.autoconfigure.data.neo4j.Neo4jDataAutoConfiguration
at org.springframework.util.Assert.state(Assert.java:70) ~[spring-core-4.3.7.RELEASE.jar:4.3.7.RELEASE]


问:
Google calendar API. Saying 403 error(insufficient permission)

```<code>{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "insufficientPermissions",
        "message": "Insufficient Permission"
      }
    ],
    "code": 403,
    "message": "Insufficient Permission"
  }
}
</code>```

While inserting new event into google calendar.

答:
```<code>{
   "error":{
      "errors":[
         {
            "domain":"global",
            "reason":"insufficientPermissions",
            "message":"Insufficient Permission"
         }
      ],
      "code":403,
      "message":"Insufficient Permission"
   }
}
</code>```

Means that the user you have currently authenticated with does not have permissions to insert your event.   Most of the Google Calendar API methods are private and there for can only be used by a user with the correct permissions.

Check the user you have authenticated with make sure that user has access to the calendar you are trying to insert events into.

Check the scopes you are authenticating with. If you are authenticating with read only access and trying to write you will also see this error.

Body:
{
  "error": {
    "errors": [
      {
        "domain": "global",
        "reason": "insufficientPermissions",
        "message": "Insufficient Permission"
      }
    ],
    "code": 403,
    "message": "Insufficient Permission"
  }
}

While inserting new event into google calendar.

Body:
{
   "error":{
      "errors":[
         {
            "domain":"global",
            "reason":"insufficientPermissions",
            "message":"Insufficient Permission"
         }
      ],
      "code":403,
      "message":"Insufficient Permission"
   }
}

Means that the user you have currently authenticated with does not have permissions to insert your event.   Most of the Google Calendar API methods are private and there for can only be used by a user with the correct permissions.

Check the user you have authenticated with make sure that user has access to the calendar you are trying to insert events into.

Check the scopes you are authenticating with. If you are authenticating with read only access and trying to write you will also see this error.


问:
Can we assign ng-model to span?
I need to assign the value to span based on the selected answer in dropdown.

```<code><tr class="tableheightQues" ng-repeat="question in questionnaireData track by $index">
<td>{{$index + 1}}) </td>
<td style="width:50%;"><span class="" title="{{question.QuestionItem}}">{{question.QuestionItem}}</span> </td>
<td>
    <div class="">
        <select ng-if="question.MasterDataCategoryId != null"
                id="answer{{question.QuestionId}}"
                ng-model="question.MasterData"
                ng-init="question.MasterData" class="form-control"
                style="width: 300px; white-space:pre-wrap;">
            <option ng-repeat="answer in answerData[question.MasterDataCategoryId]"
                    value="{{answer.MasterData}}">
              {{answer.MasterData}}
            </option>
        </select>
        <input ng-if="question.MasterDataCategoryId == null"
               id="{{question.QuestionId}}" ng-model="question.MasterData"
               type="text" style="width: 300px;" name="question.QuestionId"
               class="form-control">
        <!--<span class="help-inline" ng-show="submitted && formVHD.$valid"></span>-->
    </div>
</td>
</code>```

```<code><td>
    <div class="">
      <span ng-if="question.MasterDataCategoryId != null"
            ng-repeat="answer in answerData[question.MasterDataCategoryId] | filter : question.MasterData : true">
        <span ng-if="question.MasterData" ng-model="question.Score">
        {{answer.Score}}
        </span>
        <span ng-if="!question.MasterData"> </span>
      </span>
      <select ng-if="question.MasterDataCategoryId == null"
              id="projectlist" class="form-control"
              required ng-model="question.Score">
            <option selected="selected"></option>
            <option ng-repeat="score in scoringDetails"
                    value="{{score.Score}}"> {{score.Score}}
            </option>
      </select>
    </div>
</td>
</tr>
</code>```

Above is the code I have used.

How to assign ng-model to span show get the data while saving all information?

答:
ng-model directives are only for input elements.You can use ng-bind instead

```<code><span ng-if="question.MasterData" ng-bind="question.Score">
</code>```

or use curly braces

```<code><span ng-if="question.MasterData">{{question.Score}}</span>
</code>```

Find more about directives here

Title: Can we assign ng-model to span?

Body:
I need to assign the value to span based on the selected answer in dropdown.

{{$index + 1}})
{{question.QuestionItem}}

        <select ng-if="question.MasterDataCategoryId != null"
                id="answer{{question.QuestionId}}"
                ng-model="question.MasterData"
                ng-init="question.MasterData" class="form-control"
                style="width: 300px; white-space:pre-wrap;">
            <option ng-repeat="answer in answerData[question.MasterDataCategoryId]"
                    value="{{answer.MasterData}}">
              {{answer.MasterData}}
            </option>
        </select>
        <input ng-if="question.MasterDataCategoryId == null"
               id="{{question.QuestionId}}" ng-model="question.MasterData"
               type="text" style="width: 300px;" name="question.QuestionId"
               class="form-control">

        {{answer.Score}}

      <select ng-if="question.MasterDataCategoryId == null"
              id="projectlist" class="form-control"
              required ng-model="question.Score">
            <option selected="selected"></option>
            <option ng-repeat="score in scoringDetails"
                    value="{{score.Score}}"> {{score.Score}}
            </option>
      </select>

Above is the code I have used.

How to assign ng-model to span show get the data while saving all information?

Body:
ng-model directives are only for input elements.You can use ng-bind instead

<span ng-if="question.MasterData" ng-bind="question.Score">

or use curly braces

<span ng-if="question.MasterData">{{question.Score}}</span>

Find more about directives here


问:
What is the relation between stateful and stateless widgets in Flutter?
A stateful widget is defined as any widget which changes its state within its lifetime. But it is a very common practice for a StatelessWidget to have a StatefulWidget as one of its children. Doesn't StatelessWidget become stateful if it has StatefulWidget as one of its children?

I tried looking into the documentation as part of the code of StatelessWidget, but couldn't figure out how a StatelessWidget can have Statefulwidget as its children and still remain StatelessWidget.

What is the relation and difference between stateful and stateless widgets in Flutter?

答:
Answer for the Stack Overflow question - statefulness vs statelessness.

In Flutter, the difference is that stateless widgets can be defined by all the constructor arguments alone. If you create two stateless widgets using the same arguments, then they will be the same.

A stateful widget, however, is not necessarily the same as another built with the same constructor arguments. It might be in a different state.

Actually, a stateful widget is immutable (stateless) itself, but Flutter manages a separate state object and associates that with the widget, as explained in the StatefulWidget doc. This means that when Flutter rebuilds a stateful widget, it will check to see if it should reuse a previous state object and will, if desired, attach that state object to the widget.

The parent widget is stateless because it does not care about its child's state. The stateful child itself (or technically Flutter) will take care of its own state.

On a high level, I agree that this makes the parent widget stateful, because two parents might contain two childs with different states and thus be technically different themselves. But from the viewpoint of Flutter, it builds the parent widget without caring about the state and only when building the child will consider its statefullness.

ContentLicense: CC BY-SA 4.0


问:
Reading Avro table and schema stored in HDFS using Spark- Java
I am trying to read an Avro table stored in HDFS specifying also the schema
which is also stored in HDFS.
For the moment I have this solution that seems to work:

```<code>    RDD<String> stringRDD = sparkContext.textFile(schemaPath, 1);
    String [] collect = (String []) stringRDD.collect();
    String schema = collect[0];
    Dataset<Row> df  =sqlContext.read().format("com.databricks.spark.avro").option("avroSchema", schema)
            .load(tablePath);
</code>```

Is this the best way to do that?
What if the schema is big enough to have 2 partitions for example? Should I merge all of them using reduce()?

Cheers

答:
I know that it's been a year since this was asked, but I was recently looking to do the same thing and this question came up on top in google.

So, I was able to do this using Hadoop's FileSystem class:

```<code>import org.apache.avro.Schema;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Path;

String schemaPath = "/path/to/schema/in/hdfs.avsc";
FSDataInputStream schemaFile = FileSystem.get(sparkContext.hadoopConfiguration).open(new Path(schemaPath));
Schema schema = new Schema.Parser().parse(schemaFile);
String schemaString = schema.toString();
</code>```

Hope this helps!

Body:
I am trying to read an Avro table stored in HDFS specifying also the schema
which is also stored in HDFS.
For the moment I have this solution that seems to work:

    RDD<String> stringRDD = sparkContext.textFile(schemaPath, 1);
    String [] collect = (String []) stringRDD.collect();
    String schema = collect[0];
    Dataset<Row> df  =sqlContext.read().format("com.databricks.spark.avro").option("avroSchema", schema)
            .load(tablePath);

Is this the best way to do that?
What if the schema is big enough to have 2 partitions for example? Should I merge all of them using reduce()?

Cheers

Body:
I know that it's been a year since this was asked, but I was recently looking to do the same thing and this question came up on top in google.

So, I was able to do this using Hadoop's FileSystem class:

import org.apache.avro.Schema;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.FSDataInputStream;
import org.apache.hadoop.fs.Path;

String schemaPath = "/path/to/schema/in/hdfs.avsc";
FSDataInputStream schemaFile = FileSystem.get(sparkContext.hadoopConfiguration).open(new Path(schemaPath));
Schema schema = new Schema.Parser().parse(schemaFile);
String schemaString = schema.toString();

Hope this helps!


问:
I want to access and modify XML file using JavaScript. After modifying it I need to save it. Please help!
Here is the xml file I want to modify -

Note: Sorry somehow I cannot type '<'

```<code><nsml version="-//iNEWS//DTD NSML 2.0//EN">

<head> meta wire=o words=347 rate=175> rgroup number=214> wgroup number=214>

<fields>

<f id=title> Title /f>

<f id=headline> Headline /f>

<f id=summary >Summary /f>

</fields>
</code>```

Here is my JavaScript code -

```<code> var xmlHttp=null;

 try {

   // Firefox, Opera 8.0+, Safari

   xmlHttp=new xmlHttpRequest();

 }

 catch(e) {

   // Internet Explorer

   try {

         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

    }

    catch (e) {

        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

    }

 }

 xmlHttp.open("GET","test.xml",false);

 xmlHttp.send();

 xmlDoc=xmlHttp.responseXML;

 x=xmlDoc.getElementsByTagName("f")[0].childNodes[0]; /*says x is null or not an object */

 x.nodeValue="New Title";
</code>```

Thanks for your help!

答: You can't modify files only with javascript. Even if you can... why would you do it?</p>

ContentLicense: CC BY-SA 2.5

Body:
Here is the xml file I want to modify -

Note: Sorry somehow I cannot type '<'

<nsml version="-//iNEWS//DTD NSML 2.0//EN">

 meta wire=o words=347 rate=175> rgroup number=214> wgroup number=214>

<fields>

<f id=title> Title /f>

<f id=headline> Headline /f>

<f id=summary >Summary /f>

</fields>

Here is my JavaScript code -

 var xmlHttp=null;

 try {

   // Firefox, Opera 8.0+, Safari

   xmlHttp=new xmlHttpRequest();

 }

 catch(e) {

   // Internet Explorer

   try {

         xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");

    }

    catch (e) {

        xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");

    }

 }

 xmlHttp.open("GET","test.xml",false);

 xmlHttp.send();

 xmlDoc=xmlHttp.responseXML;

 x=xmlDoc.getElementsByTagName("f")[0].childNodes[0]; /*says x is null or not an object */

 x.nodeValue="New Title";

Thanks for your help!


问:
Query error: Resources exceeded during query execution: The query could not be executed in the allotted memory
I'm getting an error when tries to execute the following query:

```<code>select r.*
from dataset.table1 r
where id NOT IN (select id from staging_data.table1);
</code>```

It's basically a query to load incremental data on a table. The dataset.table1 has 360k rows and the incremental on staging_data has 40k. But when I try to run this on my script to load on another table, I got the error:

```<code>Resources exceeded during query execution: The query could not be executed in the allotted memory
</code>```

This started to happen on the last week, before that it was working well.

I looked over for solutions on internet, but all the solutions doesn't work on my case.

Has anyone know how to solve it?

I changed the cronjob time and it worked. Thank you!

答: You can try using writing the results to another table, as Big Query has a limitation for the maximum response size that can be processed. You can do that either if you are using Legacy or Standard SQL, and you can follow the steps to do it in the documentation.</p>

Body:
I'm getting an error when tries to execute the following query:

select r.*
from dataset.table1 r
where id NOT IN (select id from staging_data.table1);

It's basically a query to load incremental data on a table. The dataset.table1 has 360k rows and the incremental on staging_data has 40k. But when I try to run this on my script to load on another table, I got the error:

Resources exceeded during query execution: The query could not be executed in the allotted memory

This started to happen on the last week, before that it was working well.

I looked over for solutions on internet, but all the solutions doesn't work on my case.

Has anyone know how to solve it?

I changed the cronjob time and it worked. Thank you!


问:
How to save NLTK concordance results in a list?
I'm using the NLTK to find word in a text. I need to save result of concordance function into a list. The question is already asked  here
but i cannot see the changes. I try to find the type of returnde value of the function by :

```<code>type(text.concordance('myword'))
</code>```

the result was :

```<code><class 'NoneType'>
</code>```

答:
By inspecting the source of ConcordanceIndex, we can see that results are printed to stdout. If redirecting stdout to a file is not an option, you have to reimplement the ConcordanceIndex.print_concordance such that it returns the results rather than printing it to stdout.

Code:

```<code>def concordance(ci, word, width=75, lines=25):
    """
    Rewrite of nltk.text.ConcordanceIndex.print_concordance that returns results
    instead of printing them.

    See:
    http://www.nltk.org/api/nltk.html#nltk.text.ConcordanceIndex.print_concordance
    """
    half_width = (width - len(word) - 2) // 2
    context = width // 4 # approx number of words of context

    results = []
    offsets = ci.offsets(word)
    if offsets:
        lines = min(lines, len(offsets))
        for i in offsets:
            if lines <= 0:
                break
            left = (' ' * half_width +
                    ' '.join(ci._tokens[i-context:i]))
            right = ' '.join(ci._tokens[i+1:i+context])
            left = left[-half_width:]
            right = right[:half_width]
            results.append('%s %s %s' % (left, ci._tokens[i], right))
            lines -= 1

    return results
</code>```

Usage:

```<code>from nltk.book import text1
from  nltk.text import ConcordanceIndex

ci = ConcordanceIndex(text1.tokens)
results = concordance(ci, 'circumstances')

print(type(results))
<class 'list'>
</code>```

Body:
I'm using the NLTK to find word in a text. I need to save result of concordance function into a list. The question is already asked  here
but i cannot see the changes. I try to find the type of returnde value of the function by :

type(text.concordance('myword'))

the result was :

<class 'NoneType'>

Body:
By inspecting the source of ConcordanceIndex, we can see that results are printed to stdout. If redirecting stdout to a file is not an option, you have to reimplement the ConcordanceIndex.print_concordance such that it returns the results rather than printing it to stdout.

Code:

def concordance(ci, word, width=75, lines=25):
    """
    Rewrite of nltk.text.ConcordanceIndex.print_concordance that returns results
    instead of printing them.

    See:
    http://www.nltk.org/api/nltk.html#nltk.text.ConcordanceIndex.print_concordance
    """
    half_width = (width - len(word) - 2) // 2
    context = width // 4 # approx number of words of context

    results = []
    offsets = ci.offsets(word)
    if offsets:
        lines = min(lines, len(offsets))
        for i in offsets:
            if lines <= 0:
                break
            left = (' ' * half_width +
                    ' '.join(ci._tokens[i-context:i]))
            right = ' '.join(ci._tokens[i+1:i+context])
            left = left[-half_width:]
            right = right[:half_width]
            results.append('%s %s %s' % (left, ci._tokens[i], right))
            lines -= 1

    return results

Usage:

from nltk.book import text1
from  nltk.text import ConcordanceIndex

ci = ConcordanceIndex(text1.tokens)
results = concordance(ci, 'circumstances')

print(type(results))
<class 'list'>


问:
how to change directory to a path stored in variable bash
I'm trying to change the CD to a path stored in a variable. The variable gets its value from text stored in a file.

This gets the value inside the text file:

```<code>devdir=$(<\$HOME/devdir.txt)
cd $devdir
</code>```

Inside the text file is the text: $HOME/bin

The error I get is:

```<code>/bin/dev: line 41: cd: $HOME/bin: No such file or directory
</code>```

This is the result of trying to use the variable, compared to manually typing it:

UPDATE:
This is the snippet of Bash given with the improvement given by fabiotk, which seems to yield no result when it is within the script, however it works fine when run in the cmd window...Snippet

Here is the entire script so far: script
and here is me running the given line on its own, then running the script showing it doesn't work inside: enter image description here

答:
Try this:

```<code>cd $(eval "echo \"$(cat $HOME/devdir.txt)\"");
</code>```

or:

```<code>eval "cd \"$(cat $HOME/devdir.txt)\"";
</code>```

It will change the directory inside the script session that you are running. If you run ./script it won't cd externally

Body:
I'm trying to change the CD to a path stored in a variable. The variable gets its value from text stored in a file.

This gets the value inside the text file:

devdir=$(<\$HOME/devdir.txt)
cd $devdir

Inside the text file is the text: $HOME/bin

The error I get is:

/bin/dev: line 41: cd: $HOME/bin: No such file or directory

This is the result of trying to use the variable, compared to manually typing it:

UPDATE:
This is the snippet of Bash given with the improvement given by fabiotk, which seems to yield no result when it is within the script, however it works fine when run in the cmd window...Snippet

Here is the entire script so far: script
and here is me running the given line on its own, then running the script showing it doesn't work inside: enter image description here

Body:
Try this:

cd $(eval "echo \"$(cat $HOME/devdir.txt)\"");

or:

eval "cd \"$(cat $HOME/devdir.txt)\"";

It will change the directory inside the script session that you are running. If you run ./script it won't cd externally


问:
How does disqus know who I am when I go to a website that I have never been to before?
When I go to a site that I have never been to before and it has Disqus installed, somehow Disqus knows who I am.

Cookies can only be read by the site that saved the cookie. If I have never been to a site before then it does not have a cookie to read and say "aha I know you".

How do they do it?

答: They use cookies. Disqus most likely stores cookies of your session from their site when you authenticate yourself, so when you go on another site they still know its you. It's like how Facebook knows it's you on a site that has Facebook comments integrated.</p>


问:
SequelizeEagerLoadingError when relationship between models has already been defined
I have an exports file that includes all the sequelize-models and then defines the relationship among the models. It looks something like:

```<code>// Snippet from the global init file

for (let modelFile of modelFileList) {
            // ... Some code ...

            // Require the file
            appliedModels[modelName] = require(`../${MODEL_DIR}/${modelFile}`).call(null, _mysql);
 }

 //Define the relationship between the sql models
 _defineRelationship(appliedModels);

function _defineRelationship(models) {
     models._planAllocationModel.belongsTo(models._subscriptionModel, {
            foreignKey: 'subscription_id',
            targetKey: 'subscription_id'
        });
}
</code>```

But when I try to include the model like:

```<code> _subscriptionModel.findAll({
                where: {
                    start_date: {
                        _lte: today // Get all subscriptions where start_date <= today
                    }
                },
                limit,
                include: [
                    {
                        model: _planAllocationModel
                    }
                ]
            });
</code>```

There is an error thrown by sequelize: SequelizeEagerLoadingError: tbl_plan_allocation is not associated to tbl_subscription_info! What could be the reason for this? I have already initialized the relationshipt between the 2 models.

答: I was able to solve the problem. The relationship was defined as belongsTo which had to be changed to hasOne because of the type of join applied in the findAll query.

Body:
I have an exports file that includes all the sequelize-models and then defines the relationship among the models. It looks something like:

// Snippet from the global init file

for (let modelFile of modelFileList) {
            // ... Some code ...

            // Require the file
            appliedModels[modelName] = require(`../${MODEL_DIR}/${modelFile}`).call(null, _mysql);
 }

 //Define the relationship between the sql models
 _defineRelationship(appliedModels);

function _defineRelationship(models) {
     models._planAllocationModel.belongsTo(models._subscriptionModel, {
            foreignKey: 'subscription_id',
            targetKey: 'subscription_id'
        });
}

But when I try to include the model like:

 _subscriptionModel.findAll({
                where: {
                    start_date: {
                        _lte: today // Get all subscriptions where start_date <= today
                    }
                },
                limit,
                include: [
                    {
                        model: _planAllocationModel
                    }
                ]
            });

There is an error thrown by sequelize: SequelizeEagerLoadingError: tbl_plan_allocation is not associated to tbl_subscription_info! What could be the reason for this? I have already initialized the relationshipt between the 2 models.


问:
MPMoviePlayerViewController video not played using URL in ios
i am trying to play video using URL but it's not playing.
Here is my code :-

```<code>var moviePlayer = MPMoviePlayerViewController(contentURL: mediaItem.fileURL)
self.presentMoviePlayerViewControllerAnimated(moviePlayer)
moviePlayer?.moviePlayer.play()
</code>```

Not getting any kind of error and also not played .

I also checked URL value.Value pass properly but again not play video.

so any one have solution then please help me.

Thanks in advance.

答:
import AVKit

let url = URL(string: "http://km.support.apple.com/library/APPLE/APPLECARE_ALLGEOS/HT1211/sample_iTunes.mov")
let player = AVPlayer(url: url!)
let playerViewController = AVPlayerViewController()
playerViewController.player = player
self.present(playerViewController, animated: true)
{
    playerViewController.player?.play()
}
```

Body:
i am trying to play video using URL but it's not playing.
Here is my code :-

var moviePlayer = MPMoviePlayerViewController(contentURL: mediaItem.fileURL)
self.presentMoviePlayerViewControllerAnimated(moviePlayer)
moviePlayer?.moviePlayer.play()

Not getting any kind of error and also not played .

I also checked URL value.Value pass properly but again not play video.

so any one have solution then please help me.

Thanks in advance.


问:
Git chooses wrong ancestor commit
I'm using git with a few other people. We have a central repository and then local tracking branches. Recently, we've come across a problem where git will incorrectly think that the last common ancestor commit of the main branch and the new branch is a commit that was only pushed after we created the new branch, leading to changes being undone when we merge the new branch back in. An example:

Alice makes some changes in her local copy of the main branch and commits them, but does not push. Say she changes the first line of file foo.txt.

Bob pulls from the central copy of the main branch. As far as he can tell, he is up to date.

Both continue to work. At some point, Alice pushes. Later, Bob calls git log and sees that his branch is allegedly an ancestor of the commit in which Alice changed foo.txt, even though he never pulled her changes. When Bob merges, as expected, Alice's changes have disappeared.

I've been unable to reproduce this, but can tell from the logs that it did happen at one point (i.e. we have one branch which is allegedly a successor of a commit in which changes were made to a source file, but in which those changes were not present). How is this kind of thing possible, and how can I stop it?

答:
Did someone at some stage force-push some changes and overwrote a specific hash commit (using -f in push). That sounds like your case scenario could happen with this.

If that can help you, our workflow at work is to always use rebase when pulling/pushing:

Person A has done changes and push them.

Person B continues working, doing local commits

At some stage Person B wants to push live. To do that.

Person B make sure the local branch is clean (stash if not).

Person B runs git pull --rebase (this will download all changes and re-apply his own on top of the new HEAD)

If there is any conflict Person B resolves conflicts.

Person B finaly pushes local copy live.

And reapply the same process, with Person A being the one behind the origin head and needing to pull rebase

And NEVER use -f when pushing live, it's really bad.

More Info: A force push is tempting when, say person A did a commit, pushed it live, then realised there was a bug left. Person A does an ammend to the last commit. The only way to then push that commit live is to do a push -f ... and that's really bad for people working on their own copies having done local commits to their copy and pushing live

Title: Git chooses wrong ancestor commit


问:
`git rebase -i` shows ansi colour codes in editor
When I run git rebase -i, I got ansi colour codes showing just after regular todo list (any repos, any editors), where do they come from?

git versions, tried 2.13 and 2.15 and I nuked my user settings to test

color.ui & color.interactive are false.

tried vim, nano, subl and ed in git config (core.editor), all have this issue

Thank you.

```<code>pick 5c0cbe059d56e2fe2bac4bf9e3373d5882157f4a commit
[38;5;252m# Rebase b4c6863..5c0cbe0 onto b4c6863 (1 command)[39m
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
</code>```

答:
OK, I managed to fix this, this happens because I created a custom cat in my $PATH, its content is:

```<code>#!/bin/bash

if [[ ! -f $(which pygmentize) ]] ; then
  # if pygmentize not installed, use raw cat
  /bin/cat $@
else
  # pip install --user Pygments
  # html output: pygmentize -f html -O full,style=vim
  pygmentize -O style=native -f console256 -g $@;
fi
</code>```

basically it uses pygmentize for syntax highlight, I guess git is using cat to produce the rebase todo list, therefore my custom cat pollutes git output.

To fix this, simply rename custom cat to something else.

Body:
When I run git rebase -i, I got ansi colour codes showing just after regular todo list (any repos, any editors), where do they come from?

git versions, tried 2.13 and 2.15 and I nuked my user settings to test

color.ui & color.interactive are false.

tried vim, nano, subl and ed in git config (core.editor), all have this issue

Thank you.

pick 5c0cbe059d56e2fe2bac4bf9e3373d5882157f4a commit
[38;5;252m# Rebase b4c6863..5c0cbe0 onto b4c6863 (1 command)[39m
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Body:
OK, I managed to fix this, this happens because I created a custom cat in my $PATH, its content is:

#!/bin/bash

if [[ ! -f $(which pygmentize) ]] ; then
  # if pygmentize not installed, use raw cat
  /bin/cat $@
else
  # pip install --user Pygments
  # html output: pygmentize -f html -O full,style=vim
  pygmentize -O style=native -f console256 -g $@;
fi

basically it uses pygmentize for syntax highlight, I guess git is using cat to produce the rebase todo list, therefore my custom cat pollutes git output.

To fix this, simply rename custom cat to something else.


问:
ES6 import module with Gulp
I am trying to import my ES6 module into a file and running Gulp to concat and minify the file. I'm running into a ReferenceError: require is not defined at all.js(transpiled) line no 3.
I have transpiled the code using gulp-babel.

My js files are:

cart.js:

```<code>class Cart{
  constructor(){
    this.cart = [];
    this.items = items = [{
        id: 1,
        name: 'Dove Soap',
        price: 39.99
    },{
        id: 2,
        name: 'Axe Deo',
        price: 99.99
    }];
  }

  getItems(){
    return this.items;
  }

}

export {Cart};
</code>```

app.js:

```<code>import {Cart} from 'cart.js';

let cart = new Cart();

console.log(cart.getItems());
</code>```

gulpfile.js:

```<code>"use strict";

let gulp = require('gulp');
let jshint = require('gulp-jshint');
let concat = require('gulp-concat');
let uglify = require('gulp-uglify');
let rename = require('gulp-rename');
let babel = require('gulp-babel');

// Lint Task
gulp.task('lint', function() {
    return gulp.src('js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

// Concatenate & Minify JS
gulp.task('scripts', function() {
    return gulp.src('js/*.js')
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(concat('all.js'))
        .pipe(gulp.dest('dist'))
        .pipe(rename('all.min.js'))
        .pipe(uglify().on('error', function(e){
          console.dir(e);
        }))
        .pipe(gulp.dest('dist/js'));
});

// Default Task
gulp.task('default', ['lint','scripts']);
</code>```

app.js(transpiled):

```<code>'use strict';

var _cart = require('cart.js'); //Uncaught ReferenceError: require is not defined

var cart = new _cart.Cart();

console.log(cart.getItems());
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Cart = function () {
  function Cart() {
    _classCallCheck(this, Cart);

    this.cart = [];
    this.items = items = [{
      id: 1,
      name: 'Dove Soap',
      price: 39.99
    }, {
      id: 2,
      name: 'Axe Deo',
      price: 99.99
    }];
  }

  _createClass(Cart, [{
    key: 'getItems',
    value: function getItems() {
      return this.items;
    }
  }]);

  return Cart;
}();

exports.Cart = Cart;
</code>```

答:
You would need a bundler like Webpack or Browserify in order to use ES6 imports. Babel is only capable of compiling ES6 code to ES5 (native JS).

Both Webpack and Browserify have made recipes for gulp:

https://webpack.js.org/guides/integrations/#gulp

https://github.com/gulpjs/gulp/tree/master/docs/recipes

Hope this helps.

Title: ES6 import module with Gulp

Body:
I am trying to import my ES6 module into a file and running Gulp to concat and minify the file. I'm running into a ReferenceError: require is not defined at all.js(transpiled) line no 3.
I have transpiled the code using gulp-babel.

My js files are:

cart.js:

class Cart{
  constructor(){
    this.cart = [];
    this.items = items = [{
        id: 1,
        name: 'Dove Soap',
        price: 39.99
    },{
        id: 2,
        name: 'Axe Deo',
        price: 99.99
    }];
  }

  getItems(){
    return this.items;
  }

}

export {Cart};

app.js:

import {Cart} from 'cart.js';

let cart = new Cart();

console.log(cart.getItems());

gulpfile.js:

"use strict";

let gulp = require('gulp');
let jshint = require('gulp-jshint');
let concat = require('gulp-concat');
let uglify = require('gulp-uglify');
let rename = require('gulp-rename');
let babel = require('gulp-babel');

// Lint Task
gulp.task('lint', function() {
    return gulp.src('js/*.js')
        .pipe(jshint())
        .pipe(jshint.reporter('default'));
});

// Concatenate & Minify JS
gulp.task('scripts', function() {
    return gulp.src('js/*.js')
        .pipe(babel({
            presets: ['env']
        }))
        .pipe(concat('all.js'))
        .pipe(gulp.dest('dist'))
        .pipe(rename('all.min.js'))
        .pipe(uglify().on('error', function(e){
          console.dir(e);
        }))
        .pipe(gulp.dest('dist/js'));
});

// Default Task
gulp.task('default', ['lint','scripts']);

app.js(transpiled):

'use strict';

var _cart = require('cart.js'); //Uncaught ReferenceError: require is not defined

var cart = new _cart.Cart();

console.log(cart.getItems());
'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

var Cart = function () {
  function Cart() {
    _classCallCheck(this, Cart);

    this.cart = [];
    this.items = items = [{
      id: 1,
      name: 'Dove Soap',
      price: 39.99
    }, {
      id: 2,
      name: 'Axe Deo',
      price: 99.99
    }];
  }

  _createClass(Cart, [{
    key: 'getItems',
    value: function getItems() {
      return this.items;
    }
  }]);

  return Cart;
}();

exports.Cart = Cart;


问:
C# XML - Deserializing a list of classes
I'm working with an XML document which is generated using C# from a list of objects (of the 'People' class)

```<code><?xml version="1.0" encoding="utf-8"?>
<ArrayOfDeviceInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="DeviceInfoCollection">
  <DeviceInfo>
    <Partition>0</Partition>
    <SerialID>3117132000001</SerialID>
    <AzureID>2d680cd1-7320-43a9-87d4-75a2698771a3</AzureID>
    <FirmwareVersion>3.0.0</FirmwareVersion>
  </DeviceInfo>
  <DeviceInfo>
    <Partition>0</Partition>
    <SerialID>3117132000002</SerialID>
    <AzureID>646ca461-9352-4746-9fa6-6308010059fb</AzureID>
    <FirmwareVersion>1.1.2</FirmwareVersion>
  </DeviceInfo>
</code>```

My goal is to deserialize this back into a List<DeviceInfo> variable.

I've tried the following

```<code>            var xDoc = XDocument.Load(Application.StartupPath + "/devicesTEST.xml");
            if (File.ReadAllText(Application.StartupPath + "/devicesTEST.xml").Length > 0)
            {

                var envs = from e in xDoc.Root.Descendants("DeviceInfo")
                           select new DeviceInfo
                           {
                               SerialID = (string)e.Element("SerialID"),
                           };
                Manager.Devices = envs.ToList();
            }
</code>```

and it's working for me on another XML file.

Update

Contrary to previous belief, it turns out there is no error, the list just doesn't get populated with the values extracted from the XML.

答:
XML namespaces; in your xml, the namespace is defined by xmlns="DeviceInfoCollection" - but your code assumes it is the empty (default) namespace. Since xml namespaces are inherited, you need to tell it the namespace throughout:

```<code>XNamespace ns = "DeviceInfoCollection";
var devices = from e in xDoc.Root.Descendants(ns + "DeviceInfo")
           select new DeviceInfo
           {
               SerialID = (string)e.Element(ns + "SerialID"),
           };

foreach(var device in devices)
{
    Console.WriteLine(device.SerialID);
}
</code>```

Body:
I'm working with an XML document which is generated using C# from a list of objects (of the 'People' class)

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfDeviceInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="DeviceInfoCollection">
  <DeviceInfo>
    <Partition>0</Partition>
    <SerialID>3117132000001</SerialID>
    <AzureID>2d680cd1-7320-43a9-87d4-75a2698771a3</AzureID>
    <FirmwareVersion>3.0.0</FirmwareVersion>
  </DeviceInfo>
  <DeviceInfo>
    <Partition>0</Partition>
    <SerialID>3117132000002</SerialID>
    <AzureID>646ca461-9352-4746-9fa6-6308010059fb</AzureID>
    <FirmwareVersion>1.1.2</FirmwareVersion>
  </DeviceInfo>

My goal is to deserialize this back into a List<DeviceInfo> variable.

I've tried the following

            var xDoc = XDocument.Load(Application.StartupPath + "/devicesTEST.xml");
            if (File.ReadAllText(Application.StartupPath + "/devicesTEST.xml").Length > 0)
            {

                var envs = from e in xDoc.Root.Descendants("DeviceInfo")
                           select new DeviceInfo
                           {
                               SerialID = (string)e.Element("SerialID"),
                           };
                Manager.Devices = envs.ToList();
            }

and it's working for me on another XML file.

Update

Contrary to previous belief, it turns out there is no error, the list just doesn't get populated with the values extracted from the XML.

Body:
XML namespaces; in your xml, the namespace is defined by xmlns="DeviceInfoCollection" - but your code assumes it is the empty (default) namespace. Since xml namespaces are inherited, you need to tell it the namespace throughout:

XNamespace ns = "DeviceInfoCollection";
var devices = from e in xDoc.Root.Descendants(ns + "DeviceInfo")
           select new DeviceInfo
           {
               SerialID = (string)e.Element(ns + "SerialID"),
           };

foreach(var device in devices)
{
    Console.WriteLine(device.SerialID);
}


问:
Ajax - send button value to php
I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML

```<code>    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script>
$(document).ready(function(){
    $.ajax({
        url: "try.php",
        type: "POST",
        data: {
            data: val    // removed ; after val.
        }
    });
});

</script>

    <body>

      <button id="1" name="1"  value="some_value">1</button>
      <button id="2" name="2"  value="some_value">2</button>

    </body>
</code>```

PHP:

```<code><?php

$name = $_POST['data'];
echo $name;

?>
</code>```

It doesn't working...

答:
```<code><button id="example" name="name_example"  value="some_value">
1</button>

$(document).ready(function () {
     $('#example').click(function() {

         var buttonValue = $(this).val();

         $.ajax({
             url: "try.php", //assuming that your html file is in the same folder as
                    //your php script.
              type: "POST",
              data: {'example': buttonValue}
         });

    });
});
</code>```

look this: https://jsfiddle.net/willianoliveirac/yarLfdnu/

In your .php file, which should be in the same folder as your html file doing the request you will have:

```<code><?php

echo '```'; print_r($_POST); die; // see if you now have those vars.

?>
```

Title: Ajax - send button value to php

Body:
I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML

      <button id="1" name="1"  value="some_value">1</button>
      <button id="2" name="2"  value="some_value">2</button>

PHP:

<?php

$name = $_POST['data'];
echo $name;

?>

It doesn't working...

Body:
<button id="example" name="name_example"  value="some_value">
1</button>

$(document).ready(function () {
     $('#example').click(function() {

         var buttonValue = $(this).val();

         $.ajax({
             url: "try.php", //assuming that your html file is in the same folder as
                    //your php script.
              type: "POST",
              data: {'example': buttonValue}
         });

    });
});

look this: https://jsfiddle.net/willianoliveirac/yarLfdnu/

In your .php file, which should be in the same folder as your html file doing the request you will have:

<?php

echo '<pre>'; print_r($_POST); die; // see if you now have those vars.

?>


问:
Logstash 6.0.0: Unknown setting ‘index_type’ for elasticsearch
I'm trying to run logstash config files on ELK 6.0.0 docker image but I got this error:
Unknown setting 'index_type' for elasticsearch

I am retrieving Spark streaming stats and send it to elasticsearch, but even this simple task returns an error. Here is my code:

```<code>input {
  graphite {
    codec => "json"
    port => 10513
    host => "0.0.0.0"
  }
}

output {
  #stdout { codec => "json" }

  elasticsearch {
    codec => "json"
    hosts => "localhost"
    index => "spark-%{+YYYY.MM.DD}"
    index_type => "spark"
  }
}
</code>```

答:
I got this error: Unknown setting 'index_type' for elasticsearch

The error means what it says. Your configuration has index_type within the elasticsearch output, but that is not a valid setting.

Logstash does not allow you to include settings that are not recognised.

Did you mean document_type ?

Body:
I'm trying to run logstash config files on ELK 6.0.0 docker image but I got this error:
Unknown setting 'index_type' for elasticsearch

I am retrieving Spark streaming stats and send it to elasticsearch, but even this simple task returns an error. Here is my code:

input {
  graphite {
    codec => "json"
    port => 10513
    host => "0.0.0.0"
  }
}

output {
  #stdout { codec => "json" }

  elasticsearch {
    codec => "json"
    hosts => "localhost"
    index => "spark-%{+YYYY.MM.DD}"
    index_type => "spark"
  }
}


问:
Sending Email with attachment from Asset folder
```<code>    //EMAIL SENDING CODE  FROM ASSET FOLDER
    email = editTextEmail.getText().toString();
    subject = editTextSubject.getText().toString();
    message = editTextMessage.getText().toString();
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("file/html");
    emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://com.example.deepa.xmlparsing/file:///android_assets/Combination-1.html"));
    startActivity(Intent.createChooser(emailIntent, "Send email using"));
</code>```

Finally, I'm getting the file from asset folder (Combination-1.html).

It is getting

Runtime error file not found exception.

Is there any other way to send file attachment?

答:
You can use following code to achieve your goal , and can change Hard coded string according your requirements .

```<code>String filename="contacts_sid.vcf";
File filelocation = new
File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// Here you can set the type to 'email'
emailIntent .setType("abc.xyz.cursor.dir/email");
String to[] = {"android@gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
//  For the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Find Attachments with email");
startActivity(Intent.createChooser(emailIntent , "Sending  email..."));
</code>```

Body:
    //EMAIL SENDING CODE  FROM ASSET FOLDER
    email = editTextEmail.getText().toString();
    subject = editTextSubject.getText().toString();
    message = editTextMessage.getText().toString();
    final Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
    emailIntent.setType("file/html");
    emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    emailIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("content://com.example.deepa.xmlparsing/file:///android_assets/Combination-1.html"));
    startActivity(Intent.createChooser(emailIntent, "Send email using"));

Finally, I'm getting the file from asset folder (Combination-1.html).

It is getting

Runtime error file not found exception.

Is there any other way to send file attachment?

Body:
You can use following code to achieve your goal , and can change Hard coded string according your requirements .

String filename="contacts_sid.vcf";
File filelocation = new
File(Environment.getExternalStorageDirectory().getAbsolutePath(), filename);
Uri path = Uri.fromFile(filelocation);
Intent emailIntent = new Intent(Intent.ACTION_SEND);
// Here you can set the type to 'email'
emailIntent .setType("abc.xyz.cursor.dir/email");
String to[] = {"android@gmail.com"};
emailIntent .putExtra(Intent.EXTRA_EMAIL, to);
//  For the attachment
emailIntent .putExtra(Intent.EXTRA_STREAM, path);
// the mail subject
emailIntent .putExtra(Intent.EXTRA_SUBJECT, "Find Attachments with email");
startActivity(Intent.createChooser(emailIntent , "Sending  email..."));


问:
Object creation with interface
In C# we can inherit multiple interfaces. In such scenario if an object is created will it just hide the properties or methods or will the compiler avoids creation and memory allocation to those from other interface? For example, I have two interfaces and a class like below

```<code>    interface IExample1
    {
        void E1Test1();
        void E1Test2();
    }

    interface IExample2
    {
        void E2Test1();
        void E2Test2();
    }

    class Example : IExample1, IExample2
    {
        public void E1Test1()
        {
            throw new NotImplementedException();
        }

        public void E1Test2()
        {
            throw new NotImplementedException();
        }

        public void E2Test1()
        {
            throw new NotImplementedException();
        }

        public void E2Test2()
        {
            throw new NotImplementedException();
        }
    }
</code>```

When I create objects like,

```<code>IExample1 IE1 = new Example();
IExample2 IE2 = new Example();
</code>```

Will the compiler creates the complete object for both interfaces including all methods and hide it for one which don't have access? or it just creates with the methods which are available for a particular interface?

答:
The methods belong to an instance of a class. That instance is the object.
You can only create a new instance from a concrete type(like a class for example).
You can not create a new instance from an abstract type(Abstract class or Interface).

Thus the conclusion, when you create with new (), you will have all methods in the new instance.

Further:
Your new object(as in your example) can be seen in 3 ways:

Directly through the type(Example)

Though an interface(IExample1)

Through the other interface(IExample2)

Case 1) You see everything that is declared on the class(lets suppose everything is public :) )

Case 2) Even though you create new Example(), if the runtime type is IExample1 you will see only what is declared in this interface

Case 3) Even though you create new Example(), if the runtime type is IExample2 you will see only what is declared in this interface

Conclusion: The object you created is the same one(new Example()) but only the way you look at it changes.

Tip: read about implicit and explicit interface implementation

Title: Object creation with interface

Body:
In C# we can inherit multiple interfaces. In such scenario if an object is created will it just hide the properties or methods or will the compiler avoids creation and memory allocation to those from other interface? For example, I have two interfaces and a class like below

    interface IExample1
    {
        void E1Test1();
        void E1Test2();
    }

    interface IExample2
    {
        void E2Test1();
        void E2Test2();
    }

    class Example : IExample1, IExample2
    {
        public void E1Test1()
        {
            throw new NotImplementedException();
        }

        public void E1Test2()
        {
            throw new NotImplementedException();
        }

        public void E2Test1()
        {
            throw new NotImplementedException();
        }

        public void E2Test2()
        {
            throw new NotImplementedException();
        }
    }

When I create objects like,

IExample1 IE1 = new Example();
IExample2 IE2 = new Example();

Will the compiler creates the complete object for both interfaces including all methods and hide it for one which don't have access? or it just creates with the methods which are available for a particular interface?


问:
Rewrite profile.php?user=username to profile/username
I've created a very basic php templating system that I'm using to display a page with this URL: /basedir/index.php?page=home

The home content is served by the script home.php.

With a rewrite rule in .htaccess, I want my url to look like this: /basedir/home.

The problem that I'm having is that I've got stuck when it comes to rewrite one more GET variable that I'm using to display a user's profile. For now the profile page url looks like this: /basedir/profile?user=username.

Now I want it to look like this: /basedir/profile/username.

So far, my .htaccess looks like this:

```<code>RewriteEngine On

RewriteBase /basedir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) ?page=$1 [L,QSA]
</code>```

I have no idea if this is good or if i have to write a completely new .htaccess file.

答:
As you can see at http://htaccess.mwl.be/ your url http://www.example.com/profile/username is converted into http://www.example.com/basedir/?page=profile/username

Now what you need to do is put index.php in basedir where explode the page and retrieve username.

```<code>$page = $_GET['page'];
$parts = explode('/', $page);

switch($parts[0]){
    case 'profile':
        if(isset($parts[1])){
             $username = $parts[1];
             return doWhatEverYouWantToDoWithUsername($username);
        }
        return handleJustProfilePage();

    default:
        return yourDefaultHandler();

}
</code>```

This approach is called routing you can make way better with some external routing libraries.

Body:
I've created a very basic php templating system that I'm using to display a page with this URL: /basedir/index.php?page=home

The home content is served by the script home.php.

With a rewrite rule in .htaccess, I want my url to look like this: /basedir/home.

The problem that I'm having is that I've got stuck when it comes to rewrite one more GET variable that I'm using to display a user's profile. For now the profile page url looks like this: /basedir/profile?user=username.

Now I want it to look like this: /basedir/profile/username.

So far, my .htaccess looks like this:

RewriteEngine On

RewriteBase /basedir/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) ?page=$1 [L,QSA]

I have no idea if this is good or if i have to write a completely new .htaccess file.

Body:
As you can see at http://htaccess.mwl.be/ your url http://www.example.com/profile/username is converted into http://www.example.com/basedir/?page=profile/username

Now what you need to do is put index.php in basedir where explode the page and retrieve username.

$page = $_GET['page'];
$parts = explode('/', $page);

switch($parts[0]){
    case 'profile':
        if(isset($parts[1])){
             $username = $parts[1];
             return doWhatEverYouWantToDoWithUsername($username);
        }
        return handleJustProfilePage();

    default:
        return yourDefaultHandler();

}

This approach is called routing you can make way better with some external routing libraries.


问:
How to convert local time to UTC time same date but time set to midnight
I have this time

```<code>Tue Dec 05 2017 17:05:51 GMT+0530 (IST)
</code>```

I want to convert this into

```<code>Tue Dec 05 2017 00:00:00 GMT
</code>```

答:
You could try doing this:

```<code>//Convert string to Date object
var d = new Date(Date.parse('Tue Dec 05 2017 17:05:51 GMT+0530 (IST)'))
</code>```

and then run:

```<code>//crux: get utc offset from epoch in milliseconds and use .toUTCString(...) to offset timezone
var ms = Date.UTC(d.getYear()+1900, d.getMonth(), d.getDate(), 0, 0, 0)
console.log(new Date(ms).toUTCString(ms))
</code>```

Let me know if this does not suit your requirement. Thanks.

Body:
I have this time

Tue Dec 05 2017 17:05:51 GMT+0530 (IST)

I want to convert this into

Tue Dec 05 2017 00:00:00 GMT

Body:
You could try doing this:

//Convert string to Date object
var d = new Date(Date.parse('Tue Dec 05 2017 17:05:51 GMT+0530 (IST)'))

and then run:

//crux: get utc offset from epoch in milliseconds and use .toUTCString(...) to offset timezone
var ms = Date.UTC(d.getYear()+1900, d.getMonth(), d.getDate(), 0, 0, 0)
console.log(new Date(ms).toUTCString(ms))

Let me know if this does not suit your requirement. Thanks.


问:
Take the sum of 3 adc data for 3 sampling

Hi everyone,

I am a newbie in programming FPGA by verilog language. At the present, I am trying to design the firmware to calculate the sum of adc data at 3 sampling. Firstly, I will explain about one adc at one sampling in my code. When you look at the code, you can see that with rising-edge of clkr clock and adcIfEnb == 1, the adc_data will get the value from adcIfData and this is the data for one sampling. In the next rising-edge of clkr clock and adcIfEnb == 1, this data is stored in iradcTrg. Finally, I will have the 3 data of adc_data for 3 sampling which are stored in iradcTrg and then I summarize 3 these data.

```<code>wire adcIfData[79:0];
reg
always @(posedge clkr) begin
if(adcIfEnb) begin
adc_data[9:0] <= adcIfData[9:0];
end
end
reg [29:0] iradcTrg;
reg [9:0]  adcTrg;
always @(posedge clkr) begin
if (adcIfEnb) begin
iradcTrg[29:0] <= {adc_trg[19:10],adc_trg[9:0],adc_data[9:0]};
adcTrg[9:0] <= adc_trg[29:20] + adc_trg[19:10] + adc_trg[9:0];
end
end
</code>```

However, there are 2 problems which I do not know how to solve.

Firstly, at the beginning time, when the first data of adc_data is stored at iradcTrg and adcTrg also take the sum. It means that adcTrg = 0 + 0 + first_adc_data but this sum need to be avoided.

Secondly, according to my design, I see that adc_data is serialized into iradcTrg. It means that the adc_data will be stored like this:

[1 2 3] 4 5 6 => 1 [2 3 4] 5 6=> 1 2 [3 4 5] 6

But in my case, I would like that the adc_data will be stored like this to get the sum

[1 2 3] 4 5 6 => 1 2 3 [4 5 6]

Therefore, how should I repair my code to get the result that I expected or are there any documents can help me in this case ?

答:
To start: make sure your code is correctly indented when you put it on stackexchange.
Secondly: I assume you have edited the code before posting it here because that code will not compile e.g. there is a floating 'reg' at the top and no module declaration.
Thirdly: you have defined a wire adcIfData[79:0] I am going to assume you meant that to be [9:0].
Forthly: You use variables which are not defined: adc_data, adc_trg.

Fifthly: I suggest you give your variables more meaningfull names like: gater_samples, sum_off_samples.

Now lets look at the core of the code. You want to take samples and shift them into a 30 bit register. There is no need to write "adc_trg[19:10],adc_trg[9:0]" adc_trg[19:0] will suffice. Also there is no need to put it in a different register beforehand. I would just use:

```<code>always @(posedge clkr)
   if (adcIfEnb)
      iradcTrg[29:0] <= {iradcTrg[19:0],adcIfData[9:0]};
</code>```

As to your basic problem of gathering samples and not using the first two: all you have to do is add a counter which counts to three. Then you add the result on the third count. You will need a reset to give the counter a known value at startup but I don't see a reset signal. I always try to use minimal logic so I would make iradcTrg 20 bits wide to only store the intermediate result and at the count of three add it up with the latest sample. Saves another 10 registers. Here is some code. I wrote this without simulating or compiling. It is just a guide of how it all should look like.

```<code>reg [ 1:0] count;
reg [19:0] gather_samples;
reg [ 9:0] sum_of_samples;
reg        sum_valid;

always @(posedge clkr)
begin
   if (some_reset)
      count <= 2'd0;
   else
   if (adcIfEnb)
   begin
      if (count==2'd2)
      begin // third sample arriving, add it to the previous 2
         sum_of_samples <= gather_samples[19:10] + gather_samples[9:0] + adcIfData;
         count <= 2'd0;
      else
      begin // intermediate: gather samples
         gather_samples <= {gather_samples[9:0],adcIfData};
         count <= count + 2'd1;
      end
      sum_valid <= (count==2'd2);
   end // if (adcIfEnb)
end // clocked
</code>```

Body:
Hi everyone,

I am a newbie in programming FPGA by verilog language. At the present, I am trying to design the firmware to calculate the sum of adc data at 3 sampling. Firstly, I will explain about one adc at one sampling in my code. When you look at the code, you can see that with rising-edge of clkr clock and adcIfEnb == 1, the adc_data will get the value from adcIfData and this is the data for one sampling. In the next rising-edge of clkr clock and adcIfEnb == 1, this data is stored in iradcTrg. Finally, I will have the 3 data of adc_data for 3 sampling which are stored in iradcTrg and then I summarize 3 these data.

wire adcIfData[79:0];
reg
always @(posedge clkr) begin
if(adcIfEnb) begin
adc_data[9:0] <= adcIfData[9:0];
end
end
reg [29:0] iradcTrg;
reg [9:0]  adcTrg;
always @(posedge clkr) begin
if (adcIfEnb) begin
iradcTrg[29:0] <= {adc_trg[19:10],adc_trg[9:0],adc_data[9:0]};
adcTrg[9:0] <= adc_trg[29:20] + adc_trg[19:10] + adc_trg[9:0];
end
end

However, there are 2 problems which I do not know how to solve.

Firstly, at the beginning time, when the first data of adc_data is stored at iradcTrg and adcTrg also take the sum. It means that adcTrg = 0 + 0 + first_adc_data but this sum need to be avoided.

Secondly, according to my design, I see that adc_data is serialized into iradcTrg. It means that the adc_data will be stored like this:

[1 2 3] 4 5 6 => 1 [2 3 4] 5 6=> 1 2 [3 4 5] 6

But in my case, I would like that the adc_data will be stored like this to get the sum

[1 2 3] 4 5 6 => 1 2 3 [4 5 6]

Therefore, how should I repair my code to get the result that I expected or are there any documents can help me in this case ?

Body:
To start: make sure your code is correctly indented when you put it on stackexchange.
Secondly: I assume you have edited the code before posting it here because that code will not compile e.g. there is a floating 'reg' at the top and no module declaration.
Thirdly: you have defined a wire adcIfData[79:0] I am going to assume you meant that to be [9:0].
Forthly: You use variables which are not defined: adc_data, adc_trg.

Fifthly: I suggest you give your variables more meaningfull names like: gater_samples, sum_off_samples.

Now lets look at the core of the code. You want to take samples and shift them into a 30 bit register. There is no need to write "adc_trg[19:10],adc_trg[9:0]" adc_trg[19:0] will suffice. Also there is no need to put it in a different register beforehand. I would just use:

always @(posedge clkr)
   if (adcIfEnb)
      iradcTrg[29:0] <= {iradcTrg[19:0],adcIfData[9:0]};

As to your basic problem of gathering samples and not using the first two: all you have to do is add a counter which counts to three. Then you add the result on the third count. You will need a reset to give the counter a known value at startup but I don't see a reset signal. I always try to use minimal logic so I would make iradcTrg 20 bits wide to only store the intermediate result and at the count of three add it up with the latest sample. Saves another 10 registers. Here is some code. I wrote this without simulating or compiling. It is just a guide of how it all should look like.

reg [ 1:0] count;
reg [19:0] gather_samples;
reg [ 9:0] sum_of_samples;
reg        sum_valid;

always @(posedge clkr)
begin
   if (some_reset)
      count <= 2'd0;
   else
   if (adcIfEnb)
   begin
      if (count==2'd2)
      begin // third sample arriving, add it to the previous 2
         sum_of_samples <= gather_samples[19:10] + gather_samples[9:0] + adcIfData;
         count <= 2'd0;
      else
      begin // intermediate: gather samples
         gather_samples <= {gather_samples[9:0],adcIfData};
         count <= count + 2'd1;
      end
      sum_valid <= (count==2'd2);
   end // if (adcIfEnb)
end // clocked