问:
jQuery draggable with position conditionals
Trying to figure out how to be able to drag the red square ONLY AFTER the blue square has been dragged to the other end of its parent.

Also wondering if it is possible (in a separate scenario) to have the red square mirror the blue square when the blue square is dragged.

https://jsfiddle.net/t167y2ga/14/

```<code>$(function() {
  $("#draggable_left").draggable({
    containment: "parent",
  });
});

$(function() {
  $("#draggable_right").draggable({
    containment: "parent",
  });
});
</code>```

答:
You can use stop event:

```<code>stop:function(ev,ui){
        if(ui.position.left === 150) {
            $("#draggable_right").draggable({
            containment: "parent",
          });

    }
</code>```

Something like this will do the first part:

Fiddle

Body:
Trying to figure out how to be able to drag the red square ONLY AFTER the blue square has been dragged to the other end of its parent.

Also wondering if it is possible (in a separate scenario) to have the red square mirror the blue square when the blue square is dragged.

https://jsfiddle.net/t167y2ga/14/

$(function() {
  $("#draggable_left").draggable({
    containment: "parent",
  });
});

$(function() {
  $("#draggable_right").draggable({
    containment: "parent",
  });
});

Body:
You can use stop event:

stop:function(ev,ui){
        if(ui.position.left === 150) {
            $("#draggable_right").draggable({
            containment: "parent",
          });

    }

Something like this will do the first part:

Fiddle


来源: stackexchange

问:
PATINDEX with letter range exclude diacritics (accented characters)
I am trying to figure out how to use a patindex to find a range of letter characters, but exclude accented characters.  If I do a straight search, using the default collate (insensitive) works just fine.  However, when I search a range of letters, it will match on the accented character

```<code>SELECT
    IIF('Ú' = 'U' COLLATE Latin1_General_CI_AI, 'Match', 'No') AS MatchInsensitive,
    IIF('Ú' = 'U' COLLATE Latin1_General_CI_AS, 'Match', 'No') AS MatchSensitive,
    PATINDEX('%[A-Z]%', 'Ú' COLLATE Latin1_General_CI_AI)      AS PIInsensitive,
    PATINDEX('%[A-Z]%', 'Ú' COLLATE Latin1_General_CI_AS)      AS PISensitive
</code>```

Will give the following results:

```<code>MatchInsensitive MatchSensitive PIInsensitive PISensitive
---------------- -------------- ------------- -----------
Match            No             1             1
</code>```

What I am really trying to do is to identify the character position of accented characters in a string, so I was really searching for PATINDEX('%[^A-Z0-9 ]%').

If I have the following query, I would expect a result of 2 SELECT PATINDEX('%[^A-Z0-9 ]%', 'médico'), but I get 0.

答:
You could use a binary collation, e.g. Latin1_General_100_BIN2.

```<code>select patindex('%[^a-zA-Z0-9 ]%', 'médico' collate Latin1_General_100_BIN2)
</code>```

rextester: http://rextester.com/ZICLN98474

returns 2

ContentLicense: CC BY-SA 3.0

Body:
I am trying to figure out how to use a patindex to find a range of letter characters, but exclude accented characters.  If I do a straight search, using the default collate (insensitive) works just fine.  However, when I search a range of letters, it will match on the accented character

SELECT
    IIF('Ú' = 'U' COLLATE Latin1_General_CI_AI, 'Match', 'No') AS MatchInsensitive,
    IIF('Ú' = 'U' COLLATE Latin1_General_CI_AS, 'Match', 'No') AS MatchSensitive,
    PATINDEX('%[A-Z]%', 'Ú' COLLATE Latin1_General_CI_AI)      AS PIInsensitive,
    PATINDEX('%[A-Z]%', 'Ú' COLLATE Latin1_General_CI_AS)      AS PISensitive

Will give the following results:

MatchInsensitive MatchSensitive PIInsensitive PISensitive
---------------- -------------- ------------- -----------
Match            No             1             1

What I am really trying to do is to identify the character position of accented characters in a string, so I was really searching for PATINDEX('%[^A-Z0-9 ]%').

If I have the following query, I would expect a result of 2 SELECT PATINDEX('%[^A-Z0-9 ]%', 'médico'), but I get 0.

Body:
You could use a binary collation, e.g. Latin1_General_100_BIN2.

select patindex('%[^a-zA-Z0-9 ]%', 'médico' collate Latin1_General_100_BIN2)

rextester: http://rextester.com/ZICLN98474

returns 2


问:
How to render a variable in HAML and preserve white-spaces?
This is what I'm doing:

```<code>%pre
  =var
</code>```

The value of var is "foo\nbar". I'm getting this HTML:

```<code><body>
  ```foo
  bar```
</body>
</code>```

Obviously, I'm expecting:

```<code><body>
  ```foo
bar```
</body>
</code>```

What to do?

答: You have to place your var on the same line where your %pre is. So it looks like %pre= var

Body:
This is what I'm doing:

%pre
  =var

The value of var is "foo\nbar". I'm getting this HTML:

foo
  bar

Obviously, I'm expecting:

foo
bar

What to do?


问:
Detect which attributes were called in `update` in rails
Is it possible to detect which attributes were included in an update call in rails even if those attributes don't change?  The after_update callback is still called but since nothing has actually changed ActiveModel::Dirty doesn't seem to have any methods that will detect the relevant attributes.

Example:

I have a user model which has column notification_hour which defaults to 9

I call User.update(notification_hour: 9)

This triggers the callback
after_update :set_time_flag

I would like to set that the user has at least set the time even though they've set it to the same as the default.

```<code>def set_time_flag
  return unless notification_hour_changed?

  update_column(notifiation_time_set: true)
end
</code>```

This will return without setting the flag since the value didn't change.  Is there a way to detect that update was called with notification_hour even though it didn't actually change?

答:
You could try something like this</p>

```<code>class User < ApplicationRecord
  def update(changes={})
    changes[:notification_time_set] = true if changes.key?(:notification_hour)
    super(changes)
  end
end
</code>```

Body:
Is it possible to detect which attributes were included in an update call in rails even if those attributes don't change?  The after_update callback is still called but since nothing has actually changed ActiveModel::Dirty doesn't seem to have any methods that will detect the relevant attributes.

Example:

I have a user model which has column notification_hour which defaults to 9

I call User.update(notification_hour: 9)

This triggers the callback
after_update :set_time_flag

I would like to set that the user has at least set the time even though they've set it to the same as the default.

def set_time_flag
  return unless notification_hour_changed?

  update_column(notifiation_time_set: true)
end

This will return without setting the flag since the value didn't change.  Is there a way to detect that update was called with notification_hour even though it didn't actually change?

Body:
You could try something like this

class User < ApplicationRecord
  def update(changes={})
    changes[:notification_time_set] = true if changes.key?(:notification_hour)
    super(changes)
  end
end


问:
mongodb linq provider: incorrect behavior for fields of type decimal?
Using mongodb version 3.4.3, c# driver (nuget MongoDb.Driver) version 2.4.3

Given a class with a field Amount of type decimal, and a mongodb collection of this type. Querying the collection for entries with amounts bigger or smaller than a certain value gives incorrect results. When changing the type to 'int', then the code behaves correctly. Is there some issue when using decimal fields in MongoDb?

The sample code below illustrates the issue.

```<code>class C
{
    public int Id { get; set; }
    public string Description { get; set; }
    public decimal Amount { get; set; }
}

// assumes a locally installed mongodb
var connectionstring = "mongodb://localhost:27017/test";
var mongo = new MongoClient(connectionstring);
var db = mongo.GetDatabase("test");

db.DropCollection("testcollection");
db.CreateCollection("testcollection");
var collection = db.GetCollection<C>("testcollection");

// populate with 2 instances (amount 1 and amount 10)

collection.InsertMany(new[]
{
    new C{Id = 1, Description = "small", Amount = 1},
    new C{Id = 2, Description = "large", Amount = 10},
});

// verify that the documents are indeed persisted as expected
var all = collection.AsQueryable().ToList();
Debug.Assert(all.Count == 2);
Debug.Assert(all[1].Amount == 10);

// the assert below inexplicably fails (the query returns no results)
var largerThan5 = collection.AsQueryable().Where(c => c.Amount > 5).ToList();
Debug.Assert(largerThan5.Count == 1);
</code>```

答:
That's because it will convert all your decimals to strings (so they will store in string column in mongo database). Of course your gt comparisions will fail in this case. There is a very old issue here about that, which is closed as "works as intended". As far as I know - at those times there were no decimal BSON type, so that behavior was reasonable.

Now here you can see that there is new decimal BSON type in version 3.4, and actually C# driver already has support for it. However, if you will just use .NET decimal type - it will still convert it to string, even with mongo 3.4.

What you need to do (since you are running 3.4) is:

Decorate your Amount with [BsonRepresentation(BsonType.Decimal128)]:

```<code>class C
{
    public int Id { get; set; }
    public string Description { get; set; }
    [BsonRepresentation(BsonType.Decimal128)]
    public decimal Amount { get; set; }
}
</code>```

Set feature compatibility version to 3.4, because BSON decimal cannot be handled by previous versions as stated here:

```<code>db.adminCommand({setFeatureCompatibilityVersion: "3.4"})
</code>```

After that, your decimal will be correctly mapped and query will work as expected.

Body:
Using mongodb version 3.4.3, c# driver (nuget MongoDb.Driver) version 2.4.3

Given a class with a field Amount of type decimal, and a mongodb collection of this type. Querying the collection for entries with amounts bigger or smaller than a certain value gives incorrect results. When changing the type to 'int', then the code behaves correctly. Is there some issue when using decimal fields in MongoDb?

The sample code below illustrates the issue.

class C
{
    public int Id { get; set; }
    public string Description { get; set; }
    public decimal Amount { get; set; }
}

// assumes a locally installed mongodb
var connectionstring = "mongodb://localhost:27017/test";
var mongo = new MongoClient(connectionstring);
var db = mongo.GetDatabase("test");

db.DropCollection("testcollection");
db.CreateCollection("testcollection");
var collection = db.GetCollection<C>("testcollection");

// populate with 2 instances (amount 1 and amount 10)

collection.InsertMany(new[]
{
    new C{Id = 1, Description = "small", Amount = 1},
    new C{Id = 2, Description = "large", Amount = 10},
});

// verify that the documents are indeed persisted as expected
var all = collection.AsQueryable().ToList();
Debug.Assert(all.Count == 2);
Debug.Assert(all[1].Amount == 10);

// the assert below inexplicably fails (the query returns no results)
var largerThan5 = collection.AsQueryable().Where(c => c.Amount > 5).ToList();
Debug.Assert(largerThan5.Count == 1);

Body:
That's because it will convert all your decimals to strings (so they will store in string column in mongo database). Of course your gt comparisions will fail in this case. There is a very old issue here about that, which is closed as "works as intended". As far as I know - at those times there were no decimal BSON type, so that behavior was reasonable.

Now here you can see that there is new decimal BSON type in version 3.4, and actually C# driver already has support for it. However, if you will just use .NET decimal type - it will still convert it to string, even with mongo 3.4.

What you need to do (since you are running 3.4) is:

Decorate your Amount with [BsonRepresentation(BsonType.Decimal128)]:

class C
{
    public int Id { get; set; }
    public string Description { get; set; }
    [BsonRepresentation(BsonType.Decimal128)]
    public decimal Amount { get; set; }
}

Set feature compatibility version to 3.4, because BSON decimal cannot be handled by previous versions as stated here:

db.adminCommand({setFeatureCompatibilityVersion: "3.4"})

After that, your decimal will be correctly mapped and query will work as expected.


问:
Creating a Qt child after adding its parent to a QGraphicsScene makes it immobile
If you add a QtWidgets.QGraphicsEllipseItem to a QGraphicsScene, it is mobile.
If you assign it to have a QtWidgets.QGraphicsItemGroup as a parent, then add the parent to the scene, it is mobile.

It becomes immobile if you add the parent to the scene BEFORE adding the child. Why?

Below is a self-contained example. If you run the code, you'll notice that you can create four Points, all of which are mobile, then after its parent is added on the fifth Point, it becomes immobile. This was not the case in Qt4.

```<code>from PyQt5.QtWidgets import (QApplication, QGraphicsView,\
                             QGraphicsScene, QGraphicsItem)
from PyQt5 import QtWidgets, QtGui, QtCore

class Point(QtWidgets.QGraphicsEllipseItem):
    def __init__(self, pos):
        super(Point, self).__init__(0,0,10,10)
        self.setPos(pos)
        self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable | \
                      QtWidgets.QGraphicsItem.ItemIsSelectable)

class Graphics(QGraphicsItem):
    def __init__(self):
        super(Graphics, self).__init__()
        self.numPoints = 0
        self.polygon = QtWidgets.QGraphicsItemGroup()

    def paint(self, painter, option, widget):
        pass

    def boundingRect(self):
        return QtCore.QRectF(0,0,300,300)

    def mousePressEvent(self, event):
        pos = event.pos()
        itemAt = self.scene().itemAt(pos, QtGui.QTransform())

        # If nothing is under the mouse, create a new point and accept the event
        if not isinstance(itemAt, Point):
            # Add the point to the scene and set its parent
            pt = Point(pos)
            pt.setParentItem(self.polygon)
            if pt.scene() is None:
                self.scene().addItem(pt)
            else:
                print "The item was implicitly added to the scene by its parent"

            # On the fifth point, add the polygon to the scene
            self.numPoints += 1
            if self.numPoints == 4:
                self.scene().addItem(self.polygon)

            event.accept()
        super(Graphics, self).mousePressEvent(event)

class MainWindow(QGraphicsView):
    def __init__(self):
        super(MainWindow, self).__init__()
        scene = QGraphicsScene(self)
        scene.addItem(Graphics())
        scene.setSceneRect(0, 0, 300, 300)
        self.setScene(scene)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    mainWindow = MainWindow()

    mainWindow.show()
    sys.exit(app.exec_())
</code>```

答:
From the docs:

A QGraphicsItemGroup is a special type of compound item that treats itself and all its children as one item (i.e., all events and geometries for all children are merged together). It's common to use item groups in presentation tools, when the user wants to group several smaller items into one big item in order to simplify moving and copying of items.

Since all the Point(s) inside self.polygon are treated as single object, this object need to be Movable itself:

self.polygon.setFlag(QtWidgets.QGraphicsItem.ItemIsMovable, True)

If you want your "points" to be movable inside their parent QGraphicsItemGroup is not the right choice, instead you can use a GraphicsRectItem or a QGraphicsPolygonItem and others

Body:
If you add a QtWidgets.QGraphicsEllipseItem to a QGraphicsScene, it is mobile.
If you assign it to have a QtWidgets.QGraphicsItemGroup as a parent, then add the parent to the scene, it is mobile.

It becomes immobile if you add the parent to the scene BEFORE adding the child. Why?

Below is a self-contained example. If you run the code, you'll notice that you can create four Points, all of which are mobile, then after its parent is added on the fifth Point, it becomes immobile. This was not the case in Qt4.

from PyQt5.QtWidgets import (QApplication, QGraphicsView,\
                             QGraphicsScene, QGraphicsItem)
from PyQt5 import QtWidgets, QtGui, QtCore

class Point(QtWidgets.QGraphicsEllipseItem):
    def __init__(self, pos):
        super(Point, self).__init__(0,0,10,10)
        self.setPos(pos)
        self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable | \
                      QtWidgets.QGraphicsItem.ItemIsSelectable)

