问:
Color keying video with GPUImage on a SCNPlane in ARKit
I am trying to play a video, showing transparency in an ARSCNView. A SCNPlane is used as a projection space for the video and I am trying to color key this video with GPUImage.

I followed this example here. Unfortunately, I have not found a way to project that video back on my videoSpriteKitNode. Because the filter is rendered in a GPUImageView, and the SKVideoNode takes a AVPlayer.

I am not sure if it is possible at all, what I am trying to do, so if anyone could share their insight I'd be very thankful!

```<code>import UIKit
import ARKit
import GPUImage

class ARTransVC: UIViewController{

@IBOutlet weak var sceneView: ARSCNView!
let configuration = ARWorldTrackingConfiguration()
var movie: GPUImageMovie!
var filter: GPUImageChromaKeyBlendFilter!
var sourcePicture: GPUImagePicture!
var player = AVPlayer()
var gpuImageView: GPUImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints]
    self.sceneView.session.run(configuration)

    self.gpuImageView = GPUImageView()
    self.gpuImageView.translatesAutoresizingMaskIntoConstraints = false

    //a delay for ARKit to capture the surroundings
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {

        // A SpriteKit scene to contain the SpriteKit video node
        let spriteKitScene = SKScene(size: CGSize(width: self.sceneView.frame.width, height: self.sceneView.frame.height))
        spriteKitScene.scaleMode = .aspectFit

        // Create a video player, which will be responsible for the playback of the video material
        guard let url = Bundle.main.url(forResource: "FY3A4278", withExtension: "mp4") else { return }
        let playerItem = AVPlayerItem(url: url)
        self.player.replaceCurrentItem(with: playerItem)

        //trans
        self.filter = GPUImageChromaKeyBlendFilter()
        self.filter.thresholdSensitivity = 0.15
        self.filter.smoothing = 0.3
        self.filter.setColorToReplaceRed(0.322, green: 0.455, blue: 0.831)

        self.movie = GPUImageMovie(playerItem: playerItem)
        self.movie.playAtActualSpeed = true
        self.movie.addTarget(self.filter)
        self.movie.startProcessing()

        let backgroundImage = UIImage(named: "transparent.png")
        self.sourcePicture = GPUImagePicture(image: backgroundImage, smoothlyScaleOutput: true)!
        self.sourcePicture.addTarget(self.filter)
        self.sourcePicture.processImage()

        ///HERE DON'T KNOW HOW TO CONTINUE ?
        self.filter.addTarget(self.gpuImageView)

        // To make the video loop
        self.player.actionAtItemEnd = .none
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ARTransVC.playerItemDidReachEnd),
            name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
            object:  self.player.currentItem)

        // Create the SpriteKit video node, containing the video player
        let videoSpriteKitNode = SKVideoNode(avPlayer: self.player)
        videoSpriteKitNode.position = CGPoint(x: spriteKitScene.size.width / 2.0, y: spriteKitScene.size.height / 2.0)
        videoSpriteKitNode.size = spriteKitScene.size
        videoSpriteKitNode.yScale = -1.0
        videoSpriteKitNode.play()
        spriteKitScene.addChild(videoSpriteKitNode)

        // Create the SceneKit scene
        let scene = SCNScene()
        self.sceneView.scene = scene
        self.sceneView.isPlaying = true

        // Create a SceneKit plane and add the SpriteKit scene as its material
        let background = SCNPlane(width: CGFloat(1), height: CGFloat(1))
        background.firstMaterial?.diffuse.contents = spriteKitScene
        let backgroundNode = SCNNode(geometry: background)
        backgroundNode.geometry?.firstMaterial?.isDoubleSided = true

        backgroundNode.position = SCNVector3(0,0,-2.0)
        scene.rootNode.addChildNode(backgroundNode)
    }
}

@objc func playerItemDidReachEnd(notification: NSNotification) {
    if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
        playerItem.seek(to: kCMTimeZero, completionHandler: nil)
    }
}
}
</code>```

答:
try clearing the background and set the scalemode with</p>

```<code>backgroundColor = .clear
scaleMode = .aspectFit
</code>```

Body:
I am trying to play a video, showing transparency in an ARSCNView. A SCNPlane is used as a projection space for the video and I am trying to color key this video with GPUImage.

I followed this example here. Unfortunately, I have not found a way to project that video back on my videoSpriteKitNode. Because the filter is rendered in a GPUImageView, and the SKVideoNode takes a AVPlayer.

I am not sure if it is possible at all, what I am trying to do, so if anyone could share their insight I'd be very thankful!

import UIKit
import ARKit
import GPUImage

class ARTransVC: UIViewController{

@IBOutlet weak var sceneView: ARSCNView!
let configuration = ARWorldTrackingConfiguration()
var movie: GPUImageMovie!
var filter: GPUImageChromaKeyBlendFilter!
var sourcePicture: GPUImagePicture!
var player = AVPlayer()
var gpuImageView: GPUImageView!

override func viewDidLoad() {
    super.viewDidLoad()
    self.sceneView.debugOptions = [ARSCNDebugOptions.showWorldOrigin, ARSCNDebugOptions.showFeaturePoints]
    self.sceneView.session.run(configuration)

    self.gpuImageView = GPUImageView()
    self.gpuImageView.translatesAutoresizingMaskIntoConstraints = false

    //a delay for ARKit to capture the surroundings
    DispatchQueue.main.asyncAfter(deadline: .now() + 3) {

        // A SpriteKit scene to contain the SpriteKit video node
        let spriteKitScene = SKScene(size: CGSize(width: self.sceneView.frame.width, height: self.sceneView.frame.height))
        spriteKitScene.scaleMode = .aspectFit

        // Create a video player, which will be responsible for the playback of the video material
        guard let url = Bundle.main.url(forResource: "FY3A4278", withExtension: "mp4") else { return }
        let playerItem = AVPlayerItem(url: url)
        self.player.replaceCurrentItem(with: playerItem)

        //trans
        self.filter = GPUImageChromaKeyBlendFilter()
        self.filter.thresholdSensitivity = 0.15
        self.filter.smoothing = 0.3
        self.filter.setColorToReplaceRed(0.322, green: 0.455, blue: 0.831)

        self.movie = GPUImageMovie(playerItem: playerItem)
        self.movie.playAtActualSpeed = true
        self.movie.addTarget(self.filter)
        self.movie.startProcessing()

        let backgroundImage = UIImage(named: "transparent.png")
        self.sourcePicture = GPUImagePicture(image: backgroundImage, smoothlyScaleOutput: true)!
        self.sourcePicture.addTarget(self.filter)
        self.sourcePicture.processImage()

        ///HERE DON'T KNOW HOW TO CONTINUE ?
        self.filter.addTarget(self.gpuImageView)

        // To make the video loop
        self.player.actionAtItemEnd = .none
        NotificationCenter.default.addObserver(
            self,
            selector: #selector(ARTransVC.playerItemDidReachEnd),
            name: NSNotification.Name.AVPlayerItemDidPlayToEndTime,
            object:  self.player.currentItem)

        // Create the SpriteKit video node, containing the video player
        let videoSpriteKitNode = SKVideoNode(avPlayer: self.player)
        videoSpriteKitNode.position = CGPoint(x: spriteKitScene.size.width / 2.0, y: spriteKitScene.size.height / 2.0)
        videoSpriteKitNode.size = spriteKitScene.size
        videoSpriteKitNode.yScale = -1.0
        videoSpriteKitNode.play()
        spriteKitScene.addChild(videoSpriteKitNode)

        // Create the SceneKit scene
        let scene = SCNScene()
        self.sceneView.scene = scene
        self.sceneView.isPlaying = true

        // Create a SceneKit plane and add the SpriteKit scene as its material
        let background = SCNPlane(width: CGFloat(1), height: CGFloat(1))
        background.firstMaterial?.diffuse.contents = spriteKitScene
        let backgroundNode = SCNNode(geometry: background)
        backgroundNode.geometry?.firstMaterial?.isDoubleSided = true

        backgroundNode.position = SCNVector3(0,0,-2.0)
        scene.rootNode.addChildNode(backgroundNode)
    }
}

@objc func playerItemDidReachEnd(notification: NSNotification) {
    if let playerItem: AVPlayerItem = notification.object as? AVPlayerItem {
        playerItem.seek(to: kCMTimeZero, completionHandler: nil)
    }
}
}

Body:
try clearing the background and set the scalemode with

backgroundColor = .clear
scaleMode = .aspectFit


来源: stackexchange

问:
Snippet tool that is used in WWDC2010 videos
Does anyone know the code snippet tool that was used in some of the WWDC2010 videos?

It seems that the the tool allows us to create snippets of code which can be labeled.  This tool also allow us to click and drag the label to Xcode code editor window to paste the code with the formatting intact.

Any lead on this tool/utility?

答: I think you're looking for DemoMonkey. I can't get the cool eskimo icon they have, though.</p>

ContentLicense: CC BY-SA 2.5


问:
Should I copy appsetting.json to coutput directory in order to update configuration after dotnet publish
I just want to update appsetting.json after dotnet webapi published.
should I use appsetting.json to do this?</p>

答:
I think you can just left it where it is at the project folder.  in asp.net core 2.0, you do not need to do anything about its location or add the file in code.

In test environment, you need to find the appsetting.json file in code.  I can post the code here if you need which I modified from Microsoft Docs.

ContentLicense: CC BY-SA 3.0


问:
API - Isolating returned JSON keys and values within indexed objects
Building a web app using a flight data API and, welp, the struggle is real.

My returned array and it's objects look something like this:

```<code>results:

0:{destination: "YTO",
departure_date: "2018-01-24",
return_date: "2018-01-25"
airline: "TS"}

1:{destination: "BOS",
departure_date: "2018-01-08",
return_date: "2018-01-11",
airline: "AC"}

2:{destination: "SJU",
departure_date: "2018-01-31",
return_date: "2018-02-01",
airline: "AA"}
</code>```