class Graphics(QGraphicsItem):
    def __init__(self):
        super(Graphics, self).__init__()
        self.numPoints = 0
        self.polygon = QtWidgets.QGraphicsItemGroup()

    def paint(self, painter, option, widget):
        pass

    def boundingRect(self):
        return QtCore.QRectF(0,0,300,300)

    def mousePressEvent(self, event):
        pos = event.pos()
        itemAt = self.scene().itemAt(pos, QtGui.QTransform())

        # If nothing is under the mouse, create a new point and accept the event
        if not isinstance(itemAt, Point):
            # Add the point to the scene and set its parent
            pt = Point(pos)
            pt.setParentItem(self.polygon)
            if pt.scene() is None:
                self.scene().addItem(pt)
            else:
                print "The item was implicitly added to the scene by its parent"

            # On the fifth point, add the polygon to the scene
            self.numPoints += 1
            if self.numPoints == 4:
                self.scene().addItem(self.polygon)

            event.accept()
        super(Graphics, self).mousePressEvent(event)

class MainWindow(QGraphicsView):
    def __init__(self):
        super(MainWindow, self).__init__()
        scene = QGraphicsScene(self)
        scene.addItem(Graphics())
        scene.setSceneRect(0, 0, 300, 300)
        self.setScene(scene)

if __name__ == '__main__':
    import sys
    app = QApplication(sys.argv)
    mainWindow = MainWindow()

    mainWindow.show()
    sys.exit(app.exec_())


问:
Cannot automatically bind the navigation property 'Players' on entity type 'Data.Team' for the source entity set 'Teams'
I'm using EF6 Code First.

I have the following classes:

```<code>public class Player
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Player name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public int TeamClubId { get; set; }

    [ForeignKey("TeamClubId")]
    public virtual Team Club { get; set; }

    [Required]
    public int TeamNationalId { get; set; }

    [ForeignKey("TeamNationalId")]
    public virtual Team National { get; set; }

}

public class Team
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public TeamType Type { get; set; }

    public virtual ICollection<Player> Players { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}

public class Tournament
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Tournament name must be at least 2 characters length")]
    public string Name { get; set; }

    public int Year { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public ICollection<Match> Matches { get; set; }

}
</code>```

In the DBContext class I have:

```<code>protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //player - national team relations
    modelBuilder.Entity<Player>()
        .HasRequired<Team>(p => p.National)
        .WithMany()
        .WillCascadeOnDelete(false);

    //player - club team relations
    modelBuilder.Entity<Player>()
        .HasRequired<Team>(p => p.Club)
        .WithMany()
        .WillCascadeOnDelete(false);

    //match - home team relations
    modelBuilder.Entity<Match>()
        .HasRequired<Team>(p => p.HomeTeam)
        .WithMany()
        .WillCascadeOnDelete(false);

    //match - away team relations
    modelBuilder.Entity<Match>()
        .HasRequired<Team>(p => p.AwayTeam)
        .WithMany()
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}
</code>```

I get the following error when trying to connect via OData:

Cannot automatically bind the navigation property 'Players' on entity type 'Data.Team' for the source entity set 'Teams' because there are two or more matching target entity sets. The matching entity sets are: Players, Tournaments.

[NotSupportedException: Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.Http.OData.Builder.EntitySetConfiguration.FindBinding(NavigationPropertyConfiguration
  navigationConfiguration, Boolean autoCreate) +736

  System.Web.Http.OData.Builder.EdmModelHelperMethods.AddNavigationBindings(EntitySetConfiguration
  configuration, EdmEntitySet entitySet, EntitySetLinkBuilderAnnotation
  linkBuilder, ODataModelBuilder builder, Dictionary2 edmTypeMap,
  Dictionary2 edmEntitySetMap) +391

  System.Web.Http.OData.Builder.EdmModelHelperMethods.AddEntitySets(EdmModel
  model, ODataModelBuilder builder, EdmEntityContainer container,
  Dictionary2 edmTypeMap) +635

  System.Web.Http.OData.Builder.EdmModelHelperMethods.BuildEdmModel(ODataModelBuilder
  builder) +200

  System.Web.Http.OData.Builder.ODataConventionModelBuilder.GetEdmModel()
  +664    ODataAPI.WebApiConfig.Register(HttpConfiguration config) +221    System.Web.Http.GlobalConfiguration.Configure(Action1
  configurationCallback) +65

[HttpException (0x80004005): Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
  context, HttpApplication app) +12582201

  System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
  appContext, HttpContext context, MethodInfo[] handlers) +175

  System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
  MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304

  System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
  appContext, HttpContext context) +404

  System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
  appContext) +475

[HttpException (0x80004005): Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12599232
  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
  +159    System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
  wr, HttpContext context) +12438981

What's my problem?

Thanks

答:
I had the same problem here, but my problem was a typing error on WebApiConfig.cs OData contiguration:

```<code>           builder.EntitySet<User>("Users");
           builder.EntitySet<User>("Issues");
</code>```

instead of

```<code>           builder.EntitySet<User>("Users");
           builder.EntitySet<Issue>("Issues");
</code>```

Body:
I'm using EF6 Code First.

I have the following classes:

public class Player
{
    [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Player name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public int TeamClubId { get; set; }

    [ForeignKey("TeamClubId")]
    public virtual Team Club { get; set; }

    [Required]
    public int TeamNationalId { get; set; }

    [ForeignKey("TeamNationalId")]
    public virtual Team National { get; set; }

}

public class Team
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Team name must be at least 2 characters length")]
    public string Name { get; set; }

    [Required]
    public TeamType Type { get; set; }

    public virtual ICollection<Player> Players { get; set; }

    public virtual ICollection<Match> Matches { get; set; }
}

public class Tournament
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }

    [Required, MinLength(2, ErrorMessage = "Tournament name must be at least 2 characters length")]
    public string Name { get; set; }

    public int Year { get; set; }

    public DateTime StartDate { get; set; }

    public DateTime EndDate { get; set; }

    public ICollection<Match> Matches { get; set; }

}

In the DBContext class I have:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    //player - national team relations
    modelBuilder.Entity<Player>()
        .HasRequired<Team>(p => p.National)
        .WithMany()
        .WillCascadeOnDelete(false);

    //player - club team relations
    modelBuilder.Entity<Player>()
        .HasRequired<Team>(p => p.Club)
        .WithMany()
        .WillCascadeOnDelete(false);

    //match - home team relations
    modelBuilder.Entity<Match>()
        .HasRequired<Team>(p => p.HomeTeam)
        .WithMany()
        .WillCascadeOnDelete(false);

    //match - away team relations
    modelBuilder.Entity<Match>()
        .HasRequired<Team>(p => p.AwayTeam)
        .WithMany()
        .WillCascadeOnDelete(false);

    base.OnModelCreating(modelBuilder);
}

I get the following error when trying to connect via OData:

Cannot automatically bind the navigation property 'Players' on entity type 'Data.Team' for the source entity set 'Teams' because there are two or more matching target entity sets. The matching entity sets are: Players, Tournaments.

[NotSupportedException: Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.Http.OData.Builder.EntitySetConfiguration.FindBinding(NavigationPropertyConfiguration
  navigationConfiguration, Boolean autoCreate) +736

  System.Web.Http.OData.Builder.EdmModelHelperMethods.AddNavigationBindings(EntitySetConfiguration
  configuration, EdmEntitySet entitySet, EntitySetLinkBuilderAnnotation
  linkBuilder, ODataModelBuilder builder, Dictionary2 edmTypeMap,
  Dictionary2 edmEntitySetMap) +391

  System.Web.Http.OData.Builder.EdmModelHelperMethods.AddEntitySets(EdmModel
  model, ODataModelBuilder builder, EdmEntityContainer container,
  Dictionary2 edmTypeMap) +635

  System.Web.Http.OData.Builder.EdmModelHelperMethods.BuildEdmModel(ODataModelBuilder
  builder) +200

  System.Web.Http.OData.Builder.ODataConventionModelBuilder.GetEdmModel()
  +664    ODataAPI.WebApiConfig.Register(HttpConfiguration config) +221    System.Web.Http.GlobalConfiguration.Configure(Action1
  configurationCallback) +65

[HttpException (0x80004005): Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext
  context, HttpApplication app) +12582201

  System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr
  appContext, HttpContext context, MethodInfo[] handlers) +175

  System.Web.HttpApplication.InitSpecial(HttpApplicationState state,
  MethodInfo[] handlers, IntPtr appContext, HttpContext context) +304

  System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr
  appContext, HttpContext context) +404

  System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr
  appContext) +475

[HttpException (0x80004005): Cannot automatically bind the navigation
  property 'Players' on entity type 'Data.Team' for the source entity
  set 'Teams' because there are two or more matching target entity sets.
  The matching entity sets are: Players, Tournaments.]

  System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +12599232
  System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context)
  +159    System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest
  wr, HttpContext context) +12438981

What's my problem?

Thanks

Body:
I had the same problem here, but my problem was a typing error on WebApiConfig.cs OData contiguration:

           builder.EntitySet<User>("Users");
           builder.EntitySet<User>("Issues");

instead of

           builder.EntitySet<User>("Users");
           builder.EntitySet<Issue>("Issues");


问:
WorldPay Apple Pay SDK unrecognized selector sent to instance
I am trying to make a payment via Apple pay using world pay and their SDK HERE https://github.com/Worldpay/worldpay-lib-ios. Within my app this payment is done via a notification, the user clicks on the notification, my app opens and the apple pay view is presented.

When I try to make my payment request (follow code below) with this line

```<code>let request = wp.createPaymentRequest(withMerchantIdentifier: ApplePaySwagMerchantID)
</code>```

However my app crashes with:

```<code>2017-03-30 20:38:20.026378 CarGo[757:79619] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Worldpay createPaymentRequestWithMerchantIdentifier:]: unrecognized selector sent to instance 0x1740fea00'
</code>```

I'm not really sure what could be causing this or how to go about debugging it?

my complete method which runs in the app delegate:

```<code>func makePayment(locationString: String){

        let defaults = UserDefaults.standard

        let topWindow: UIWindow = UIWindow(frame: UIScreen.main.bounds)
        topWindow.rootViewController = UIViewController()
        topWindow.windowLevel = UIWindowLevelAlert + 1
        topWindow.makeKeyAndVisible()

        let wp: Worldpay = Worldpay.sharedInstance();
        wp.clientKey = "xxxxxxx";
        wp.reusable = true;

        let request = wp.createPaymentRequest(withMerchantIdentifier: ApplePaySwagMerchantID)
        request?.supportedNetworks = SupportedPaymentNetworks
        request?.countryCode = "GB"
        request?.currencyCode = "GBP"
        request?.merchantCapabilities = PKMerchantCapability.capability3DS

        var decimalValue = NSDecimalNumber(string: defaults.string(forKey: locationString))

        decimalValue = decimalValue.multiplying(by: 100)

        self.transactionsDescription = "Toll Payment: " + locationString
        self.transactionCost = decimalValue.intValue

        request?.paymentSummaryItems = [
            PKPaymentSummaryItem(label: "Toll Payment: " + locationString, amount:NSDecimalNumber(string: defaults.string(forKey: locationString)))
        ]

        let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request!)
        applePayController.delegate = self

        topWindow.rootViewController?.present(applePayController, animated: true, completion: nil)

    }
</code>```

My bridge header file:

```<code>#import "Worldpay.h"
#import "APMController.h"
#import "WorldpayAPMViewController.h"
#import "ThreeDSController.h"
#import "WorldpayCardViewController.h"
#import "Worldpay+ApplePay.h"
</code>```

答:
I think I might have found the issue. Have you included the following import in your Objective-C Bridging Header?

```<code>import "Worldpay+ApplePay.h"
</code>```

This is a category that extends the WorldPay class with methods related to Apple Pay, and likely contains the method in question.

EDIT:

Make sure to include the -ObjC linker flag in your project's Other Linker Flags property in the Build Settings.

Body:
I am trying to make a payment via Apple pay using world pay and their SDK HERE https://github.com/Worldpay/worldpay-lib-ios. Within my app this payment is done via a notification, the user clicks on the notification, my app opens and the apple pay view is presented.

When I try to make my payment request (follow code below) with this line

let request = wp.createPaymentRequest(withMerchantIdentifier: ApplePaySwagMerchantID)

However my app crashes with:

2017-03-30 20:38:20.026378 CarGo[757:79619] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[Worldpay createPaymentRequestWithMerchantIdentifier:]: unrecognized selector sent to instance 0x1740fea00'

I'm not really sure what could be causing this or how to go about debugging it?

my complete method which runs in the app delegate:

func makePayment(locationString: String){

        let defaults = UserDefaults.standard

        let topWindow: UIWindow = UIWindow(frame: UIScreen.main.bounds)
        topWindow.rootViewController = UIViewController()
        topWindow.windowLevel = UIWindowLevelAlert + 1
        topWindow.makeKeyAndVisible()

        let wp: Worldpay = Worldpay.sharedInstance();
        wp.clientKey = "xxxxxxx";
        wp.reusable = true;

        let request = wp.createPaymentRequest(withMerchantIdentifier: ApplePaySwagMerchantID)
        request?.supportedNetworks = SupportedPaymentNetworks
        request?.countryCode = "GB"
        request?.currencyCode = "GBP"
        request?.merchantCapabilities = PKMerchantCapability.capability3DS

        var decimalValue = NSDecimalNumber(string: defaults.string(forKey: locationString))

        decimalValue = decimalValue.multiplying(by: 100)

        self.transactionsDescription = "Toll Payment: " + locationString
        self.transactionCost = decimalValue.intValue

        request?.paymentSummaryItems = [
            PKPaymentSummaryItem(label: "Toll Payment: " + locationString, amount:NSDecimalNumber(string: defaults.string(forKey: locationString)))
        ]

        let applePayController = PKPaymentAuthorizationViewController(paymentRequest: request!)
        applePayController.delegate = self

        topWindow.rootViewController?.present(applePayController, animated: true, completion: nil)

    }

My bridge header file:

#import "Worldpay.h"
#import "APMController.h"
#import "WorldpayAPMViewController.h"
#import "ThreeDSController.h"
#import "WorldpayCardViewController.h"
#import "Worldpay+ApplePay.h"

Body:
I think I might have found the issue. Have you included the following import in your Objective-C Bridging Header?

import "Worldpay+ApplePay.h"

This is a category that extends the WorldPay class with methods related to Apple Pay, and likely contains the method in question.

EDIT:

Make sure to include the -ObjC linker flag in your project's Other Linker Flags property in the Build Settings.


问:
How can I use Linq with JSON to get all the Ids from this odd JSON?
I receive JSON from a web service that looks something like this:

```<code>{
   "RESULTS": {
      "1220": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 5199,
           "DDR_NAME": "Mesa Building"
      },
      "5455": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 417,
           "DDR_NAME": "Scottsdale Building"
      },
      "1462": {
           "DDR_TYPE_ID": 12,
           "DDR_ID": 3324,
           "DDR_NAME": "Gentry Building"
      }
   }
}
</code>```

I can't really serialize in my usual method because this isn't an array of the same objects thanks the the strange numbered keys.

All I need from this is a list of the DDR_ID values.

Is there a way to use Linq to JSON to get these values from this JSON?  Or is there a better way?

答:
The "strange numbered keys" (or any other dynamic keys) can be taken care of by deserializing to a dictionary. So, for example, if you had a class like this:

```<code>public class MyJSON
{
    public Dictionary<int,ResultItem> Results { get; set; }
}

public class ResultItem
{
    public int DDR_ID { get; set; }
}
</code>```

Then, after deserializing you should be able to get your id's with something like:

```<code>var myObj = JsonConvert.DeserializeObject<MyJSON>(jsonString);   // using JSON.Net
var ids = myObj.Results.Select(p => p.Value.DDR_ID);
</code>```

Here's a fiddle

Body:
I receive JSON from a web service that looks something like this:

{
   "RESULTS": {
      "1220": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 5199,
           "DDR_NAME": "Mesa Building"
      },
      "5455": {
           "DDR_TYPE_ID": 7,
           "DDR_ID": 417,
           "DDR_NAME": "Scottsdale Building"
      },
      "1462": {
           "DDR_TYPE_ID": 12,
           "DDR_ID": 3324,
           "DDR_NAME": "Gentry Building"
      }
   }
}