Before I can dump the results into the DOM to display them to the visitor of the site, I need to run certain returned values through an additional API (long story) so I obviously need to isolate them somehow.

For this example, I'm using destination so my initial thought process is start by to logging out:

```<code>console.log(response.results[0].destination);
</code>```

Which we know will print the FIRST destination in the FIRST object, since [0] is the index of that object (so in this case in this case we get back YTO).

Since every returned object has an index number, I think I need to loop through them (for each?) to pull the values I need but I'm trying variations of that with no luck.....or for all I know it's something else entirely.

(your two cents goes here)

答:
forEach works for arrays.
try using for loop

for(let key in response.results){
  console.log(response.results[key].destination);
}```

Body:
Building a web app using a flight data API and, welp, the struggle is real.

My returned array and it's objects look something like this:

results:

0:{destination: "YTO",
departure_date: "2018-01-24",
return_date: "2018-01-25"
airline: "TS"}

1:{destination: "BOS",
departure_date: "2018-01-08",
return_date: "2018-01-11",
airline: "AC"}

2:{destination: "SJU",
departure_date: "2018-01-31",
return_date: "2018-02-01",
airline: "AA"}

Before I can dump the results into the DOM to display them to the visitor of the site, I need to run certain returned values through an additional API (long story) so I obviously need to isolate them somehow.

For this example, I'm using destination so my initial thought process is start by to logging out:

console.log(response.results[0].destination);

Which we know will print the FIRST destination in the FIRST object, since [0] is the index of that object (so in this case in this case we get back YTO).

Since every returned object has an index number, I think I need to loop through them (for each?) to pull the values I need but I'm trying variations of that with no luck.....or for all I know it's something else entirely.

(your two cents goes here)


问:
How can I build a better SPARQL query, to get only the data I want from DBpedia? (was: "How to get rid of multiple rows with DBPEDIA SPARQL")

I run from SPARQL Explorer at DBpedia. I wish to get each President only once, but as some of them have multiple entries for birthplace it gives multiple rows.

```<code>SELECT DISTINCT ?person ?birthPlace  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.
      ?person dbo:birthPlace ?birthPlace .

       OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
       OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .

FILTER ( regex(?birthPlace,   "_")  OR
         regex(?birthPlace, ";_")
       ) .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100
</code>```

I would like to have only the STATE where they are born.

```<code>:Abraham_Lincoln [http] :Hodgenville,_Kentucky [http]   -   -
:Barack_Obama [http]    :Kapiolani_Medical_Center_for_Women_and_Children [http] -   -
:Bill_Clinton [http]    :Hope,_Arkansas [http]  -   -
:Dwight_D._Eisenhower [http]    :Denison,_Texas [http]  -   -
:George_W._Bush [http]  :New_Haven,_Connecticut [http]  -   -
:George_Washington [http]   :Westmoreland_County,_Virginia [http]   -   -
:George_Washington [http]   :British_America [http] -   -
:George_Washington [http]   :George_Washington_Birthplace_National_Monument [http]  -   -
:James_A._Garfield [http]   :Orange,_Ohio [http]    -   -
:James_A._Garfield [http]   :Moreland_Hills,_Ohio [http]    -   -
:Jimmy_Carter [http]    :Plains,_Georgia
</code>```

答:
As SPARQL is a pattern matching language, the trick, when your query result is "too broad/general", is to create a more specific pattern. In this case, your intent is not just to get back all resources that are marked as dbo:birthPlace values, but only those resources that represent U.S. states.

So we need to figure out how U.S. states are distinguished from other locations in DBPedia.

Let's take Kentucky as an example. The resource representing Kentucky is http://dbpedia.org/resource/Kentucky . If we scroll down the page outlining the properties of that resource, we find multiple entries for the rdf:type relation, but the one that jumps out at me as most suitable is yago:WikicatStatesOfTheUnitedStates (http://dbpedia.org/class/yago/WikicatStatesOfTheUnitedStates).

If we modify your query to put that in as an extra restriction, and drop the weird regular expression, like so:

```<code>SELECT DISTINCT ?person ?birthPlace  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.
      ?person dbo:birthPlace ?birthPlace .
      ?birthPlace a yago:WikicatStatesOfTheUnitedStates .

   OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
   OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100
</code>```

You should get what you need.

Unfortunately, if you try, you find that you don't. This is because DBPedia data is messy. The above query only returns three results, and worse, one result is clearly incorrect:

```<code>person                 birthPlace   presidentStart  presidentEnd
dbr:Barack_Obama       dbr:Hawaii
dbr:George_Washington  dbr:Virginia
dbr:Theodore_Roosevelt dbr:New_York_City
</code>```

There's two things going on here: first of all, New York City is incorrectly classified as a state in DBPedia. Secondly, most presidents do not explicitly have their state marked as their birthplace, but only things like their home town.

Fortunately, we can amend slightly. DBPedia knows that HodgenVille, Kentucky, is located in Kentucky. How does it know? Well, have a look at the resource page for Hodgenville: http://dbpedia.org/resource/Hodgenville,_Kentucky . You'll see that it has a dbo:isPartOf relation with the resource representing the state of Kentucky.

So, we need to rephrase our query again: we want the state for each president where their birthplace is part of that state. In SPARQL:

```<code>SELECT DISTINCT ?person ?birthState  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.
      ?person dbo:birthPlace ?birthPlace .
      ?birthPlace dbo:isPartOf ?birthState .
      ?birthState a yago:WikicatStatesOfTheUnitedStates .

   OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
   OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100
</code>```

This should get you almost completely the result you need.

Update as you noted, Donald Trump is missing from the list. This looks to be because DBPedia is behind the times, and he's still classified as a "presidential candidate" rather than a president.

As for Grover Cleveland appearing four times, this is an interesting anomaly. Cleveland served two non-consecutive terms as president, from 1885 to 1889, and again from 1893 to 1897. So there's two start dates, and two end dates. Because in DBPeda it is not explicitly modeled which start date belongs to which end date, you simply get a result for each combination of start and end dates, four in total. There may be a way to query around this (one option would be to group start and end dates together using a group_concat aggregate), but it's such an edge case that it might be simpler to just handle it in post-processing.

Body:
I run from SPARQL Explorer at DBpedia. I wish to get each President only once, but as some of them have multiple entries for birthplace it gives multiple rows.

SELECT DISTINCT ?person ?birthPlace  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.
      ?person dbo:birthPlace ?birthPlace .

       OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
       OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .

FILTER ( regex(?birthPlace,   "_")  OR
         regex(?birthPlace, ";_")
       ) .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100

I would like to have only the STATE where they are born.

:Abraham_Lincoln [http] :Hodgenville,_Kentucky [http]   -   -
:Barack_Obama [http]    :Kapiolani_Medical_Center_for_Women_and_Children [http] -   -
:Bill_Clinton [http]    :Hope,_Arkansas [http]  -   -
:Dwight_D._Eisenhower [http]    :Denison,_Texas [http]  -   -
:George_W._Bush [http]  :New_Haven,_Connecticut [http]  -   -
:George_Washington [http]   :Westmoreland_County,_Virginia [http]   -   -
:George_Washington [http]   :British_America [http] -   -
:George_Washington [http]   :George_Washington_Birthplace_National_Monument [http]  -   -
:James_A._Garfield [http]   :Orange,_Ohio [http]    -   -
:James_A._Garfield [http]   :Moreland_Hills,_Ohio [http]    -   -
:Jimmy_Carter [http]    :Plains,_Georgia

Body:
As SPARQL is a pattern matching language, the trick, when your query result is "too broad/general", is to create a more specific pattern. In this case, your intent is not just to get back all resources that are marked as dbo:birthPlace values, but only those resources that represent U.S. states.

So we need to figure out how U.S. states are distinguished from other locations in DBPedia.

Let's take Kentucky as an example. The resource representing Kentucky is http://dbpedia.org/resource/Kentucky . If we scroll down the page outlining the properties of that resource, we find multiple entries for the rdf:type relation, but the one that jumps out at me as most suitable is yago:WikicatStatesOfTheUnitedStates (http://dbpedia.org/class/yago/WikicatStatesOfTheUnitedStates).

If we modify your query to put that in as an extra restriction, and drop the weird regular expression, like so:

SELECT DISTINCT ?person ?birthPlace  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.
      ?person dbo:birthPlace ?birthPlace .
      ?birthPlace a yago:WikicatStatesOfTheUnitedStates .

   OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
   OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100

You should get what you need.

Unfortunately, if you try, you find that you don't. This is because DBPedia data is messy. The above query only returns three results, and worse, one result is clearly incorrect:

person                 birthPlace   presidentStart  presidentEnd
dbr:Barack_Obama       dbr:Hawaii
dbr:George_Washington  dbr:Virginia
dbr:Theodore_Roosevelt dbr:New_York_City

There's two things going on here: first of all, New York City is incorrectly classified as a state in DBPedia. Secondly, most presidents do not explicitly have their state marked as their birthplace, but only things like their home town.

Fortunately, we can amend slightly. DBPedia knows that HodgenVille, Kentucky, is located in Kentucky. How does it know? Well, have a look at the resource page for Hodgenville: http://dbpedia.org/resource/Hodgenville,_Kentucky . You'll see that it has a dbo:isPartOf relation with the resource representing the state of Kentucky.

So, we need to rephrase our query again: we want the state for each president where their birthplace is part of that state. In SPARQL:

SELECT DISTINCT ?person ?birthState  ?presidentStart ?presidentEnd
WHERE {
      ?person dct:subject dbc:Presidents_of_the_United_States.
      ?person dbo:birthPlace ?birthPlace .
      ?birthPlace dbo:isPartOf ?birthState .
      ?birthState a yago:WikicatStatesOfTheUnitedStates .

   OPTIONAL { ?person dbp:presidentEnd   ?presidentEnd }  .
   OPTIONAL { ?person dbp:presidentStart ?presidentStart }  .
}
GROUP BY ?person
ORDER BY  ?presidentStart ?person
LIMIT 100

This should get you almost completely the result you need.

Update as you noted, Donald Trump is missing from the list. This looks to be because DBPedia is behind the times, and he's still classified as a "presidential candidate" rather than a president.

As for Grover Cleveland appearing four times, this is an interesting anomaly. Cleveland served two non-consecutive terms as president, from 1885 to 1889, and again from 1893 to 1897. So there's two start dates, and two end dates. Because in DBPeda it is not explicitly modeled which start date belongs to which end date, you simply get a result for each combination of start and end dates, four in total. There may be a way to query around this (one option would be to group start and end dates together using a group_concat aggregate), but it's such an edge case that it might be simpler to just handle it in post-processing.


问:
ExtJs best practices
it seems that most ExtJS books and ExtJS introductions just focus on showing all the nice features but most of them don't really explain how to build stable, maintainable layouts / applications with ExtJS. And how to write them without creating an unreadable mess...

I've no specific application in mind, I'm just wondering how I can "beatify" my ExtJS code. So if you need an example, a "regular" application for item management (library) or something like a job board would best describe what I was thinking of.

So can anyone share some good links or advices on how to structure such applications when I want to build them with ExtJS for the client side code?

Thanks in advance,
Cheers

答:
Useful links:

API documentation - really useful

Tutorials - official tuts

Screencasts - by real-world ExtJS users

Community manual

ExtJS override

ExtJS forum - user apps thread

Title: ExtJs best practices


问:
How to save many has_many_through objects in one form with Rails?
I'm working on an app where I have two Tables that have a many-to-many relationship, joined in the middle by a join table.

Stadium model:

```<code>class Stadium < ActiveRecord::Base