I can't really serialize in my usual method because this isn't an array of the same objects thanks the the strange numbered keys.

All I need from this is a list of the DDR_ID values.

Is there a way to use Linq to JSON to get these values from this JSON?  Or is there a better way?

Body:
The "strange numbered keys" (or any other dynamic keys) can be taken care of by deserializing to a dictionary. So, for example, if you had a class like this:

public class MyJSON
{
    public Dictionary<int,ResultItem> Results { get; set; }
}

public class ResultItem
{
    public int DDR_ID { get; set; }
}

Then, after deserializing you should be able to get your id's with something like:

var myObj = JsonConvert.DeserializeObject<MyJSON>(jsonString);   // using JSON.Net
var ids = myObj.Results.Select(p => p.Value.DDR_ID);

Here's a fiddle


问:
Calling service from Html
i want to call asp.net web service from java script and pass the parameters to it .is there any code sample or demostration  that will help me to acheive that??
thanks in advance</p>

答:
JQuery:</p>

```<code>function AddLocation(ParentID) {
    $.ajax({
        type: "POST",
        url: "../server.asmx/Save",
        data: "{'ID':'0','ParentID':'" + ParentID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var item = document.createElement('option');
            item.value = data.d.split("$")[0];
            item.text = name;
            //do stuff
        }
    });
}
</code>```

OwnerDisplayName: Shoun

ContentLicense: CC BY-SA 2.5

Title: Calling service from Html

Body:
JQuery:

function AddLocation(ParentID) {
    $.ajax({
        type: "POST",
        url: "../server.asmx/Save",
        data: "{'ID':'0','ParentID':'" + ParentID + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var item = document.createElement('option');
            item.value = data.d.split("$")[0];
            item.text = name;
            //do stuff
        }
    });
}


问:
python setup.py egg_info failed when installing python-bioformats
I am working on Ubuntu 16.04, and I have installed virtualenvs. I am in one env and trying to install python-bioformats
The installation instruction form the official website just indicate to install as:

```<code>pip install python-bioformats
</code>```

I did but I got the following error message:

```<code>(env2) daniel@Caenor:~/Envs$ pip install python-bioformats
Collecting python-bioformats
  Using cached python-bioformats-1.1.0.tar.gz
Collecting javabridge>=1.0 (from python-bioformats)
  Using cached javabridge-1.0.14.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-SUD0_e/javabridge/setup.py", line 375, in <module>
        ext_modules=ext_modules(),
      File "/tmp/pip-build-SUD0_e/javabridge/setup.py", line 93, in ext_modules
        java_home = find_javahome()
      File "/tmp/pip-build-SUD0_e/javabridge/javabridge/locate.py", line 73, in find_javahome
        java_bin = get_out(["bash", "-c", "type -p java"])
      File "/tmp/pip-build-SUD0_e/javabridge/javabridge/locate.py", line 70, in get_out
        raise Exception("Error finding javahome on linux: %s" % cmd)
    Exception: Error finding javahome on linux: ['bash', '-c', 'type -p java']

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-SUD0_e/javabridge/
</code>```

I think this means I need the javabridge. I tried to install but I also get an error:

```<code>(env2) daniel@Caenor:~$ pip install javabridge
Collecting javabridge
  Using cached javabridge-1.0.14.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-KrBfqr/javabridge/setup.py", line 375, in <module>
        ext_modules=ext_modules(),
      File "/tmp/pip-build-KrBfqr/javabridge/setup.py", line 93, in ext_modules
        java_home = find_javahome()
      File "/tmp/pip-build-KrBfqr/javabridge/javabridge/locate.py", line 73, in find_javahome
        java_bin = get_out(["bash", "-c", "type -p java"])
      File "/tmp/pip-build-KrBfqr/javabridge/javabridge/locate.py", line 70, in get_out
        raise Exception("Error finding javahome on linux: %s" % cmd)
    Exception: Error finding javahome on linux: ['bash', '-c', 'type -p java']

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-KrBfqr/javabridge/
</code>```

From the documentation to install the javabridge I need numpy (I already have), the Java Development Kit (JDK) and a C compiler.

I have installed JPype1 (I think this is the JDK)
I tried to install the Javabridge but I got the error again.

What is missing to get the Javabridge and python-bioformats to be installed?

答: The problem is that you have note installed Java. You need to install Java on you system. If you think it is installed, then sure it is not on the Linux's paths to search for executables and you need to add the path to Java to environment variable PATH. Whenever you have Java installed/add to Linux's PATH then execute type -p java on command line and it should return the path to the java executable.

Body:
I am working on Ubuntu 16.04, and I have installed virtualenvs. I am in one env and trying to install python-bioformats
The installation instruction form the official website just indicate to install as:

pip install python-bioformats

I did but I got the following error message:

(env2) daniel@Caenor:~/Envs$ pip install python-bioformats
Collecting python-bioformats
  Using cached python-bioformats-1.1.0.tar.gz
Collecting javabridge>=1.0 (from python-bioformats)
  Using cached javabridge-1.0.14.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-SUD0_e/javabridge/setup.py", line 375, in <module>
        ext_modules=ext_modules(),
      File "/tmp/pip-build-SUD0_e/javabridge/setup.py", line 93, in ext_modules
        java_home = find_javahome()
      File "/tmp/pip-build-SUD0_e/javabridge/javabridge/locate.py", line 73, in find_javahome
        java_bin = get_out(["bash", "-c", "type -p java"])
      File "/tmp/pip-build-SUD0_e/javabridge/javabridge/locate.py", line 70, in get_out
        raise Exception("Error finding javahome on linux: %s" % cmd)
    Exception: Error finding javahome on linux: ['bash', '-c', 'type -p java']

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-SUD0_e/javabridge/

I think this means I need the javabridge. I tried to install but I also get an error:

(env2) daniel@Caenor:~$ pip install javabridge
Collecting javabridge
  Using cached javabridge-1.0.14.tar.gz
    Complete output from command python setup.py egg_info:
    Traceback (most recent call last):
      File "<string>", line 1, in <module>
      File "/tmp/pip-build-KrBfqr/javabridge/setup.py", line 375, in <module>
        ext_modules=ext_modules(),
      File "/tmp/pip-build-KrBfqr/javabridge/setup.py", line 93, in ext_modules
        java_home = find_javahome()
      File "/tmp/pip-build-KrBfqr/javabridge/javabridge/locate.py", line 73, in find_javahome
        java_bin = get_out(["bash", "-c", "type -p java"])
      File "/tmp/pip-build-KrBfqr/javabridge/javabridge/locate.py", line 70, in get_out
        raise Exception("Error finding javahome on linux: %s" % cmd)
    Exception: Error finding javahome on linux: ['bash', '-c', 'type -p java']

    ----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in /tmp/pip-build-KrBfqr/javabridge/

From the documentation to install the javabridge I need numpy (I already have), the Java Development Kit (JDK) and a C compiler.

I have installed JPype1 (I think this is the JDK)
I tried to install the Javabridge but I got the error again.

What is missing to get the Javabridge and python-bioformats to be installed?


问:
Looping Dictionary with unexpected returns
It has been a long night and day. I could use some help why this is not working can not think straight. This script opens a .csv file checks if a certain word is contained in a the title which is at row[4] and then it will loop through a dictionary that contains list and if the word is in the title then it will return the dictionary key to be written to a new csv file.

What I am getting is uncategorized for every row which should not be correct because the title does contain words in the list.

Thanks for the help in advance.

Example CSV in BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2Boom BX320K,2Boom BX320K Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2BOOMBX320K,2Boom,BX320K,7.08192E+11,,USD,,19.88,19.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225377.jpg,Bluetooth & Docking Speakers,,,,,,,,,,,,,,,,yes,,,
BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2Boom BX320R,2Boom BX320R Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2BOOMBX320R,2Boom,BX320R,7.08192E+11,,USD,,19.88,19.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225393.jpg,Bluetooth & Docking Speakers,,,,,,,,,,,,,,,,yes,,,
BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Bluetooth Noise-Cancelling Earbud Headphones,2Boom EPBT690B,2Boom EPBT690B Bluetooth Noise-Cancelling Earbud Headphones,2BOOMEPBT690B,2Boom,EPBT690B,7.44751E+11,,USD,,9.88,9.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225398.jpg,Earbuds,,,,,,,,,,,,,,,,yes,,,

Using Python 3

```<code>import os, csv, time

csv_path = os.path.dirname(os.path.abspath(__file__))

row_list = []

# Appliances
category_list = {"Appliance Accessories": ['Air Conditioner Accessories', 'Air Purifier Accessories', "Coffee Maker Accessories",
                           'Dishwasher Accessories', 'Food Processor Accessories', 'Heater Accessories',
                           'Humidifier Accessories', 'Humidifier Accessories', 'Mixer Accessories',
                           'Range & Oven Accessories', 'Range Hood Accessories', 'Refrigerator Accessories',
                           'Vacuum Accessories', 'Washer & Dryer Accessories'],
 "Electronics Accessories": ['cables & adapters', 'audio accessories', 'video accessories', 'camcorder accessories',
                             'cell phone accessories', 'clock radios', 'Digital Book Reader Accessories',
                             'Digital Picture Frames', 'Electronics Cases & Bags', 'GPS Accessories',
                             'Projector Accessories', 'Telephone Accessories', 'batteries', 'battery'],
 "Photography": ['Camcorders', 'Cameras', 'Digital Camera Accessories', 'Digital Cameras', 'Camera', 'Digital Camera',
                 'Photography', 'Darkroom']}

category = ""

with open(csv_path + "/pre.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        for k, val in category_list.items():
            for v in val:
                if v.lower() in row[4].lower():
                    category = k
                else:
                    category = "Uncategorized"

        new_row = [str(row[0]),  # company
                   str(row[1]),  # company url
                   str(row[4]),  # product name
                   str(row[5]),  # keywords
                   str(row[6]),  # descripition
                   str(row[7]),  # sku
                   str(row[8]),  # manufacturer
                   str(row[13]),  # saleprice
                   str(row[14]),  # price
                   str(row[15]),  # retailprice
                   str(row[17]),  # buy_link
                   str(row[19]),  # product_image_url
                   str(row[31]),  # promotional_text
                   str(row[36]),  # stock
                   str(row[37]),  # condition
                   str(row[38]),  # warrenty
                   str(row[39]),  # shipping_cost
                   category,
                   ]
        row_list.append(new_row)

    f.close()

with open(csv_path + "/final.csv", 'w') as ff:
    writer = csv.writer(ff)
    writer.writerows(row_list)
    ff.close()
</code>```

答:
Ok so I took a little bit from everyone above to achieve my needs. Thank you all that helped.</p>

```<code>csv_row_map =  [0,  # company
                1,  # company url
                4,  # product name
                5,  # keywords
                6,  # descripition
                7,  # sku
                8,  # manufacturer
                13,  # saleprice
                14,  # price
                15,  # retailprice
                17,  # buy_link
                19,  # product_image_url
                31,  # promotional_text
                36,  # stock
                37,  # condition
                38,  # warrenty
                39,  # shipping_cost
                ]

product_to_category_index = {}
for category, products in category_list.items():
    product_to_category_index.update(((product.lower(), category) for product in products))

with open(csv_path + '/pre.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        for k, v in product_to_category_index.items():
            if k in row[4].lower():
                category = v
                break
            else:
                category = "Uncategorized"
        #category = product_to_category_index.get(row[4].lower(), "Uncategorized")
        new_row = [row[csv_row_map[i]] for i in range(len(csv_row_map))]
        new_row.append(category)
        row_list.append(new_row)

with open(csv_path + "/final.csv", 'w') as ff:
    writer = csv.writer(ff)
    writer.writerows(row_list)
</code>```

Body:
It has been a long night and day. I could use some help why this is not working can not think straight. This script opens a .csv file checks if a certain word is contained in a the title which is at row[4] and then it will loop through a dictionary that contains list and if the word is in the title then it will return the dictionary key to be written to a new csv file.

What I am getting is uncategorized for every row which should not be correct because the title does contain words in the list.

Thanks for the help in advance.

Example CSV in BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2Boom BX320K,2Boom BX320K Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2BOOMBX320K,2Boom,BX320K,7.08192E+11,,USD,,19.88,19.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225377.jpg,Bluetooth & Docking Speakers,,,,,,,,,,,,,,,,yes,,,
BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2Boom BX320R,2Boom BX320R Mini Bass King Jr Bluetooth Portable Outdoor Speaker,2BOOMBX320R,2Boom,BX320R,7.08192E+11,,USD,,19.88,19.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225393.jpg,Bluetooth & Docking Speakers,,,,,,,,,,,,,,,,yes,,,
BrandsMart USA,http://www.BrandsMartUSA.com,BrandsMart Product Catalog,01:30.8,Bluetooth Noise-Cancelling Earbud Headphones,2Boom EPBT690B,2Boom EPBT690B Bluetooth Noise-Cancelling Earbud Headphones,2BOOMEPBT690B,2Boom,EPBT690B,7.44751E+11,,USD,,9.88,9.88,,http://www.example.com,http://www.ftjcfx.com/image-8299186-11133500,https://www.brandsmartusa.com/images/product/large/20225398.jpg,Earbuds,,,,,,,,,,,,,,,,yes,,,

Using Python 3

import os, csv, time

csv_path = os.path.dirname(os.path.abspath(__file__))

row_list = []

# Appliances
category_list = {"Appliance Accessories": ['Air Conditioner Accessories', 'Air Purifier Accessories', "Coffee Maker Accessories",
                           'Dishwasher Accessories', 'Food Processor Accessories', 'Heater Accessories',
                           'Humidifier Accessories', 'Humidifier Accessories', 'Mixer Accessories',
                           'Range & Oven Accessories', 'Range Hood Accessories', 'Refrigerator Accessories',
                           'Vacuum Accessories', 'Washer & Dryer Accessories'],
 "Electronics Accessories": ['cables & adapters', 'audio accessories', 'video accessories', 'camcorder accessories',
                             'cell phone accessories', 'clock radios', 'Digital Book Reader Accessories',
                             'Digital Picture Frames', 'Electronics Cases & Bags', 'GPS Accessories',
                             'Projector Accessories', 'Telephone Accessories', 'batteries', 'battery'],
 "Photography": ['Camcorders', 'Cameras', 'Digital Camera Accessories', 'Digital Cameras', 'Camera', 'Digital Camera',
                 'Photography', 'Darkroom']}

category = ""

with open(csv_path + "/pre.csv") as f:
    reader = csv.reader(f)
    for row in reader:
        for k, val in category_list.items():
            for v in val:
                if v.lower() in row[4].lower():
                    category = k
                else:
                    category = "Uncategorized"

        new_row = [str(row[0]),  # company
                   str(row[1]),  # company url
                   str(row[4]),  # product name
                   str(row[5]),  # keywords
                   str(row[6]),  # descripition
                   str(row[7]),  # sku
                   str(row[8]),  # manufacturer
                   str(row[13]),  # saleprice
                   str(row[14]),  # price
                   str(row[15]),  # retailprice
                   str(row[17]),  # buy_link
                   str(row[19]),  # product_image_url
                   str(row[31]),  # promotional_text
                   str(row[36]),  # stock
                   str(row[37]),  # condition
                   str(row[38]),  # warrenty
                   str(row[39]),  # shipping_cost
                   category,
                   ]
        row_list.append(new_row)

    f.close()

with open(csv_path + "/final.csv", 'w') as ff:
    writer = csv.writer(ff)
    writer.writerows(row_list)
    ff.close()

Body:
Ok so I took a little bit from everyone above to achieve my needs. Thank you all that helped.

csv_row_map =  [0,  # company
                1,  # company url
                4,  # product name
                5,  # keywords
                6,  # descripition
                7,  # sku
                8,  # manufacturer
                13,  # saleprice
                14,  # price
                15,  # retailprice
                17,  # buy_link
                19,  # product_image_url
                31,  # promotional_text
                36,  # stock
                37,  # condition
                38,  # warrenty
                39,  # shipping_cost
                ]

product_to_category_index = {}
for category, products in category_list.items():
    product_to_category_index.update(((product.lower(), category) for product in products))

with open(csv_path + '/pre.csv', newline='') as f:
    reader = csv.reader(f)
    for row in reader:
        for k, v in product_to_category_index.items():
            if k in row[4].lower():
                category = v
                break
            else:
                category = "Uncategorized"
        #category = product_to_category_index.get(row[4].lower(), "Uncategorized")
        new_row = [row[csv_row_map[i]] for i in range(len(csv_row_map))]
        new_row.append(category)
        row_list.append(new_row)

with open(csv_path + "/final.csv", 'w') as ff:
    writer = csv.writer(ff)
    writer.writerows(row_list)


问:
How to wait for all async tasks to finish in Node.js?
My program needs to run many async tasks.

And one task must run when all async tasks complete.

How can I make this function to wait all async functions?

```<code>let urls=[....]

for(var i=0; i<urls.length; i++){
    doRequest(urls[i])
}
finish()

function doRequest(url){
    request({
      uri: url,
    }, function(error, response, body) {
        //do some tasks
    });
}

function finish(){
    console.log('finish')
}
</code>```

答:
Promise are exactly what you need. They're native in JS nowadays, no need for extra libraries.</p>

```<code>function finish () {
    console.log("finish");
}

function doRequest (uri) {
    // wrap code in promise
    return new Promise((resolve, reject) => {
        request(
            { uri },
            (error, response, body) => {
                if (error) {
                    // error case, similar to "throw"
                    reject(error);
                }
                else {
                    // success case, similar to "return"
                    resolve({ response, body });
                }
            }
        );
    });
}

let urls=[...];

// Basic way to do it:
Promise.all(urls.map(doRequest)).then(finish);

// async/await notation:
// you must be in an "async" environement to use "await"
async function wrapper () {
    await Promise.all(urls.map(doRequest));
    finish();
}
// async function return a promise transparently
wrapper();
</code>```

Body:
My program needs to run many async tasks.

And one task must run when all async tasks complete.

How can I make this function to wait all async functions?

let urls=[....]

for(var i=0; i<urls.length; i++){
    doRequest(urls[i])
}
finish()

function doRequest(url){
    request({
      uri: url,
    }, function(error, response, body) {
        //do some tasks
    });
}

function finish(){
    console.log('finish')
}

Body:
Promise are exactly what you need. They're native in JS nowadays, no need for extra libraries.

function finish () {
    console.log("finish");
}

function doRequest (uri) {
    // wrap code in promise
    return new Promise((resolve, reject) => {
        request(
            { uri },
            (error, response, body) => {
                if (error) {
                    // error case, similar to "throw"
                    reject(error);
                }
                else {
                    // success case, similar to "return"
                    resolve({ response, body });
                }
            }
        );
    });
}

let urls=[...];

// Basic way to do it:
Promise.all(urls.map(doRequest)).then(finish);

// async/await notation:
// you must be in an "async" environement to use "await"
async function wrapper () {
    await Promise.all(urls.map(doRequest));
    finish();
}
// async function return a promise transparently
wrapper();


问:
how to sort values of 1st column and print only corresponding values of third column using awk
I tried to sort the file using awk '{print $0|"sort -t',' -nk1 "}' but I want to print only the third column of sorted file. Input file:

1   4   7   9
9   7   4   1
4   6   8   9
1   2   3   4
5   4   5   2

the expected output:

3
7
8
5
4

答:
Two simple ways "to print only the third column of sorted file":

with tr + cut command:

```<code>sort -n file | tr -s ' ' | cut -d' ' -f3
</code>```

with awk:

```<code>sort -n file | awk '{print $3}'
</code>```

Body:
Two simple ways "to print only the third column of sorted file":

with tr + cut command:

sort -n file | tr -s ' ' | cut -d' ' -f3

with awk:

sort -n file | awk '{print $3}'


问:
Create a new column to a dataframe based on the values of another dataframe
I have a dataframe like this:

```<code>name
Google
Amazon
Google
Yahoo
Google
Yahoo
</code>```

And another one like this:

```<code>name   stock_name
Google  stockA
Amazon  stockB
Yahoo   stockC
</code>```

The final result I would like to take from the merge of these 2 dataframes:

```<code>name stock_name
Google stockA
Amazon stockB
Google stockA
Yahoo  stockC
Google stockA
Yahoo  stockC
</code>```

Using the merge it is not possible to make it. Any hind on how could make it?

答:
Another way to solve this:</p>

```<code>df1 <- data.frame(data = c("Google", "Amazon", "Google", "Yahoo", "Google", "Yahoo"))

df2 <- data.frame(data = c("Google" = "stockA", "Amazon"  = "stockB", "Yahoo" = "stockC"))
colnames(df2) <- "stock_name"

df1$stock_name <- df2[df1$data, 1]
</code>```

Body:
I have a dataframe like this:

name
Google
Amazon
Google
Yahoo
Google
Yahoo