has_many :stadiumteams
has_many :teams, :through => :stadiumteams
</code>```

Team model:

```<code>class Team < ActiveRecord::Base
    has_many :stadiumteams
    has_many :stadiums, :through => :stadiumteams
end
</code>```

StadiumTeam model (the jointable):

```<code>class StadiumTeam < ActiveRecord::Base
belongs_to :stadium
belongs_to :team
end
</code>```

When I create a new Stadium I want to be able to select one or multiple teams that are associated with a stadium and save the relationship to the join-table (stadiumteams).

Here's the create action form the Stadiums Controller.

```<code>  def create
    @stadium = current_user.stadiums.build(stadium_params)

    respond_to do |format|
      if @stadium.save
         teams = Team.where(:id => params[:team])
         teams.each {|team| @stadium.teams << team}

        format.html { redirect_to @stadium, notice: 'Stadium was successfully created.' }
        format.json { render :show, status: :created, location: @stadium }
      else
        format.html { render :new }
        format.json { render json: @stadium.errors, status: :unprocessable_entity }
      end
    end
  end
</code>```

When I try to create a new Stadium I get this output from the terminal.

```<code>  Parameters: {"utf8"=>"✓", "authenticity_token"=>"m+HAw4LRPmozIkigzuB/SFdcAFPTL735n6FyavH0SwjGXl7NHCLmDCXMTvx8bVixz+sL7tfn1zzCl04Q+w6Pdw==", "stadium"=>{"name"=>"Friends Arena", "capacity"=>"100000", "surface"=>"", "official_opening_date(1i)"=>"2017", "official_opening_date(2i)"=>"12", "official_opening_date(3i)"=>"4", "cost"=>"10000", "web_url"=>"teststadium.com", "record_attendance"=>"999790", "city"=>"", "country"=>"", "location_name"=>"", "longitude"=>"", "latitude"=>"", "address"=>"Friends Arena, Solna, Sweden"}, "team_id"=>"3", "commit"=>"Create Stadium"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (0.2ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "stadiums" ("name", "capacity", "city", "country", "location_name", "address", "surface", "cost", "web_url", "record_attendance", "official_opening_date", "user_id", "latitude", "longitude", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["name", "Friends Arena"], ["capacity", 100000], ["city", "Solna"], ["country", "Sweden"], ["location_name", ""], ["address", "Friends Arena, Solna, Sweden"], ["surface", ""], ["cost", 10000.0], ["web_url", "teststadium.com"], ["record_attendance", 999790], ["official_opening_date", "2017-12-04"], ["user_id", 1], ["latitude", 59.3727005], ["longitude", 18.0002317], ["created_at", "2017-12-04 13:18:45.841931"], ["updated_at", "2017-12-04 13:18:45.841931"]]
   (2.8ms)  commit transaction
</code>```

It seems like "team_id"=>"3"" is added as a parameter but it's not inserted into any table. And I can't output the relationship between Stadiums and Teams in any way right now.

What I want to accomplish is to be able to show all Teams that are associated with Stadium on the Stadium show page. And all Stadiums that are associated with a Team on the teams Show page.

Any help or guidance would be very appreciated!

EDIT:
Stadium params:

```<code>def stadium_params
  params.require(:stadium).permit(:name, :capacity, :city, :country, :location_name, :address, :longitude, :latitude, :image, :surface, :official_opening_date, :cost, :web_url, :also_known_as, :record_attendance)
end
</code>```

EDIT2: SOLVED:

After struggling with this. I finally found a solution: has_many :through uninitialized constant

I simply added :class_name => 'StadiumTeam' to the team and stadium model and it worked!

答:
I finally found a solution to this.

I simply added :class_name => 'StadiumTeam' to the team and stadium model and it worked!

More info here:
has_many :through uninitialized constant

Body:
I'm working on an app where I have two Tables that have a many-to-many relationship, joined in the middle by a join table.

Stadium model:

class Stadium < ActiveRecord::Base

has_many :stadiumteams
has_many :teams, :through => :stadiumteams

Team model:

class Team < ActiveRecord::Base
    has_many :stadiumteams
    has_many :stadiums, :through => :stadiumteams
end

StadiumTeam model (the jointable):

class StadiumTeam < ActiveRecord::Base
belongs_to :stadium
belongs_to :team
end

When I create a new Stadium I want to be able to select one or multiple teams that are associated with a stadium and save the relationship to the join-table (stadiumteams).

Here's the create action form the Stadiums Controller.

  def create
    @stadium = current_user.stadiums.build(stadium_params)

    respond_to do |format|
      if @stadium.save
         teams = Team.where(:id => params[:team])
         teams.each {|team| @stadium.teams << team}

        format.html { redirect_to @stadium, notice: 'Stadium was successfully created.' }
        format.json { render :show, status: :created, location: @stadium }
      else
        format.html { render :new }
        format.json { render json: @stadium.errors, status: :unprocessable_entity }
      end
    end
  end

When I try to create a new Stadium I get this output from the terminal.

  Parameters: {"utf8"=>"✓", "authenticity_token"=>"m+HAw4LRPmozIkigzuB/SFdcAFPTL735n6FyavH0SwjGXl7NHCLmDCXMTvx8bVixz+sL7tfn1zzCl04Q+w6Pdw==", "stadium"=>{"name"=>"Friends Arena", "capacity"=>"100000", "surface"=>"", "official_opening_date(1i)"=>"2017", "official_opening_date(2i)"=>"12", "official_opening_date(3i)"=>"4", "cost"=>"10000", "web_url"=>"teststadium.com", "record_attendance"=>"999790", "city"=>"", "country"=>"", "location_name"=>"", "longitude"=>"", "latitude"=>"", "address"=>"Friends Arena, Solna, Sweden"}, "team_id"=>"3", "commit"=>"Create Stadium"}
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ?  ORDER BY "users"."id" ASC LIMIT 1  [["id", 1]]
   (0.2ms)  begin transaction
  SQL (0.5ms)  INSERT INTO "stadiums" ("name", "capacity", "city", "country", "location_name", "address", "surface", "cost", "web_url", "record_attendance", "official_opening_date", "user_id", "latitude", "longitude", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)  [["name", "Friends Arena"], ["capacity", 100000], ["city", "Solna"], ["country", "Sweden"], ["location_name", ""], ["address", "Friends Arena, Solna, Sweden"], ["surface", ""], ["cost", 10000.0], ["web_url", "teststadium.com"], ["record_attendance", 999790], ["official_opening_date", "2017-12-04"], ["user_id", 1], ["latitude", 59.3727005], ["longitude", 18.0002317], ["created_at", "2017-12-04 13:18:45.841931"], ["updated_at", "2017-12-04 13:18:45.841931"]]
   (2.8ms)  commit transaction

It seems like "team_id"=>"3"" is added as a parameter but it's not inserted into any table. And I can't output the relationship between Stadiums and Teams in any way right now.

What I want to accomplish is to be able to show all Teams that are associated with Stadium on the Stadium show page. And all Stadiums that are associated with a Team on the teams Show page.

Any help or guidance would be very appreciated!

EDIT:
Stadium params:

def stadium_params
  params.require(:stadium).permit(:name, :capacity, :city, :country, :location_name, :address, :longitude, :latitude, :image, :surface, :official_opening_date, :cost, :web_url, :also_known_as, :record_attendance)
end

EDIT2: SOLVED:

After struggling with this. I finally found a solution: has_many :through uninitialized constant

I simply added :class_name => 'StadiumTeam' to the team and stadium model and it worked!


问:
Confusion matrix generates a and b as labels but not what I need
I have a bin and my label should be 'points' but when I generate the confusion matrix, it generates something known as a and b as labels but it doesn't show the labels as points above 90 and points below 90 which is as per my bins. Here is my code.

```<code>print(y_test.values)
cm = confusion_matrix(y_test.values, preds)
def plot_confusion_matrix(cm, classes,
                      normalize=False,
                      title='Confusion matrix',
                      cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    print("Normalized confusion matrix")
else:
    print('Confusion matrix, without normalization')

print(cm)

plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)

fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
    plt.text(j, i, format(cm[i, j], fmt),
             horizontalalignment="center",
             color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.figure()
plot_confusion_matrix(cm)
plt.show()
</code>```

And here is my graph, which shows a and b instead of points below and points above

答:
Working through the model I observed few thing which I believe is the best approach for this question. Maybe someone would find this helpful so I just wanted to clear this question.

I had created a bin from one label, so the label was points and the
  bins I created was 'points above 90' and 'points below 90' so these
  were the labels for the graph which had to show the value instead of
  'a' and 'b'. In the above case I had balanced the data well during
  bin's creation.

Hence, I changed my code to get the plot of my confusion matrix like below

```<code> plt.tight_layout()
 plt.ylabel('True label')
 plt.xlabel('Predicted label')
 plt.figure()
 plot_confusion_matrix(cm,['points above 90', 'points below 90'])
</code>```

Body:
I have a bin and my label should be 'points' but when I generate the confusion matrix, it generates something known as a and b as labels but it doesn't show the labels as points above 90 and points below 90 which is as per my bins. Here is my code.

print(y_test.values)
cm = confusion_matrix(y_test.values, preds)
def plot_confusion_matrix(cm, classes,
                      normalize=False,
                      title='Confusion matrix',
                      cmap=plt.cm.Blues):
"""
This function prints and plots the confusion matrix.
Normalization can be applied by setting `normalize=True`.
"""
if normalize:
    cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]
    print("Normalized confusion matrix")
else:
    print('Confusion matrix, without normalization')

print(cm)

plt.imshow(cm, interpolation='nearest', cmap=cmap)
plt.title(title)
plt.colorbar()
tick_marks = np.arange(len(classes))
plt.xticks(tick_marks, classes, rotation=45)
plt.yticks(tick_marks, classes)

fmt = '.2f' if normalize else 'd'
thresh = cm.max() / 2.
for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):
    plt.text(j, i, format(cm[i, j], fmt),
             horizontalalignment="center",
             color="white" if cm[i, j] > thresh else "black")
plt.tight_layout()
plt.ylabel('True label')
plt.xlabel('Predicted label')
plt.figure()
plot_confusion_matrix(cm)
plt.show()

And here is my graph, which shows a and b instead of points below and points above

Body:
Working through the model I observed few thing which I believe is the best approach for this question. Maybe someone would find this helpful so I just wanted to clear this question.

I had created a bin from one label, so the label was points and the
  bins I created was 'points above 90' and 'points below 90' so these
  were the labels for the graph which had to show the value instead of
  'a' and 'b'. In the above case I had balanced the data well during
  bin's creation.

Hence, I changed my code to get the plot of my confusion matrix like below

 plt.tight_layout()
 plt.ylabel('True label')
 plt.xlabel('Predicted label')
 plt.figure()
 plot_confusion_matrix(cm,['points above 90', 'points below 90'])


问:
import class file in Jruby
I have several scripts written in Jruby that I would like to obfuscate by converting them to .class files. But I am running into an error when I tried to access the .class file using Jruby.

My file structure looks like this:

```<code>temp/action.rb
temp/src/Test2.rb

#temp/src/Test2.rb

class Test2
    def self.add(num1,num2)
        return num1 + num2
    end
end
</code>```

I converted Test2.rb to .class files using

```<code>jrubyc Test2.rb
</code>```

which produce the following .class files :

Test2.class

Now, I trying to access Test2 and its methods from another jruby file, action.rb

```<code>    #temp/action.rb

    require 'java'

    $CLASSPATH << "src"

    java_import 'Test2'

    t = Test2.new
    puts t.add(2,3)
</code>```

But I am getting the following error:

```<code>NoMethodError: undefined method 'add' for <Java::Default::Test2:0x369f73a2>
</code>```

I'm not sure what I am doing wrong, any help would be appreciated.

答:
I haven't used JRuby for five years and discover strange things. Given the file Test2.rb :

```<code>class Test2
    def self.addc(num1, num2)
        num1 + num2
    end

    def self.xyz
        puts 'xyz'
    end

    def addi(num1, num2)
        num1 + num2
    end
end

puts Test2.addc(4,6)

t = Test2.new
puts t.addi(2, 3)
</code>```

which I compile :

```<code>$ jrubyc Test2.rb
$ jruby -J-cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar use_t.rb
in use_t.rb
NoMethodError: undefined method `addc' for Java::Default::Test2:Class
</code>```

Then I read in Using Jruby (from Pragmatic Programmers, but no longer available) :

If you pass the --java option to jrubyc, it will generate a .java file
  instead of a .class file. You can then fall back on familiar Java
  tools to finish the job.

```<code>$ jrubyc --java Test2.rb
$ javac -cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar Test2.java
Test2.java:16: error: unclosed string literal
        String source = new StringBuilder("class Test2
                                          ^
Test2.java:17: error: illegal character: '\'
\n" +
^
</code>```

I open Test2.java and see :

```<code>public class Test2 extends RubyObject  {
    private static final Ruby __ruby__ = Ruby.getGlobalRuntime();
    private static final RubyClass __metaclass__;

    static {
        String source = new StringBuilder("class Test2
\n" +
            "    def self.addc(num1, num2)
\n" +
            "        num1 + num2
\n" +
            "    end
\n" +
...
</code>```

I edit this file to "repair" it like so :

```<code>static {
    String source = new StringBuilder("class Test2\n" +
        "    def self.addc(num1, num2)\n" +
        "        num1 + num2\n" +
        "    end\n" +
        "    \n" +
        "    def self.xyz\n" +
        "        puts 'xyz'\n" +
        "    end\n" +
        "\n" +
...
</code>```

Then recompile

```<code>$ javac -cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar Test2.java
</code>```

and, with file use_t.rb :

```<code>require 'java'

#$CLASSPATH << '.'
java_import 'Test2'

puts "in #{__FILE__}"

Test2.xyz

puts ::Test2.addc(8,9)

t = ::Test2.new
puts t.addi(2,3)
</code>```

execute :

```<code>$ jruby -J-cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar use_t.rb
10
5
uri:classloader:/jruby/java/core_ext/object.rb:93: warning: already initialized constant Test2
in use_t.rb
xyz
17
5
</code>```

It works ! Strange detour.

It's not a problem of coercing parameters, because xyz alone :

```<code>NoMethodError: undefined method `xyz' for Java::Default::Test2:Class
</code>```

Then I try another version :

```<code>$ rvm install jruby
...
jruby-9.1.7.0 - #configure
jruby-9.1.7.0 - #download
...
jruby-9.1.7.0 - #generating default wrappers........
$ rvm use jruby
Using /Users/b/.rvm/gems/jruby-9.1.7.0
</code>```

Compile again :

```<code>$ jrubyc Test2.rb
$ jruby -J-cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar use_t.rb
in use_t.rb
NoMethodError: undefined method `addc' for Java::Default::Test2:Class
</code>```0

Then I download the latest release (jruby-complete-9.1.15.0.jar) from jruby.org and, with this error, I find in a forum that somebody used the following command and try it :

```<code>$ jrubyc Test2.rb
$ jruby -J-cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar use_t.rb
in use_t.rb
NoMethodError: undefined method `addc' for Java::Default::Test2:Class
</code>```1

It works, but don't ask why :(

Title: import class file in Jruby

Body:
I have several scripts written in Jruby that I would like to obfuscate by converting them to .class files. But I am running into an error when I tried to access the .class file using Jruby.

My file structure looks like this:

temp/action.rb
temp/src/Test2.rb

#temp/src/Test2.rb

class Test2
    def self.add(num1,num2)
        return num1 + num2
    end
end

I converted Test2.rb to .class files using

jrubyc Test2.rb

which produce the following .class files :

Test2.class

Now, I trying to access Test2 and its methods from another jruby file, action.rb

    #temp/action.rb

    require 'java'

    $CLASSPATH << "src"

    java_import 'Test2'

    t = Test2.new
    puts t.add(2,3)

But I am getting the following error:

NoMethodError: undefined method 'add' for <Java::Default::Test2:0x369f73a2>

I'm not sure what I am doing wrong, any help would be appreciated.

Body:
I haven't used JRuby for five years and discover strange things. Given the file Test2.rb :

class Test2
    def self.addc(num1, num2)
        num1 + num2
    end

    def self.xyz
        puts 'xyz'
    end

    def addi(num1, num2)
        num1 + num2
    end
end

puts Test2.addc(4,6)

t = Test2.new
puts t.addi(2, 3)

which I compile :

$ jrubyc Test2.rb
$ jruby -J-cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar use_t.rb
in use_t.rb
NoMethodError: undefined method `addc' for Java::Default::Test2:Class

Then I read in Using Jruby (from Pragmatic Programmers, but no longer available) :

If you pass the --java option to jrubyc, it will generate a .java file
  instead of a .class file. You can then fall back on familiar Java
  tools to finish the job.

$ jrubyc --java Test2.rb
$ javac -cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar Test2.java
Test2.java:16: error: unclosed string literal
        String source = new StringBuilder("class Test2
                                          ^
Test2.java:17: error: illegal character: '\'
\n" +
^

I open Test2.java and see :

public class Test2 extends RubyObject  {
    private static final Ruby __ruby__ = Ruby.getGlobalRuntime();
    private static final RubyClass __metaclass__;

    static {
        String source = new StringBuilder("class Test2
\n" +
            "    def self.addc(num1, num2)
\n" +
            "        num1 + num2
\n" +
            "    end
\n" +
...

I edit this file to "repair" it like so :

static {
    String source = new StringBuilder("class Test2\n" +
        "    def self.addc(num1, num2)\n" +
        "        num1 + num2\n" +
        "    end\n" +
        "    \n" +
        "    def self.xyz\n" +
        "        puts 'xyz'\n" +
        "    end\n" +
        "\n" +
...

Then recompile

$ javac -cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar Test2.java

and, with file use_t.rb :

require 'java'

#$CLASSPATH << '.'
java_import 'Test2'

puts "in #{__FILE__}"

Test2.xyz

puts ::Test2.addc(8,9)

t = ::Test2.new
puts t.addi(2,3)

execute :

$ jruby -J-cp .:/Users/b/.rvm/rubies/jruby-9.0.5.0/lib/jruby.jar use_t.rb
10
5
uri:classloader:/jruby/java/core_ext/object.rb:93: warning: already initialized constant Test2
in use_t.rb
xyz
17
5

It works ! Strange detour.

It's not a problem of coercing parameters, because xyz alone :

NoMethodError: undefined method `xyz' for Java::Default::Test2:Class

Then I try another version :

$ rvm install jruby
...
jruby-9.1.7.0 - #configure
jruby-9.1.7.0 - #download
...
jruby-9.1.7.0 - #generating default wrappers........
$ rvm use jruby
Using /Users/b/.rvm/gems/jruby-9.1.7.0

Compile again :

$ jrubyc Test2.rb
TypeError: failed to coerce org.objectweb.asm.ClassWriter to org.jruby.org.objectweb.asm.ClassVisitor
  block in compile_files_with_options at /Users/b/.rvm/rubies/jruby-9.1.7.0/lib/ruby/stdlib/jruby/compiler.rb:189

Then I download the latest release (jruby-complete-9.1.15.0.jar) from jruby.org and, with this error, I find in a forum that somebody used the following command and try it :

$ java -cp .:/userdata/Sources/jruby-complete-9.1.15.0.jar org.jruby.Main ./use_t.rb
10
5
uri:classloader:/jruby/java/core_ext/object.rb:95: warning: already initialized constant Test2
in ./use_t.rb
xyz
17
5

It works, but don't ask why :(


问:
pandas group by and assign a group id then ungroup
I have a large data set in the following format:

```<code>id, socialmedia
1, facebook
2, facebook
3, google
4, google
5, google
6, twitter
7, google
8, twitter
9, snapchat
10, twitter
11, facebook
</code>```

I want to group by then and assign a group_id column and then ungroup (expand) back to individual records.

```<code>id, socialmedia, groupId
1, facebook, 1
2, facebook, 1
3, google, 2
4, google, 2
5, google, 2
6, twitter, 3
7, google, 2
8, twitter, 3
9, snapchat, 4
10, twitter, 3
11, facebook, 1
</code>```

I tried following but end up with 'DataFrameGroupBy' object does not support item assignment.

```<code>x['grpId'] = x.groupby('socialmedia')['socialmedia'].rank(method='dense').astype(int)
</code>```

答:
We could also create a dictionary and map it:

```<code>import pandas as pd

df = pd.DataFrame(dict(id=range(1,5),social=["Facebook","Twitter","Facebook","Google"]))

d = dict((k,v) for v,k in enumerate(df['social'].unique(),1))
df['groupid'] = df['social'].map(m)

print(df)
</code>```

Returns

```<code>   id    social  groupid
0   1  Facebook        1
1   2   Twitter        2
2   3  Facebook        1
3   4    Google        3
</code>```

Or one-line like this:

```<code>df['groupid'] = df['social'].map({k:v for v,k in enumerate(df['social'].unique(),1)})
</code>```

Timings:

```<code>%timeit df['grpId']=df.groupby('social').ngroup().add(1)
%timeit df['grpId']=pd.factorize(df['social'])[0]+1
%timeit df['grpId']=df['social'].astype('category').cat.codes.add(1)
%timeit df['groupid'] = df['social'].map(dict((k,v) for v,k in enumerate(df['social'].unique(),1)))
</code>```

Returns

```<code>100 loops, best of 3: 1.5 ms per loop   <- Wen1
1000 loops, best of 3: 493 µs per loop  <- Wen2
1000 loops, best of 3: 990 µs per loop  <- Wen3
1000 loops, best of 3: 802 µs per loop  <- Antonvbr
</code>```

Body:
I have a large data set in the following format:

id, socialmedia
1, facebook
2, facebook
3, google
4, google
5, google
6, twitter
7, google
8, twitter
9, snapchat
10, twitter
11, facebook

I want to group by then and assign a group_id column and then ungroup (expand) back to individual records.

id, socialmedia, groupId
1, facebook, 1
2, facebook, 1
3, google, 2
4, google, 2
5, google, 2
6, twitter, 3
7, google, 2
8, twitter, 3
9, snapchat, 4
10, twitter, 3
11, facebook, 1

I tried following but end up with 'DataFrameGroupBy' object does not support item assignment.

x['grpId'] = x.groupby('socialmedia')['socialmedia'].rank(method='dense').astype(int)

Body:
We could also create a dictionary and map it:

import pandas as pd

df = pd.DataFrame(dict(id=range(1,5),social=["Facebook","Twitter","Facebook","Google"]))

d = dict((k,v) for v,k in enumerate(df['social'].unique(),1))
df['groupid'] = df['social'].map(m)

print(df)

Returns

   id    social  groupid
0   1  Facebook        1
1   2   Twitter        2
2   3  Facebook        1
3   4    Google        3

Or one-line like this:

df['groupid'] = df['social'].map({k:v for v,k in enumerate(df['social'].unique(),1)})

Timings:

%timeit df['grpId']=df.groupby('social').ngroup().add(1)
%timeit df['grpId']=pd.factorize(df['social'])[0]+1
%timeit df['grpId']=df['social'].astype('category').cat.codes.add(1)
%timeit df['groupid'] = df['social'].map(dict((k,v) for v,k in enumerate(df['social'].unique(),1)))

Returns

100 loops, best of 3: 1.5 ms per loop   <- Wen1
1000 loops, best of 3: 493 µs per loop  <- Wen2
1000 loops, best of 3: 990 µs per loop  <- Wen3
1000 loops, best of 3: 802 µs per loop  <- Antonvbr


问:
What exactly is a binding?
I have been seeing the term "binding" and "live-binding" more and more recently, especially in JavaScript frameworks like Ember.js, Can.js, Knockout.js, and Backbone.js, and more traditionally, in Cocoa and Objective-C, and wonder what exactly a binding is?  (and what exactly is a "live-binding"?).

It seems that from a loose sense, we can "bind A to B", and then we can say, "A is bound to B", and that means changes in B will be reflected in A -- automatically, without the user worrying having to set up an observer but the observer is set up earlier automatically and notified automatically when B changes.

And when we do that, we are creating a "binding".

And from a stricter sense, it seems the Cocoa and Objective-C defines it like this: a binding is a property foo of Object A, and this property observes and get changed to the value of property bar of object B.  How it happens, we don't care and it is supposed to be hidden (like a black box), and usually it is implemented by the Observer Pattern.  So the word "binding" actually means a "property", not an action -- and this property observes and get changed to the same value as the other property has.

And this binding is not limited to UI elements being bound to data.  It can be an outer, larger UI element that contains a smaller piece of UI element, and the outer UI element has a property that is bound to the inner UI element property.  Or it can be one non-UI data property bound to another non-UI data property.

Is this what a binding is exactly?  And what about a live-binding?

答:
It's not dissimilar from the original use of the .bind method in vanilla javascript: you bind the scope of an object to a method.

Consider this.iterable.map( this.flush ) and this.iterable.map( this.flush.bind(this)). In the first, we're simple running a method on each interation of the iterable property on this - but in order for the this.flush method to access the this property, you must bind it to this.

In the same way, in frameworks like Ember, the model is a declaration. In order to populate that model from a remote source, you need an instance. In order to modify the model from handlebars, you need an instance. If your UI changes immediately effect the model instance - they're bound.

Pseudo-coded:
UI.view.bind(modelInstance)
RemoteSource.bind(modelInstance)

"Live-Binding", in my experience, is the binding of the data to the remote source immediately on change in the UI.

Pseudo-coded:
UI.view.bind(modelInstance)
RemoteSource.bind(modelInstance)
modelInstance.onChange(RemoteSource.update.bind(modelInstance))

Title: What exactly is a binding?


问:
floats not stacking beneath eachother
Using Post Type Builder, I created a CPT called Concerts. On a clean install of the theme on my server, I produced this result, which is structurally correct: https://plushdesign.net/plush8/concert/deck-the-hall/

Each component is set in a unique div within a parent div, and they should all be floating to the right of the photo. The divs are all set to float left.

When I moved the CPT/css over to the development site, the same css displays this: http://spiderman.ephronsystems.com/concert/san-francisco-symphony-presents-deck-the-hall/

How to get the purple button to float down below the details, and the text to wrap beneath it (it will not wrap around the photo, which is the desired behavior). I tried every combination of clearing and display properties but it is very stubborn.

Here is the relevant html:

```<code>div class="ptb_items_wrapper entry-content" itemtype="http://schema.org/Article" itemscope="">
<div class="ptb_first_row ptb_row ptb_concert_row ">
<div class="ptb_col ptb_col1-1 ptb_col_first">
<div class="ptb_module ptb_thumbnail ptb_module_inline">
<div class="title ptb_module ptb_title">
<div class="details ptb_module ptb_text ptb_details">
<div class="purchasetickets ptb_module ptb_text ptb_purchase_tickets">
<div class="description ptb_module ptb_text ptb_description">
</div>
</div>
</code>```

Here is the relevant css:

```<code>div.ptb_items_wrapper.entry-content {float:left;overflow:auto;padding-top:2em;border-top:1px solid #ededed;}
div.ptb_module.ptb_thumbnail.ptb_module_inline {float:left;margin-right: 1em;}
div.title.ptb_module.ptb_title {float:left;}
div.details.ptb_module.ptb_text.ptb_details {float:left;/*margin-right: 200px;*/}

div.purchasetickets.ptb_module.ptb_text.ptb_purchase_tickets {float:left;color:#fff !important;}
.purchasetickets { padding: 6px 16px; background: #872c8c;margin:3px 0 12px !important;border-radius: 1.2em;font-size: 14px;text-transform: uppercase;letter-spacing: 2px;color:#fff !important;}
a.purchasetickets, .ptb_purchase_tickets a {color:#fff !important;}
.purchasetickets:hover {opacity:.5;}

div.description.ptb_module.ptb_text.ptb_description {float:left;}
</code>```

thanks!

答:
Here's the new CSS:

```<code>div.ptb_items_wrapper.entry-content {float:left;overflow:auto;padding-top:2em;border-top:1px solid #ededed;}
div.ptb_module.ptb_thumbnail.ptb_module_inline {float:left;margin-right: 1em;}
div.title.ptb_module.ptb_title {}
div.details.ptb_module.ptb_text.ptb_details {/*margin-right: 200px;*/}

div.purchasetickets.ptb_module.ptb_text.ptb_purchase_tickets {color:#fff !important;display: inline-block;}
    .purchasetickets { padding: 6px 16px; background: #872c8c;margin:3px 0 12px !important;border-radius: 1.2em;font-size: 14px;text-transform: uppercase;letter-spacing: 2px;color:#fff !important;}
    a.purchasetickets, .ptb_purchase_tickets a {color:#fff !important;}
    .purchasetickets:hover {opacity:.5;}

div.description.ptb_module.ptb_text.ptb_description {float:left;}
</code>```

Summary change:

Only float the image

Apply display: inline-block on the button.

Also, to help others, please add the appropriate tags to your question, as mentioned by @Andrei Gheorghiu. :)

Title: floats not stacking beneath eachother

Body:
Using Post Type Builder, I created a CPT called Concerts. On a clean install of the theme on my server, I produced this result, which is structurally correct: https://plushdesign.net/plush8/concert/deck-the-hall/

Each component is set in a unique div within a parent div, and they should all be floating to the right of the photo. The divs are all set to float left.

When I moved the CPT/css over to the development site, the same css displays this: http://spiderman.ephronsystems.com/concert/san-francisco-symphony-presents-deck-the-hall/

How to get the purple button to float down below the details, and the text to wrap beneath it (it will not wrap around the photo, which is the desired behavior). I tried every combination of clearing and display properties but it is very stubborn.

Here is the relevant html:

div class="ptb_items_wrapper entry-content" itemtype="http://schema.org/Article" itemscope="">

Here is the relevant css:

div.ptb_items_wrapper.entry-content {float:left;overflow:auto;padding-top:2em;border-top:1px solid #ededed;}
div.ptb_module.ptb_thumbnail.ptb_module_inline {float:left;margin-right: 1em;}
div.title.ptb_module.ptb_title {float:left;}
div.details.ptb_module.ptb_text.ptb_details {float:left;/*margin-right: 200px;*/}

div.purchasetickets.ptb_module.ptb_text.ptb_purchase_tickets {float:left;color:#fff !important;}
.purchasetickets { padding: 6px 16px; background: #872c8c;margin:3px 0 12px !important;border-radius: 1.2em;font-size: 14px;text-transform: uppercase;letter-spacing: 2px;color:#fff !important;}
a.purchasetickets, .ptb_purchase_tickets a {color:#fff !important;}
.purchasetickets:hover {opacity:.5;}

div.description.ptb_module.ptb_text.ptb_description {float:left;}

thanks!

Body:
Here's the new CSS:

div.ptb_items_wrapper.entry-content {float:left;overflow:auto;padding-top:2em;border-top:1px solid #ededed;}
div.ptb_module.ptb_thumbnail.ptb_module_inline {float:left;margin-right: 1em;}
div.title.ptb_module.ptb_title {}
div.details.ptb_module.ptb_text.ptb_details {/*margin-right: 200px;*/}

div.purchasetickets.ptb_module.ptb_text.ptb_purchase_tickets {color:#fff !important;display: inline-block;}
    .purchasetickets { padding: 6px 16px; background: #872c8c;margin:3px 0 12px !important;border-radius: 1.2em;font-size: 14px;text-transform: uppercase;letter-spacing: 2px;color:#fff !important;}
    a.purchasetickets, .ptb_purchase_tickets a {color:#fff !important;}
    .purchasetickets:hover {opacity:.5;}

div.description.ptb_module.ptb_text.ptb_description {float:left;}

Summary change:

Only float the image

Apply display: inline-block on the button.

Also, to help others, please add the appropriate tags to your question, as mentioned by @Andrei Gheorghiu. :)


问:
Implementing facenet in keras

Here I am trying to implement open face in keras.
but i am confused about that how to do triplet embedding (As Image in above link)
I know about triplet selection and convolution neural network

can someone help to figure out:

1> model structure for triplet training

2> triplet loss function

答: The model can be anything, but generally it's a convolutional net. The triplet loss is computed on one of the late dense layer outputs, according to the formula you linked. Basically, if d(A, B) is the euclidean distance between outputs A and B (treated as vectors), then take max(0, d(A, P)^2 - d(A, N)^2 + alpha)

ContentLicense: CC BY-SA 4.0

Title: Implementing facenet in keras


问:
Knockout js unable to remove object from observableArray
I've got two ways that I'm filling in an observableArray, one for testing purposes and one for the way I intend on using this array.

The first way I'm defining these objects and pushing them in one at a time, the second way I'm reading a JSON stream and pushing them in with a loop.

Here's my code for this shuttle-menu I'm using.

```<code>var StateModel = function() {
    var self = this;
    // initialize containers
    self.leftStateBox = ko.observableArray();
    self.rightStateBox = ko.observableArray();

    // selected ids
    self.selectedLeftStateBox = ko.observableArray();
    self.selectedRightStateBox = ko.observableArray();

    self.moveLeft = function () {
        var sel = self.selectedRightStateBox();
        for (var i = 0; i < sel.length; i++) {
            var selCat = sel[i];
            var result = self.rightStateBox.remove(function (item) {
                return item.id == selCat;
            });
            if (result && result.length > 0) {
                self.leftStateBox.push(result[0]);
            }
        }
        self.selectedRightStateBox.removeAll();
    }

    self.moveRight = function () {
        var sel = self.selectedLeftStateBox();
        for (var i = 0; i < sel.length; i++) {
            var selCat = sel[i];
            var result = self.leftStateBox.remove(function (item) {
                return item.id == selCat;
            });
            if (result && result.length > 0) {
                self.rightStateBox.push(result[0]);
            }
        }
        self.selectedLeftStateBox.removeAll();
    }

    self.leftStateBox.push({
        id: "CAA"
        , name: 'State 1'
    });
    self.leftStateBox.push({
        id: "VAA"
        , name: 'State 2'
    });
    self.leftStateBox.push({
        id: "BAA"
        , name: 'State 3'
    });

    self.loadStates = function() {
        var self = this;
        $.getJSON("${baseAppUrl}/public/company/" + companyId + "/json/searchStates/list",
            function (searchStatesData) {
                var states = JSON.parse(searchStatesData).searchStates;
                for(var i = 0; i < states.length; i++) {
                    self.leftStateBox.push(new State(states[i]));
                }
            });
    };
    self.loadStates();
}

var State = function (state) {
    var self = this;
    self.name = ko.observable(state.name);
    self.id = ko.observable(state.id);
}

$(function () {
    ko.applyBindings(new StateModel(), document.getElementById("statesBox"));
});
</code>```

Here's my view section:

```<code>'<div id="statesBox">
    <div>
        Available States:
        <select multiple='multiple' data-bind="options: leftStateBox, optionsText: 'name', optionsValue: 'id', selectedOptions: selectedLeftStateBox"></select>
    </div>
    <div>
        <p><button data-bind="click: moveRight">Add Selected</button></p>
        <p><button data-bind="click: moveLeft">Remove Selected</button></p>
    </div>
    <div>
        Selected States:
        <select multiple='multiple' data-bind="options: rightStateBox, optionsText: 'name', optionsValue: 'id', selectedOptions: selectedRightStateBox"></select>
    </div>
    <br /><br />
</div>'
</code>```

When I try to shuttle things back and forth on the list it works for the three I manually entered in but it doesn't work for the ones imported through the JSON call. They all show up on the list though and seem to have the same information, I structured the manually created objects after how the JSON objects look. When I trace the JS function moveRight, the remove works for the manually created objects but fails on the imported ones. I'm not really sure what I'm doing wrong at this point, has anyone seen something like this?

I grabbed the shuttle menu code from this post

答:
The items you're adding have an important difference.

```<code>self.leftStateBox.push({
    id: "BAA"
    , name: 'State 3'
});

...

var State = function (state) {
    var self = this;
    self.name = ko.observable(state.name);
    self.id = ko.observable(state.id);
}
</code>```

The first have non-observable property values and the second have observable property values. In general, you should only make things observable if they need to be so (are you ever going to want to change the name or id of an item?).

```<code>var State = function (state) {
    var self = this;
    self.name = state.name;
    self.id = state.id;
}
</code>```

If a property is always observable, you can just "unwrap" it directly: item.id(). If it may sometimes be observable, you can use ko.unwrap(item.id).

```<code>var result = self.rightStateBox.remove(function (item) {
    return ko.unwrap(item.id) == selCat;
});
</code>```

Body:
I've got two ways that I'm filling in an observableArray, one for testing purposes and one for the way I intend on using this array.

The first way I'm defining these objects and pushing them in one at a time, the second way I'm reading a JSON stream and pushing them in with a loop.

Here's my code for this shuttle-menu I'm using.

var StateModel = function() {
    var self = this;
    // initialize containers
    self.leftStateBox = ko.observableArray();
    self.rightStateBox = ko.observableArray();

    // selected ids
    self.selectedLeftStateBox = ko.observableArray();
    self.selectedRightStateBox = ko.observableArray();

    self.moveLeft = function () {
        var sel = self.selectedRightStateBox();
        for (var i = 0; i < sel.length; i++) {
            var selCat = sel[i];
            var result = self.rightStateBox.remove(function (item) {
                return item.id == selCat;
            });
            if (result && result.length > 0) {
                self.leftStateBox.push(result[0]);
            }
        }
        self.selectedRightStateBox.removeAll();
    }

    self.moveRight = function () {
        var sel = self.selectedLeftStateBox();
        for (var i = 0; i < sel.length; i++) {
            var selCat = sel[i];
            var result = self.leftStateBox.remove(function (item) {
                return item.id == selCat;
            });
            if (result && result.length > 0) {
                self.rightStateBox.push(result[0]);
            }
        }
        self.selectedLeftStateBox.removeAll();
    }

    self.leftStateBox.push({
        id: "CAA"
        , name: 'State 1'
    });
    self.leftStateBox.push({
        id: "VAA"
        , name: 'State 2'
    });
    self.leftStateBox.push({
        id: "BAA"
        , name: 'State 3'
    });

    self.loadStates = function() {
        var self = this;
        $.getJSON("${baseAppUrl}/public/company/" + companyId + "/json/searchStates/list",
            function (searchStatesData) {
                var states = JSON.parse(searchStatesData).searchStates;
                for(var i = 0; i < states.length; i++) {
                    self.leftStateBox.push(new State(states[i]));
                }
            });
    };
    self.loadStates();
}

var State = function (state) {
    var self = this;
    self.name = ko.observable(state.name);
    self.id = ko.observable(state.id);
}

$(function () {
    ko.applyBindings(new StateModel(), document.getElementById("statesBox"));
});

Here's my view section:

'

        Available States:
        <select multiple='multiple' data-bind="options: leftStateBox, optionsText: 'name', optionsValue: 'id', selectedOptions: selectedLeftStateBox"></select>

<button data-bind="click: moveRight">Add Selected</button>

<button data-bind="click: moveLeft">Remove Selected</button>

        Selected States:
        <select multiple='multiple' data-bind="options: rightStateBox, optionsText: 'name', optionsValue: 'id', selectedOptions: selectedRightStateBox"></select>

'

When I try to shuttle things back and forth on the list it works for the three I manually entered in but it doesn't work for the ones imported through the JSON call. They all show up on the list though and seem to have the same information, I structured the manually created objects after how the JSON objects look. When I trace the JS function moveRight, the remove works for the manually created objects but fails on the imported ones. I'm not really sure what I'm doing wrong at this point, has anyone seen something like this?

I grabbed the shuttle menu code from this post

Body:
The items you're adding have an important difference.

self.leftStateBox.push({
    id: "BAA"
    , name: 'State 3'
});

...

var State = function (state) {
    var self = this;
    self.name = ko.observable(state.name);
    self.id = ko.observable(state.id);
}

The first have non-observable property values and the second have observable property values. In general, you should only make things observable if they need to be so (are you ever going to want to change the name or id of an item?).

var State = function (state) {
    var self = this;
    self.name = state.name;
    self.id = state.id;
}

If a property is always observable, you can just "unwrap" it directly: item.id(). If it may sometimes be observable, you can use ko.unwrap(item.id).

var result = self.rightStateBox.remove(function (item) {
    return ko.unwrap(item.id) == selCat;
});


问:
Javascript validation for a html form not working
----------SOLVED------------

I'm trying to do a validation for a form so that if any of the fields are left blank, there is an alert and the form wont go through, but it is still inputting null values into the database

function validateAdd() {
  var a = document.add_product.product_id.value;
  var b = document.add_product.brand.value;
  var c = document.add_product.model.value;
  var h = document.add_product.description.value;
  var d = document.add_product.cam_mpx.value;
  var e = document.add_product.storage.value;
  var f = document.add_product.more_storage.value;
  var g = document.add_product.price.value;
  if (a == "" || b == "" || c == "" || d == "" || e == "" || f = "" || g == "" || h == "" ||
    a == null || b == null || c == null || d == null || e == null || f = null || g == null || h == null) {
    alert("All fields must be filled in");
    return false;
  }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form name="add_product" action="index.php" method="post" onsubmit="return validateAdd()">
  <label>Product ID:</label><br>
  <input type="text" name="product_id"><br>
  <label>Brand:</label><br>
  <input type="text" name="brand"><br>
  <label>Model:</label><br>
  <input type="text" name="model"><br>
  <label>Description:</label><br>
  <input type="text" name="description"><br>
  <label>Camera Megapixel:</label><br>
  <input type="text" name="cam_mpx"><br>
  <label>Storage:</label><br>
  <input type="text" name="storage"><br>
  <label>Expandable Storage?:</label><br>
  <input type="text" name="more_storage"><br>
  <label>Price:</label><br>
  <input type="text" name="price"><br>
  <button class="button" type="submit" name="save" onclick="return confirm('Are you sure you want to add this to the system?')">Add</button><br>
  <p></p>
</form></code>```

答:
Well, on these two lines, you do f = "" and f = null instead of f == "" and f == null:

```<code>if (a == "" || b == "" || c == "" || d == "" || e == "" || f = "" || g == "" || h == ""
        || a == null || b == null || c == null || d == null || e == null || f = null || g == null || h == null) {
</code>```

You would have noticed to look there from Uncaught ReferenceError: Invalid left-hand side in assignment being errored to the console.

I would suggest that you shorten that down to

```<code>if (!(a && b && c && d && e && f && g && h)) {
</code>```

because it's way easier to debug.

Body:
----------SOLVED------------

I'm trying to do a validation for a form so that if any of the fields are left blank, there is an alert and the form wont go through, but it is still inputting null values into the database

function validateAdd() {
  var a = document.add_product.product_id.value;
  var b = document.add_product.brand.value;
  var c = document.add_product.model.value;
  var h = document.add_product.description.value;
  var d = document.add_product.cam_mpx.value;
  var e = document.add_product.storage.value;
  var f = document.add_product.more_storage.value;
  var g = document.add_product.price.value;
  if (a == "" || b == "" || c == "" || d == "" || e == "" || f = "" || g == "" || h == "" ||
    a == null || b == null || c == null || d == null || e == null || f = null || g == null || h == null) {
    alert("All fields must be filled in");
    return false;
  }
}

<form name="add_product" action="index.php" method="post" onsubmit="return validateAdd()">
  Product ID:

  <input type="text" name="product_id">

  Brand:

  <input type="text" name="brand">

  Model:

  <input type="text" name="model">

  Description:

  <input type="text" name="description">

  Camera Megapixel:

  <input type="text" name="cam_mpx">

  Storage:

  <input type="text" name="storage">

  Expandable Storage?:

  <input type="text" name="more_storage">

  Price:

  <input type="text" name="price">

  <button class="button" type="submit" name="save" onclick="return confirm('Are you sure you want to add this to the system?')">Add</button>

</form>

Body:
Well, on these two lines, you do f = "" and f = null instead of f == "" and f == null:

if (a == "" || b == "" || c == "" || d == "" || e == "" || f = "" || g == "" || h == ""
        || a == null || b == null || c == null || d == null || e == null || f = null || g == null || h == null) {

You would have noticed to look there from Uncaught ReferenceError: Invalid left-hand side in assignment being errored to the console.

I would suggest that you shorten that down to

if (!(a && b && c && d && e && f && g && h)) {

because it's way easier to debug.


问:
leaflet markers not appearing
```<code>for (var f=0; f<group.length; f++) {
    var longitude = group[f][1];
    var latitude = group[f][0];
    var popupText = group[f][2];

    var markerLocation = new L.LatLng(longitude,latitude);
    var marker = new L.Marker(markerLocation);
    mymap.addLayer(marker);

    marker.bindPopup(popupText);
}
</code>```

my group array is in this format

```<code> [0]
 [0]53.522753
 [1]-1.126298
 [2]ASB
</code>```

my console is saying

```<code>Uncaught Error: Invalid LatLng object: (undefined, 53.522731)
    at new M (leaflet.js:5)
    at create_marker (hello.html:212)
    at JSON_callback (hello.html:169)
    at XMLHttpRequest.xmlhttp.onreadystatechange (requests.js:26)
</code>```

setting group

```<code>var group = [];
var n = 3;

for (var i = 0, j = 0; i < current_lat_lng.length; i++) {
    if (i >= n && i % n === 0)
        j++;
    group[j] = group[j] || [];
    group[j].push(current_lat_lng[i])
}
</code>```

I think the object is correct? but I'm not sure why this is happening. any help is appreciated thanks.

答:
Try the following:</p>

```<code>for (var f=0; f<group.length; f++) {
    var longitude = group[f][1];
    var latitude = group[f][0];
    var popupText = group[f][2];

    if (longitude && latitude && popupText) {
        L.marker([latitude, longitude]).bindPopup(popupText).addTo(mymap);
    } else {
        console.error('group[' + f + '] has invalid entries:');
        console.error('longitude', longitude);
        console.error('latitude', latitude);
        console.error('popupText', popupText);
    }
}
</code>```

Title: leaflet markers not appearing

Body:
for (var f=0; f<group.length; f++) {
    var longitude = group[f][1];
    var latitude = group[f][0];
    var popupText = group[f][2];

    var markerLocation = new L.LatLng(longitude,latitude);
    var marker = new L.Marker(markerLocation);
    mymap.addLayer(marker);

    marker.bindPopup(popupText);
}

my group array is in this format

 [0]
 [0]53.522753
 [1]-1.126298
 [2]ASB

my console is saying

Uncaught Error: Invalid LatLng object: (undefined, 53.522731)
    at new M (leaflet.js:5)
    at create_marker (hello.html:212)
    at JSON_callback (hello.html:169)
    at XMLHttpRequest.xmlhttp.onreadystatechange (requests.js:26)

setting group

var group = [];
var n = 3;

for (var i = 0, j = 0; i < current_lat_lng.length; i++) {
    if (i >= n && i % n === 0)
        j++;
    group[j] = group[j] || [];
    group[j].push(current_lat_lng[i])
}

I think the object is correct? but I'm not sure why this is happening. any help is appreciated thanks.

Body:
Try the following:

for (var f=0; f<group.length; f++) {
    var longitude = group[f][1];
    var latitude = group[f][0];
    var popupText = group[f][2];

    if (longitude && latitude && popupText) {
        L.marker([latitude, longitude]).bindPopup(popupText).addTo(mymap);
    } else {
        console.error('group[' + f + '] has invalid entries:');
        console.error('longitude', longitude);
        console.error('latitude', latitude);
        console.error('popupText', popupText);
    }
}


问:
c# Given 2 numbers X and Y, make X approach Y but not surpass it
I've been racking my brains for ages trying to work out a good formula for this.

Essentially what i want is given 2 numbers X and Y, I would like X to approach Y but not surpass it depending on the difference between the 2 numbers.

Both X and Y are floats between 0 and 1.

Examples:

X = 0 Y = 1. X should become about 0.7-0.8 ish.

X = 0.5 Y = 1 X should become between 0.8-0.9.

X = 0.9 y = 1 X should become 0.97 ish.

Heres what i've tried:

(1-X) * Y = Just gives linear progression....

0.08/(1.1-(Y-X)) - Better.. but gives a value 0.13 when the difference is 0.5, 0.8 when the difference is 1 and 0.4 when the difference is 0.9.... not quite what i wanted...

Any ideas guys?

Thanks,

Phil.

答:
```<code>float Result(float x, float y)
{
    return y - ((y - x) / 4); // you can change 4 to whatever you need.
}
</code>```

Is this what you're looking for?

Body:
float Result(float x, float y)
{
    return y - ((y - x) / 4); // you can change 4 to whatever you need.
}

Is this what you're looking for?


问:
Visual Studio Resources
I've got a relatively small program that runs on a proxy socket class I fount from the mentalis website. For some reason this program has quickly become a 100% cpu resource hog when running. I've done all I can think to find the problem in the code is there a function in visual studio that helps to identify what sections of the code are the most resource intensive? Any ideas on why a socket class would be such a cpu hog?</p>

答:
Run your program in debug mode and when the CPU load goes to 100%, break the running process with Ctrl-Alt-Break. It is very likely that you stop the program exactly in the part of the code which is cause of your problem. If one break is not enough to find the right code line, repeat this several times.

Just a guess: perhaps the socket class does some kind of polling or busy-waiting?

Title: Visual Studio Resources


答:
We can't tell what's the perfect value for you, but you can basically use a generic formula for blending between two points, coordinates, or whatever:

x = a × x1 + (1 - a) × x2

The same can be done for y or any other value, even whole vectors or points.

To apply this to your specific variables:

Xnew = a × X + (1 - a) × Y

a basically determines the position relative between the first and the second point. 0 means the point is on the first one, 0.5 puts the point exactly in the middle, and 1 represents the second point.

How you change a over time depends on which kind of tweening you want (e.g. linear, quadratic, ease-in, ease-out, etc.

If you want to read more regarding this topic, try looking for tweens, tweening, etc.

Title: c# Given 2 numbers X and Y, make X approach Y but not surpass it

Body:
I've been racking my brains for ages trying to work out a good formula for this.

Essentially what i want is given 2 numbers X and Y, I would like X to approach Y but not surpass it depending on the difference between the 2 numbers.

Both X and Y are floats between 0 and 1.

Examples:

X = 0 Y = 1. X should become about 0.7-0.8 ish.

X = 0.5 Y = 1 X should become between 0.8-0.9.

X = 0.9 y = 1 X should become 0.97 ish.

Heres what i've tried:

(1-X) * Y = Just gives linear progression....

0.08/(1.1-(Y-X)) - Better.. but gives a value 0.13 when the difference is 0.5, 0.8 when the difference is 1 and 0.4 when the difference is 0.9.... not quite what i wanted...

Any ideas guys?

Thanks,

Phil.


问:
How to declare a global variable in a module
In the main program I have

```<code>import medallia_utils
from collections import defaultdict
Opers   = defaultdict(int)
</code>```

Later on in this program, I will be calling a function in medallia_utils called word_checker.

I want to manipulate the dictionary variable Opers in a function word_checker defined inside medallia_utils so I want to declare it as Global.

When I do this inside of medallia_utils:

```<code>def word_checker(name, comment):
    import re
    from collections import defaultdict
    global Opers
</code>```

The system says

```<code>NameError: global name 'Opers' is not defined
</code>```

I also tried to define this variable globally in medallia_utils outside of the function word_checker by doing

```<code>global Opers
</code>```

or

```<code>global __Opers__
</code>```

but nothing working so far. I get the same error.

What is the syntax fix to get this to work?

答: There is no "syntax fix" that can make this work. If you want to use a variable defined in another module, you need to import it.</p>

Body:
In the main program I have

import medallia_utils
from collections import defaultdict
Opers   = defaultdict(int)

Later on in this program, I will be calling a function in medallia_utils called word_checker.

I want to manipulate the dictionary variable Opers in a function word_checker defined inside medallia_utils so I want to declare it as Global.

When I do this inside of medallia_utils:

def word_checker(name, comment):
    import re
    from collections import defaultdict
    global Opers

The system says

NameError: global name 'Opers' is not defined

I also tried to define this variable globally in medallia_utils outside of the function word_checker by doing

global Opers

or

global __Opers__

but nothing working so far. I get the same error.

What is the syntax fix to get this to work?


问:
Python skipping XML child nodes while parsing in BeautifulSoup
I'm running into a problem where a certain group of child tags aren't parsing fully. I follow the same logic as this with other tags but for reasons I cannot see it's skipping all but the first entries of the tags I want. A basic snippet of my current script looks something like this:

```<code>for xml_string in separated_xml(infile):

   soup = BeautifulSoup(xml_string, "lxml")

        us_grant = soup.findAll("us-patent-grant")

        with open('./output.csv', 'ab+') as f:
            writer = csv.writer(f, dialect = 'excel')

            for info in us_grant:

              data = []
              us_class_search = soup.findAll("us-field-of-classification-search")

              for item2 in us_class_search:

                if item2.find("classification-national"):

                  country_search = item2.find("country")
                  main_class_search = item2.find("main-classification")

                  data.append((country_search).text)
                  data.append((main_class_search).text)
              print(data)
</code>```

Once I print(data) after each iteration it only gives me the first entry of each country and main-classification tag under every us-patent-grant parent; but there are many more. For example the XML file with these tags looks like:

```<code><us-field-of-classification-search>
<classification-national>
<country>US</country>
<main-classification>D 1100-130</main-classification>
<additional-info>unstructured</additional-info>
</classification-national>
<classification-national>
<country>US</country>
<main-classification>D 1199</main-classification>
</classification-national>
<classification-national>
<country>US</country>
<main-classification>426  5</main-classification>
</classification-national>
<classification-national>
<country>US</country>
<main-classification>426 76</main-classification>
</classification-national>
</us-field-of-classification-search>
</code>```

I know that the if item2 statement does not follow through correctly because even if I take it out it still runs the for item2 loop the same way; finding and appending only the first tags under each. This means it must be the loop itself not running through and finding each instance and treating the first tag as all of them.

Any ideas? I don't see any obvious fault in logic.

If you'd like to see the XML itself you can find it here on USPTO

答:
item2 is iterating over all <us-field-of-classification-search> elements, of which there is only one in your sample.

Within that loop you should then be iterating over <classification-national> elements, but you are examining only the first one.

Body:
I'm running into a problem where a certain group of child tags aren't parsing fully. I follow the same logic as this with other tags but for reasons I cannot see it's skipping all but the first entries of the tags I want. A basic snippet of my current script looks something like this:

for xml_string in separated_xml(infile):

   soup = BeautifulSoup(xml_string, "lxml")

        us_grant = soup.findAll("us-patent-grant")

        with open('./output.csv', 'ab+') as f:
            writer = csv.writer(f, dialect = 'excel')

            for info in us_grant:

              data = []
              us_class_search = soup.findAll("us-field-of-classification-search")

              for item2 in us_class_search:

                if item2.find("classification-national"):

                  country_search = item2.find("country")
                  main_class_search = item2.find("main-classification")

                  data.append((country_search).text)
                  data.append((main_class_search).text)
              print(data)

Once I print(data) after each iteration it only gives me the first entry of each country and main-classification tag under every us-patent-grant parent; but there are many more. For example the XML file with these tags looks like:

<us-field-of-classification-search>
<classification-national>
<country>US</country>
D 1100-130
<additional-info>unstructured</additional-info>
</classification-national>
<classification-national>
<country>US</country>
D 1199
</classification-national>
<classification-national>
<country>US</country>
426  5
</classification-national>
<classification-national>
<country>US</country>
426 76
</classification-national>
</us-field-of-classification-search>

I know that the if item2 statement does not follow through correctly because even if I take it out it still runs the for item2 loop the same way; finding and appending only the first tags under each. This means it must be the loop itself not running through and finding each instance and treating the first tag as all of them.

Any ideas? I don't see any obvious fault in logic.

If you'd like to see the XML itself you can find it here on USPTO


问:
pinterest api: cannot find user when adding collaborators
I want to add collaborators to my pinterest api. But when I type the name of my friend's pinterest username i get an error "no user found". I have follow them, do I need to do something else?</p>

答: before you can add a developer or contributor, you must first follow each other. have them follow you too. </p>


问:
Windows Phone 7 Spell Check on textboxes
How do I implement the spell check feature for my large text boxes for my app?</p>

答:
Generally there is no spell check. If you are talking about generalized suggestions, you can get those by using a specific SIP (Software Input Panel) - Text.

Official documentation: MSDN

You will have to manually specify the InputScope:

```<code><TextBox>
    <TextBox.InputScope>
        <InputScope>
            <InputScopeName NameValue="Text"/>
        </InputScope>
    </TextBox.InputScope>
</TextBox>
</code>```

Body:
Generally there is no spell check. If you are talking about generalized suggestions, you can get those by using a specific SIP (Software Input Panel) - Text.

Official documentation: MSDN

You will have to manually specify the InputScope:

<TextBox>
    <TextBox.InputScope>
        <InputScope>
            <InputScopeName NameValue="Text"/>
        </InputScope>
    </TextBox.InputScope>
</TextBox>