And another one like this:

name   stock_name
Google  stockA
Amazon  stockB
Yahoo   stockC

The final result I would like to take from the merge of these 2 dataframes:

name stock_name
Google stockA
Amazon stockB
Google stockA
Yahoo  stockC
Google stockA
Yahoo  stockC

Using the merge it is not possible to make it. Any hind on how could make it?

Body:
Another way to solve this:

df1 <- data.frame(data = c("Google", "Amazon", "Google", "Yahoo", "Google", "Yahoo"))

df2 <- data.frame(data = c("Google" = "stockA", "Amazon"  = "stockB", "Yahoo" = "stockC"))
colnames(df2) <- "stock_name"

df1$stock_name <- df2[df1$data, 1]


问:
An app that made with sdk 4.0.1 doesn't install on device with os 4.2
I made an app with ios sdk 4.0.1 but now i want to install it from xcode on ipod touch with os 4.2 but says

No provisioned iPhone OS device is
  connected.

答:
If the above doesn't work (and it almost certainly should help), you might try disconnecting and reconnecting your device and or rebooting your device and/or mac.

Side note - it's good practice to always compile against the latest SDK (currently 4.2) and set your build Deployment Target to the minimum version of the OS you wish to support.


问:
Elasticsearch NEST HttpClientHandler Certificate
I am trying to use Elasticsearch NEST with .NET Core and our Elasticsearch instance. We are connecting via SSL and it has a wildcard certificate which we need to accept programmatically. I am trying to figure out how to hook the HttpClientHandler to NEST to accept it. There doesn't appear to be good documentation on how, it just says to do it on their instructions https://www.elastic.co/guide/en/elasticsearch/client/net-api/current/connecting.html#configuring-ssl.

I am looking for an example if possible. Thanks in advance!

答:
I figured this out. I needed to create an HttpConnection and override the CreateHttpClientHandler method. Here is an example that returns true regardless of what the certificate is.

```<code>public class ConnectionWithCert : HttpConnection
{
    protected override HttpClientHandler CreateHttpClientHandler(RequestData requestData)
    {
        var handler = base.CreateHttpClientHandler(requestData);
        handler.ServerCertificateCustomValidationCallback = ValidateCertificate;
        return handler;
    }

    private bool ValidateCertificate(HttpRequestMessage message, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true;
    }
}
</code>```

A person would want to check the cert to ensure that it is one they expect.

Then, I added this connection in the ConnectionSettings

```<code>var connectionSettings = new ConnectionSettings(connnectionPool, new ConnectionWithCert());
</code>```

Probably want to do some Dependency Injection, but figured I would share the solution just in case anyone else wonders what they need to do.

Body:
I figured this out. I needed to create an HttpConnection and override the CreateHttpClientHandler method. Here is an example that returns true regardless of what the certificate is.

public class ConnectionWithCert : HttpConnection
{
    protected override HttpClientHandler CreateHttpClientHandler(RequestData requestData)
    {
        var handler = base.CreateHttpClientHandler(requestData);
        handler.ServerCertificateCustomValidationCallback = ValidateCertificate;
        return handler;
    }

    private bool ValidateCertificate(HttpRequestMessage message, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors errors)
    {
        return true;
    }
}

A person would want to check the cert to ensure that it is one they expect.

Then, I added this connection in the ConnectionSettings

var connectionSettings = new ConnectionSettings(connnectionPool, new ConnectionWithCert());

Probably want to do some Dependency Injection, but figured I would share the solution just in case anyone else wonders what they need to do.


问:
How to regex string that includes html
I have this string which is part of a larger string with multiple occurrences of "content" and "/content": I want to capture the whole string between "content ..." and "/content".

<content type="xhtml">

RATING: ★★★★

TAGS: Fiction, General, Science Fiction

SERIES: 20 SienceFiction Greats [19]

SUMMARY:
Luna is an open colony and the regime is a harsh one....

    </content>```
</div>
</div>

I want to capture all between "content type="xhtml"" and "/content"
I tried this code:</p>

```let regexPattern = "<content type=\"xhtml\">.*</content>"
let result:[String] = matches(for: regexPattern, in: dataString)
```

but it returns an empty array.

答:
Your regex pattern is close. You do not have any capturing groups within the regex. A capturing group is defined as any pattern between (). So with a little adjustment of the regex you will get a match. The updated Regex should look like this:

let regexPattern = "<content type=\"xhtml\">(.*)<\/content>"

Title: How to regex string that includes html

Body:
I have this string which is part of a larger string with multiple occurrences of "content" and "/content": I want to capture the whole string between "content ..." and "/content".

<content type="xhtml">

RATING: ★★★★

TAGS: Fiction, General, Science Fiction

SERIES: 20 SienceFiction Greats [19]

SUMMARY:
Luna is an open colony and the regime is a harsh one....

    </content>

I want to capture all between "content type="xhtml"" and "/content"
I tried this code:

let regexPattern = "<content type=\"xhtml\">.*</content>"
let result:[String] = matches(for: regexPattern, in: dataString)

but it returns an empty array.


问:
How to save custom fields to DB in Django registrationform?
ive been struggling with this particular part for days now, and other posts on this problem dont seem to help me out.
So I have connected the User model with my own Gebruiker model that has fields like city, postalcode etc. Now I have managed to show them up on the registerform, but they dont seem to work. My second question is about the order of the inputfields, every time they appear in a random order. How can I set up a steady order?
This is my forms.py

```<code>from django import forms
from django.contrib.auth.models import User
from .models import Gebruiker
from django.contrib.auth.forms import UserCreationForm

class RegistrationForm(UserCreationForm):
woonplaats = forms.CharField(required=True)
postcode = forms.CharField(required=True)

class Meta:
    model = User
    fields = {'username','email', 'password1', 'password2',  'first_name', 'last_name', 'woonplaats', 'postcode'}

    def save(self, commit=True):

        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        gebruiker = Gebruiker(user=user, woonplaats=self.cleaned_data['woonplaats'], postcode=self.cleaned_data['postcode'])
        gebruiker.save()
        if commit:
            gebruiker.save()
            user.save()

        return user, gebruiker
</code>```

(where woonplaats = place of residence)

Here is a part from views.py

```<code>def register(request):
if request.method == 'POST':
    form = RegistrationForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('/aanmelden')
else:
    form = RegistrationForm()

args = {'form' : form}
return render(request, 'aanmelden/reg_form.html', args)
</code>```

Models file:

```<code>from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save

# Create your models here.
class Gebruiker(models.Model):
user = models.OneToOneField(User, null=True)
woonplaats = models.CharField(max_length=100)
postcode = models.CharField(max_length=100,  default="")
email = models.CharField(max_length=100,  default="")

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
    Gebruiker.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.gebruiker.save()
</code>```

Gebruiker part in User:

!(http://imgur.com/RKVCbc2)

答:
You have to create object Gebruiker. So, instead of this line:

```<code> gebruiker = Gebruiker(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
 gebruiker.save()
</code>```

change to this:

```<code>  gebruiker = Gebruiker.objects.create(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
  gebruiker.save()
</code>```

if Gebruiker created already, you have to get this object:

```<code>gebruiker = Gebruiker.objects.get(your_parameter)
gebruiker = Gebruiker(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
gebruiker.save()
</code>```

And the second answer, about ordering of the fields. As I understand your template looks something like that:

```<code>{{form}}
</code>```

but you can access to the different fields using this code:

```<code><form action="" method="post">
   ...
   {{ form.woonplaats }}
   {{ form.postcode }}
   ...
   <input type="submit" alt="register" value="Order" />
</form>
</code>```

In this case you can change the order as you want

UPDATE:

```<code>  gebruiker = Gebruiker.objects.get(user = user)
  gebruiker.woonplaats = self.cleaned_data['woonplaats'],
  gebruiker.postcode = self.cleaned_data['postcode'])
  gebruiker.save()
</code>```

Body:
ive been struggling with this particular part for days now, and other posts on this problem dont seem to help me out.
So I have connected the User model with my own Gebruiker model that has fields like city, postalcode etc. Now I have managed to show them up on the registerform, but they dont seem to work. My second question is about the order of the inputfields, every time they appear in a random order. How can I set up a steady order?
This is my forms.py

from django import forms
from django.contrib.auth.models import User
from .models import Gebruiker
from django.contrib.auth.forms import UserCreationForm

class RegistrationForm(UserCreationForm):
woonplaats = forms.CharField(required=True)
postcode = forms.CharField(required=True)

class Meta:
    model = User
    fields = {'username','email', 'password1', 'password2',  'first_name', 'last_name', 'woonplaats', 'postcode'}

    def save(self, commit=True):

        user = super(UserCreationForm, self).save(commit=False)
        user.email = self.cleaned_data['email']
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']

        gebruiker = Gebruiker(user=user, woonplaats=self.cleaned_data['woonplaats'], postcode=self.cleaned_data['postcode'])
        gebruiker.save()
        if commit:
            gebruiker.save()
            user.save()

        return user, gebruiker

(where woonplaats = place of residence)

Here is a part from views.py

def register(request):
if request.method == 'POST':
    form = RegistrationForm(request.POST)
    if form.is_valid():
        form.save()
        return redirect('/aanmelden')
else:
    form = RegistrationForm()

args = {'form' : form}
return render(request, 'aanmelden/reg_form.html', args)

Models file:

from django.db import models
from django.contrib.auth.models import User
from django.dispatch import receiver
from django.db.models.signals import post_save

# Create your models here.
class Gebruiker(models.Model):
user = models.OneToOneField(User, null=True)
woonplaats = models.CharField(max_length=100)
postcode = models.CharField(max_length=100,  default="")
email = models.CharField(max_length=100,  default="")

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
if created:
    Gebruiker.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
instance.gebruiker.save()

Gebruiker part in User:

!(http://imgur.com/RKVCbc2)

Body:
You have to create object Gebruiker. So, instead of this line:

 gebruiker = Gebruiker(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
 gebruiker.save()

change to this:

  gebruiker = Gebruiker.objects.create(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
  gebruiker.save()

if Gebruiker created already, you have to get this object:

gebruiker = Gebruiker.objects.get(your_parameter)
gebruiker = Gebruiker(user = user, woonplaats = self.cleaned_data['woonplaats'], postcode = self.cleaned_data['postcode'])
gebruiker.save()

And the second answer, about ordering of the fields. As I understand your template looks something like that:

{{form}}

but you can access to the different fields using this code:

<form action="" method="post">
   ...
   {{ form.woonplaats }}
   {{ form.postcode }}
   ...
   <input type="submit" alt="register" value="Order" />
</form>

In this case you can change the order as you want

UPDATE:

  gebruiker = Gebruiker.objects.get(user = user)
  gebruiker.woonplaats = self.cleaned_data['woonplaats'],
  gebruiker.postcode = self.cleaned_data['postcode'])
  gebruiker.save()


问:
How to divide page in two column FPDF
I want to divide page in to two column using FPDF. I am using below code which created pdf in two cloumn but issue is that the gap is some bit more between column. I want to reduce gap between the column only.

My code here

```<code>class PDF extends FPDF
{
protected $col = 0; // Current column
protected $y0;      // Ordinate of column start

function Header()
{
}

function Footer()
{
}

function SetCol($col)
{
    // Set position at a given column
    $this->col = $col;
    $x = 10+$col*50;
    $this->SetLeftMargin($x);
    $this->SetX($x);
}

function AcceptPageBreak()
{
    if($this->col<2)
    {
        // Go to next column
        $this->SetCol($this->col+2);
        // Set ordinate to top
        $this->SetY($this->y0);
        // Keep on page
        return false;
    }
    else
    {
        // Go back to first column
        $this->SetCol(0);
        // Page break
        return true;
    }
}

function ChapterBody($file)
{
    $txt = file_get_contents($file);
    $this->SetFont('Times','',12);
    $this->MultiCell(100, 7, $txt);

    $this->Ln();
    $this->SetCol(0);
}

function PrintChapter($num, $title, $file)
{
    // Add chapter
    $this->AddPage();
    $this->ChapterBody($file);
}
}

$pdf = new PDF();
$title = '20000 Leagues Under the Seas';
$pdf->SetTitle($title);
$pdf->SetAuthor('Jules Verne');
$pdf->PrintChapter(1,'A RUNAWAY REEF','20k_c1.txt');
$pdf->Output();
</code>```

In the below image you can see

答:
You are skipping to third column. See bellow with two columns per page:</p>

```<code>function AcceptPageBreak()
{
    if($this->col<1)
    {
        // Go to next column
        $this->SetCol($this->col+1);
        // Set ordinate to top
        $this->SetY($this->y0);
        // Keep on page
        return false;
    }
    else
    {
        // Go back to first column
        $this->SetCol(0);
        // Page break
        return true;
    }
}
</code>```

Title: How to divide page in two column FPDF

Body:
I want to divide page in to two column using FPDF. I am using below code which created pdf in two cloumn but issue is that the gap is some bit more between column. I want to reduce gap between the column only.

My code here

class PDF extends FPDF
{
protected $col = 0; // Current column
protected $y0;      // Ordinate of column start

function Header()
{
}

function Footer()
{
}

function SetCol($col)
{
    // Set position at a given column
    $this->col = $col;
    $x = 10+$col*50;
    $this->SetLeftMargin($x);
    $this->SetX($x);
}

function AcceptPageBreak()
{
    if($this->col<2)
    {
        // Go to next column
        $this->SetCol($this->col+2);
        // Set ordinate to top
        $this->SetY($this->y0);
        // Keep on page
        return false;
    }
    else
    {
        // Go back to first column
        $this->SetCol(0);
        // Page break
        return true;
    }
}

function ChapterBody($file)
{
    $txt = file_get_contents($file);
    $this->SetFont('Times','',12);
    $this->MultiCell(100, 7, $txt);

    $this->Ln();
    $this->SetCol(0);
}

function PrintChapter($num, $title, $file)
{
    // Add chapter
    $this->AddPage();
    $this->ChapterBody($file);
}
}

$pdf = new PDF();
$title = '20000 Leagues Under the Seas';
$pdf->SetTitle($title);
$pdf->SetAuthor('Jules Verne');
$pdf->PrintChapter(1,'A RUNAWAY REEF','20k_c1.txt');
$pdf->Output();

In the below image you can see

Body:
You are skipping to third column. See bellow with two columns per page:

function AcceptPageBreak()
{
    if($this->col<1)
    {
        // Go to next column
        $this->SetCol($this->col+1);
        // Set ordinate to top
        $this->SetY($this->y0);
        // Keep on page
        return false;
    }
    else
    {
        // Go back to first column
        $this->SetCol(0);
        // Page break
        return true;
    }
}


问:
Chrome interprets ISO time without Z as UTC; C# issue
Run this jsfiddle: http://jsfiddle.net/E9gq9/7/ on Chrome, FF, and IE and you get:

Chrome:

Chrome http://images.devs-on.net/Image/vBTz86J0f4o8zlL3-Region.png

Firefox:

Firefox http://images.devs-on.net/Image/aNPxNPUpltyjVpSX-Region.png

IE:

IE http://images.devs-on.net/Image/WXLM5Ev1Viq4ecFq-Region.png

Safari:

Safari http://images.devs-on.net/Image/AEcyUouX04k2yIPo-Region.png

ISO 8601 does not appear to say how a string without a trailing Z should be interpreted.

Our server (ASP.NET MVC4) is pulling UTC times out of our database as DateTimes and simply stuffing them in JSON. As you can see because of this we are getting inconsistent results on the browser.

Should we just append Z to them on the server side?

答:
David Hammond's answer is great but doesn't play all the tricks; so here is a modified version:

allows for fractional part in date/time string

allows for optional seconds in date/time string

considers crossing over daylight-saving time

appendTimezone = function (/*String*/ d) {
    // check for ISO 8601 date-time string (seconds and fractional part are optional)
    if (d.search(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(?::\d{2}(?:\.\d{1-3})?)?$/) == 0) {
        var pad = function (num) {
            norm = Math.abs(Math.floor(num));
            return (norm < 10 ? '0' : '') + norm;
        },
        tzo = -new Date(d).getTimezoneOffset(),
        sign = tzo >= 0 ? '+' : '-';

        var adjusted = d + sign + pad(tzo / 60) + ':' + pad(tzo % 60);

        // check whether timezone offsets are equal;
        // if not then the specified date is just within the hour when the clock
        // has been turned forward or back
        if (-new Date(adjusted).getTimezoneOffset() != tzo) {
            // re-adjust
            tzo -= 60;
            adjusted = d + sign + pad(tzo / 60) + ':' + pad(tzo % 60);
        }

        return adjusted;
    } else {
        return d;
    }
}

parseDate = function (/*String*/ d) {
    return new Date(appendTimezone(d));
}
```


问:
Detect which attributes were called in `update` in rails
Is it possible to detect which attributes were included in an update call in rails even if those attributes don't change?  The after_update callback is still called but since nothing has actually changed ActiveModel::Dirty doesn't seem to have any methods that will detect the relevant attributes.

Example:

I have a user model which has column notification_hour which defaults to 9

I call User.update(notification_hour: 9)

This triggers the callback
after_update :set_time_flag

I would like to set that the user has at least set the time even though they've set it to the same as the default.

```<code>def set_time_flag
  return unless notification_hour_changed?

  update_column(notifiation_time_set: true)
end
</code>```

This will return without setting the flag since the value didn't change.  Is there a way to detect that update was called with notification_hour even though it didn't actually change?

答:
When you update a record, it executes a setter method for each attribute being updated.

update(notification_hour: 9) will execute notification_hour=(9)

So, you can play with it. Just overload the method to detect if the attribute was set:

```<code>after_update :set_time_flag

def notification_hour=(hour)
  @notification_hour_was_set = true
  super
end

private

def set_time_flag
  if @notification_hour_was_set
      update_column(notifiation_time_set: true)
  end
end
</code>```

Updated

SteveTurczyn's answer gave me the better idea. You don't really need the after_update callback and extra update. Just set notifiation_time_set to true when notification_hour is set:

```<code>def notification_hour=(hour)
  self.notification_time_set = true
  super
end
</code>```

Body:
Is it possible to detect which attributes were included in an update call in rails even if those attributes don't change?  The after_update callback is still called but since nothing has actually changed ActiveModel::Dirty doesn't seem to have any methods that will detect the relevant attributes.

Example:

I have a user model which has column notification_hour which defaults to 9

I call User.update(notification_hour: 9)

This triggers the callback
after_update :set_time_flag

I would like to set that the user has at least set the time even though they've set it to the same as the default.

def set_time_flag
  return unless notification_hour_changed?

  update_column(notifiation_time_set: true)
end

This will return without setting the flag since the value didn't change.  Is there a way to detect that update was called with notification_hour even though it didn't actually change?

Body:
When you update a record, it executes a setter method for each attribute being updated.

update(notification_hour: 9) will execute notification_hour=(9)

So, you can play with it. Just overload the method to detect if the attribute was set:

after_update :set_time_flag

def notification_hour=(hour)
  @notification_hour_was_set = true
  super
end

private

def set_time_flag
  if @notification_hour_was_set
      update_column(notifiation_time_set: true)
  end
end

Updated

SteveTurczyn's answer gave me the better idea. You don't really need the after_update callback and extra update. Just set notifiation_time_set to true when notification_hour is set:

def notification_hour=(hour)
  self.notification_time_set = true
  super
end


问:
Can scripts adapt to state changes on custom controls by accessibility clients?
From WCAG 2.0 section 4.1:

4.1.2 Name, Role, Value: For all user interface components (including but not limited to: form elements, links and components generated by scripts), the name and role can be programmatically determined; states, properties, and values that can be set by the user can be programmatically set; and notification of changes to these items is available to user agents, including assistive technologies.

(Emphasis mine.)

Does this mean that user agents may directly add, remove or alter relevant aria-* states and value attributes, essentially altering the DOM state? If so, how would a script (e.g. a React app) maintain consistent state? Would events be fired to indicate that a change occurred?

答:
Does this mean that user agents may directly add, remove or alter relevant aria-* states and value attributes, essentially altering the DOM state?

No. User agents do not do this on their own.

It is up to the developer to assign these ARIA values and to maintain and adjust them as the user interacts with the page (or as the page does its own thing).

ARIA is a stop-gap (think of ARIA tabs and the proposed tabpanel — ARIA is the stopgap until/if that element gets implemented) to allow developers to make unique interface components while conveying useful information to user agents (which pass it along to screen readers).

So if you have a control that expands or collapses, it is up to you to first add the aria-expanded attribute to the control, then to add the true or false state, and then to toggle that value each time the control expands or collapses (whether by direct user action or some timed or other process).

The browser has no way of knowing that your thing is doing the thing nor that you want it to report as a thing with a state of... thing.

If so, how would a script (e.g. a React app) maintain consistent state? Would events be fired to indicate that a change occurred?

React, Angular, etc. already have methods that convey state. It is up to you as the developer to push those into the appropriate ARIA attributes where appropriate and manage them.


问:
Get .txt file from the available .pgp file(Data) and .asc file(Key)
Using Python 2.17.12, Pycharm and Linux Ubuntu

Want to know how can I decrypt .pgp file to .txt file, using a key(.asc file) in Python Script.

Able to do it in python command line, but want to write a script for it.

答:
```<code>import gnupg

gpg = gnupg.GPG(gnupghome='/path/to/directory')
</code>```

imported key

```<code>key_to_import = '.asc key file'
key_data = open(key_to_import).read()
import_result = gpg.import_keys(key_data)
</code>```

decrypt File

```<code>with open('.pgp file name', 'rb') as f:
    status = gpg.decrypt_file(f,passphrase='**appropriate_one**', output='.txt file name')
</code>```

check status

```<code>print 'ok: ', status.ok
print 'status: ', status.status
print 'stderr: ', status.stderr
</code>```

Worked for me, might help someone else.

Body:
import gnupg

gpg = gnupg.GPG(gnupghome='/path/to/directory')

imported key

key_to_import = '.asc key file'
key_data = open(key_to_import).read()
import_result = gpg.import_keys(key_data)

decrypt File

with open('.pgp file name', 'rb') as f:
    status = gpg.decrypt_file(f,passphrase='**appropriate_one**', output='.txt file name')

check status

print 'ok: ', status.ok
print 'status: ', status.status
print 'stderr: ', status.stderr

Worked for me, might help someone else.


问:
DB2 SELECT FOR UPDATE with INNER JOIN
I am trying to work out a DB2 Issue. I make an update based on a previous Select and occasionally encounter Deadlocks when two transactions run the select in parallel and none of them is able to update afterwards.

So I am trying to solve this using Select For Update, but apparently, Select For Update does not work with inner join, is that correct? And is there a way around it?

Here's my Select Statement

```<code>SELECT s.ID FROM DATA.TABLE_A s
    INNER JOIN DATA.TABLE_B n ON s.ID = n.ID
    WHERE n.N_ID = ?
        AND n.N_TYPE = ?
        AND n.PN_ID = ?
        AND n.PN_TYPE = ?
        AND n.RN_ID = ?
        AND s.P_ID = ?
        AND s.C_ID = ?
FOR UPDATE
</code>```

答:
Have you tried the following, means specify WITH RS (Read Stability) in your select statement:

```<code>SELECT ....(
............
) FOR UPDATE WITH RS USE AND KEEP UPDATE LOCKS
</code>```

Title: DB2 SELECT FOR UPDATE with INNER JOIN

Body:
I am trying to work out a DB2 Issue. I make an update based on a previous Select and occasionally encounter Deadlocks when two transactions run the select in parallel and none of them is able to update afterwards.

So I am trying to solve this using Select For Update, but apparently, Select For Update does not work with inner join, is that correct? And is there a way around it?

Here's my Select Statement

SELECT s.ID FROM DATA.TABLE_A s
    INNER JOIN DATA.TABLE_B n ON s.ID = n.ID
    WHERE n.N_ID = ?
        AND n.N_TYPE = ?
        AND n.PN_ID = ?
        AND n.PN_TYPE = ?
        AND n.RN_ID = ?
        AND s.P_ID = ?
        AND s.C_ID = ?
FOR UPDATE

Body:
Have you tried the following, means specify WITH RS (Read Stability) in your select statement:

SELECT ....(
............
) FOR UPDATE WITH RS USE AND KEEP UPDATE LOCKS


问:
display label next to icon in Google Maps KML
I am using KML with the Google Maps API.  The KML is used to display Mile Markers on interstates (see screenshot):

A snippet of the KML:

```<code><?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
   <Document>
      <Style id="randomLabelColor">
         <LabelStyle>
            <color>ff0000cc</color>
            <colorMode>random</colorMode>
            <scale>1.5</scale>
         </LabelStyle>
      </Style>
      <Placemark>
         <name>17</name>
         <styleUrl>#randomLabelColor</styleUrl>
         <description>I-684 MM NORTHBOUND: 17</description>
         <Style>
            <IconStyle>
               <Icon>
                  <href>http://www.xxxx.com/images/mapicons/milemarker.png</href>
               </Icon>
            </IconStyle>
         </Style>
         <Point>
            <coordinates>-73.67661,41.25393</coordinates>
         </Point>
      </Placemark>
   </Document>
</kml>
</code>```

I realize clicking the Mile Marker icon will display a callout with the name and description.  But is it possible to have a label drawn on the map next to the icon?  I would like to put the numeric mile marker on the map (e.g. 17)

Or instead of KML do I need to use javascript and create markers?

答: I've been looking for an answer to the same question. Going over the Google Maps API "KML and GeoRSS Layers" guide I noticed that the <LabelStyle> element is not supported.

Body:
I am using KML with the Google Maps API.  The KML is used to display Mile Markers on interstates (see screenshot):

A snippet of the KML:

<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
   <Document>

      <Placemark>
         <name>17</name>

         <description>I-684 MM NORTHBOUND: 17</description>

         <Point>
            <coordinates>-73.67661,41.25393</coordinates>
         </Point>
      </Placemark>
   </Document>
</kml>

I realize clicking the Mile Marker icon will display a callout with the name and description.  But is it possible to have a label drawn on the map next to the icon?  I would like to put the numeric mile marker on the map (e.g. 17)

Or instead of KML do I need to use javascript and create markers?


问:
How to detach shell from erlang process?
I want to detach shell from erlang process without closing process. Does exist function like halt() or q() but for detaching shell? I tried to use Ctrl+D but it doesn't work, i use ssh maybe problem in that

--------Update --------------

I run my rebar3 release with command "bin/timeio start", sometimes i need to execute commands in that process from shell then I connecting to that process with rebar3 release command "bin/timeio attach" (it is simple erlang shell, I assume) but i can't detach from process

答:
CTRL-D should get you out and keep the app running. when you "attach" you are doing the same thing as running to_erl. To exit in from this you type control-D.,</p>

```<code> bin ⚑ ◒  → ./otto attach                                                                                master ✗ 83d
Attaching to /tmp/erl_pipes/otto@127.0.0.1/erlang.pipe.1 (^D to exit)

(otto@127.0.0.1)1> [Quit]
 bin ⚑ ◒  → ./otto attach                                                                                master ✗ 83d
Attaching to /tmp/erl_pipes/otto@127.0.0.1/erlang.pipe.1 (^D to exit)

(otto@127.0.0.1)1> [Quit]
 bin ⚑ ◒  → ./otto attach                                                                                master ✗ 83d
Attaching to /tmp/erl_pipes/otto@127.0.0.1/erlang.pipe.1 (^D to exit)

(otto@127.0.0.1)1> [Quit]
 bin ⚑ ◒  →                                                                                master ✗ 83d
</code>```

Body:
CTRL-D should get you out and keep the app running. when you "attach" you are doing the same thing as running to_erl. To exit in from this you type control-D.,

 bin ⚑ ◒  → ./otto attach                                                                                master ✗ 83d
Attaching to /tmp/erl_pipes/otto@127.0.0.1/erlang.pipe.1 (^D to exit)

(otto@127.0.0.1)1> [Quit]
 bin ⚑ ◒  → ./otto attach                                                                                master ✗ 83d
Attaching to /tmp/erl_pipes/otto@127.0.0.1/erlang.pipe.1 (^D to exit)

(otto@127.0.0.1)1> [Quit]
 bin ⚑ ◒  → ./otto attach                                                                                master ✗ 83d
Attaching to /tmp/erl_pipes/otto@127.0.0.1/erlang.pipe.1 (^D to exit)

(otto@127.0.0.1)1> [Quit]
 bin ⚑ ◒  →                                                                                master ✗ 83d


问:
How do I undo the most recent local commits in Git?
I accidentally committed the wrong files to Git, but didn't push the commit to the server yet.

How do I undo those commits from the local repository?

答:
Reference: How to undo last commit in Git?

If you have Git Extensions installed you can easily undo/revert any commit (you can download Git Extensions from here).

Open Git Extensions, right click on the commit you want to revert then select "Revert commit".

A popup will be opened (see the screenshot below)

Select "Automatically create a commit" if you want to directly commit the reverted changes or if you want to manually commit the reverted changes keep the box un-selected and click on "Revert this commit" button.

ContentLicense: CC BY-SA 4.0


问:
Regex to check if the user submitted price is really a valid price
I'm trying to create a regex code to match a price with or without a dollar sign $, and with or without a comma or decimal point.

The following prices should be valid.

```<code>$1
$5.00
$.10
$.07
$03 //this should be interpreted as $0.03 in case if you are confused
$10,000
$10,000.00

1
5.00
.10
.07
03 //this should be interpreted as $0.03 in case if you are confused
10,000
10,000.00
</code>```

Here is my code so far:

```<code>preg_match('/^([1-9][0-9]*|0)(\.[0-9]{2})?$/', $price)
</code>```

答:
You can use this regex -

```<code>^\$?(?:(?:\d+(?:,\d+)?(?:\.\d+)?)|(?:\.\d+))$
</code>```

Here's a demo, which also explains it.

Note that I've added 03 and .03 as separate entries. This regex will just match them.

Body:
I'm trying to create a regex code to match a price with or without a dollar sign $, and with or without a comma or decimal point.

The following prices should be valid.

$1
$5.00
$.10
$.07
$03 //this should be interpreted as $0.03 in case if you are confused
$10,000
$10,000.00

1
5.00
.10
.07
03 //this should be interpreted as $0.03 in case if you are confused
10,000
10,000.00

Here is my code so far:

preg_match('/^([1-9][0-9]*|0)(\.[0-9]{2})?$/', $price)

Body:
You can use this regex -

^\$?(?:(?:\d+(?:,\d+)?(?:\.\d+)?)|(?:\.\d+))$

Here's a demo, which also explains it.

Note that I've added 03 and .03 as separate entries. This regex will just match them.


问:
casting exception
```<code>Set cust = customer.getCustomerBills();
Iterator<Customer> seriter = (Iterator)cust;
</code>```

I am facing a casting exception when I iterate on Set.

Exception is: org.hibernate.collection.PersistentSet cannot be cast to java.util.Iterator. What am I doing wrong?

答:
Iterator seriter = (Iterator)cust;
is not a proper casting so an exception is being thrown.

use Iterator seriter = cust.iterator();

Title: casting exception

Body:
Set cust = customer.getCustomerBills();
Iterator<Customer> seriter = (Iterator)cust;

I am facing a casting exception when I iterate on Set.

Exception is: org.hibernate.collection.PersistentSet cannot be cast to java.util.Iterator. What am I doing wrong?